diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d89296..743a188 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,15 @@ All notable changes to this project are documented here. The format follows ### Added +- **Context receipts and correlation in the recall log** (#119 H1; specs/memkernel-0-15-harness-foundations, + amendment H1). `recall` and `retain` take `run_id`, `agent_id` and `task_id` (or `MEMKERNEL_RUN_ID`, + `MEMKERNEL_AGENT_ID`, `MEMKERNEL_TASK_ID` for the process), at most 128 characters each, a longer argument + refused. With `MEMKERNEL_RECALL_LOG` on, each record also carries those ids and a receipt: per returned memory + its `content_hash` and hashing scheme (`sha256-raw`), source, source hash and state, never content; the + characters returned (the whole response or block); and for an MCP recall its latency and the candidates left out as superseded, flagged or + expired. A new memory keeps `run_id` as provenance (older records load with none). The repeated-mistake count + groups its report by run and agent when the log has them. The `recall` response and the tool set are unchanged. + - **One store across Codex, Cursor, Antigravity and Claude Code** (#107; specs/memkernel-0-13-one-store-across-tools). Templates for Codex (`config.toml`, `AGENTS.md`, a `SessionStart` hook), Cursor (`mcp.json`, an always-applied rule) and Antigravity (`mcp_config.json`, an always-on rule), each over stdio or one shared HTTP server; a new diff --git a/README.md b/README.md index 311fd5d..ba17860 100644 --- a/README.md +++ b/README.md @@ -228,7 +228,7 @@ Templates, checked against each tool's documentation on 2026-11-18: | Tool | Templates | Copy to | Session start | |------|-----------|---------|---------------| -| Codex | [`templates/codex/`](templates/codex/): `config.toml` (stdio) or `config.http.toml`; `AGENTS.md`; `hooks.json` | `.codex/config.toml` (a trusted project); your `AGENTS.md`; `.codex/hooks.json` | a `SessionStart` hook runs `memkernel session-start --format plain --max-chars 6000` under `env` with the same `MEMKERNEL_*` values as `config.toml` (its `env` table reaches only the MCP server, and the hook is its own process, so set them in both files); Codex runs no hook you have not trusted: open `/hooks` in Codex, review the memkernel hook and trust it, once and again after any change to it | +| Codex | [`templates/codex/`](templates/codex/): `config.toml` (stdio) or `config.http.toml`; `AGENTS.md`; `hooks.json` | `.codex/config.toml` (a trusted project); your `AGENTS.md`; `.codex/hooks.json` | a `SessionStart` hook runs `memkernel session-start --format plain --max-chars 6000` under `env` with the same `MEMKERNEL_*` values as `config.toml` (its `env` table reaches only the MCP server, and the hook is its own process, so set them in both files; use paths without spaces, since the command passes them unquoted); Codex runs no hook you have not trusted: open `/hooks` in Codex, review the memkernel hook and trust it, once and again after any change to it | | Cursor | [`templates/cursor/`](templates/cursor/): `mcp.json` (stdio) or `mcp.http.json`; `rules/memkernel.mdc` | `.cursor/mcp.json`; `.cursor/rules/memkernel.mdc` | the rule (`alwaysApply: true`) tells the agent to recall the latest checkpoint and the project's decisions | | Antigravity | [`templates/antigravity/`](templates/antigravity/): `mcp_config.json` (stdio) or `mcp_config.http.json`; `rules/memkernel.md` | `.agents/mcp_config.json`; `.agents/rules/memkernel.md` | the rule (`trigger: always_on`), likewise | @@ -255,8 +255,8 @@ Limits: | 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). 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. | +| `retain(content, type, session_id?, checkpoint?, source?, importance?, tags?, supersedes?, run_id?, agent_id?, task_id?)` | Store a memory. Returns `ref_id`. Idempotent — identical content + type returns the same `ref_id`. `supersedes` hides the memory it replaces. A new memory keeps `run_id` (or `MEMKERNEL_RUN_ID`) as provenance; a matching retain keeps the original's. `agent_id` and `task_id` are checked but not recorded. | +| `recall(query, type?, tier?, session_id?, checkpoint_only?, top_k?, include_needs_review?, order?, run_id?, agent_id?, task_id?)` | 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. `run_id`, `agent_id` and `task_id` name the calling harness's run, agent and task (default: `MEMKERNEL_RUN_ID`, `MEMKERNEL_AGENT_ID`, `MEMKERNEL_TASK_ID`) for the recall log; at most 128 characters each, a longer one is refused. | | `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`. | @@ -360,8 +360,9 @@ setting is logged as a warning at startup. | `MEMKERNEL_RECALL_WEIGHT_IMPORTANCE` | `0.3` | Weight of importance in the final recall score | | `MEMKERNEL_WIKI_DIR` | `` | Directory of the LLM wiki used by `wiki_export` / `wiki_import` (empty = pass `wiki_dir` explicitly) | | `MEMKERNEL_STATE_DIR` | `.memkernel/state` | memkernel's own state outside ChromaDB: the wiki sync ledger. Resolved like `MEMKERNEL_CHROMA_PERSIST_PATH` (a relative path is relative to the process's working directory, so set it absolute when the persist path is); keep it out of git | -| `MEMKERNEL_RECALL_LOG` | `false` | Keep a recall log: each MCP `recall`, and each hook block that shows memories, appends one line (time, query, filters, returned `ref_id`s) to `MEMKERNEL_STATE_DIR/recall-log//recall.jsonl`, created readable by you only. It stores query text, so it is off by default; it stays on this computer, so keep it out of git. Nothing is written for an in-memory store. The log is locked on POSIX (Linux, macOS) only: on Windows it runs unlocked with one logged warning, and concurrent writers can lose records or pass the size limit. Used by the repeated-mistake count (see [Counting repeated mistakes](#counting-repeated-mistakes)) | -| `MEMKERNEL_RECALL_LOG_MAX_BYTES` | `5000000` | Size of one recall-log file before it is rotated to `recall.jsonl.1`, at least `4096`; a single record larger than this gives up query text first, then trailing `ref_id`s, and is marked `truncated` | +| `MEMKERNEL_RECALL_LOG` | `false` | Keep a recall log: each MCP `recall`, and each hook block that shows memories, appends one line (time, query, filters, returned `ref_id`s, and a context receipt: the run, agent and task ids; each returned memory's `content_hash` with its hashing scheme, its source and source hash, and whether it is live or flagged, never its content; the characters returned (an MCP `recall`'s whole response, or a hook's whole block); and for an MCP `recall`, its latency and how many candidates it left out as superseded, flagged or expired) to `MEMKERNEL_STATE_DIR/recall-log//recall.jsonl`, created readable by you only. It stores query text, so it is off by default; it stays on this computer, so keep it out of git. Nothing is written for an in-memory store. The log is locked on POSIX (Linux, macOS) only: on Windows it runs unlocked with one logged warning, and concurrent writers can lose records or pass the size limit. Used by the repeated-mistake count (see [Counting repeated mistakes](#counting-repeated-mistakes)) | +| `MEMKERNEL_RECALL_LOG_MAX_BYTES` | `5000000` | Size of one recall-log file before it is rotated to `recall.jsonl.1`, at least `4096`; a single record larger than this gives up query text first, then the per-memory receipt details (`memories_truncated`), then trailing `ref_id`s (`ref_ids_truncated`), and is marked `truncated` | +| `MEMKERNEL_RUN_ID`, `MEMKERNEL_AGENT_ID`, `MEMKERNEL_TASK_ID` | `` | The calling harness's run, agent and task ids for every call of this process, for a harness that starts one server per agent; a `recall` or `retain` argument wins. They go into the recall log, and `run_id` onto new memories. Caller-chosen text, not authentication: at most 128 characters each, and a longer value is ignored with a logged warning | | `MEMKERNEL_RECALL_LOG_MAX_FILES` | `10` | Recall-log files kept, the current one included; the oldest is deleted at rotation | | `MEMKERNEL_CAPTURE` | `false` | Capture failed-then-fixed commands from ended sessions' transcripts at the next normal startup (see [Capture](#capture-opt-in)). It reads Claude Code transcripts and stores text from them (redacted, best-effort), so it is off by default. It needs a persistent store and file locking: on Windows it stays off with one logged warning | | `MEMKERNEL_WIKI_PROPOSALS_DIR` | `""` | Where wiki-studio patch-sets are written before promote (`memkernel[wiki]`); empty means `/.memkernel/wiki-proposals`. Setting it requests the gate: without wiki-studio installed, a warning is logged. | @@ -411,6 +412,10 @@ The rule is fixed and mechanical (it follows the one posted on #112, with the fi the failure). Malformed log lines are skipped and counted. For a miss, the report says how many MCP recalls and hook blocks came before the failure, and whether every MCP recall's type, tier, session or checkpoint filter excluded the memory. It also counts the later sessions (each once) that were shown a memory and did not repeat its error. +- **By run and agent:** when the log records of a repeat's session carry a harness `run_id` or `agent_id` + (`MEMKERNEL_RUN_ID`, `MEMKERNEL_AGENT_ID`, or the `recall` arguments), the report adds the same outcome counts per + run and per agent (`by_run`, `by_agent`; `several` when one session's records name more than one). Without ids + the report is as before. **Check the report before sharing it.** It quotes each matched error text, which is text from your memories and from the sessions' command output in the transcripts, together with memory ids and session ids. The `--json` file diff --git a/eval/repeat-mistakes/count.py b/eval/repeat-mistakes/count.py index 323eafe..343eb64 100644 --- a/eval/repeat-mistakes/count.py +++ b/eval/repeat-mistakes/count.py @@ -16,6 +16,10 @@ A subagent gets no startup context: its repeat is ``shown`` only when its own recall returned the memory, and ``not shown`` rather than ``missed`` (R10, R14). +4. **By run and agent** (memkernel-0-15-harness-foundations FR-006, A6): when the log records attributed to a + repeat's thread carry a harness ``run_id`` or ``agent_id``, the report adds ``by_run`` and ``by_agent``, the same + outcome counts per id (``several`` when that thread's records name more than one). Without ids it is unchanged. + A hook record names its session; a tool record is paired with the transcript's own recall call (the same full query, by its hash, within 5 seconds, one to one, nearest first). A record whose candidates lie in more than one session is never guessed (D2). @@ -53,6 +57,7 @@ OUTCOMES = (SHOWN, MISSED, OTHER_STORE, UNKNOWN) SUBAGENT_OUTCOMES = (SHOWN, NOT_SHOWN, OTHER_STORE, UNKNOWN) MAIN_THREAD = "" +SEVERAL = "several" # a thread whose log records name more than one run or agent id DEFAULT_RECALL_TOOL = "mcp__memkernel__recall" LIMITS = ( "exact text only: a reworded or differently quoted error is not matched", @@ -102,6 +107,8 @@ class LogRecord: ref_ids: list[str] query_sha256: str = "" truncated: bool = False # ref_ids were cut: not proof that a memory was not returned + run_id: str = "" # the harness's ids (memkernel-0-15-harness-foundations FR-002), empty in older logs + agent_id: str = "" @dataclass @@ -116,6 +123,8 @@ class Repeat: command: str = "" # the failing run's command, redacted and cut (R8) agent_id: str = MAIN_THREAD # empty on the main thread; a subagent's repeat is reported apart (R10) captured: bool = False # the memory is a captured record (FR-011) + run_id: str = "" # the harness's run and agent ids from the thread's log records (A6); not Claude Code's agent_id + harness_agent_id: str = "" @dataclass @@ -228,6 +237,8 @@ def _parse(store: str, raw: Any) -> LogRecord | None: "session_id": raw.get("session_id", ""), "query": raw.get("query", ""), "query_sha256": raw.get("query_sha256", ""), + "run_id": raw.get("run_id", ""), + "agent_id": raw.get("agent_id", ""), } filters, ref_ids = raw.get("filters", {}), raw.get("ref_ids", []) truncated, ids_cut = raw.get("truncated", False), raw.get("ref_ids_truncated", False) @@ -252,6 +263,8 @@ def _parse(store: str, raw: Any) -> LogRecord | None: ref_ids, fields["query_sha256"], ids_cut, # a record that lost only query text still lists every id it returned + fields["run_id"], + fields["agent_id"], ) @@ -387,6 +400,34 @@ def classify_subagent( return NOT_SHOWN, {"tool_recalls_before_failure": sum(r.store == error.store for r in before)} +def _one_id(values: list[str]) -> str: + """The id a thread's records name: the one non-empty value, SEVERAL for more than one, empty for none.""" + named = {value for value in values if value} + return SEVERAL if len(named) > 1 else next(iter(named), "") + + +def _grouped(repeats: list[Repeat], key: str) -> dict[str, dict[str, Any]]: + """Repeat and outcome counts per harness id (A6); repeats without one are left out.""" + groups: dict[str, dict[str, Any]] = {} + for repeat in repeats: + name = getattr(repeat, key) + if not name: + continue + group = groups.setdefault(name, {"repeats": 0, "by_outcome": {}}) + group["repeats"] += 1 + group["by_outcome"][repeat.outcome] = group["by_outcome"].get(repeat.outcome, 0) + 1 + return dict(sorted(groups.items())) + + +def _detail(repeat: Repeat) -> dict[str, Any]: + """A repeat for the report; the harness ids only when set, so a log without them reports as before (A6).""" + detail = asdict(repeat) + for key in ("run_id", "harness_agent_id"): + if not detail[key]: + del detail[key] + return detail + + def count(stores: list[Store], sessions: list[Session]) -> dict[str, Any]: errors = [e for store in stores for e in stored_errors(store)] logs = [read_log(store) for store in stores] @@ -417,7 +458,8 @@ def count(stores: list[Store], sessions: list[Session]) -> dict[str, Any]: for thread, (out, error) in hits.items(): key = (session.session_id, thread) judge = classify if thread == MAIN_THREAD else classify_subagent - outcome, evidence = judge(error, by_thread.get(key, []), out.time, possible.get(key)) + thread_records = by_thread.get(key, []) + outcome, evidence = judge(error, thread_records, out.time, possible.get(key)) repeats.append( Repeat( store_name, @@ -430,11 +472,13 @@ def count(stores: list[Store], sessions: list[Session]) -> dict[str, Any]: stored_text(out.command), thread, error.captured, + _one_id([r.run_id for r in thread_records]), + _one_id([r.agent_id for r in thread_records]), ) ) main = [r for r in repeats if r.agent_id == MAIN_THREAD] subagent = [r for r in repeats if r.agent_id != MAIN_THREAD] - return { + report: dict[str, Any] = { "stored_errors": len(errors), "captured_errors": sum(e.captured for e in errors), "memories_with_errors": len(memories), @@ -452,9 +496,14 @@ def count(stores: list[Store], sessions: list[Session]) -> dict[str, Any]: "shown_without_repeat": len(shown_without_repeat), "unattributed_tool_records": unattributed, "malformed_log_records": sum(bad for _, bad in logs), - "details": [asdict(r) for r in repeats], + "details": [_detail(r) for r in repeats], "limits": list(LIMITS), } + for name, attribute_name in (("by_run", "run_id"), ("by_agent", "harness_agent_id")): + groups = _grouped(repeats, attribute_name) + if groups: + report[name] = groups + return report def render(report: dict[str, Any]) -> str: @@ -489,6 +538,10 @@ def render(report: dict[str, Any]) -> str: lines.append(f"{report['malformed_log_records']} malformed recall-log line(s) were skipped.") if report["unattributed_tool_records"]: lines.append(f"{report['unattributed_tool_records']} tool record(s) could not be paired with a session.") + for name, label in (("by_run", "run"), ("by_agent", "agent")): + for harness_id, group in report.get(name, {}).items(): + outcomes = ", ".join(f"{n} {o}" for o, n in sorted(group["by_outcome"].items())) + lines.append(f"By {label} {harness_id}: {group['repeats']} repeat(s): {outcomes}.") for r in report["details"]: thread = (f" (subagent {r['agent_id']})" if r["agent_id"] else "") + (" (captured)" if r["captured"] else "") lines.append( diff --git a/specs/memkernel-0-15-harness-foundations/spec.md b/specs/memkernel-0-15-harness-foundations/spec.md index d1855d4..d8ad7c2 100644 --- a/specs/memkernel-0-15-harness-foundations/spec.md +++ b/specs/memkernel-0-15-harness-foundations/spec.md @@ -108,3 +108,42 @@ with a default from older stores (CLAUDE.md); `core/` depends only on ports. H2, then H3. #119 asks that the three areas be evaluated together, which this spec does; it leaves the number of PRs to the plan. - **D6 Who decides an agent or task id:** the caller (the harness), never memkernel. + +## Amendment H1: receipts and correlation (approved by the owner, 2026-11-23) + +The H1 build (D5) as it will be built; nothing in H2 or H3 changes. The owner decided A1, A2 and A8 on 2026-11-23; +A3–A7 follow from the spec and the review, and are stated so the review can check them. + +- **A1 Argument names (owner: yes).** `recall` and `retain` take `run_id`, `agent_id` and `task_id`, the names of the + environment variables (`MEMKERNEL_RUN_ID`, `MEMKERNEL_AGENT_ID`, `MEMKERNEL_TASK_ID`, FR-002). H2 reuses + `agent_id` and `task_id` for scope, so FR-001's "the caller's `agent` and `task`" means these two arguments: a + caller passes its ids once, and from H2 they also widen `recall` to that agent's or task's records. In H1 they are + only logged. +- **A2 What a retained record keeps (owner: yes).** `run_id` only, as FR-002 says (`agent_id` and `task_id` reach the log, + not the record; H2's `scope` carries an agent or task where it matters). A new metadata key that loads as `""` from + older stores. Set when a record is created, like `source_hash`: a retain that matches an existing record keeps that + record's `run_id`, so it names the run that created the memory. +- **A3 Receipt fields.** Each recall-log record, MCP `recall` and hook block alike, adds `run_id`, `agent_id`, + `task_id`; `memories`, one entry per returned memory in `ref_ids` order (`ref_id`, `content_hash`, `source`, + `source_hash` where it has one, `state`: `live` or `flagged`); `returned_chars` (the length of the MCP + response the agent receives, or the block's length); and, for MCP `recall`, `latency_ms` and `excluded` (`superseded`, withdrawn included, `flagged`, + `expired`). `ref_ids` stays as it is, so the count and older readers work unchanged. +- **A4 What `excluded` counts.** Candidates the search returned in its last window and the live filter dropped, by + reason: not the whole store. `recall(order="newest")` selects by metadata and reports `excluded` as absent, not + zero. H2 adds `out_of_scope`. +- **A5 One size limit.** Receipts make records larger. A record over `recall_log_max_bytes` drops, in order: query + text, then the per-memory details (trailing `memories` entries, marked `memories_truncated`), then trailing + `ref_ids` (marked `ref_ids_truncated`, as now). Each cut marks the record `truncated`. `ref_ids` go last, so the + count keeps the evidence it relies on. +- **A6 The count (FR-006).** When attributed log records carry `run_id` or `agent_id`, the report adds `by_run` and + `by_agent`: the same outcome counts per id. Without ids the report is unchanged. +- **A7 Ids are caller text, capped.** `run_id`, `agent_id` and `task_id` are at most 128 characters. A longer call + argument is refused with an error naming the limit; a longer environment value is ignored, with one warning per + process. So a harness cannot bloat the log or the records with them. +- **A8 Hashing scheme in the receipt (owner: yes).** Each `memories` entry records the scheme that produced its + `content_hash`, one short field (`content_hash_scheme`, today `sha256-raw`: SHA-256 of the UTF-8 content). If #59's + S4 (#153) changes the hashing, H3 can then tell "hashed differently" from "content changed", and S4 need not be settled + before H3. Order after H1 (the owner, 2026-11-23): H2, H3, then S4 (#153) and #90's build in either order. + +Unchanged: the MCP tool set and the `recall` response (a JSON list); `MemoryService.recall` returns the same list +(the receipt comes back through an optional argument); the log stays off unless `MEMKERNEL_RECALL_LOG` is set. diff --git a/specs/memkernel-0-15-harness-foundations/tasks.md b/specs/memkernel-0-15-harness-foundations/tasks.md index fd8148e..218f30e 100644 --- a/specs/memkernel-0-15-harness-foundations/tasks.md +++ b/specs/memkernel-0-15-harness-foundations/tasks.md @@ -1,8 +1,8 @@ # Tasks: memkernel-0-15-harness-foundations ## US1 (H1): receipts and correlation -- [ ] Run, agent and task ids per call and per process (FR-002) -- [ ] Receipt fields in the recall log: hashes, states, latency, size, exclusion counts (FR-003); the count grouped by run and agent (FR-006) +- [x] Run, agent and task ids per call and per process (FR-002) +- [x] Receipt fields in the recall log: hashes, states, latency, size, exclusion counts (FR-003); the count grouped by run and agent (FR-006) ## US2 (H2): scope and abstention - [ ] `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) diff --git a/src/memkernel/config.py b/src/memkernel/config.py index 40921fd..e0c0df3 100644 --- a/src/memkernel/config.py +++ b/src/memkernel/config.py @@ -7,13 +7,16 @@ import logging from typing import TYPE_CHECKING, Any, Literal -from pydantic import Field +from pydantic import Field, ValidationInfo, field_validator from pydantic_settings import BaseSettings, EnvSettingsSource, PydanticBaseSettingsSource, SettingsConfigDict +from memkernel.core.models import ID_MAX_CHARS + if TYPE_CHECKING: from pydantic.fields import FieldInfo logger = logging.getLogger(__name__) +_warned_ids: set[str] = set() # an over-long id setting is reported once per process ENV_PREFIX = "MEMKERNEL_" ENV_FILE = ".env" @@ -109,6 +112,23 @@ class MemKernelSettings(BaseSettings): # MEMKERNEL_HOST implies. Needed for a wildcard bind (0.0.0.0, ::), where clients send the machine's real name. allowed_hosts: str = "" + # Correlation (memkernel-0-15-harness-foundations FR-002, D2): the harness's run, agent and task ids for every call + # of this process; a call's own argument wins. At most ID_MAX_CHARS each: a longer value is ignored, with a warning. + run_id: str = "" + agent_id: str = "" + task_id: str = "" + + @field_validator("run_id", "agent_id", "task_id") + @classmethod + def _id_within_limit(cls, value: str, info: ValidationInfo) -> str: + if len(value) <= ID_MAX_CHARS: + return value + name = f"{ENV_PREFIX}{(info.field_name or '').upper()}" + if name not in _warned_ids: + _warned_ids.add(name) + logger.warning("memkernel: %s is %d characters (limit %d) and is ignored", name, len(value), ID_MAX_CHARS) + return "" + @classmethod def settings_customise_sources( cls, diff --git a/src/memkernel/core/models.py b/src/memkernel/core/models.py index ee016cc..919fa3c 100644 --- a/src/memkernel/core/models.py +++ b/src/memkernel/core/models.py @@ -119,6 +119,15 @@ class MemoryType(StrEnum): # 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" +# Correlation (memkernel-0-15-harness-foundations FR-002, A1, A2, A7): the run that created a record, set on new records +# only; absent, so empty, on older records. Run, agent and task ids are caller text of at most ID_MAX_CHARS. +RUN_ID_KEY = "run_id" +ID_MAX_CHARS = 128 +# Why the live filter dropped a candidate, as a recall receipt counts it (A3, A4); withdrawn counts as superseded. +EXCLUDED_SUPERSEDED = "superseded" +EXCLUDED_FLAGGED = "flagged" +EXCLUDED_EXPIRED = "expired" +EXCLUSION_REASONS = (EXCLUDED_SUPERSEDED, EXCLUDED_FLAGGED, EXCLUDED_EXPIRED) # 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" @@ -214,6 +223,7 @@ class Memory(BaseModel): # 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 + run_id: str = "" # memkernel-0-15-harness-foundations A2: the run that created the record def retired(self) -> bool: """True for history: superseded by another record or withdrawn (memkernel-0-7 FR-002).""" @@ -307,6 +317,25 @@ class ArtifactRef(BaseModel): review_reason: str = "" +class RecallReceipt(BaseModel): + """What one recall returned and left out (memkernel-0-15-harness-foundations FR-003, A3, A4), filled in by + ``MemoryService.recall`` when the caller passes one. + + ``memories`` holds the returned records in result order. ``excluded`` counts, by reason, the candidates the + search's last window returned and the live filter dropped; None for ``order="newest"``, which selects by metadata. + """ + + memories: list[Memory] = [] + excluded: dict[str, int] | None = None + + +def check_id(name: str, value: str) -> str: + """``value`` if it is a valid run, agent or task id (at most ID_MAX_CHARS); else ValueError naming the limit.""" + if len(value) > ID_MAX_CHARS: + raise ValueError(f"{name} is {len(value)} characters; the limit is {ID_MAX_CHARS}") + return value + + class SearchResult(BaseModel): """Internal pre-fusion search result from a single source.""" diff --git a/src/memkernel/core/services.py b/src/memkernel/core/services.py index ef5092f..b291ff3 100644 --- a/src/memkernel/core/services.py +++ b/src/memkernel/core/services.py @@ -28,6 +28,10 @@ DOCUMENT_BODY_TAG, DOCUMENT_CHUNK_TAG, DOCUMENT_PART_KEY, + EXCLUDED_EXPIRED, + EXCLUDED_FLAGGED, + EXCLUDED_SUPERSEDED, + EXCLUSION_REASONS, HEALTH_CATEGORIES, HEALTH_DANGLING_LINKS, HEALTH_EXPIRED_PRESENT, @@ -42,6 +46,7 @@ REVIEW_REASON_CHANGED, REVIEW_REASON_KEY, REVIEW_REASON_MISSING, + RUN_ID_KEY, SOURCE_HASH_KEY, SUPERSEDED_BY_KEY, WIKI_ID_TAG, @@ -61,7 +66,9 @@ MemoryTier, MemoryType, ReasonerError, + RecallReceipt, SearchQuery, + check_id, has_wiki_identity, tier_of, ) @@ -120,6 +127,7 @@ class _ExtraMeta: supersedes: str | None = None promoted_from: str | None = None document_id: str | None = None + run_id: str = "" # memkernel-0-15-harness-foundations A2: new records only def _is_owner_answer(memory: Memory) -> bool: @@ -312,6 +320,7 @@ def retain( dedup_owner: Callable[[Memory], bool] | None = None, wiki_identity: tuple[str, str | None] | None = None, content_dedup: bool = True, + run_id: str = "", ) -> str: """Store content and return its ref_id. @@ -343,11 +352,21 @@ def retain( ``content_dedup=False`` skips the identical-content check for a single record, so a later write never rewrites its session, timestamp or tags (memkernel-0-12-capture-core R1: a captured record is keyed by capture alone). + + ``run_id`` (memkernel-0-15-harness-foundations FR-002, A2), or the process's ``MEMKERNEL_RUN_ID``, is written on + a new record as provenance; a retain that matches an existing record keeps that record's own. Longer than + ID_MAX_CHARS raises ``ValueError``. """ reserved = [tag for tag in tags or [] if tag.startswith(WIKI_IDENTITY_TAGS)] if reserved: raise ValueError(f"tags {reserved} are reserved for the wiki import ({', '.join(WIKI_IDENTITY_TAGS)})") - extra = _ExtraMeta(importance=importance, tags=tags or [], supersedes=supersedes, promoted_from=promoted_from) + extra = _ExtraMeta( + importance=importance, + tags=tags or [], + supersedes=supersedes, + promoted_from=promoted_from, + run_id=check_id("run_id", run_id) or self._settings.run_id, + ) if type == MemoryType.DOCUMENT and self._document_store is not None: return self._retain_document(content, session_id, checkpoint, source, extra) if type == MemoryType.CODE: @@ -786,6 +805,8 @@ def _new_metadata( metadata["supersedes"] = extra.supersedes if extra.promoted_from: metadata["promoted_from"] = extra.promoted_from + if extra.run_id: + metadata[RUN_ID_KEY] = extra.run_id if extra.document_id: metadata["document_id"] = extra.document_id metadata[DOCUMENT_PART_KEY] = False # a summary record, not a body/chunk part @@ -844,6 +865,7 @@ def recall( touch: bool = True, include_needs_review: bool = False, order: str = ORDER_RELEVANCE, + receipt: RecallReceipt | None = None, ) -> list[ArtifactRef]: """Search for memories matching the query. @@ -857,13 +879,17 @@ def recall( Returned memories are marked as accessed (``touch``), which reinforces their retention — unless ``touch=False`` (used by maintenance paths). BM25 index is self-healed (rebuilt from vector store) if needs_rebuild is set. + + With ``receipt`` (memkernel-0-15-harness-foundations FR-003, A3, A4), it is filled with the returned records + and, for a relevance recall, the candidates the last search window returned and the live filter dropped, by + reason. The returned list is the same either way. """ if order not in (ORDER_RELEVANCE, ORDER_NEWEST): raise ValueError(f"order must be {ORDER_RELEVANCE!r} or {ORDER_NEWEST!r}, got {order!r}") if order == ORDER_NEWEST: if not checkpoint_only: raise ValueError(f"order={ORDER_NEWEST!r} is only for checkpoint_only=true (the latest checkpoints)") - return self._newest_checkpoints(type, session_id, top_k, tier, touch) + return self._newest_checkpoints(type, session_id, top_k, tier, touch, receipt) _start = time.perf_counter() self._catch_up_with_other_writers() @@ -877,6 +903,8 @@ def recall( # guard is the correct termination condition and handles any corpus size. fetch_k = desired_k * 2 live: list[ArtifactRef] = [] + excluded: dict[str, int] = {} + kept: dict[str, Memory] = {} while True: search_query = SearchQuery( @@ -888,7 +916,9 @@ def recall( top_k=fetch_k, ) results = self._search_service.search(search_query) - live = self._filter_live(results, search_query, include_needs_review) + excluded = dict.fromkeys(EXCLUSION_REASONS, 0) # the last window's, as A4 says + kept = {} + live = self._filter_live(results, search_query, include_needs_review, excluded, kept) store_exhausted = len(results) < fetch_k if len(live) >= desired_k or store_exhausted: @@ -900,11 +930,19 @@ def recall( if touch: for ref in live: self._touch(ref.ref_id) + if receipt is not None: + receipt.memories = [kept[ref.ref_id] for ref in live if ref.ref_id in kept] # never fails a recall + receipt.excluded = excluded self._last_recall_ms = (time.perf_counter() - _start) * 1000 return live def _filter_live( - self, results: list[ArtifactRef], query: SearchQuery, include_needs_review: bool = False + self, + results: list[ArtifactRef], + query: SearchQuery, + include_needs_review: bool = False, + excluded: dict[str, int] | None = None, + kept: dict[str, Memory] | None = None, ) -> list[ArtifactRef]: """Drop expired and superseded memories; resolve document chunk hits to their summary. @@ -921,7 +959,15 @@ def _filter_live( every owner of a body and are exempt from metadata filters at search time, so the query's filters (type, tier, session, checkpoint) are applied here, to the owning summary that is actually returned. + + ``excluded`` counts each candidate dropped as superseded (or withdrawn), flagged or expired; ``kept`` maps + each returned ref_id to the record it stands for (a receipt's details, A3). """ + counts = excluded if excluded is not None else {} + + def drop(reason: str) -> None: + counts[reason] = counts.get(reason, 0) + 1 + memories: dict[str, Memory] = {} for ref in results: memory = self._vector_store.get_by_id(ref.ref_id) @@ -935,9 +981,13 @@ def _filter_live( captured_per_session: dict[str, int] = {} for ref in results: memory = memories.get(ref.ref_id) - if memory is None or memory.retired(): + if memory is None: + continue + if memory.retired(): + drop(EXCLUDED_SUPERSEDED) continue if memory.needs_review and not include_needs_review and not _exempt_from_review_hiding(memory): + drop(EXCLUDED_FLAGGED) continue if memory.parent_ref: # A code chunk lives and dies with its owner: dropped when the @@ -945,7 +995,13 @@ def _filter_live( if memory.parent_ref not in owners: owners[memory.parent_ref] = self._vector_store.get_by_id(memory.parent_ref) owner = owners[memory.parent_ref] - if owner is None or owner.retired() or (owner.needs_review and not include_needs_review): + if owner is None: + continue + if owner.retired(): + drop(EXCLUDED_SUPERSEDED) + continue + if owner.needs_review and not include_needs_review: + drop(EXCLUDED_FLAGGED) continue if not _matches_query(owner, query): continue # the query's filters apply to the owner the chunk stands for @@ -957,9 +1013,13 @@ def _filter_live( continue memory = summary ref = _artifact_ref(summary, ref.score, self._settings.preview_length) - if ref.ref_id in seen or ref.ref_id in superseded: + if ref.ref_id in seen: + continue + if ref.ref_id in superseded: + drop(EXCLUDED_SUPERSEDED) continue if memory_is_expired(memory, self._settings): + drop(EXCLUDED_EXPIRED) continue origin = _capture_session(memory) if origin is not None: # memkernel-0-14-capture-signals D7: one heavy session cannot fill a result @@ -968,6 +1028,8 @@ def _filter_live( captured_per_session[origin] = captured_per_session.get(origin, 0) + 1 seen.add(ref.ref_id) live.append(ref) + if kept is not None: + kept[ref.ref_id] = memory return live def _document_summary_record(self, document_id: str, query: SearchQuery) -> Memory | None: @@ -1038,10 +1100,13 @@ def _newest_checkpoints( top_k: int | None, tier: MemoryTier | None, touch: bool, + receipt: RecallReceipt | None = None, ) -> list[ArtifactRef]: - """``recall(order="newest", checkpoint_only=True)``: the newest live checkpoints, filtered like recall.""" + """``recall(order="newest", checkpoint_only=True)``: the newest live checkpoints, filtered like recall. A + ``receipt`` gets the records and no ``excluded`` counts: the selection is by metadata (A4).""" limit = top_k if top_k is not None else self._settings.search_top_k picked: list[ArtifactRef] = [] + records: list[Memory] = [] for candidate in self.checkpoints_newest_first(include_flagged_decisions=True): if len(picked) >= limit: break @@ -1054,6 +1119,9 @@ def _newest_checkpoints( memory = self.get(candidate.ref_id, touch=touch) if memory is not None: picked.append(_artifact_ref(memory, 1.0, self._settings.preview_length)) + records.append(memory) + if receipt is not None: + receipt.memories, receipt.excluded = records, None return picked def checkpoints_newest_first(self, include_flagged_decisions: bool = False) -> list[Memory]: diff --git a/src/memkernel/lifecycle.py b/src/memkernel/lifecycle.py index d8a4f31..d833ef6 100644 --- a/src/memkernel/lifecycle.py +++ b/src/memkernel/lifecycle.py @@ -279,9 +279,22 @@ def on_session_end(self, summary: str) -> str: # ------------------------------------------------------------------ def _logged(self, text: str, block: str, candidates: list[str], session_id: str) -> str: - """Log the memories whose ref_id ``text`` shows, in order of appearance (A1); return ``text``.""" + """Log the memories whose ref_id ``text`` shows, in order of appearance (A1), with their receipt details and the + block's length (memkernel-0-15-harness-foundations A3); return ``text``.""" + settings = self._service.settings + if recall_log.log_path(settings) is None: + return text # the log is off: no record, and no lookups for one shown = sorted({ref for ref in candidates if ref and ref in text}, key=text.index) - recall_log.append(self._service.settings, recall_log.ORIGIN_HOOK, shown, session_id=session_id, block=block) + found = [self._service.get(ref, touch=False) for ref in shown] + recall_log.append( + settings, + recall_log.ORIGIN_HOOK, + shown, + session_id=session_id, + block=block, + memories=[memory for memory in found if memory is not None], + returned_chars=len(text), + ) return text def _retain_checkpoint(self, summary: str, now: datetime, tags: list[str]) -> str: diff --git a/src/memkernel/mcp/tools/memory.py b/src/memkernel/mcp/tools/memory.py index d58259e..b5145d8 100644 --- a/src/memkernel/mcp/tools/memory.py +++ b/src/memkernel/mcp/tools/memory.py @@ -5,12 +5,13 @@ from __future__ import annotations import json +import time from typing import Any from mcp.server.mcpserver import Context, MCPServer # noqa: TC002 — runtime import required by MCPServer introspection from memkernel import recall_log -from memkernel.core.models import DEFAULT_ASK_MODE, MemoryTier, MemoryType +from memkernel.core.models import DEFAULT_ASK_MODE, MemoryTier, MemoryType, RecallReceipt, check_id from memkernel.mcp.tools.errors import reported_errors @@ -20,6 +21,16 @@ def _service(ctx: Context[Any, Any] | None) -> Any: return ctx.request_context.lifespan_context.memory_service +def _correlation(svc: Any, run_id: str | None, agent_id: str | None, task_id: str | None) -> recall_log.Correlation: + """A call's ids, each falling back to the process's setting (FR-002); longer than ID_MAX_CHARS raises (A7).""" + process = recall_log.Correlation.from_settings(svc.settings) + return recall_log.Correlation( + check_id("run_id", run_id) if run_id else process.run_id, + check_id("agent_id", agent_id) if agent_id else process.agent_id, + check_id("task_id", task_id) if task_id else process.task_id, + ) + + def register_memory_tools(server: MCPServer[Any]) -> None: """Register the memory tools on the server.""" @@ -34,6 +45,9 @@ async def retain( importance: float | None = None, tags: list[str] | None = None, supersedes: str | None = None, + run_id: str | None = None, + agent_id: str | None = None, + task_id: str | None = None, ctx: Context[Any, Any] | None = None, ) -> str: """Store a memory. Returns ref_id. Idempotent for identical content+type. @@ -44,8 +58,12 @@ async def retain( chunk-indexed, get() returns a summary, ask(ref_id, question) reads the body. importance: 0..1, defaults per type. supersedes: ref_id this memory replaces. Tags starting with wiki-path: or wiki-id: are reserved for wiki_import and refused. + run_id, agent_id, task_id: the calling harness's ids (at most 128 characters each); a new + memory keeps run_id as provenance. agent_id and task_id are checked but not recorded by retain. + Default: MEMKERNEL_RUN_ID, MEMKERNEL_AGENT_ID, MEMKERNEL_TASK_ID. """ svc = _service(ctx) + ids = _correlation(svc, run_id, agent_id, task_id) ref_id = svc.retain( content=content, type=MemoryType(type), @@ -55,6 +73,7 @@ async def retain( importance=importance, tags=tags, supersedes=supersedes, + run_id=ids.run_id, ) return json.dumps({"ref_id": ref_id}) @@ -69,6 +88,9 @@ async def recall( top_k: int | None = None, include_needs_review: bool = False, order: str = "relevance", + run_id: str | None = None, + agent_id: str | None = None, + task_id: str | None = None, ctx: Context[Any, Any] | None = None, ) -> str: """Search memories by query. Returns ref_id + preview pairs ranked by relevance, @@ -83,8 +105,13 @@ async def recall( 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. + run_id, agent_id, task_id: the calling harness's ids (at most 128 characters each), written + to the recall log when it is on. Default: MEMKERNEL_RUN_ID, MEMKERNEL_AGENT_ID, MEMKERNEL_TASK_ID. """ svc = _service(ctx) + ids = _correlation(svc, run_id, agent_id, task_id) + receipt = RecallReceipt() + started = time.perf_counter() results = svc.recall( query=query, type=MemoryType(type) if type else None, @@ -94,7 +121,10 @@ async def recall( top_k=top_k, include_needs_review=include_needs_review, order=order, + receipt=receipt, ) + latency_ms = (time.perf_counter() - started) * 1000 + response = json.dumps([ref.model_dump(mode="json") for ref in results]) recall_log.append( svc.settings, recall_log.ORIGIN_TOOL, @@ -109,8 +139,13 @@ async def recall( "include_needs_review": include_needs_review, "order": order, }, + ids=ids, + memories=receipt.memories, + returned_chars=len(response), # what the agent receives, not only the previews + latency_ms=latency_ms, + excluded=receipt.excluded, ) - return json.dumps([ref.model_dump(mode="json") for ref in results]) + return response @server.tool() @reported_errors diff --git a/src/memkernel/memory/dedup.py b/src/memkernel/memory/dedup.py index fe95afc..ad6547c 100644 --- a/src/memkernel/memory/dedup.py +++ b/src/memkernel/memory/dedup.py @@ -6,6 +6,10 @@ import hashlib +# The scheme compute_content_hash implements, recorded with each hash in a recall receipt +# (memkernel-0-15-harness-foundations A8), so a later scheme (#153) can be told apart from changed content. +CONTENT_HASH_SCHEME = "sha256-raw" + def compute_content_hash(content: str) -> str: """Return the SHA-256 hex digest of the UTF-8 encoded content string.""" diff --git a/src/memkernel/recall_log.py b/src/memkernel/recall_log.py index b54de18..9411493 100644 --- a/src/memkernel/recall_log.py +++ b/src/memkernel/recall_log.py @@ -6,9 +6,13 @@ and so does each hook block that shows memories (amendment A1), under ``MEMKERNEL_STATE_DIR/recall-log//recall.jsonl``. Before an append that would pass ``recall_log_max_bytes`` the file is rotated (``recall.jsonl.1``, ``.2``, ...), keeping ``recall_log_max_files`` files; -a single record larger than the limit gives up query text first, then trailing ``ref_ids``, and is marked -``truncated`` (and ``ref_ids_truncated`` when ids were dropped); ``query_sha256`` always hashes the full query, so -a record can be paired with its call either way. +a single record larger than the limit gives up query text first, then trailing ``memories`` details +(``memories_truncated``), then trailing ``ref_ids`` (``ref_ids_truncated``), and is marked ``truncated``; +``query_sha256`` always hashes the full query, so a record can be paired with its call either way. + +Each record is also a context receipt (memkernel-0-15-harness-foundations FR-002, FR-003, A3): the run, agent and +task ids; per returned memory its ``content_hash`` with the hashing scheme, source, source hash and state; the +characters returned; and for an MCP recall its latency and the candidates excluded, by reason. A write failure is logged once per process and never fails the recall. With an in-memory store there is no log. The lock is POSIX-only (``fcntl``): on Windows the log runs unlocked, with one warning per process. """ @@ -19,17 +23,20 @@ import json import logging import os +from dataclasses import dataclass from datetime import UTC, datetime from pathlib import Path from typing import TYPE_CHECKING, Any from memkernel import session_spool +from memkernel.memory.dedup import CONTENT_HASH_SCHEME from memkernel.session_spool import locked if TYPE_CHECKING: from collections.abc import Sequence from memkernel.config import MemKernelSettings + from memkernel.core.models import Memory logger = logging.getLogger(__name__) @@ -39,6 +46,8 @@ ORIGIN_HOOK = "hook" QUERY_MAX_CHARS = 2_000 FILE_MODE = 0o600 +STATE_LIVE = "live" +STATE_FLAGGED = "flagged" _warned = False _warned_unlocked = False @@ -61,11 +70,21 @@ def append( filters: dict[str, Any] | None = None, block: str = "", now: datetime | None = None, + ids: Correlation | None = None, + memories: Sequence[Memory] = (), + returned_chars: int = 0, + latency_ms: float | None = None, + excluded: dict[str, int] | None = None, ) -> None: - """Append one record; nothing when the log is off. Never raises: a failure is logged once per process.""" + """Append one record; nothing when the log is off. Never raises: a failure is logged once per process. + + ``memories`` are the returned records in ``ref_ids`` order; ``ids`` default to the process's settings. + ``latency_ms`` and ``excluded`` are left out of the record when None (a hook block, or ``order="newest"``). + """ path = log_path(settings) if path is None: return + correlation = ids or Correlation.from_settings(settings) record: dict[str, Any] = { "time": (now or datetime.now(UTC)).isoformat(), "origin": origin, @@ -74,9 +93,18 @@ def append( "query_sha256": query_hash(query), "filters": filters or {}, "ref_ids": list(ref_ids), + "run_id": correlation.run_id, + "agent_id": correlation.agent_id, + "task_id": correlation.task_id, + "memories": [receipt_entry(memory) for memory in memories], + "returned_chars": returned_chars, } if block: record["block"] = block + if latency_ms is not None: + record["latency_ms"] = round(latency_ms, 3) + if excluded is not None: + record["excluded"] = dict(excluded) line = _fit(record, settings.recall_log_max_bytes) if line is None: _warn_once(path, "a record does not fit in recall_log_max_bytes") @@ -95,6 +123,34 @@ def append( _warn_once(path, str(exc)) +@dataclass(frozen=True) +class Correlation: + """The run, agent and task ids a record carries (FR-002): a call's own, or the process's settings.""" + + run_id: str = "" + agent_id: str = "" + task_id: str = "" + + @classmethod + def from_settings(cls, settings: MemKernelSettings) -> Correlation: + return cls(settings.run_id, settings.agent_id, settings.task_id) + + +def receipt_entry(memory: Memory) -> dict[str, str]: + """One returned memory as a receipt lists it (A3, A8): hashes and state, never content.""" + entry = { + "ref_id": memory.ref_id, + "content_hash": memory.content_hash, + "content_hash_scheme": CONTENT_HASH_SCHEME, + "state": STATE_FLAGGED if memory.needs_review else STATE_LIVE, + } + if memory.source: + entry["source"] = memory.source + if memory.source_hash: + entry["source_hash"] = memory.source_hash + return entry + + def _warn_once(path: Path, reason: str) -> None: global _warned if not _warned: @@ -112,27 +168,44 @@ def query_hash(query: str) -> str: def _fit(record: dict[str, Any], max_bytes: int) -> bytes | None: - """The record as one line within ``max_bytes``: query text is cut first, then trailing ref_ids, and the record is - marked ``truncated``; None if even an empty query and no ref_ids do not fit. Both cuts are binary searches.""" + """The record as one line within ``max_bytes``, cutting in order (A5): query text, then trailing ``memories`` + details, then trailing ref_ids, marking the record ``truncated``; None if even an empty query, no details and no + ref_ids do not fit. Each cut is a binary search. ref_ids go last: the count relies on them.""" line = _encode(record) if len(line) <= max_bytes: return line - refs = list(record["ref_ids"]) - query = record["query"] - - def size(query_chars: int, ref_count: int) -> int: - trial = {**record, "query": query[:query_chars], "ref_ids": refs[:ref_count], "truncated": True} + refs, details, query = list(record["ref_ids"]), list(record["memories"]), record["query"] + + def size(query_chars: int, detail_count: int, ref_count: int) -> int: + trial = { + **record, + "query": query[:query_chars], + "memories": details[:detail_count], + "ref_ids": refs[:ref_count], + "truncated": True, + } return len(_encode(trial)) - keep_refs = len(refs) - if size(0, keep_refs) > max_bytes: - keep_refs = _largest(lambda n: size(0, n) <= max_bytes, len(refs)) - if keep_refs < 0: - return None + keep_query, keep_details, keep_refs = len(query), len(details), len(refs) + if size(0, keep_details, keep_refs) <= max_bytes: + keep_query = _largest(lambda n: size(n, keep_details, keep_refs) <= max_bytes, len(query)) + elif size(0, 0, keep_refs) <= max_bytes: keep_query = 0 + keep_details = _largest(lambda n: size(0, n, keep_refs) <= max_bytes, len(details)) else: - keep_query = _largest(lambda n: size(n, keep_refs) <= max_bytes, len(query)) - fitted = {**record, "query": query[:keep_query], "ref_ids": refs[:keep_refs], "truncated": True} + keep_query, keep_details = 0, 0 + keep_refs = _largest(lambda n: size(0, 0, n) <= max_bytes, len(refs)) + if keep_refs < 0: + return None + fitted = { + **record, + "query": query[:keep_query], + "memories": details[:keep_details], + "ref_ids": refs[:keep_refs], + "truncated": True, + } + if keep_details < len(details): + fitted["memories_truncated"] = True if keep_refs < len(refs): fitted["ref_ids_truncated"] = True # the count cannot take this record as proof that a memory was missed return _encode(fitted) diff --git a/src/memkernel/storage/chroma.py b/src/memkernel/storage/chroma.py index 62fc5e5..18dbde0 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, + RUN_ID_KEY, SOURCE_HASH_KEY, STORE_LOCK_NAMES, STORE_LOCK_TAGS, @@ -200,6 +201,7 @@ def _memory_from_chroma( 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 ""), + run_id=str(meta.get(RUN_ID_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/e2e/test_recall_log_tool.py b/tests/e2e/test_recall_log_tool.py index aa68ec5..bae748e 100644 --- a/tests/e2e/test_recall_log_tool.py +++ b/tests/e2e/test_recall_log_tool.py @@ -14,7 +14,9 @@ from memkernel import recall_log from memkernel.config import MemKernelSettings +from memkernel.core.models import EXCLUSION_REASONS, ID_MAX_CHARS from memkernel.mcp.server import create_server +from memkernel.memory.dedup import CONTENT_HASH_SCHEME from tests.conftest import MockEmbedding if TYPE_CHECKING: @@ -51,3 +53,51 @@ async def test_each_mcp_recall_leaves_one_record(tmp_path: Path) -> None: "order": "relevance", } assert second["query"] == "nothing" and second["filters"]["tier"] == "working" and second["ref_ids"] == [] + + +def _text(result: object) -> str: + item = result.content[0] # type: ignore[attr-defined] + assert isinstance(item, TextContent) + return item.text + + +@pytest.mark.e2e +async def test_an_mcp_recall_record_is_a_receipt_with_the_callers_ids(tmp_path: Path) -> None: + """memkernel-0-15-harness-foundations SC-3: run, agent and task ids (the call's winning over the process's), + per-memory hashes and state, latency, size and exclusion counts; retain keeps the run; the response is a list.""" + settings = MemKernelSettings( + project_id=f"e2e_{uuid.uuid4().hex[:8]}", + chroma_persist_path=str(tmp_path / "chroma"), + state_dir=str(tmp_path / "state"), + recall_log=True, + run_id="run-env", + agent_id="agent-env", + ) + async with Client(create_server(settings=settings, embedding=MockEmbedding(dimension=384))) as client: + retained = await client.call_tool( + "retain", arguments={"content": "We use PostgreSQL for users", "type": "decision", "run_id": "run-call"} + ) + ref_id = json.loads(_text(retained))["ref_id"] + got = json.loads(_text(await client.call_tool("get", arguments={"ref_id": ref_id}))) + result = await client.call_tool( + "recall", arguments={"query": "database", "top_k": 3, "run_id": "run-call", "task_id": "task-7"} + ) + long_id = "x" * (ID_MAX_CHARS + 1) + refused_recall = await client.call_tool("recall", arguments={"query": "database", "agent_id": long_id}) + refused_retain = await client.call_tool( + "retain", arguments={"content": "Another decision", "type": "decision", "task_id": long_id} + ) + returned = json.loads(_text(result)) + assert isinstance(returned, list) and [ref["ref_id"] for ref in returned] == [ref_id] + assert got["run_id"] == "run-call" + path = recall_log.log_path(settings) + assert path is not None + (record,) = (json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()) + assert (record["run_id"], record["agent_id"], record["task_id"]) == ("run-call", "agent-env", "task-7") + (entry,) = record["memories"] + assert entry["ref_id"] == ref_id and entry["content_hash"] == got["content_hash"] + assert entry["content_hash_scheme"] == CONTENT_HASH_SCHEME and entry["state"] == "live" + assert record["returned_chars"] == len(_text(result)) # the whole response, not only the previews + assert record["latency_ms"] >= 0 and set(record["excluded"]) == set(EXCLUSION_REASONS) + for refused in (refused_recall, refused_retain): + assert refused.is_error and f"the limit is {ID_MAX_CHARS}" in _text(refused) diff --git a/tests/unit/test_harness_receipts.py b/tests/unit/test_harness_receipts.py new file mode 100644 index 0000000..1fbb352 --- /dev/null +++ b/tests/unit/test_harness_receipts.py @@ -0,0 +1,259 @@ +# Copyright (c) 2026 EGOGE +# SPDX-License-Identifier: Apache-2.0 +"""Receipts and correlation (memkernel-0-15-harness-foundations H1: FR-002, FR-003, A2–A5, A7, A8).""" + +from __future__ import annotations + +import json +import logging +import uuid +from datetime import UTC, datetime, timedelta +from typing import TYPE_CHECKING, Any + +import chromadb +import pytest + +from memkernel import config, recall_log +from memkernel.config import RECALL_LOG_MIN_BYTES, MemKernelSettings +from memkernel.core.models import ( + EXCLUSION_REASONS, + ID_MAX_CHARS, + NEEDS_REVIEW_KEY, + REVIEW_REASON_KEY, + RUN_ID_KEY, + Memory, + MemoryType, + RecallReceipt, +) +from memkernel.factory import build_service +from memkernel.lifecycle import MemoryLifecycle +from memkernel.memory.dedup import CONTENT_HASH_SCHEME, compute_content_hash +from tests.conftest import MockEmbedding + +if TYPE_CHECKING: + from pathlib import Path + +pytestmark = pytest.mark.unit + + +def _settings(tmp_path: Path, **overrides: Any) -> MemKernelSettings: + base: dict[str, Any] = { + "project_id": f"h1-{uuid.uuid4().hex[:8]}", + "chroma_persist_path": str(tmp_path / "chroma"), + "state_dir": str(tmp_path / "state"), + "recall_log": True, + } + base.update(overrides) + return MemKernelSettings(**base) + + +def _service(settings: MemKernelSettings) -> Any: + return build_service(settings, embedding=MockEmbedding(), chroma_client=chromadb.EphemeralClient()) + + +def _records(settings: MemKernelSettings) -> list[dict[str, Any]]: + path = recall_log.log_path(settings) + assert path is not None + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] + + +def _memory(index: int, **overrides: Any) -> Memory: + base: dict[str, Any] = { + "ref_id": f"ref-{index:032d}", + "content": "x", + "type": MemoryType.FACT, + "project_id": "p", + "session_id": "s", + "timestamp": datetime.now(UTC), + "content_hash": "h" * 64, + "token_count": 1, + "source": "docs/" + "s" * 40, + } + base.update(overrides) + return Memory(**base) + + +# --- run_id on records (A2) and the id limit (A7) --------------------------------------------------------------- + + +def test_a_new_record_keeps_the_calls_run_id_or_the_processes(tmp_path: Path) -> None: + svc = _service(_settings(tmp_path, run_id="run-env")) + from_call = svc.retain("Deploys go out on Tuesdays.", MemoryType.DECISION, run_id="run-call") + from_process = svc.retain("Releases are tagged on main.", MemoryType.DECISION) + assert svc.get(from_call, touch=False).run_id == "run-call" + assert svc.get(from_process, touch=False).run_id == "run-env" + + +def test_a_dedup_hit_keeps_the_run_that_created_the_record(tmp_path: Path) -> None: + svc = _service(_settings(tmp_path)) + first = svc.retain("Deploys go out on Tuesdays.", MemoryType.DECISION, run_id="run-1") + again = svc.retain("Deploys go out on Tuesdays.", MemoryType.DECISION, run_id="run-2") + assert again == first and svc.get(first, touch=False).run_id == "run-1" + + +def test_a_record_without_a_run_loads_with_an_empty_one(tmp_path: Path) -> None: + """SC-4: a record written without the key, as by an older memkernel, loads with the default.""" + svc = _service(_settings(tmp_path)) + ref = svc.retain("Deploys go out on Tuesdays.", MemoryType.DECISION) + stored = svc._vector_store._collection.get(ids=[ref], include=["metadatas"])["metadatas"][0] + assert RUN_ID_KEY not in stored and svc.get(ref, touch=False).run_id == "" + + +def test_an_over_long_run_id_is_refused_at_retain(tmp_path: Path) -> None: + svc = _service(_settings(tmp_path)) + with pytest.raises(ValueError, match=f"run_id is {ID_MAX_CHARS + 1} characters; the limit is {ID_MAX_CHARS}"): + svc.retain("Deploys go out on Tuesdays.", MemoryType.DECISION, run_id="r" * (ID_MAX_CHARS + 1)) + svc.retain("Exactly at the limit.", MemoryType.DECISION, run_id="r" * ID_MAX_CHARS) + + +def test_an_over_long_id_setting_is_ignored_with_one_warning( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + monkeypatch.setattr(config, "_warned_ids", set()) + monkeypatch.setenv("MEMKERNEL_AGENT_ID", "a" * (ID_MAX_CHARS + 1)) + with caplog.at_level(logging.WARNING, logger="memkernel.config"): + first, second = _settings(tmp_path), _settings(tmp_path) + assert first.agent_id == "" and second.agent_id == "" + warnings = [r for r in caplog.records if "MEMKERNEL_AGENT_ID" in r.getMessage()] + assert len(warnings) == 1 and "is ignored" in warnings[0].getMessage() + + +# --- the receipt (A3, A4) --------------------------------------------------------------------------------------- + + +def test_a_recall_receipt_counts_each_exclusion_and_lists_what_it_returned(tmp_path: Path) -> None: + svc = _service(_settings(tmp_path, observation_ttl_days=7)) + old = svc.retain("The user store runs on MySQL.", MemoryType.DECISION) + svc.retain("The user store runs on Postgres.", MemoryType.DECISION, supersedes=old) + flagged = svc.retain("The user store schema lives in schema.sql.", MemoryType.FACT) + svc._vector_store.update_metadata(flagged, {NEEDS_REVIEW_KEY: True, REVIEW_REASON_KEY: "changed"}) + expired = svc.retain("The user store was slow on Monday.", MemoryType.OBSERVATION) + svc._vector_store.update_metadata(expired, {"timestamp": (datetime.now(UTC) - timedelta(days=60)).isoformat()}) + svc.retain("The user store is backed up nightly.", MemoryType.CONVENTION) + + receipt = RecallReceipt() + results = svc.recall("user store", top_k=10, receipt=receipt) + + assert receipt.excluded == {"superseded": 1, "flagged": 1, "expired": 1} + assert [m.ref_id for m in receipt.memories] == [r.ref_id for r in results] + assert {old, flagged, expired}.isdisjoint(r.ref_id for r in results) + + +def test_exclusions_are_the_last_windows_not_a_sum_over_windows(tmp_path: Path) -> None: + """A4: three flagged candidates and nothing live; top_k=1 searches a window of 2, then of 4 (the store runs out). + The last window dropped 3; a sum over windows would say 5.""" + svc = _service(_settings(tmp_path)) + for text in ("The user store runs on Postgres.", "The user store has a replica.", "The user store is sharded."): + ref = svc.retain(text, MemoryType.FACT) + svc._vector_store.update_metadata(ref, {NEEDS_REVIEW_KEY: True, REVIEW_REASON_KEY: "changed"}) + receipt = RecallReceipt() + assert svc.recall("user store", top_k=1, receipt=receipt) == [] + assert receipt.excluded == {"superseded": 0, "flagged": 3, "expired": 0} and receipt.memories == [] + + +def test_a_recall_without_a_receipt_returns_the_same_list(tmp_path: Path) -> None: + svc = _service(_settings(tmp_path)) + for text in ("The user store runs on Postgres.", "The user store is backed up nightly."): + svc.retain(text, MemoryType.DECISION) + plain = svc.recall("user store", top_k=5, touch=False) + with_receipt = svc.recall("user store", top_k=5, touch=False, receipt=RecallReceipt()) + assert [r.ref_id for r in plain] == [r.ref_id for r in with_receipt] + + +def test_a_newest_recall_receipt_lists_the_checkpoints_and_no_exclusions(tmp_path: Path) -> None: + svc = _service(_settings(tmp_path)) + checkpoint = svc.retain("SESSION CHECKPOINT\nDone: schema.", MemoryType.EPISODE, checkpoint=True) + receipt = RecallReceipt(excluded={"superseded": 9}) + svc.recall("session checkpoint", checkpoint_only=True, order="newest", top_k=1, receipt=receipt) + assert [m.ref_id for m in receipt.memories] == [checkpoint] and receipt.excluded is None + + +def test_a_receipt_entry_keeps_hashes_and_state_never_content() -> None: + flagged = recall_log.receipt_entry( + _memory(1, content="secret body", source="src/app.py", source_hash="abc", needs_review=True) + ) + assert flagged == { + "ref_id": _memory(1).ref_id, + "content_hash": "h" * 64, + "content_hash_scheme": CONTENT_HASH_SCHEME, + "source": "src/app.py", + "source_hash": "abc", + "state": "flagged", + } + plain = recall_log.receipt_entry(_memory(2, source="")) + assert plain["state"] == "live" and "source" not in plain and "source_hash" not in plain + assert CONTENT_HASH_SCHEME == "sha256-raw" and compute_content_hash("a") == compute_content_hash("a") + + +# --- the record (FR-002, FR-003, A5) ---------------------------------------------------------------------------- + + +def test_a_record_carries_the_process_ids_unless_the_call_names_its_own(tmp_path: Path) -> None: + settings = _settings(tmp_path, run_id="run-env", agent_id="agent-env", task_id="task-env") + recall_log.append(settings, recall_log.ORIGIN_TOOL, [], query="a") + recall_log.append(settings, recall_log.ORIGIN_TOOL, [], query="b", ids=recall_log.Correlation("run-call")) + first, second = _records(settings) + assert (first["run_id"], first["agent_id"], first["task_id"]) == ("run-env", "agent-env", "task-env") + assert (second["run_id"], second["agent_id"], second["task_id"]) == ("run-call", "", "") + assert first["memories"] == [] and first["returned_chars"] == 0 + assert "latency_ms" not in first and "excluded" not in first + + +def test_a_long_query_is_cut_before_any_detail(tmp_path: Path) -> None: + settings = _settings(tmp_path, recall_log_max_bytes=RECALL_LOG_MIN_BYTES) + memories = [_memory(i) for i in range(10)] + recall_log.append(settings, "tool", [m.ref_id for m in memories], query="q" * 2_000, memories=memories) + (record,) = _records(settings) + assert 0 < len(record["query"]) < 2_000 and len(record["memories"]) == 10 and len(record["ref_ids"]) == 10 + assert record["truncated"] is True and "memories_truncated" not in record and "ref_ids_truncated" not in record + + +def test_details_are_cut_before_ref_ids(tmp_path: Path) -> None: + settings = _settings(tmp_path, recall_log_max_bytes=RECALL_LOG_MIN_BYTES) + memories = [_memory(i) for i in range(40)] + recall_log.append(settings, "tool", [m.ref_id for m in memories], query="q" * 500, memories=memories) + (record,) = _records(settings) + assert record["query"] == "" and 0 < len(record["memories"]) < 40 and len(record["ref_ids"]) == 40 + assert record["memories"] == [recall_log.receipt_entry(m) for m in memories[: len(record["memories"])]] + assert record["memories_truncated"] is True and "ref_ids_truncated" not in record + + +def test_ref_ids_go_last(tmp_path: Path) -> None: + settings = _settings(tmp_path, recall_log_max_bytes=RECALL_LOG_MIN_BYTES) + memories = [_memory(i) for i in range(200)] + recall_log.append(settings, "tool", [m.ref_id for m in memories], query="q", memories=memories) + (record,) = _records(settings) + assert record["memories"] == [] and 0 < len(record["ref_ids"]) < 200 + assert record["memories_truncated"] is True and record["ref_ids_truncated"] is True + + +def test_the_size_floor_holds_a_full_receipt_with_ids_at_their_limit(tmp_path: Path) -> None: + settings = _settings(tmp_path, recall_log_max_bytes=RECALL_LOG_MIN_BYTES) + longest = recall_log.Correlation("r" * ID_MAX_CHARS, "a" * ID_MAX_CHARS, "t" * ID_MAX_CHARS) + filters = {"type": "decision", "tier": "long_term", "session_id_filter": "s" * 40, "top_k": 5, "order": "relevance"} + recall_log.append( + settings, + "tool", + ["a" * 36], + query="q" * 2_000, + filters=filters, + ids=longest, + memories=[_memory(1)], + returned_chars=200, + latency_ms=12.5, + excluded=dict.fromkeys(EXCLUSION_REASONS, 3), + ) + (record,) = _records(settings) + assert record["run_id"] == longest.run_id and record["ref_ids"] == ["a" * 36] and len(record["memories"]) == 1 + assert record["excluded"] == dict.fromkeys(EXCLUSION_REASONS, 3) and record["latency_ms"] == 12.5 + + +def test_a_hook_record_lists_what_the_block_showed_with_the_process_ids(tmp_path: Path) -> None: + settings = _settings(tmp_path, run_id="run-9", agent_id="planner") + svc = _service(settings) + decision = svc.retain("Use Postgres for the user store.", MemoryType.DECISION) + text = MemoryLifecycle(svc, settings).on_session_start("startup", session_id="s1") + (record,) = _records(settings) + assert decision in record["ref_ids"] and [m["ref_id"] for m in record["memories"]] == record["ref_ids"] + assert record["returned_chars"] == len(text) and (record["run_id"], record["agent_id"]) == ("run-9", "planner") + assert "latency_ms" not in record and "excluded" not in record diff --git a/tests/unit/test_repeat_mistakes_count.py b/tests/unit/test_repeat_mistakes_count.py index 615db1c..23758da 100644 --- a/tests/unit/test_repeat_mistakes_count.py +++ b/tests/unit/test_repeat_mistakes_count.py @@ -577,3 +577,70 @@ def test_sc8_outcomes_on_the_claude_code_shaped_folder(tmp_path: Path) -> None: assert report["stored_errors"] == SC8_EXPECTED["stored_errors"] assert report["repeats"] == SC8_EXPECTED["repeats_main"] assert report["subagent_repeats"] == SC8_EXPECTED["subagent_repeats"] + + +def test_repeats_are_grouped_by_the_harness_run_and_agent(tmp_path: Path) -> None: + """memkernel-0-15-harness-foundations FR-006, A6: per-id outcome counts; several ids on one thread are `several`; + a thread without ids is not grouped, and a report without any ids has no groups.""" + a = _settings(tmp_path, "a") + svc = build_service(a, embedding=MockEmbedding(dimension=384)) + svc.retain("agent note: `Error: disk full` on the build host", MemoryType.FACT) + del svc + folder = tmp_path / "transcripts" + folder.mkdir() + start = datetime.now(UTC) + timedelta(hours=1) + sessions = { + "s1": [recall_log.Correlation("run-1", "planner")], + "s2": [recall_log.Correlation("run-2", "coder")], + "s3": [recall_log.Correlation("run-1", "coder"), recall_log.Correlation("run-3", "coder")], + "s4": [recall_log.Correlation()], + } + for index, (session_id, ids) in enumerate(sessions.items()): + when = start + timedelta(minutes=10 * index) + for offset, correlation in enumerate(ids): + recall_log.append( + a, + "hook", + [], + session_id=session_id, + block="session-start", + now=when + timedelta(seconds=offset), + ids=correlation, + ) + Transcript(folder, session_id).tool( + when + timedelta(minutes=1), "Bash", {"command": "make"}, "Error: disk full", True + ) + report = count_module.count( + [count_module.parse_store(_store_arg(tmp_path, "a"))], count_module.read_sessions(folder, "x") + ) + assert report["repeats"] == 4 + assert report["by_run"] == { + "run-1": {"repeats": 1, "by_outcome": {"missed": 1}}, + "run-2": {"repeats": 1, "by_outcome": {"missed": 1}}, + count_module.SEVERAL: {"repeats": 1, "by_outcome": {"missed": 1}}, + } + assert report["by_agent"] == { + "coder": {"repeats": 2, "by_outcome": {"missed": 2}}, + "planner": {"repeats": 1, "by_outcome": {"missed": 1}}, + } + by_session = {d["session_id"]: d for d in report["details"]} + assert by_session["s1"]["run_id"] == "run-1" and by_session["s1"]["harness_agent_id"] == "planner" + assert "run_id" not in by_session["s4"] and "harness_agent_id" not in by_session["s4"] + assert "By run run-1: 1 repeat(s): 1 missed." in count_module.render(report) + + +def test_a_log_without_harness_ids_reports_no_groups(tmp_path: Path) -> None: + a = _settings(tmp_path, "a") + svc = build_service(a, embedding=MockEmbedding(dimension=384)) + svc.retain("agent note: `Error: disk full` on the build host", MemoryType.FACT) + del svc + folder = tmp_path / "transcripts" + folder.mkdir() + when = datetime.now(UTC) + timedelta(hours=1) + recall_log.append(a, "hook", [], session_id="s1", block="session-start", now=when) + Transcript(folder, "s1").tool(when + timedelta(minutes=1), "Bash", {"command": "make"}, "Error: disk full", True) + report = count_module.count( + [count_module.parse_store(_store_arg(tmp_path, "a"))], count_module.read_sessions(folder, "x") + ) + assert report["repeats"] == 1 and "by_run" not in report and "by_agent" not in report + assert "run_id" not in report["details"][0] and "By run" not in count_module.render(report)