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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 10 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

Expand All @@ -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`. |
Expand Down Expand Up @@ -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/<project_id>/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/<project_id>/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 `<project root>/.memkernel/wiki-proposals`. Setting it requests the gate: without wiki-studio installed, a warning is logged. |
Expand Down Expand Up @@ -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
Expand Down
59 changes: 56 additions & 3 deletions eval/repeat-mistakes/count.py
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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"],
)


Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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,
Expand All @@ -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),
Expand All @@ -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:
Expand Down Expand Up @@ -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(
Expand Down
Loading
Loading