fix: add wing param to diary_write/diary_read, derive from transcript path (#659)

* fix: add wing param to diary_write/diary_read, derive from transcript path

Without a wing override, all diary entries from the stop hook land in
wing_session-hook regardless of which project the session is in, making
per-project diary search impossible.

- tool_diary_write(): add optional `wing` param; sanitize and use it when
  provided, fall back to wing_{agent_name} when omitted
- tool_diary_read(): add optional `wing` param for filtering by target wing
- TOOLS dict: expose `wing` in input_schema for both diary tools
- hooks_cli: add _wing_from_transcript_path() helper that extracts the
  project name from Claude Code paths like
  ~/.claude/projects/-home-jp-Projects-kiyo-xhci-fix/... → kiyo-xhci-fix
- hook_stop: derive project wing and append wing= hint to block reason so
  Claude writes diary entries to the correct per-project wing

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: sanitize wing param, cross-platform paths, tighten test assertions

Addresses Copilot review feedback on #659.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: wing_ prefix + agent filter on diary_read

Addresses bensig's 2-issue review on this PR.

1. _wing_from_transcript_path() was returning bare project names
   (e.g. "myproject") while all existing wings follow the wing_*
   convention from AAAK_SPEC. Entries landed in wing="myproject"
   while diary_read defaulted to wing="wing_<agent_name>" —
   orphaning every diary entry written by the stop hook. Now
   returns "wing_<project>" and falls back to "wing_sessions".

2. tool_diary_read() did not include agent_name in the ChromaDB
   where filter when a custom wing was provided — any caller with
   a shared wing could read entries written by other agents.
   Add {"agent": agent_name} to the $and clause. Also flagged by
   Qudo and left unresolved until now.

Tests updated to expect the wing_ prefix (6 tests).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Jeffrey Hein
2026-04-23 15:07:25 -07:00
committed by GitHub
parent 818b7f4d48
commit df3ee289fc
3 changed files with 107 additions and 10 deletions
+31 -2
View File
@@ -379,10 +379,15 @@ def _extract_themes(messages: list[str], max_themes: int = 3) -> list[str]:
def _save_diary_direct(
transcript_path: str,
session_id: str,
wing: str = "",
toast: bool = False,
) -> dict:
"""Write a diary checkpoint by calling the tool function directly (no MCP roundtrip).
If `wing` is set, the entry lands in that wing (typically the project wing
derived from the transcript path). Otherwise falls back to `tool_diary_write`'s
default of `wing_session-hook`.
Returns {"count": N, "themes": [...]} on success, {"count": 0} on failure.
"""
messages = _extract_recent_messages(transcript_path)
@@ -407,6 +412,7 @@ def _save_diary_direct(
agent_name="session-hook",
entry=entry,
topic="checkpoint",
wing=wing,
)
if result.get("success"):
_log(f"Diary checkpoint saved: {result.get('entry_id', '?')}")
@@ -481,6 +487,24 @@ def _parse_harness_input(data: dict, harness: str) -> dict:
}
def _wing_from_transcript_path(transcript_path: str) -> str:
"""Derive a project wing name from a Claude Code transcript path.
Claude Code stores transcripts at:
~/.claude/projects/-home-<user>-Projects-<project>/session.jsonl
We extract <project> and return ``wing_<project>`` to match the
AAAK_SPEC convention (``wing_user``, ``wing_agent``, ``wing_code``,
``wing_<project>``…). Falls back to ``wing_sessions``.
"""
# Normalize path separators for cross-platform (Windows backslashes)
normalized = transcript_path.replace("\\", "/")
match = re.search(r"-Projects-([^/]+?)(?:/|$)", normalized)
if match:
project = match.group(1).lower().replace(" ", "_")
return f"wing_{project}"
return "wing_sessions"
def hook_stop(data: dict, harness: str):
"""Stop hook: block every N messages for auto-save."""
parsed = _parse_harness_input(data, harness)
@@ -543,11 +567,15 @@ def hook_stop(data: dict, harness: str):
silent = True
toast = False
project_wing = _wing_from_transcript_path(transcript_path)
if silent:
# Save directly via Python API — systemMessage renders in terminal
result = {"count": 0}
if transcript_path:
result = _save_diary_direct(transcript_path, session_id, toast=toast)
result = _save_diary_direct(
transcript_path, session_id, wing=project_wing, toast=toast
)
_ingest_transcript(transcript_path)
_maybe_auto_ingest(transcript_path)
# Only advance save marker after successful save
@@ -580,7 +608,8 @@ def hook_stop(data: dict, harness: str):
if transcript_path:
_ingest_transcript(transcript_path)
_maybe_auto_ingest(transcript_path)
_output({"decision": "block", "reason": STOP_BLOCK_REASON})
reason = STOP_BLOCK_REASON + f" Write diary entry to wing={project_wing}."
_output({"decision": "block", "reason": reason})
else:
_output({})
+32 -7
View File
@@ -918,10 +918,10 @@ def tool_kg_stats():
# ==================== AGENT DIARY ====================
def tool_diary_write(agent_name: str, entry: str, topic: str = "general"):
def tool_diary_write(agent_name: str, entry: str, topic: str = "general", wing: str = ""):
"""
Write a diary entry for this agent. Each agent gets its own wing
with a diary room. Entries are timestamped and accumulate over time.
Write a diary entry for this agent. Entries are timestamped and
accumulate over time in a diary room.
This is the agent's personal journal — observations, thoughts,
what it worked on, what it noticed, what it thinks matters.
@@ -932,7 +932,10 @@ def tool_diary_write(agent_name: str, entry: str, topic: str = "general"):
except ValueError as e:
return {"success": False, "error": str(e)}
wing = f"wing_{agent_name.lower().replace(' ', '_')}"
if wing:
wing = sanitize_name(wing)
else:
wing = f"wing_{agent_name.lower().replace(' ', '_')}"
room = "diary"
col = _get_collection(create=True)
if not col:
@@ -987,24 +990,38 @@ def tool_diary_write(agent_name: str, entry: str, topic: str = "general"):
return {"success": False, "error": str(e)}
def tool_diary_read(agent_name: str, last_n: int = 10):
def tool_diary_read(agent_name: str, last_n: int = 10, wing: str = ""):
"""
Read an agent's recent diary entries. Returns the last N entries
in chronological order — the agent's personal journal.
When ``wing`` is provided, reads from that wing instead of the
agent's default ``wing_<agent_name>`` wing. This lets hooks
direct diary reads to a project-specific wing derived from
the transcript path.
"""
try:
agent_name = sanitize_name(agent_name, "agent_name")
if wing:
wing = sanitize_name(wing)
except ValueError as e:
return {"error": str(e)}
last_n = max(1, min(last_n, 100))
wing = f"wing_{agent_name.lower().replace(' ', '_')}"
if not wing:
wing = f"wing_{agent_name.lower().replace(' ', '_')}"
col = _get_collection()
if not col:
return _no_palace()
try:
results = col.get(
where={"$and": [{"wing": wing}, {"room": "diary"}]},
where={
"$and": [
{"wing": wing},
{"room": "diary"},
{"agent": agent_name},
]
},
include=["documents", "metadatas"],
limit=10000,
)
@@ -1497,6 +1514,10 @@ TOOLS = {
"type": "string",
"description": "Topic tag (optional, default: general)",
},
"wing": {
"type": "string",
"description": "Target wing for this diary entry (optional). If omitted, uses wing_{agent_name}. Use this to write diary entries to a project wing instead of an agent-specific wing.",
},
},
"required": ["agent_name", "entry"],
},
@@ -1515,6 +1536,10 @@ TOOLS = {
"type": "integer",
"description": "Number of recent entries to read (default: 10)",
},
"wing": {
"type": "string",
"description": "Wing to read diary entries from (optional). If omitted, reads from wing_{agent_name}.",
},
},
"required": ["agent_name"],
},
+44 -1
View File
@@ -20,6 +20,7 @@ from mempalace.hooks_cli import (
_parse_harness_input,
_sanitize_session_id,
_validate_transcript_path,
_wing_from_transcript_path,
hook_stop,
hook_session_start,
hook_precompact,
@@ -233,7 +234,27 @@ def test_stop_hook_saves_silently_at_interval(tmp_path):
# Saves silently — systemMessage notification with themes, no block
assert result["systemMessage"].startswith("\u2726 15 memories woven into the palace")
assert "hooks" in result["systemMessage"]
mock_save.assert_called_once_with(str(transcript), "test", toast=False)
# tmp_path has no "-Projects-" segment, so _wing_from_transcript_path falls back to "wing_sessions"
mock_save.assert_called_once_with(str(transcript), "test", wing="wing_sessions", toast=False)
def test_stop_hook_derives_wing_from_transcript_path(tmp_path):
"""When transcript path looks like a Claude Code path, wing is derived from it."""
project_dir = tmp_path / ".claude" / "projects" / "-home-jp-Projects-myproject"
project_dir.mkdir(parents=True)
transcript = project_dir / "session.jsonl"
_write_transcript(
transcript,
[{"message": {"role": "user", "content": f"msg {i}"}} for i in range(SAVE_INTERVAL)],
)
save_result = {"count": 15, "themes": []}
with patch("mempalace.hooks_cli._save_diary_direct", return_value=save_result) as mock_save:
_capture_hook_output(
hook_stop,
{"session_id": "test", "stop_hook_active": False, "transcript_path": str(transcript)},
state_dir=tmp_path,
)
mock_save.assert_called_once_with(str(transcript), "test", wing="wing_myproject", toast=False)
def test_stop_hook_tracks_save_point(tmp_path):
@@ -281,6 +302,28 @@ def test_precompact_allows(tmp_path):
assert result == {}
# --- _wing_from_transcript_path ---
def test_wing_from_transcript_path_extracts_project():
path = "/home/jp/.claude/projects/-home-jp-Projects-memorypalace/session.jsonl"
assert _wing_from_transcript_path(path) == "wing_memorypalace"
def test_wing_from_transcript_path_fallback():
assert _wing_from_transcript_path("/some/random/path.jsonl") == "wing_sessions"
def test_wing_from_transcript_path_windows_backslashes():
path = "C:\\Users\\jp\\.claude\\projects\\-home-jp-Projects-myapp\\session.jsonl"
assert _wing_from_transcript_path(path) == "wing_myapp"
def test_wing_from_transcript_path_lowercases():
path = "/home/jp/.claude/projects/-home-jp-Projects-MyProject/session.jsonl"
assert _wing_from_transcript_path(path) == "wing_myproject"
# --- _log ---