Skip to content

The agent that grows with you

fix(memory): a journey node id names the card's text, not just its index

rodricksz4h5dc2660384613
diff --git a/agent/learning_graph.py b/agent/learning_graph.py
index 394cd2eb31b..7a46d8822cc 100644
--- a/agent/learning_graph.py
+++ b/agent/learning_graph.py
@@ -8,6 +8,7 @@ memory→skill links are derived from lexical overlap.
from __future__ import annotations
+import hashlib
import json
import re
from collections import Counter
@@ -126,6 +127,23 @@ def density_stats(nodes: dict[str, SkillNode], edges: list[tuple[str, str]]) ->
}
+def memory_fingerprint(entry: str) -> str:
+ """Short stable digest of a memory entry's TEXT, carried in the node id.
+
+ A journey card is identified by what it says, not by where it sat: the list can be
+ prepended to (an agent ``memory_tool`` add mid-turn) between the graph being drawn and the
+ user submitting an edit, and a bare index then names somebody else's card (#119668).
+ Both producers of an entry — this module's chunking and ``MemoryStore._parse_entries`` —
+ strip and split on the same delimiter, so the same entry digests the same on both sides.
+ """
+ return hashlib.sha256(entry.strip().encode("utf-8")).hexdigest()[:12]
+
+
+def memory_node_id(card: dict[str, Any], index: int) -> str:
+ """``memory:<source>:<index>:<fingerprint>`` — position for the occurrence, text for identity."""
+ return f"memory:{card['source']}:{index}:{card['fingerprint']}"
+
+
def _memory_cards() -> list[dict[str, Any]]:
"""``MEMORY.md`` / ``USER.md`` prose split on bare ``§`` separators; every
non-empty chunk becomes one card (MEMORY.md cards first, then USER.md)."""
@@ -143,6 +161,8 @@ def _memory_cards() -> list[dict[str, Any]]:
cards.append({
"source": source, "timestamp": file_ts + chunk_idx if file_ts is not None else None,
"title": (first[:80] + "…") if len(first) > 80 else first, "body": chunk[:1200],
+ # Digest the WHOLE chunk, not the truncated ``body`` a long memory renders with.
+ "fingerprint": memory_fingerprint(chunk),
})
return cards
@@ -162,7 +182,7 @@ def _memory_skill_edges(memory_cards: list[dict[str, Any]], skills: list[SkillNo
((score, name) for name, tokens, name_lower in skill_meta if (score := (6 if name_lower in text else 0) + len(tokens & text_tokens)) > 0),
key=lambda x: (-x[0], x[1]),
)
- edges.extend((f"memory:{card['source']}:{idx}", name) for _, name in scored[:4])
+ edges.extend((memory_node_id(card, idx), name) for _, name in scored[:4])
return edges
@@ -197,7 +217,7 @@ def build_learning_graph() -> dict[str, Any]:
for n in learned_skills.values()
] + [
{
- "id": f"memory:{card['source']}:{i}", "label": card["title"], "kind": "memory",
+ "id": memory_node_id(card, i), "label": card["title"], "kind": "memory",
"memorySource": card["source"], "timestamp": card.get("timestamp"), "category": "memory",
"useCount": 0, "state": "active", "createdBy": "memory", "pinned": False,
}
diff --git a/agent/learning_mutations.py b/agent/learning_mutations.py
index 05c2b69d616..0f0705b582c 100644
--- a/agent/learning_mutations.py
+++ b/agent/learning_mutations.py
@@ -1,8 +1,11 @@
"""User-initiated edit/delete for journey nodes (learned skills + memories).
Node ids (from ``agent.learning_graph``): skills → the skill name; memories →
-``memory:<source>:<index>`` (``source`` = ``memory`` for MEMORY.md / ``profile``
-for USER.md; ``index`` = position in the combined card list, MEMORY.md first).
+``memory:<source>:<index>:<fingerprint>`` (``source`` = ``memory`` for MEMORY.md /
+``profile`` for USER.md; ``index`` = position in the combined card list, MEMORY.md
+first; ``fingerprint`` = digest of the card's text, so the entry the user clicked is
+still nameable once the list has shifted). Ids from an older graph carry no
+fingerprint and resolve by position alone.
Shared by CLI ``hermes journey``, the TUI ``/journey`` overlay and the desktop.
Deleting a skill *archives* it (``hermes curator restore`` recovers it);
deleting a memory rewrites its file under the memory tool's lock.
@@ -21,17 +24,43 @@ def parse_node_kind(node_id: str) -> str:
return "memory" if node_id.startswith("memory:") else "skill"
-def _parse_memory_id(node_id: str) -> tuple[str, int]:
- """``memory:<source>:<index>`` → (source, global_index)."""
- parts = node_id.split(":", 2)
+def _parse_memory_id(node_id: str) -> tuple[str, int, str]:
+ """``memory:<source>:<index>[:<fingerprint>]`` → (source, global_index, fingerprint).
+
+ The fingerprint is empty for an id minted before the graph carried one."""
+ parts = node_id.split(":")
try:
- if len(parts) != 3 or parts[0] != "memory" or parts[1] not in _MEMORY_FILES:
+ if len(parts) not in (3, 4) or parts[0] != "memory" or parts[1] not in _MEMORY_FILES:
raise ValueError
- return parts[1], int(parts[2])
+ return parts[1], int(parts[2]), parts[3] if len(parts) == 4 else ""
except ValueError as exc:
raise ValueError(f"bad memory node id: {node_id!r}") from exc
+def _local_index_hint(gidx: int, cards: list, source: str) -> int:
+ """Where the id says the entry sits in ITS file, or -1 when the index names no such card."""
+ if not 0 <= gidx < len(cards) or cards[gidx].get("source") != source:
+ return -1
+ return gidx if source == "memory" else gidx - sum(1 for c in cards if c.get("source") == "memory")
+
+
+def _resolve_fingerprint(chunks: list[str], fingerprint: str, hint: int) -> int | None:
+ """Index of the clicked card in *chunks*, or None when its text is gone or ambiguous.
+
+ The hinted position wins while it still carries that text — identical entries are separate
+ cards, and that is the occurrence the user clicked. Otherwise the text names the entry, which
+ is what survives a list that shifted under the user (another writer prepending an entry
+ between the graph being drawn and the edit being submitted). Several copies and a moved
+ position cannot be told apart, so the caller refuses instead of editing an arbitrary one.
+ """
+ from agent.learning_graph import memory_fingerprint
+
+ matches = [i for i, chunk in enumerate(chunks) if memory_fingerprint(chunk) == fingerprint]
+ if hint in matches:
+ return hint
+ return matches[0] if len(matches) == 1 else None
+
+
def _locate_memory(node_id: str) -> tuple[Path, list[str], int]:
"""Resolve a memory node id to (file, all §-delimited entries, local index).
Entries come from ``MemoryStore._read_file`` — the memory tool's own parser —
@@ -42,12 +71,19 @@ def _locate_memory(node_id: str) -> tuple[Path, list[str], int]:
from agent.learning_graph import _memory_cards
from tools.memory_tool import MemoryStore
- source, gidx = _parse_memory_id(node_id)
+ source, gidx, fingerprint = _parse_memory_id(node_id)
path = get_hermes_home() / "memories" / _MEMORY_FILES[source]
if not path.exists():
raise ValueError(f"{path.name} not found")
chunks = MemoryStore._read_file(path)
cards = _memory_cards()
+ if fingerprint:
+ # The id names the card's TEXT, so a list that shifted since the graph was drawn still
+ # resolves to the entry the user clicked instead of whatever now sits at that index.
+ local = _resolve_fingerprint(chunks, fingerprint, _local_index_hint(gidx, cards, source))
+ if local is None:
+ raise ValueError("memory node id is stale — refresh the graph")
+ return path, chunks, local
if not 0 <= gidx < len(cards):
raise IndexError(f"memory index {gidx} out of range")
if cards[gidx].get("source") != source:
@@ -68,7 +104,7 @@ def _mutate_memory(node_id: str, replacement: str | None) -> dict[str, Any]:
text against the store's re-read entries; a target gone under the lock is refused."""
from tools.memory_tool import load_on_disk_store
- source, _ = _parse_memory_id(node_id)
+ source, _, _ = _parse_memory_id(node_id)
name = _MEMORY_FILES[source]
message = f"deleted memory from {name}" if replacement is None else f"updated memory in {name}"
diff --git a/tests/agent/test_learning_mutations.py b/tests/agent/test_learning_mutations.py
index 2927d6f58fa..e257cecc701 100644
--- a/tests/agent/test_learning_mutations.py
+++ b/tests/agent/test_learning_mutations.py
@@ -180,3 +180,81 @@ def test_unreadable_memory_file_is_refused_unchanged(home):
assert not res["ok"] and "could not be read" in res["message"]
assert path.read_bytes() == b"alpha note\n\xc3\x28\n\xc2\xa7\nbeta"
+
+
+# ── Node identity: the card the user clicked, not the index it sat at ────────
+
+
+def _memory_entries(home) -> list[str]:
+ from tools.memory_tool import MemoryStore
+
+ return MemoryStore._read_file(home / "memories" / "MEMORY.md")
+
+
+def _write_memory_file(home, *entries):
+ from tools.memory_tool import ENTRY_DELIMITER
+
+ (home / "memories" / "MEMORY.md").write_text(ENTRY_DELIMITER.join(entries), encoding="utf-8")
+
+
+def _journey_id(home, label: str) -> str:
+ """The node id Journey renders for the card whose text starts with *label*."""
+ from agent.learning_graph import build_learning_graph
+
+ nodes = [n for n in build_learning_graph()["nodes"] if n["kind"] == "memory"]
+ index = next(i for i, entry in enumerate(_memory_entries(home)) if entry.startswith(label))
+ return nodes[index]["id"]
+
+
+def test_the_id_journey_renders_names_the_cards_text(home):
+ from agent.learning_graph import memory_fingerprint
+
+ node_id = _journey_id(home, "beta")
+
+ assert node_id.split(":")[:3] == ["memory", "memory", "1"]
+ assert node_id.split(":")[3] == memory_fingerprint("beta note")
+
+
+def test_edit_targets_the_clicked_card_when_the_list_shifted_before_submit(home):
+ """The window a displayed-index identity cannot see: another writer prepends an entry AFTER
+ the graph is drawn and BEFORE the edit is submitted, so by the time the mutation reads the
+ file that index names somebody else's card."""
+ node_id = _journey_id(home, "beta") # what Journey showed the user
+ _write_memory_file(home, "zeta first", "alpha note\nline two", "beta note")
+
+ assert lm.edit_node(node_id, "beta rewritten")["ok"]
+
+ assert _memory_entries(home) == ["zeta first", "alpha note\nline two", "beta rewritten"]
+
+
+def test_delete_targets_the_clicked_card_when_the_list_shifted_before_submit(home):
+ node_id = _journey_id(home, "beta")
+ _write_memory_file(home, "zeta first", "alpha note\nline two", "beta note")
+
+ assert lm.delete_node(node_id)["ok"]
+
+ assert _memory_entries(home) == ["zeta first", "alpha note\nline two"]
+
+
+def test_detail_prefills_the_clicked_card_after_a_shift(home):
+ node_id = _journey_id(home, "beta")
+ _write_memory_file(home, "zeta first", "alpha note\nline two", "beta note")
+
+ assert lm.node_detail(node_id)["content"] == "beta note"
+
+
+def test_a_clicked_card_that_is_gone_refuses_even_though_its_index_still_exists(home):
+ node_id = _journey_id(home, "beta")
+ _write_memory_file(home, "alpha note\nline two", "gamma replaced beta")
+
+ result = lm.edit_node(node_id, "beta rewritten")
+
+ assert result["ok"] is False and "stale" in result["message"]
+ assert _memory_entries(home) == ["alpha note\nline two", "gamma replaced beta"]
+
+
+def test_an_id_from_an_older_graph_still_resolves_by_position(home):
+ """Pre-fingerprint ids (a cached graph, an older shell) keep working."""
+ assert lm.edit_node("memory:memory:1", "beta rewritten")["ok"]
+
+ assert _memory_entries(home) == ["alpha note\nline two", "beta rewritten"]