|
| 1 | +"""Compact-aware re-injection: the recall hook must re-emit learnings after a |
| 2 | +/compact, in the format each event supports. |
| 3 | +
|
| 4 | +Background (see hook_recall module docstring): compaction can drop the learnings |
| 5 | +injected at SessionStart, so the agent stops applying them mid-session. We re-inject |
| 6 | +on two events — SessionStart(source=compact) via JSON additionalContext, and |
| 7 | +PostCompact via plain stdout — because neither is fully reliable alone on current |
| 8 | +Claude Code. These tests pin the routing and the installer registration. |
| 9 | +""" |
| 10 | + |
| 11 | +import io |
| 12 | +import json |
| 13 | +import os |
| 14 | +import importlib |
| 15 | +import tempfile |
| 16 | +from unittest import mock |
| 17 | + |
| 18 | +import pytest |
| 19 | + |
| 20 | +from komi.adapters.claude_code import hook_recall as hr |
| 21 | + |
| 22 | + |
| 23 | +_BLOCK = "<komi-recall>SAMPLE LEARNING</komi-recall>" |
| 24 | + |
| 25 | + |
| 26 | +def _run_main(payload: dict) -> str: |
| 27 | + """Drive hook_recall.main() with a given stdin payload + a stub recall block. |
| 28 | + Returns whatever it wrote to stdout.""" |
| 29 | + out = io.StringIO() |
| 30 | + with mock.patch.object(hr, "build_block", lambda cwd, p: _BLOCK), \ |
| 31 | + mock.patch.object(hr, "_maybe_sync_pool", lambda: None), \ |
| 32 | + mock.patch.object(hr, "_read_stdin_json", lambda: payload), \ |
| 33 | + mock.patch("sys.stdout", out): |
| 34 | + rc = hr.main() |
| 35 | + assert rc == 0 |
| 36 | + return out.getvalue() |
| 37 | + |
| 38 | + |
| 39 | +# ── event routing ──────────────────────────────────────────────────────────── |
| 40 | + |
| 41 | +def test_startup_emits_json_additionalcontext_unframed(): |
| 42 | + out = _run_main({"hook_event_name": "SessionStart", "source": "startup", "cwd": "."}) |
| 43 | + obj = json.loads(out) |
| 44 | + assert obj["hookSpecificOutput"]["hookEventName"] == "SessionStart" |
| 45 | + ctx = obj["hookSpecificOutput"]["additionalContext"] |
| 46 | + assert _BLOCK in ctx |
| 47 | + assert "compacted" not in ctx # normal start: no re-application framing |
| 48 | + |
| 49 | + |
| 50 | +def test_sessionstart_compact_emits_json_with_framing(): |
| 51 | + out = _run_main({"hook_event_name": "SessionStart", "source": "compact", "cwd": "."}) |
| 52 | + obj = json.loads(out) # still JSON additionalContext |
| 53 | + ctx = obj["hookSpecificOutput"]["additionalContext"] |
| 54 | + assert _BLOCK in ctx |
| 55 | + assert "compacted" in ctx # tells the model these are re-applied |
| 56 | + |
| 57 | + |
| 58 | +def test_postcompact_emits_plain_stdout_not_json(): |
| 59 | + out = _run_main({"hook_event_name": "PostCompact", "trigger": "manual", "cwd": "."}) |
| 60 | + # PostCompact uses the plain-stdout add-to-context path, so it must NOT be JSON |
| 61 | + with pytest.raises(json.JSONDecodeError): |
| 62 | + json.loads(out) |
| 63 | + assert _BLOCK in out |
| 64 | + assert "compacted" in out |
| 65 | + |
| 66 | + |
| 67 | +def test_legacy_payload_behaves_as_session_start(): |
| 68 | + # a bare/old payload (no hook_event_name) must still inject as SessionStart JSON |
| 69 | + out = _run_main({"cwd": "."}) |
| 70 | + obj = json.loads(out) |
| 71 | + assert obj["hookSpecificOutput"]["hookEventName"] == "SessionStart" |
| 72 | + assert _BLOCK in obj["hookSpecificOutput"]["additionalContext"] |
| 73 | + |
| 74 | + |
| 75 | +def test_empty_block_emits_nothing_actionable(): |
| 76 | + out = io.StringIO() |
| 77 | + with mock.patch.object(hr, "build_block", lambda cwd, p: ""), \ |
| 78 | + mock.patch.object(hr, "_maybe_sync_pool", lambda: None), \ |
| 79 | + mock.patch.object(hr, "_read_stdin_json", |
| 80 | + lambda: {"hook_event_name": "PostCompact", "trigger": "auto"}), \ |
| 81 | + mock.patch("sys.stdout", out): |
| 82 | + hr.main() |
| 83 | + # nothing to inject → emit an empty JSON object, never a stray block |
| 84 | + assert out.getvalue() == "{}" |
| 85 | + |
| 86 | + |
| 87 | +def test_recall_failure_never_breaks_session(): |
| 88 | + def boom(cwd, p): |
| 89 | + raise RuntimeError("store exploded") |
| 90 | + out = io.StringIO() |
| 91 | + with mock.patch.object(hr, "build_block", boom), \ |
| 92 | + mock.patch.object(hr, "_maybe_sync_pool", lambda: None), \ |
| 93 | + mock.patch.object(hr, "_read_stdin_json", |
| 94 | + lambda: {"hook_event_name": "PostCompact"}), \ |
| 95 | + mock.patch("sys.stdout", out): |
| 96 | + rc = hr.main() |
| 97 | + assert rc == 0 # graceful, non-fatal |
| 98 | + assert "_note" in json.loads(out.getvalue()) # records why it skipped |
| 99 | + |
| 100 | + |
| 101 | +def test_compaction_skips_background_maintenance(): |
| 102 | + """A compaction re-inject must NOT kick off pool sync / curator (those belong to |
| 103 | + a genuine session start; firing them mid-session is wrong).""" |
| 104 | + called = {"sync": False, "curate": False} |
| 105 | + with mock.patch.object(hr, "build_block", lambda cwd, p: _BLOCK), \ |
| 106 | + mock.patch.object(hr, "_maybe_sync_pool", |
| 107 | + lambda: called.__setitem__("sync", True)), \ |
| 108 | + mock.patch.object(hr, "_read_stdin_json", |
| 109 | + lambda: {"hook_event_name": "PostCompact", "trigger": "manual"}), \ |
| 110 | + mock.patch("sys.stdout", io.StringIO()): |
| 111 | + hr.main() |
| 112 | + assert called["sync"] is False # not synced on a compaction event |
| 113 | + |
| 114 | + |
| 115 | +def test_session_start_does_run_background_maintenance(): |
| 116 | + called = {"sync": False} |
| 117 | + with mock.patch.object(hr, "build_block", lambda cwd, p: _BLOCK), \ |
| 118 | + mock.patch.object(hr, "_maybe_sync_pool", |
| 119 | + lambda: called.__setitem__("sync", True)), \ |
| 120 | + mock.patch.object(hr, "_read_stdin_json", |
| 121 | + lambda: {"hook_event_name": "SessionStart", "source": "startup"}), \ |
| 122 | + mock.patch("sys.stdout", io.StringIO()): |
| 123 | + hr.main() |
| 124 | + assert called["sync"] is True # genuine start: maintenance runs |
| 125 | + |
| 126 | + |
| 127 | +# ── installer registers PostCompact ─────────────────────────────────────────── |
| 128 | + |
| 129 | +@pytest.fixture |
| 130 | +def home(tmp_path, monkeypatch): |
| 131 | + monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path)) |
| 132 | + from komi.adapters.claude_code import paths, setup |
| 133 | + importlib.reload(paths) |
| 134 | + importlib.reload(setup) |
| 135 | + return setup |
| 136 | + |
| 137 | + |
| 138 | +def _cmds(setup_mod, event): |
| 139 | + data = json.loads(setup_mod.settings_path().read_text(encoding="utf-8")) |
| 140 | + return [h["command"] for e in data.get("hooks", {}).get(event, []) |
| 141 | + for h in e.get("hooks", [])] |
| 142 | + |
| 143 | + |
| 144 | +def test_install_registers_postcompact(home): |
| 145 | + setup = home |
| 146 | + setup._install_hooks() |
| 147 | + pc = _cmds(setup, "PostCompact") |
| 148 | + assert len(pc) == 1 |
| 149 | + assert "hook_compact" in pc[0] |
| 150 | + assert pc[0].split(" -m ")[0].strip().strip('"') not in ("python", "python3") # absolute |
| 151 | + |
| 152 | + |
| 153 | +def test_install_postcompact_idempotent(home): |
| 154 | + setup = home |
| 155 | + setup._install_hooks(); setup._install_hooks(); setup._install_hooks() |
| 156 | + assert len(_cmds(setup, "PostCompact")) == 1 |
| 157 | + |
| 158 | + |
| 159 | +def test_uninstall_removes_postcompact(home): |
| 160 | + setup = home |
| 161 | + setup._install_hooks() |
| 162 | + setup.uninstall(keep_data=True) |
| 163 | + komi_pc = [c for c in _cmds(setup, "PostCompact") if "komi" in c] |
| 164 | + assert komi_pc == [] |
| 165 | + |
| 166 | + |
| 167 | +def test_plugin_manifest_has_postcompact(): |
| 168 | + """The plugin install path uses hooks/hooks.json; it must declare PostCompact too.""" |
| 169 | + from pathlib import Path |
| 170 | + manifest = Path(__file__).resolve().parents[1] / "hooks" / "hooks.json" |
| 171 | + data = json.loads(manifest.read_text(encoding="utf-8")) |
| 172 | + pc = data["hooks"].get("PostCompact", []) |
| 173 | + cmds = [h["command"] for e in pc for h in e.get("hooks", [])] |
| 174 | + assert any("hook_compact" in c for c in cmds) |
0 commit comments