switchroom 0.21.16 → 0.21.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,329 @@
1
+ """M4 prefetch-buffer MUTATION INVALIDATION — red-team-M3 R2 (BLOCKER).
2
+
3
+ The M4 prefetch buffer holds a RECALLED memories block captured at a prior
4
+ turn's Stop hook and consumed at the next UserPromptSubmit. If a mutation —
5
+ a rule/directive retire, or a retain that supersedes a fact — lands between
6
+ producing that buffer and consuming it, the pre-mutation snapshot can
7
+ resurrect the just-retired/just-changed content on a later turn. Worse,
8
+ ``prefetch.run_prefetch`` returns early WITHOUT overwriting the buffer when
9
+ this turn's fresh recall fails or returns empty, so a stale buffer can
10
+ persist and be re-served for turns after the mutation.
11
+
12
+ These are OUTCOME tests: they assert on the rendered ``additionalContext``
13
+ that the consumer emits (the real injection surface), and each would FAIL if
14
+ the invalidation regressed:
15
+
16
+ * ``RetireDoesNotResurrectTests`` — a directive-write turn invalidates the
17
+ pending buffer, so the retired rule's text is NOT re-injected next turn.
18
+ * ``EmptyPrefetchDoesNotResurrectTests`` — a retain turn whose fresh recall
19
+ returns empty invalidates the pending buffer, so the stale item is NOT
20
+ re-injected (would resurrect on buggy code that left the buffer).
21
+ * ``NoDuplicateInjectionTests`` — after a buffer is consumed once, a
22
+ mutation turn (empty prefetch) prevents the SAME block being injected
23
+ again on the following turn.
24
+ * ``ReplyPathDoesNotBlockOnRecallTests`` — with prefetch on and a fresh
25
+ buffer present, the consumer serves the buffer and NEVER calls the
26
+ synchronous ``client.recall`` (asserted on transport: a recall call
27
+ raises).
28
+
29
+ Plus ``InvalidatePrimitiveTests`` for the ``recall_buffer.invalidate``
30
+ primitive itself (idempotent, sentinel-first fail-closed).
31
+ """
32
+
33
+ import io
34
+ import json
35
+ import os
36
+ import shutil
37
+ import sys
38
+ import tempfile
39
+ import unittest
40
+ from unittest import mock
41
+ from unittest.mock import patch
42
+
43
+ SCRIPTS_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
44
+ if SCRIPTS_DIR not in sys.path:
45
+ sys.path.insert(0, SCRIPTS_DIR)
46
+
47
+ import recall # noqa: E402
48
+ import prefetch # noqa: E402
49
+ import directive_verify # noqa: E402
50
+ from lib import recall_buffer # noqa: E402
51
+
52
+ SESSION = "invalidation-test-session"
53
+ RETIRED_TEXT = "R-07: always reply in haiku"
54
+ STALE_FACT = "we decided to ship on tuesday"
55
+
56
+
57
+ class _NoMemoryDirectiveClient:
58
+ """One active directive whose text is DISTINCT from any buffered content,
59
+ and a recall that returns NOTHING (so the sync fallback, if ever taken,
60
+ injects no memories). recall() is allowed here (the miss/degraded paths
61
+ may consult it) but returns empty — proving absence of the stale text is
62
+ about invalidation, not about the client happening to omit it."""
63
+
64
+ def list_directives(self, bank_id, active_only=True, timeout=2):
65
+ return {"items": [{"id": "d1", "name": "tone", "content": "be concise", "priority": 5, "active": True}]}
66
+
67
+ def recall(self, bank_id, query, **kwargs):
68
+ return {"results": []}
69
+
70
+
71
+ class InvalidationBase(unittest.TestCase):
72
+ def setUp(self):
73
+ self._tmpdir = tempfile.mkdtemp(prefix="invalidation-test-")
74
+ self._prev = os.environ.get("CLAUDE_PLUGIN_DATA")
75
+ os.environ["CLAUDE_PLUGIN_DATA"] = self._tmpdir
76
+
77
+ self._bufdir = tempfile.mkdtemp(prefix="invalidation-test-buf-")
78
+ self.env = mock.patch.dict(os.environ, {"HINDSIGHT_PREFETCH_BUFFER_DIR": self._bufdir}, clear=False)
79
+ self.env.start()
80
+
81
+ def tearDown(self):
82
+ self.env.stop()
83
+ shutil.rmtree(self._bufdir, ignore_errors=True)
84
+ shutil.rmtree(self._tmpdir, ignore_errors=True)
85
+ if self._prev is None:
86
+ os.environ.pop("CLAUDE_PLUGIN_DATA", None)
87
+ else:
88
+ os.environ["CLAUDE_PLUGIN_DATA"] = self._prev
89
+
90
+ def _config(self, prefetch_enabled=True):
91
+ return {
92
+ "autoRecall": True,
93
+ "bankId": "test-bank",
94
+ "recallMaxTokens": 4096,
95
+ "recallBudget": "mid",
96
+ "recallContextTurns": 1,
97
+ "recallMaxQueryChars": 800,
98
+ "recallPromptPreamble": "",
99
+ "recallParallelDeadlineSeconds": 5,
100
+ "directivesCacheTtlSeconds": 0,
101
+ "memoryPrefetchEnabled": prefetch_enabled,
102
+ "memoryPrefetchPollCapMs": 100,
103
+ }
104
+
105
+ def _consume(self, config, client, prompt="what did we decide"):
106
+ """Drive the recall.py consumer (UserPromptSubmit) once; return the
107
+ emitted additionalContext string (or "" if nothing emitted)."""
108
+ hook_input = {"prompt": prompt, "session_id": SESSION, "transcript_path": "", "cwd": "/tmp"}
109
+ stdout = io.StringIO()
110
+ with patch("recall.load_config", return_value=config), \
111
+ patch("recall.get_api_url", return_value="http://fake"), \
112
+ patch("recall.HindsightClient", return_value=client), \
113
+ patch("recall.ensure_bank_mission"), \
114
+ patch("sys.stdin", io.StringIO(json.dumps(hook_input))), \
115
+ patch("sys.stdout", stdout):
116
+ recall.main()
117
+ out = stdout.getvalue()
118
+ if not out:
119
+ return ""
120
+ return json.loads(out)["hookSpecificOutput"]["additionalContext"]
121
+
122
+
123
+ class InvalidatePrimitiveTests(InvalidationBase):
124
+ def test_invalidate_removes_buffer_and_sentinel(self):
125
+ recall_buffer.write_buffer(SESSION, RETIRED_TEXT, {})
126
+ recall_buffer.write_sentinel(SESSION)
127
+ self.assertTrue(os.path.isfile(recall_buffer._buffer_path(SESSION)))
128
+ self.assertTrue(os.path.isfile(recall_buffer._sentinel_path(SESSION)))
129
+
130
+ recall_buffer.invalidate(SESSION)
131
+
132
+ self.assertFalse(os.path.isfile(recall_buffer._buffer_path(SESSION)))
133
+ self.assertFalse(os.path.isfile(recall_buffer._sentinel_path(SESSION)))
134
+ # read_if_fresh must now report nothing fresh (fail-closed).
135
+ payload, _ = recall_buffer.read_if_fresh(SESSION, last_consumed_token=None)
136
+ self.assertIsNone(payload)
137
+
138
+ def test_invalidate_is_idempotent_on_absent_files(self):
139
+ # No buffer written — must not raise.
140
+ recall_buffer.invalidate(SESSION)
141
+ recall_buffer.invalidate(SESSION)
142
+
143
+ def test_orphaned_payload_after_sentinel_first_delete_fails_closed(self):
144
+ # Simulate a partial invalidation where only the sentinel unlink
145
+ # landed (sentinel is deleted FIRST by design): an orphaned payload
146
+ # must never read as fresh.
147
+ recall_buffer.write_buffer(SESSION, RETIRED_TEXT, {})
148
+ recall_buffer.write_sentinel(SESSION)
149
+ os.remove(recall_buffer._sentinel_path(SESSION))
150
+ payload, _ = recall_buffer.read_if_fresh(SESSION, last_consumed_token=None)
151
+ self.assertIsNone(payload)
152
+
153
+
154
+ class RetireDoesNotResurrectTests(InvalidationBase):
155
+ """Assertion (1): a directive retire invalidates the pending buffer so the
156
+ retired item is NOT re-injected on the next turn."""
157
+
158
+ def _retire_turn_messages(self):
159
+ # A real turn transcript: the user retires a rule, the assistant issues
160
+ # a delete_directive tool_use. This is what directive_verify inspects.
161
+ return [
162
+ {"role": "user", "content": "Retire the haiku rule R-07, it no longer applies."},
163
+ {
164
+ "role": "assistant",
165
+ "content": [
166
+ {"type": "tool_use", "id": "t1", "name": "delete_directive", "input": {"id": "d-r07"}}
167
+ ],
168
+ },
169
+ ]
170
+
171
+ def test_directive_write_turn_invalidates_buffer_and_blocks_resurrection(self):
172
+ config = self._config(prefetch_enabled=True)
173
+
174
+ # Turn N Stop: prefetch buffered the rule text while it was still active.
175
+ recall_buffer.write_buffer(SESSION, RETIRED_TEXT, {})
176
+ recall_buffer.write_sentinel(SESSION)
177
+
178
+ # Turn N+1: the retire lands. directive_verify's Stop-hook invalidation
179
+ # detects the delete_directive write and drops the pending buffer.
180
+ directive_verify.invalidate_prefetch_buffer_on_directive_write(
181
+ self._retire_turn_messages(), config, SESSION
182
+ )
183
+ self.assertFalse(
184
+ os.path.isfile(recall_buffer._sentinel_path(SESSION)),
185
+ "directive-write turn must invalidate the pending prefetch buffer",
186
+ )
187
+
188
+ # Turn N+2 UserPromptSubmit: the consumer must NOT re-inject the retired
189
+ # rule text. (With no fresh buffer it takes the sync/degraded path, which
190
+ # here surfaces only the fresh directive block, not the retired text.)
191
+ ctx = self._consume(config, _NoMemoryDirectiveClient())
192
+ self.assertNotIn(
193
+ "R-07", ctx,
194
+ "retired rule text must not resurrect from a pre-retire prefetch buffer",
195
+ )
196
+ self.assertNotIn("haiku", ctx)
197
+
198
+ def test_non_directive_turn_leaves_buffer_intact(self):
199
+ # Guard against over-invalidation: an ordinary turn (no directive write)
200
+ # must NOT drop the buffer, or every turn would lose the prefetch.
201
+ config = self._config(prefetch_enabled=True)
202
+ recall_buffer.write_buffer(SESSION, "- a normal prefetched memory", {})
203
+ recall_buffer.write_sentinel(SESSION)
204
+ directive_verify.invalidate_prefetch_buffer_on_directive_write(
205
+ [
206
+ {"role": "user", "content": "what's the weather"},
207
+ {"role": "assistant", "content": "Sunny."},
208
+ ],
209
+ config,
210
+ SESSION,
211
+ )
212
+ self.assertTrue(os.path.isfile(recall_buffer._sentinel_path(SESSION)))
213
+
214
+ def test_flag_off_is_a_noop(self):
215
+ # Kill switch: with prefetch off, the directive-write invalidation must
216
+ # not touch the buffer module at all.
217
+ config = self._config(prefetch_enabled=False)
218
+ recall_buffer.write_buffer(SESSION, RETIRED_TEXT, {})
219
+ recall_buffer.write_sentinel(SESSION)
220
+ with patch("directive_verify.recall_buffer.invalidate",
221
+ side_effect=AssertionError("must not invalidate when prefetch is off")):
222
+ directive_verify.invalidate_prefetch_buffer_on_directive_write(
223
+ self._retire_turn_messages(), config, SESSION
224
+ )
225
+ self.assertTrue(os.path.isfile(recall_buffer._sentinel_path(SESSION)))
226
+
227
+
228
+ class EmptyPrefetchDoesNotResurrectTests(InvalidationBase):
229
+ """Assertion (1) via the RETAIN mutation path: a retain turn whose fresh
230
+ recall returns empty must invalidate the pending buffer so the stale item
231
+ is NOT re-served. This FAILS on buggy code that returns early leaving the
232
+ old buffer in place."""
233
+
234
+ def test_retain_turn_with_empty_recall_invalidates_stale_buffer(self):
235
+ config = self._config(prefetch_enabled=True)
236
+
237
+ # Turn N Stop: a stale fact was buffered.
238
+ recall_buffer.write_buffer(SESSION, STALE_FACT, {})
239
+ recall_buffer.write_sentinel(SESSION)
240
+
241
+ # Turn N+1 Stop: prefetch runs (a retain mutation), but this turn's
242
+ # fresh recall returns NOTHING. run_prefetch must have already
243
+ # invalidated the old buffer up front — so no stale buffer survives.
244
+ empty_client = mock.Mock()
245
+ empty_client.recall.return_value = {"results": []}
246
+ hook_input = {
247
+ "prompt": "and another thing",
248
+ "session_id": SESSION,
249
+ "transcript_path": "", # _last_human_prompt degrades to "" -> we inject a query below
250
+ "cwd": "/tmp",
251
+ }
252
+ with patch("prefetch.retain_module.run_retain", return_value={"status": "ok"}), \
253
+ patch("prefetch.HindsightClient", return_value=empty_client), \
254
+ patch("prefetch.get_api_url", return_value="http://fake"), \
255
+ patch("prefetch._last_human_prompt", return_value="and another thing"):
256
+ wrote = prefetch.run_prefetch(hook_input, config)
257
+
258
+ self.assertFalse(wrote, "empty recall must not write a fresh buffer")
259
+ self.assertFalse(
260
+ os.path.isfile(recall_buffer._sentinel_path(SESSION)),
261
+ "a mutation (retain) turn must invalidate the stale buffer even when the fresh recall is empty",
262
+ )
263
+
264
+ # Turn N+2 UserPromptSubmit: the stale fact must NOT re-inject.
265
+ ctx = self._consume(config, _NoMemoryDirectiveClient())
266
+ self.assertNotIn(
267
+ STALE_FACT, ctx,
268
+ "stale buffered fact must not resurrect after a mutation turn with an empty recall",
269
+ )
270
+
271
+
272
+ class NoDuplicateInjectionTests(InvalidationBase):
273
+ """Assertion (2): the same buffered block is not injected twice. After a
274
+ turn consumes a buffer, a mutation turn (empty prefetch) prevents the SAME
275
+ block from being re-served on the following turn."""
276
+
277
+ def test_consumed_buffer_not_reinjected_after_mutation_turn(self):
278
+ config = self._config(prefetch_enabled=True)
279
+ marker = "- unique-fact-abc123 decided at standup"
280
+
281
+ recall_buffer.write_buffer(SESSION, marker, {})
282
+ recall_buffer.write_sentinel(SESSION)
283
+
284
+ # Turn N+1: consumer injects the buffered block once.
285
+ first = self._consume(config, _NoMemoryDirectiveClient())
286
+ self.assertIn("unique-fact-abc123", first)
287
+
288
+ # Turn N+1 Stop: a mutation turn whose recall returns empty -> the old
289
+ # buffer is invalidated, nothing fresh written.
290
+ empty_client = mock.Mock()
291
+ empty_client.recall.return_value = {"results": []}
292
+ hook_input = {"prompt": "next", "session_id": SESSION, "transcript_path": "", "cwd": "/tmp"}
293
+ with patch("prefetch.retain_module.run_retain", return_value={"status": "ok"}), \
294
+ patch("prefetch.HindsightClient", return_value=empty_client), \
295
+ patch("prefetch.get_api_url", return_value="http://fake"), \
296
+ patch("prefetch._last_human_prompt", return_value="next"):
297
+ prefetch.run_prefetch(hook_input, config)
298
+
299
+ # Turn N+2: the same block must NOT be injected a second time.
300
+ second = self._consume(config, _NoMemoryDirectiveClient())
301
+ self.assertNotIn(
302
+ "unique-fact-abc123", second,
303
+ "a consumed buffer must not be re-injected after a mutation invalidated it",
304
+ )
305
+
306
+
307
+ class ReplyPathDoesNotBlockOnRecallTests(InvalidationBase):
308
+ """Assertion (3): with prefetch on and a fresh buffer present, the reply
309
+ path (UserPromptSubmit consumer) joins the buffer and NEVER blocks on a
310
+ synchronous recall. Asserted on transport: client.recall raises if called."""
311
+
312
+ def test_fresh_buffer_served_without_calling_recall(self):
313
+ config = self._config(prefetch_enabled=True)
314
+ recall_buffer.write_buffer(SESSION, "- a prefetched memory xyz", {})
315
+ recall_buffer.write_sentinel(SESSION)
316
+
317
+ class _ExplodingRecallClient:
318
+ def list_directives(self, bank_id, active_only=True, timeout=2):
319
+ return {"items": []}
320
+
321
+ def recall(self, bank_id, query, **kwargs):
322
+ raise AssertionError("reply path must not block on synchronous recall when a fresh buffer exists")
323
+
324
+ ctx = self._consume(config, _ExplodingRecallClient())
325
+ self.assertIn("a prefetched memory xyz", ctx)
326
+
327
+
328
+ if __name__ == "__main__":
329
+ unittest.main()
@@ -0,0 +1,328 @@
1
+ """Memory v2 M3 (Surface-A) — directive-injection flip guard tests.
2
+
3
+ carve-M3.md §4/§8. The flip's whole point is DETERMINISTIC: once an agent has
4
+ migrated its standing directives into the CLAUDE.md rules block (M1) and the
5
+ operator sets `memory.inject_directives: false`, this hook must STOP injecting
6
+ the `<active_directives>` block on every turn — but ONLY when a non-empty rules
7
+ block physically carries the same guarantees. These tests assert on TRANSPORT
8
+ (what reaches stdout across all three recall emit surfaces), never on an
9
+ internal flag, and each one is written so it would FAIL on the pre-guard code
10
+ (directives always injected).
11
+
12
+ Three defenses under test:
13
+ * flag OFF + rules block present → SUPPRESS `<active_directives>`
14
+ * flag ON (default) → inject normally (control)
15
+ * flag OFF but NO/empty rules block → FAIL SAFE: still inject + degraded
16
+ canary notice (a mis-sequenced flip is loud, never silently memoryless)
17
+
18
+ The rules-block bytes come from the golden fixture generated by the TS
19
+ `renderRulesBlock` (pinned by src/memory/m3-rules-block-golden.test.ts), so a
20
+ format change on the TS side trips both languages.
21
+ """
22
+
23
+ import io
24
+ import json
25
+ import os
26
+ import shutil
27
+ import sys
28
+ import tempfile
29
+ import unittest
30
+ from unittest.mock import patch
31
+
32
+ SCRIPTS_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
33
+ if SCRIPTS_DIR not in sys.path:
34
+ sys.path.insert(0, SCRIPTS_DIR)
35
+
36
+ import recall # noqa: E402
37
+
38
+ _FIXTURE = os.path.join(
39
+ os.path.dirname(__file__), "fixtures", "rules-block.golden.md"
40
+ )
41
+
42
+
43
+ def _golden_rules_block() -> str:
44
+ with open(_FIXTURE, encoding="utf-8") as fh:
45
+ return fh.read()
46
+
47
+
48
+ # An empty rules block (markers present, only the `(none)` placeholder inside)
49
+ # — the shape M1 writes for an agent that has enabled the toolchain but added
50
+ # no rules yet. This MUST NOT count as a populated block (fail-safe fires).
51
+ _EMPTY_RULES_BLOCK = "\n".join(
52
+ [
53
+ "<!-- switchroom:rules:begin -->",
54
+ "Standing rules — sanctioned via the `memory rule` tool. Do not hand-edit;",
55
+ "edits made outside the tool break the tamper sentinel below.",
56
+ "",
57
+ "(none)",
58
+ "",
59
+ "<!-- switchroom:rules:sentinel sha256="
60
+ + ("0" * 64)
61
+ + " rules=0 -->",
62
+ "<!-- switchroom:rules:end -->",
63
+ ]
64
+ )
65
+
66
+
67
+ class _DirectiveClient:
68
+ """A client that always has one active directive AND one recallable memory.
69
+
70
+ `recall_called` records whether the noisy memory fetch ran — irrelevant to
71
+ the M3 assertions but kept so a test can prove recall still happens on the
72
+ non-flipped control (memory text present ⇒ synchronous path ran).
73
+ """
74
+
75
+ def __init__(self):
76
+ self.recall_called = False
77
+
78
+ def list_directives(self, bank_id, active_only=True, timeout=2):
79
+ return {"items": [{
80
+ "id": "d1", "name": "always-wave", "priority": 10,
81
+ "content": "always end replies with a wave",
82
+ }]}
83
+
84
+ def recall(self, bank_id, query, **kwargs):
85
+ self.recall_called = True
86
+ return {"results": [{
87
+ "text": "a real memory", "type": "fact",
88
+ "mentioned_at": "2026-01-01", "id": "m1", "scores": {"final": 0.9},
89
+ }]}
90
+
91
+
92
+ class _DirectiveFlipTestBase(unittest.TestCase):
93
+ def setUp(self):
94
+ self._tmpdir = tempfile.mkdtemp(prefix="recall-m3-flip-test-")
95
+ self._prev_data = os.environ.get("CLAUDE_PLUGIN_DATA")
96
+ os.environ["CLAUDE_PLUGIN_DATA"] = self._tmpdir
97
+ # Project dirs are resolved via CLAUDE_PROJECT_DIR / hook cwd. Pin the
98
+ # env to a NON-project sentinel so tests that rely on the hook `cwd`
99
+ # fallback aren't polluted by an inherited CLAUDE_PROJECT_DIR.
100
+ self._prev_proj = os.environ.get("CLAUDE_PROJECT_DIR")
101
+ os.environ.pop("CLAUDE_PROJECT_DIR", None)
102
+
103
+ def tearDown(self):
104
+ shutil.rmtree(self._tmpdir, ignore_errors=True)
105
+ for key, prev in (
106
+ ("CLAUDE_PLUGIN_DATA", self._prev_data),
107
+ ("CLAUDE_PROJECT_DIR", self._prev_proj),
108
+ ):
109
+ if prev is None:
110
+ os.environ.pop(key, None)
111
+ else:
112
+ os.environ[key] = prev
113
+
114
+ def _project_dir(self, claude_md: str | None) -> str:
115
+ """Create a project dir; write CLAUDE.md with `claude_md` if given."""
116
+ proj = tempfile.mkdtemp(prefix="proj-", dir=self._tmpdir)
117
+ if claude_md is not None:
118
+ with open(os.path.join(proj, "CLAUDE.md"), "w", encoding="utf-8") as fh:
119
+ fh.write(claude_md)
120
+ return proj
121
+
122
+ def _config(self, inject_directives):
123
+ cfg = {
124
+ "autoRecall": True,
125
+ "bankId": "test-bank",
126
+ "recallMaxTokens": 4096,
127
+ "recallBudget": "mid",
128
+ "recallContextTurns": 1,
129
+ "recallMaxQueryChars": 800,
130
+ "recallPromptPreamble": "",
131
+ "recallParallelDeadlineSeconds": 5,
132
+ "directivesCacheTtlSeconds": 0,
133
+ }
134
+ if inject_directives is not None:
135
+ cfg["injectDirectives"] = inject_directives
136
+ return cfg
137
+
138
+ def _run_main(self, prompt, config, cwd, client):
139
+ hook_input = {
140
+ "prompt": prompt,
141
+ "session_id": "test-session",
142
+ "transcript_path": "",
143
+ "cwd": cwd,
144
+ }
145
+ stdout = io.StringIO()
146
+ with patch("recall.load_config", return_value=config), \
147
+ patch("recall.get_api_url", return_value="http://fake"), \
148
+ patch("recall.HindsightClient", return_value=client), \
149
+ patch("recall.ensure_bank_mission"), \
150
+ patch("sys.stdin", io.StringIO(json.dumps(hook_input))), \
151
+ patch("sys.stdout", stdout):
152
+ recall.main()
153
+ return stdout.getvalue()
154
+
155
+
156
+ class RulesBlockDetectionTests(_DirectiveFlipTestBase):
157
+ """Unit coverage for the physical-evidence check the guard turns on."""
158
+
159
+ def test_present_block_from_golden_fixture_is_detected(self):
160
+ proj = self._project_dir("# Agent\n\n" + _golden_rules_block())
161
+ self.assertTrue(recall.rules_block_present(proj))
162
+
163
+ def test_empty_none_placeholder_block_is_not_a_present_block(self):
164
+ proj = self._project_dir("# Agent\n\n" + _EMPTY_RULES_BLOCK)
165
+ self.assertFalse(
166
+ recall.rules_block_present(proj),
167
+ "the `(none)` placeholder must not count as a populated rules block",
168
+ )
169
+
170
+ def test_no_markers_is_not_a_present_block(self):
171
+ proj = self._project_dir("# Agent\n\njust some prose, no rules block.")
172
+ self.assertFalse(recall.rules_block_present(proj))
173
+
174
+ def test_missing_claude_md_is_not_a_present_block(self):
175
+ proj = self._project_dir(None)
176
+ self.assertFalse(recall.rules_block_present(proj))
177
+
178
+ def test_none_project_dir_is_not_a_present_block(self):
179
+ self.assertFalse(recall.rules_block_present(None))
180
+
181
+ def test_project_dir_prefers_env_then_hook_cwd(self):
182
+ proj = self._project_dir("# Agent\n\n" + _golden_rules_block())
183
+ # env wins when set
184
+ os.environ["CLAUDE_PROJECT_DIR"] = proj
185
+ self.assertEqual(recall._recall_project_dir({"cwd": "/nope"}), proj)
186
+ # falls back to hook cwd when env unset
187
+ os.environ.pop("CLAUDE_PROJECT_DIR", None)
188
+ self.assertEqual(recall._recall_project_dir({"cwd": proj}), proj)
189
+
190
+
191
+ class DirectiveInjectionDecisionTests(_DirectiveFlipTestBase):
192
+ """The pure decision function — the deterministic core the surfaces share."""
193
+
194
+ def test_flag_on_injects(self):
195
+ proj = self._project_dir("# Agent\n\n" + _golden_rules_block())
196
+ inject, notice = recall.directive_injection_decision(
197
+ self._config(True), {"cwd": proj}
198
+ )
199
+ self.assertTrue(inject)
200
+ self.assertIsNone(notice)
201
+
202
+ def test_flag_absent_defaults_to_inject(self):
203
+ proj = self._project_dir("# Agent\n\n" + _golden_rules_block())
204
+ inject, notice = recall.directive_injection_decision(
205
+ self._config(None), {"cwd": proj}
206
+ )
207
+ self.assertTrue(inject, "injectDirectives must default TRUE when unset")
208
+ self.assertIsNone(notice)
209
+
210
+ def test_flag_off_with_rules_block_suppresses(self):
211
+ proj = self._project_dir("# Agent\n\n" + _golden_rules_block())
212
+ inject, notice = recall.directive_injection_decision(
213
+ self._config(False), {"cwd": proj}
214
+ )
215
+ self.assertFalse(inject, "flipped agent with a rules block must suppress")
216
+ self.assertIsNone(notice)
217
+
218
+ def test_flag_off_without_rules_block_fails_safe(self):
219
+ proj = self._project_dir("# Agent\n\nno rules block here.")
220
+ inject, notice = recall.directive_injection_decision(
221
+ self._config(False), {"cwd": proj}
222
+ )
223
+ self.assertTrue(inject, "flag off + no rules block must FAIL SAFE (inject)")
224
+ self.assertIsNotNone(notice)
225
+ self.assertIn("injectDirectives is OFF", notice)
226
+
227
+
228
+ class MainPathTransportTests(_DirectiveFlipTestBase):
229
+ """Surface 1 (synchronous main path) — assert on stdout transport."""
230
+
231
+ def test_flipped_in_budget_agent_suppresses_active_directives(self):
232
+ proj = self._project_dir("# Agent\n\n" + _golden_rules_block())
233
+ client = _DirectiveClient()
234
+ out = self._run_main("what did we decide about X?", self._config(False), proj, client)
235
+ # Recall still ran and returned a memory — but the directives block is gone.
236
+ self.assertTrue(out, "a flipped agent still emits its recalled memories")
237
+ ctx = json.loads(out)["hookSpecificOutput"]["additionalContext"]
238
+ self.assertNotIn(
239
+ "<active_directives>", ctx,
240
+ "flipped + in-budget agent must NOT inject the directives block",
241
+ )
242
+ self.assertNotIn("always end replies with a wave", ctx)
243
+ self.assertIn("a real memory", ctx, "non-directive recall must be untouched")
244
+
245
+ def test_unflipped_agent_still_injects_active_directives(self):
246
+ # Control: identical setup, flag ON — directives MUST still appear. A
247
+ # test that passed under the pre-guard code (always injects) is only
248
+ # valid because its sibling above proves suppression actually happens.
249
+ proj = self._project_dir("# Agent\n\n" + _golden_rules_block())
250
+ out = self._run_main("what did we decide about X?", self._config(True), proj, _DirectiveClient())
251
+ ctx = json.loads(out)["hookSpecificOutput"]["additionalContext"]
252
+ self.assertIn("<active_directives>", ctx)
253
+ self.assertIn("always end replies with a wave", ctx)
254
+
255
+ def test_flag_off_no_rules_block_fails_safe_with_notice(self):
256
+ proj = self._project_dir("# Agent\n\nno rules block here.")
257
+ out = self._run_main("what did we decide about X?", self._config(False), proj, _DirectiveClient())
258
+ ctx = json.loads(out)["hookSpecificOutput"]["additionalContext"]
259
+ # Fail-safe: directives STILL injected, plus the degraded canary notice.
260
+ self.assertIn("<active_directives>", ctx)
261
+ self.assertIn("always end replies with a wave", ctx)
262
+ self.assertIn("injectDirectives is OFF", ctx)
263
+
264
+
265
+ class DirectivesOnlyPathTransportTests(_DirectiveFlipTestBase):
266
+ """Surface 2 (task-notification directives-only fast path)."""
267
+
268
+ def _run_directives_only(self, config, cwd, client):
269
+ return self._run_main(
270
+ "<task-notification>a background task finished</task-notification>",
271
+ config, cwd, client,
272
+ )
273
+
274
+ def test_flipped_in_budget_suppresses_on_task_notification(self):
275
+ proj = self._project_dir("# Agent\n\n" + _golden_rules_block())
276
+ out = self._run_directives_only(self._config(False), proj, _DirectiveClient())
277
+ self.assertEqual(
278
+ out, "",
279
+ "flipped agent's task-notification path must emit no directives",
280
+ )
281
+
282
+ def test_unflipped_injects_directives_on_task_notification(self):
283
+ proj = self._project_dir("# Agent\n\n" + _golden_rules_block())
284
+ out = self._run_directives_only(self._config(True), proj, _DirectiveClient())
285
+ self.assertTrue(out, "unflipped agent still injects directives on this path")
286
+ ctx = json.loads(out)["hookSpecificOutput"]["additionalContext"]
287
+ self.assertIn("<active_directives>", ctx)
288
+ self.assertIn("always end replies with a wave", ctx)
289
+
290
+
291
+ class PrefetchPathTransportTests(_DirectiveFlipTestBase):
292
+ """Surface 3 (memory-prefetch fast path, `_handle_prefetch_buffer`)."""
293
+
294
+ def _run_prefetch(self, config, cwd, client):
295
+ hook_input = {
296
+ "prompt": "what did we decide about X?",
297
+ "session_id": "test-session",
298
+ "transcript_path": "",
299
+ "cwd": cwd,
300
+ }
301
+ stdout = io.StringIO()
302
+ with patch("recall.get_api_url", return_value="http://fake"), \
303
+ patch("recall.HindsightClient", return_value=client), \
304
+ patch("recall.recall_buffer.sentinel_exists", return_value=False), \
305
+ patch("recall.recall_buffer.read_if_fresh", return_value=(None, None)), \
306
+ patch("recall.read_state", return_value={}), \
307
+ patch("sys.stdout", stdout):
308
+ emitted = recall._handle_prefetch_buffer(config, hook_input, hook_input["prompt"])
309
+ return emitted, stdout.getvalue()
310
+
311
+ def test_flipped_in_budget_suppresses_on_prefetch_fast_path(self):
312
+ proj = self._project_dir("# Agent\n\n" + _golden_rules_block())
313
+ _emitted, out = self._run_prefetch(self._config(False), proj, _DirectiveClient())
314
+ self.assertNotIn(
315
+ "<active_directives>", out,
316
+ "flipped agent must not leak directives on the prefetch fast path",
317
+ )
318
+ self.assertNotIn("always end replies with a wave", out)
319
+
320
+ def test_unflipped_injects_directives_on_prefetch_fast_path(self):
321
+ proj = self._project_dir("# Agent\n\n" + _golden_rules_block())
322
+ _emitted, out = self._run_prefetch(self._config(True), proj, _DirectiveClient())
323
+ self.assertIn("<active_directives>", out)
324
+ self.assertIn("always end replies with a wave", out)
325
+
326
+
327
+ if __name__ == "__main__":
328
+ unittest.main()