-
Notifications
You must be signed in to change notification settings - Fork 7.5k
Expand file tree
/
Copy pathtest_hooks_cli.py
More file actions
1959 lines (1577 loc) · 76.2 KB
/
Copy pathtest_hooks_cli.py
File metadata and controls
1959 lines (1577 loc) · 76.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import contextlib
import io
import json
import os
import subprocess
import sys
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
import mempalace.hooks_cli as hooks_cli_mod
from mempalace.hooks_cli import (
SAVE_INTERVAL,
_count_human_messages,
_diary_agent_for_harness,
_extract_recent_messages,
_get_mine_targets,
_hooks_daemon_enabled,
_log,
_maybe_auto_ingest,
_mempalace_python,
_mine_already_running,
_mine_sync,
_parse_harness_input,
_sanitize_session_id,
_save_diary_direct,
_validate_transcript_path,
_wing_from_transcript_path,
hook_stop,
hook_session_start,
hook_precompact,
run_hook,
_claim_mine_slot,
_pid_file_for_cmd,
)
@pytest.fixture(autouse=True)
def _isolated_existing_palace_root(monkeypatch, tmp_path):
"""Give every test an isolated, *existing* PALACE_ROOT/STATE_DIR.
Regression for #1510: nine save / log / precompact tests assumed
``~/.mempalace`` existed and only passed in the full suite because an
earlier test file (``test_cli.py``) created it as a side effect, so
the ``_palace_root_exists()`` kill-switch was satisfied. Run in
isolation they short-circuited and failed.
Defaulting every test to a per-test palace root that exists makes
them robust on their own and protects future tests from the same
trap. ``_MINE_PID_DIR`` is patched too: it is derived from
``STATE_DIR`` *at module import* (hooks_cli.py:277), so patching
``STATE_DIR`` alone would leave mine-spawning tests writing PID files
under the import-time location instead of the per-test root. The
state dir is created so the docstring's "existing" promise holds.
Tests that exercise the absent-root kill-switch path call
``_redirect_palace_root`` (or set their own PALACE_ROOT) *after* this
fixture; ``monkeypatch``'s last-write-wins means they keep their
absent/file root and teardown still restores the real module value.
"""
root = tmp_path / ".mempalace"
state_dir = root / "hook_state"
state_dir.mkdir(parents=True, exist_ok=True)
monkeypatch.setattr(hooks_cli_mod, "PALACE_ROOT", root)
monkeypatch.setattr(hooks_cli_mod, "STATE_DIR", state_dir)
monkeypatch.setattr(hooks_cli_mod, "_MINE_PID_DIR", state_dir / "mine_pids")
monkeypatch.setattr(hooks_cli_mod, "_state_dir_initialized", False)
return root
# --- _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()
def test_mempalace_python_handles_shallow_path_without_crashing(monkeypatch):
"""Regression: _mempalace_python must not raise IndexError when the
package lives at a shallow filesystem path.
The function used to index ``Path(__file__).resolve().parents[3]`` to
find the venv root for the standard ``<venv>/lib/python3.X/site-packages/
mempalace/`` install. In editable installs at a shallow path (Docker
containers mounting at ``/work``, ``/opt/app``, etc.), ``parents`` has
fewer than 4 elements and the bare index would raise ``IndexError``.
Affected sites: Docker-based dev, OrbStack-style cross-platform CI,
minimal-prefix production installs.
The fix uses ``len(parents)`` LBYL checks so the function falls through
to the editable-install branch (``parents[1]``) and ultimately to
``sys.executable``, instead of crashing.
"""
from pathlib import Path as RealPath
from unittest.mock import MagicMock, patch
# Build a fake parents sequence with only 3 elements (indices 0, 1, 2);
# ``parents[3]`` would raise IndexError if accessed. Production code
# uses ``len(parents) > 3`` LBYL guard to skip that branch, so the
# IndexError should never actually fire — but ``side_effect`` keeps it
# defensive against a future regression that drops the length check.
def get_item(idx):
if idx == 1:
return RealPath("/work/mempalace")
raise IndexError(idx)
fake_parents = MagicMock()
fake_parents.__len__.return_value = 3
fake_parents.__getitem__.side_effect = get_item
fake_path = MagicMock()
fake_path.resolve.return_value.parents = fake_parents
with patch("mempalace.hooks_cli.Path", return_value=fake_path):
# Must not raise; must return SOME string (either editable-venv
# fallback path or sys.executable).
result = _mempalace_python()
assert isinstance(result, str)
assert "python" in result.lower()
# --- _sanitize_session_id ---
def test_sanitize_normal_id():
assert _sanitize_session_id("abc-123_XYZ") == "abc-123_XYZ"
def test_sanitize_strips_dangerous_chars():
assert _sanitize_session_id("../../etc/passwd") == "etcpasswd"
def test_sanitize_empty_returns_unknown():
assert _sanitize_session_id("") == "unknown"
assert _sanitize_session_id("!!!") == "unknown"
# --- _count_human_messages ---
def _write_transcript(path: Path, entries: list[dict]):
with open(path, "w", encoding="utf-8") as f:
for entry in entries:
f.write(json.dumps(entry) + "\n")
def test_count_human_messages_basic(tmp_path):
transcript = tmp_path / "t.jsonl"
_write_transcript(
transcript,
[
{"message": {"role": "user", "content": "hello"}},
{"message": {"role": "assistant", "content": "hi"}},
{"message": {"role": "user", "content": "bye"}},
],
)
assert _count_human_messages(str(transcript)) == 2
def test_count_skips_command_messages(tmp_path):
transcript = tmp_path / "t.jsonl"
_write_transcript(
transcript,
[
{
"message": {
"role": "user",
"content": "<command-message>status</command-message>",
}
},
{"message": {"role": "user", "content": "real question"}},
],
)
assert _count_human_messages(str(transcript)) == 1
def test_count_handles_list_content(tmp_path):
transcript = tmp_path / "t.jsonl"
_write_transcript(
transcript,
[
{
"message": {
"role": "user",
"content": [{"type": "text", "text": "hello"}],
}
},
{
"message": {
"role": "user",
"content": [{"type": "text", "text": "<command-message>x</command-message>"}],
}
},
],
)
assert _count_human_messages(str(transcript)) == 1
def test_count_missing_file():
assert _count_human_messages("/nonexistent/path.jsonl") == 0
def test_count_empty_file(tmp_path):
transcript = tmp_path / "t.jsonl"
transcript.write_text("")
assert _count_human_messages(str(transcript)) == 0
def test_count_malformed_json_lines(tmp_path):
transcript = tmp_path / "t.jsonl"
transcript.write_text('not json\n{"message": {"role": "user", "content": "ok"}}\n')
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": "<command-message>status</command-message>"}},
{"message": {"role": "user", "content": "<system-reminder>hook</system-reminder>"}},
],
)
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)
hook_fn(data, harness)
return json.loads(buf.getvalue())
def test_stop_hook_passthrough_when_active(tmp_path):
with patch("mempalace.hooks_cli.STATE_DIR", tmp_path):
result = _capture_hook_output(
hook_stop,
{"session_id": "test", "stop_hook_active": True, "transcript_path": ""},
state_dir=tmp_path,
)
assert result == {}
def test_stop_hook_passthrough_when_active_string(tmp_path):
with patch("mempalace.hooks_cli.STATE_DIR", tmp_path):
result = _capture_hook_output(
hook_stop,
{"session_id": "test", "stop_hook_active": "true", "transcript_path": ""},
state_dir=tmp_path,
)
assert result == {}
def test_stop_hook_passthrough_below_interval(tmp_path):
transcript = tmp_path / "t.jsonl"
_write_transcript(
transcript,
[{"message": {"role": "user", "content": f"msg {i}"}} for i in range(SAVE_INTERVAL - 1)],
)
result = _capture_hook_output(
hook_stop,
{
"session_id": "test",
"stop_hook_active": False,
"transcript_path": str(transcript),
},
state_dir=tmp_path,
)
assert result == {}
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)],
)
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"]
# 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, agent_name="claude"
)
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, agent_name="claude"
)
def test_stop_hook_tracks_save_point(tmp_path):
transcript = tmp_path / "t.jsonl"
_write_transcript(
transcript,
[{"message": {"role": "user", "content": f"msg {i}"}} for i in range(SAVE_INTERVAL)],
)
data = {
"session_id": "test",
"stop_hook_active": False,
"transcript_path": str(transcript),
}
# 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)
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()
# --- #1693: hook checkpoints must be discoverable by diary_read ---
def test_diary_agent_for_harness_maps_known_harnesses():
assert _diary_agent_for_harness("claude-code") == "claude"
assert _diary_agent_for_harness("codex") == "codex"
def test_diary_agent_for_harness_unknown_falls_back_to_name():
"""A future harness must never collapse to the legacy 'session-hook'
identity, which no diary_read(agent_name=...) call ever matches (#1693)."""
assert _diary_agent_for_harness("cursor") == "cursor"
for harness in ("claude-code", "codex", "cursor", "gemini"):
assert _diary_agent_for_harness(harness) != "session-hook"
@pytest.mark.parametrize(
"harness,expected_agent",
[("claude-code", "claude"), ("codex", "codex")],
)
def test_stop_hook_files_checkpoint_under_harness_agent(tmp_path, harness, expected_agent):
"""The Stop hook must file checkpoints under the agent identity that the
session's harness reads with, not the legacy hardcoded 'session-hook'
(#1693)."""
# _save_diary_direct is mocked below, so the transcript format is irrelevant
# here: _count_human_messages counts both harness shapes, and we assert only
# the harness -> agent_name routing, not transcript parsing.
transcript = tmp_path / "t.jsonl"
_write_transcript(
transcript,
[{"message": {"role": "user", "content": f"msg {i}"}} for i in range(SAVE_INTERVAL)],
)
with patch(
"mempalace.hooks_cli._save_diary_direct", return_value={"count": 5, "themes": []}
) as mock_save:
_capture_hook_output(
hook_stop,
{"session_id": "test", "stop_hook_active": False, "transcript_path": str(transcript)},
harness=harness,
state_dir=tmp_path,
)
assert mock_save.call_args.kwargs["agent_name"] == expected_agent
def test_stop_hook_checkpoint_visible_to_diary_read(monkeypatch, config, palace_path, kg, tmp_path):
"""End-to-end regression for #1693: a checkpoint written by the Stop hook
save path is discoverable via diary_read under the harness agent identity,
and is not siloed under the legacy 'session-hook' identity."""
import chromadb
from mempalace import mcp_server
from mempalace.mcp_server import tool_diary_read
monkeypatch.setattr(mcp_server, "_config", config)
monkeypatch.setattr(mcp_server, "_get_kg", lambda *a, **kw: kg)
client = chromadb.PersistentClient(path=palace_path)
client.get_or_create_collection("mempalace_drawers", metadata={"hnsw:space": "cosine"})
del client
transcript = tmp_path / "session.jsonl"
_write_transcript(
transcript,
[{"message": {"role": "user", "content": f"msg {i}"}} for i in range(5)],
)
agent = _diary_agent_for_harness("claude-code")
res = _save_diary_direct(str(transcript), "sess1", wing="wing_.claude", agent_name=agent)
assert res["count"] > 0
visible = tool_diary_read(agent_name="claude")
assert visible.get("total", 0) >= 1
assert "CHECKPOINT" in visible["entries"][0]["content"]
# The legacy identity no longer captures hook checkpoints.
legacy = tool_diary_read(agent_name="session-hook")
assert legacy.get("entries") == []
def test_save_diary_direct_daemon_opt_in_submits_job(tmp_path):
transcript = tmp_path / "session.jsonl"
palace_dir = tmp_path / "palace"
palace_dir.mkdir()
_write_transcript(
transcript,
[{"message": {"role": "user", "content": f"message {i}"}} for i in range(3)],
)
env = {"MEMPALACE_HOOKS_DAEMON": "yes", "MEMPALACE_PALACE_PATH": str(palace_dir)}
job = {"id": "job", "state": "succeeded", "result": {"success": True, "entry_id": "e1"}}
with patch.dict("os.environ", env):
with patch("mempalace.hooks_cli.STATE_DIR", tmp_path):
with patch("mempalace.hooks_cli._daemon_available", return_value=True):
with patch("mempalace.daemon.submit_job", return_value=job) as mock_submit:
result = _save_diary_direct(
str(transcript),
"sess1",
wing="wing_project",
agent_name="claude",
)
assert result["count"] == 3
mock_submit.assert_called_once()
assert mock_submit.call_args.args[0] == "diary_write"
payload = mock_submit.call_args.args[1]
assert payload["agent_name"] == "claude"
assert payload["wing"] == "wing_project"
assert payload["topic"] == "checkpoint"
assert (tmp_path / "last_checkpoint").exists()
def test_hooks_daemon_enabled_requires_explicit_true():
with patch("mempalace.hooks_cli.MempalaceConfig") as mock_cfg_cls:
assert _hooks_daemon_enabled() is False
mock_cfg_cls.return_value.hook_use_daemon = True
assert _hooks_daemon_enabled() is True
# --- hook_session_start ---
def test_session_start_passes_through(tmp_path):
result = _capture_hook_output(
hook_session_start,
{"session_id": "test"},
state_dir=tmp_path,
)
assert result == {}
# --- hook_precompact ---
def test_precompact_allows(tmp_path):
result = _capture_hook_output(
hook_precompact,
{"session_id": "test"},
state_dir=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"
def test_wing_from_transcript_path_non_projects_layout():
# Linux user with code under ~/dev/. The encoded form ``dev-MemPalace-mempalace``
# is ambiguous between ``~/dev/MemPalace/mempalace/`` (project = mempalace) and
# ``~/dev/MemPalace-mempalace/`` (hyphenated single-name project). With no JSONL
# cwd to disambiguate, we preserve all post-``dev-`` segments rather than silently
# truncating to the last token (which would drop ``MemPalace`` here and collide
# with any other ``-mempalace`` leaf elsewhere on the system).
path = "/home/igor/.claude/projects/-home-igor-dev-MemPalace-mempalace/session.jsonl"
assert _wing_from_transcript_path(path) == "wing_mempalace_mempalace"
def test_wing_from_transcript_path_macos_users_layout():
# macOS ~/ layout without a Projects/ segment — single-token project name
# so the heuristic produces the same result as the leaf-only approach.
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():
# Deep tree: ``-home-bob-work-clients-acme-frontend``. Without JSONL cwd we
# can't tell whether ``frontend`` is the project, ``acme-frontend`` is a
# hyphenated project, or the project lives several levels in. Strip the
# user-home and one common parent (``work-``), then keep the remaining
# path as the wing — collision-safe even if multiple clients have a
# ``frontend/`` subdir.
path = "/home/bob/.claude/projects/-home-bob-work-clients-acme-frontend/session.jsonl"
assert _wing_from_transcript_path(path) == "wing_clients_acme_frontend"
# --- _wing_from_transcript_path: hyphenated project names (issue #1410) ---
def test_wing_from_transcript_path_hyphenated_claude_code():
"""Regression: ``claude-code`` was truncated to ``wing_code`` (#1410)."""
path = "/Users/me/.claude/projects/-Users-me-claude-code/abc.jsonl"
assert _wing_from_transcript_path(path) == "wing_claude_code"
def test_wing_from_transcript_path_hyphenated_react_native():
"""Regression: ``react-native`` was truncated to ``wing_native`` (#1410)."""
path = "/Users/me/.claude/projects/-Users-me-react-native/abc.jsonl"
assert _wing_from_transcript_path(path) == "wing_react_native"
def test_wing_from_transcript_path_no_collision_between_hyphenated_siblings():
"""Regression: ``customer-portal`` and ``admin-portal`` both truncated to
``wing_portal`` under the old heuristic, merging diary entries from two
independent projects into one wing (#1410)."""
customer = _wing_from_transcript_path(
"/Users/me/.claude/projects/-Users-me-customer-portal/abc.jsonl"
)
admin = _wing_from_transcript_path(
"/Users/me/.claude/projects/-Users-me-admin-portal/abc.jsonl"
)
assert customer == "wing_customer_portal"
assert admin == "wing_admin_portal"
assert customer != admin
def test_wing_from_transcript_path_strips_parent_dir_with_hyphenated_project():
"""Reporter's example: ``-home-alice-projects-react-native`` should keep
the full project name after stripping the ``projects-`` parent (#1410)."""
path = "/home/alice/.claude/projects/-home-alice-projects-react-native/abc.jsonl"
assert _wing_from_transcript_path(path) == "wing_react_native"
# --- _wing_from_transcript_path: cwd-from-JSONL primary path ---
def test_wing_from_transcript_path_uses_cwd_from_jsonl(tmp_path):
"""When the JSONL records ``cwd``, the leaf segment of cwd is the wing —
even if the encoded folder name would have produced a different (and
noisier) wing."""
# Encoded folder says ``-home-igor-dev-MemPalace-mempalace`` (would yield
# ``wing_mempalace_mempalace`` via fallback), but cwd is the truth.
project_dir = tmp_path / "-home-igor-dev-MemPalace-mempalace"
project_dir.mkdir()
transcript = project_dir / "session.jsonl"
transcript.write_text(
'{"type":"queue-operation","operation":"enqueue","timestamp":"2026-05-09T00:00:00Z"}\n'
'{"type":"user","cwd":"/home/igor/dev/MemPalace/mempalace","content":"hi"}\n',
encoding="utf-8",
)
assert _wing_from_transcript_path(str(transcript)) == "wing_mempalace"
def test_wing_from_transcript_path_cwd_with_hyphenated_project(tmp_path):
"""cwd primary path correctly handles hyphenated project names without
truncation."""
project_dir = tmp_path / "-Users-me-claude-code"
project_dir.mkdir()
transcript = project_dir / "session.jsonl"
transcript.write_text(
'{"type":"user","cwd":"/Users/me/git/claude-code","content":"hi"}\n',
encoding="utf-8",
)
assert _wing_from_transcript_path(str(transcript)) == "wing_claude_code"
def test_wing_from_transcript_path_cwd_skips_lines_without_cwd(tmp_path):
"""Lines that lack ``cwd`` (queue-operation, etc.) are skipped; the first
line that records cwd wins."""
project_dir = tmp_path / "-Users-me-foo"
project_dir.mkdir()
transcript = project_dir / "session.jsonl"
lines = [
'{"type":"queue-operation","operation":"enqueue"}',
'{"type":"queue-operation","operation":"dequeue"}',
'{"type":"queue-operation","operation":"complete"}',
'{"type":"tool_use","cwd":"/Users/me/work/real-project","content":"ok"}',
'{"type":"user","cwd":"/Users/me/somewhere-else","content":"later"}',
]
transcript.write_text("\n".join(lines) + "\n", encoding="utf-8")
# First cwd record wins (line 4, real-project).
assert _wing_from_transcript_path(str(transcript)) == "wing_real_project"
def test_wing_from_transcript_path_cwd_falls_back_when_no_cwd_in_jsonl(tmp_path):
"""If no JSONL line has cwd, fall through to the encoded-folder heuristic."""
project_dir = tmp_path / "-Users-me-no-cwd-project"
project_dir.mkdir()
transcript = project_dir / "session.jsonl"
transcript.write_text(
'{"type":"queue-operation","operation":"enqueue"}\n'
'{"type":"queue-operation","operation":"complete"}\n',
encoding="utf-8",
)
# tmp_path leaks into the path before .claude/projects, so the regex
# won't match and we hit the wing_sessions default. The point of this
# test: the cwd reader doesn't crash and returns None cleanly.
result = _wing_from_transcript_path(str(transcript))
assert result == "wing_sessions"
def test_wing_from_transcript_path_cwd_handles_malformed_jsonl(tmp_path):
"""Malformed JSON lines must not crash the wing extraction."""
project_dir = tmp_path / "-Users-me-broken-project"
project_dir.mkdir()
transcript = project_dir / "session.jsonl"
transcript.write_text(
"this is not json at all\n"
'{"type":"broken",\n' # truncated mid-record
'{"type":"valid","cwd":"/Users/me/git/clean-name","content":"ok"}\n',
encoding="utf-8",
)
assert _wing_from_transcript_path(str(transcript)) == "wing_clean_name"
def test_wing_from_transcript_path_cwd_handles_missing_file():
"""Nonexistent transcript path falls back cleanly to the encoded heuristic."""
path = "/Users/me/.claude/projects/-Users-me-claude-code/does-not-exist.jsonl"
assert _wing_from_transcript_path(path) == "wing_claude_code"
def test_wing_from_transcript_path_cwd_handles_non_string_cwd(tmp_path):
"""A cwd field that isn't a string (e.g. null, number) must be skipped."""
project_dir = tmp_path / "-Users-me-fallback-name"
project_dir.mkdir()
transcript = project_dir / "session.jsonl"
transcript.write_text(
'{"type":"x","cwd":null}\n'
'{"type":"x","cwd":42}\n'
'{"type":"x","cwd":"/Users/me/git/proper-name"}\n',
encoding="utf-8",
)
assert _wing_from_transcript_path(str(transcript)) == "wing_proper_name"
# --- _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")
log_path = tmp_path / "hook.log"
assert log_path.is_file()
content = log_path.read_text()
assert "test message" in content
def test_log_oserror_is_silenced(tmp_path):
"""_log should not raise if the directory cannot be created."""
with patch("mempalace.hooks_cli.STATE_DIR", Path("/nonexistent/deeply/nested/dir")):
# Should not raise
_log("this will fail silently")
# --- _maybe_auto_ingest ---
def test_maybe_auto_ingest_no_env(tmp_path):
"""Without MEMPAL_DIR or transcript_path, does nothing."""
with patch.dict("os.environ", {}, clear=True):
with patch("mempalace.hooks_cli.STATE_DIR", tmp_path):
_maybe_auto_ingest() # should not raise
def test_maybe_auto_ingest_with_env(tmp_path):
"""With MEMPAL_DIR set, spawns mine in projects mode against that dir."""
mempal_dir = tmp_path / "project"
mempal_dir.mkdir()
with patch.dict("os.environ", {"MEMPAL_DIR": str(mempal_dir)}):
with patch("mempalace.hooks_cli.STATE_DIR", tmp_path):
with patch("mempalace.hooks_cli._MINE_PID_DIR", tmp_path / "mine_pids"):
with patch("mempalace.hooks_cli.subprocess.Popen") as mock_popen:
_maybe_auto_ingest()
mock_popen.assert_called_once()
cmd = mock_popen.call_args[0][0]
assert "mine" in cmd
assert str(mempal_dir.resolve()) in cmd
assert cmd[cmd.index("--mode") + 1] == "projects"
def test_maybe_auto_ingest_daemon_opt_in_submits_job(tmp_path):
"""Daemon-enabled hooks submit a background mine instead of spawning one."""
mempal_dir = tmp_path / "project"
palace_dir = tmp_path / "palace"
mempal_dir.mkdir()
palace_dir.mkdir()
env = {
"MEMPAL_DIR": str(mempal_dir),
"MEMPALACE_HOOKS_DAEMON": "yes",
"MEMPALACE_PALACE_PATH": str(palace_dir),
}
with patch.dict("os.environ", env):
with patch("mempalace.hooks_cli.STATE_DIR", tmp_path):
with patch("mempalace.hooks_cli._daemon_available", return_value=True):
with patch("mempalace.hooks_cli.subprocess.Popen") as mock_popen:
with patch(
"mempalace.daemon.submit_job", return_value={"id": "job"}
) as mock_submit:
_maybe_auto_ingest()
mock_popen.assert_not_called()
mock_submit.assert_called_once()
assert mock_submit.call_args.args[0] == "mine"
assert mock_submit.call_args.args[1]["source"] == str(mempal_dir.resolve())
assert mock_submit.call_args.kwargs["wait"] is False
def test_maybe_auto_ingest_uses_mempalace_python(tmp_path):
"""Spawned mine command uses _mempalace_python(), not bare sys.executable.
Hook subprocesses inherit the harness PATH which on GUI-launched
Claude Code may resolve to a system Python without chromadb. The
interpreter used here must be the same one the hook itself runs
under (typically the venv that owns mempalace).
"""
mempal_dir = tmp_path / "project"
mempal_dir.mkdir()
with patch.dict("os.environ", {"MEMPAL_DIR": str(mempal_dir)}):
with patch("mempalace.hooks_cli.STATE_DIR", tmp_path):
with patch("mempalace.hooks_cli._MINE_PID_DIR", tmp_path / "mine_pids"):
with patch(
"mempalace.hooks_cli._mempalace_python", return_value="/fake/venv/python"
):
with patch("mempalace.hooks_cli.subprocess.Popen") as mock_popen:
_maybe_auto_ingest()
cmd = mock_popen.call_args[0][0]
assert cmd[0] == "/fake/venv/python"
def test_mine_sync_with_env_uses_projects_mode(tmp_path):
"""Precompact sync path uses projects mode when MEMPAL_DIR is set."""
mempal_dir = tmp_path / "project"
mempal_dir.mkdir()
with patch.dict("os.environ", {"MEMPAL_DIR": str(mempal_dir)}):
with patch("mempalace.hooks_cli.STATE_DIR", tmp_path):
with patch("mempalace.hooks_cli.subprocess.run") as mock_run:
_mine_sync()
mock_run.assert_called_once()
cmd = mock_run.call_args[0][0]
assert cmd[cmd.index("--mode") + 1] == "projects"
def test_mine_sync_uses_mempalace_python(tmp_path):
"""Sync mine command uses _mempalace_python(), not bare sys.executable."""
mempal_dir = tmp_path / "project"
mempal_dir.mkdir()
with patch.dict("os.environ", {"MEMPAL_DIR": str(mempal_dir)}):
with patch("mempalace.hooks_cli.STATE_DIR", tmp_path):
with patch("mempalace.hooks_cli._mempalace_python", return_value="/fake/venv/python"):
with patch("mempalace.hooks_cli.subprocess.run") as mock_run:
_mine_sync()
cmd = mock_run.call_args[0][0]
assert cmd[0] == "/fake/venv/python"
def test_claim_mine_slot_writes_live_placeholder_pid(tmp_path):
"""Regression #1443: claimed slots must not be empty during spawn startup."""
cmd = ["mempalace", "mine", "/tmp/proj", "--mode", "projects"]
pid_dir = tmp_path / "mine_pids"
with patch("mempalace.hooks_cli._MINE_PID_DIR", pid_dir):
pid_file = _claim_mine_slot(cmd)
assert pid_file == _pid_file_for_cmd(cmd)
# Format: "{pid} {unix_timestamp}" — first token must be our PID.
content = pid_file.read_text().strip()
assert content.split()[0] == str(os.getpid())
assert _mine_already_running(cmd) is True
assert _claim_mine_slot(cmd) is None
def test_claim_mine_slot_reclaimed_slot_writes_live_placeholder_pid(tmp_path):
"""Regression #1443: stale-slot reclaim must also write a live placeholder."""
cmd = ["mempalace", "mine", "/tmp/proj", "--mode", "projects"]
pid_dir = tmp_path / "mine_pids"
with (
patch("mempalace.hooks_cli._MINE_PID_DIR", pid_dir),
patch("mempalace.hooks_cli._pid_alive", return_value=False),
):
pid_file = _pid_file_for_cmd(cmd)
pid_file.parent.mkdir(parents=True, exist_ok=True)
pid_file.write_text("12345")
reclaimed = _claim_mine_slot(cmd)
assert reclaimed == pid_file
# Format: "{pid} {unix_timestamp}" — first token must be our PID.
assert pid_file.read_text().strip().split()[0] == str(os.getpid())
def test_maybe_auto_ingest_ignores_transcript_arg_path(tmp_path):
"""_maybe_auto_ingest does NOT mine the transcript directory.
Transcript convos are handled by _ingest_transcript (called separately
in hook handlers). _maybe_auto_ingest only handles MEMPAL_DIR — even
when invoked in a context where a transcript is also being processed,
no second spawn for the transcript dir should appear here.
"""
convo_dir = tmp_path / "convos"
convo_dir.mkdir()
transcript = convo_dir / "session.jsonl"
transcript.write_text("")
with patch.dict("os.environ", {}, clear=True):
with patch("mempalace.hooks_cli.STATE_DIR", tmp_path):
with patch("mempalace.hooks_cli._MINE_PID_DIR", tmp_path / "mine_pids"):
with patch("mempalace.hooks_cli.subprocess.Popen") as mock_popen:
_maybe_auto_ingest()
mock_popen.assert_not_called()
def test_mine_sync_ignores_transcript(tmp_path):
"""_mine_sync does not run a convos mine for the transcript dir.
The precompact transcript ingest is the responsibility of
_ingest_transcript; routing it through _mine_sync would stack a
second 60s timeout against the harness 30s ceiling.
"""
convo_dir = tmp_path / "convos"
convo_dir.mkdir()
transcript = convo_dir / "session.jsonl"
transcript.write_text("")
with patch.dict("os.environ", {}, clear=True):
with patch("mempalace.hooks_cli.STATE_DIR", tmp_path):
with patch("mempalace.hooks_cli.subprocess.run") as mock_run:
_mine_sync()
mock_run.assert_not_called()
def test_maybe_auto_ingest_oserror(tmp_path):
"""OSError during subprocess spawn is silenced."""
mempal_dir = tmp_path / "project"
mempal_dir.mkdir()
with patch.dict("os.environ", {"MEMPAL_DIR": str(mempal_dir)}):
with patch("mempalace.hooks_cli.STATE_DIR", tmp_path):
with patch("mempalace.hooks_cli._MINE_PID_DIR", tmp_path / "mine_pids"):
with patch("mempalace.hooks_cli.subprocess.Popen", side_effect=OSError("fail")):
_maybe_auto_ingest() # should not raise
def test_maybe_auto_ingest_skips_when_mine_running(tmp_path):
"""Does not spawn a new mine process if a mine for the same target is alive."""
mempal_dir = tmp_path / "project"
mempal_dir.mkdir()
pid_dir = tmp_path / "mine_pids"
with patch.dict("os.environ", {"MEMPAL_DIR": str(mempal_dir)}):
with patch("mempalace.hooks_cli.STATE_DIR", tmp_path):
with patch("mempalace.hooks_cli._MINE_PID_DIR", pid_dir):
# Pre-populate the per-target slot with a live PID (our own).
from mempalace.hooks_cli import _pid_file_for_cmd