kuri-memory-guard/tests/test_memory_guard.py

1662 lines
70 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Tests for kuri-memory-guard plugin — hard + soft block."""
from __future__ import annotations
import importlib.machinery
import importlib.util
import sys
import unittest
from pathlib import Path
from typing import Any
from unittest.mock import MagicMock, patch
PLUGIN_DIR = Path(__file__).resolve().parent.parent
PLUGIN_INIT = PLUGIN_DIR / "__init__.py"
_NAMESPACE = "hermes_plugins"
_MODULE_NAME = f"{_NAMESPACE}.kuri_memory_guard"
POLICY_FIXTURES = {
"allowed": ["user prefers concise", "uses pytest with xdist"],
"hard": ["2026-07-05 note", "TODO: verify this"],
"soft": ["fixed the bug", "主人說「先確認再動作」"],
"known_bypass": [" fixed the bug "],
}
def _load_mod() -> Any:
"""Load the plugin as Hermes does: inside its namespace package."""
sys.modules.pop(_MODULE_NAME, None)
sys.modules.pop(f"{_MODULE_NAME}.messages", None)
if _NAMESPACE not in sys.modules:
namespace_spec = importlib.machinery.ModuleSpec(
_NAMESPACE,
loader=None,
is_package=True,
)
namespace_spec.submodule_search_locations = [str(PLUGIN_DIR.parent)]
namespace = importlib.util.module_from_spec(namespace_spec)
sys.modules[_NAMESPACE] = namespace
spec = importlib.util.spec_from_file_location(
_MODULE_NAME,
PLUGIN_INIT,
submodule_search_locations=[str(PLUGIN_DIR)],
)
assert spec is not None and spec.loader is not None
mod = importlib.util.module_from_spec(spec)
sys.modules[_MODULE_NAME] = mod
spec.loader.exec_module(mod)
return mod
_SID = "test-session"
# ═══════════════════════════════════════════════════════════════════
# Hard Guard 1 — Date
# ═══════════════════════════════════════════════════════════════════
class TestDateGuard(unittest.TestCase):
"""_guard_date — always hard block."""
def setUp(self):
self.mod = _load_mod()
def test_block_iso_date(self):
assert self.mod._guard_date("2026-07-05") is not None
def test_block_iso_datetime(self):
assert self.mod._guard_date("2026-07-05T14:30:00Z") is not None
def test_block_md_date(self):
assert self.mod._guard_date("6/30 update") is not None
def test_block_md_date_single_digit(self):
assert self.mod._guard_date("7/3 note") is not None
def test_allow_plain_text(self):
assert self.mod._guard_date("user prefers concise") is None
def test_allow_semver(self):
assert self.mod._guard_date("version 3.12") is None
# Dot-date with valid month/day (Fix 1)
def test_block_dot_date(self):
assert self.mod._guard_date("03.15") is not None
def test_block_dot_date_dec31(self):
assert self.mod._guard_date("12.31") is not None
def test_allow_dot_date_invalid_month(self):
"""No valid month in IP or invalid ranges."""
assert self.mod._guard_date("92.16") is None
assert self.mod._guard_date("68.01") is None
def test_allow_ip_segments_no_false_positive(self):
"""192.168.1.1 should not trigger dot-date matcher."""
assert self.mod._guard_date("192.168.1.1") is None
def test_dot_date_matched_text(self):
"""_guard_date should return the exact matched dot-date text."""
matched = self.mod._guard_date("start 03.15 end")
assert matched == "03.15"
# Full slash date before short M/D (Fix 2)
def test_date_slash_full_preferred(self):
"""2026/03/15 should match the full YYYY/MM/DD pattern, not just 03/15."""
matched = self.mod._guard_date("2026/03/15")
assert matched is not None
assert matched == "2026/03/15"
# Relative dates moved from work-verb (soft) to date (hard) (Fix 3)
def test_block_date_today(self):
assert self.mod._guard_date("today's status") is not None
def test_block_date_yesterday(self):
assert self.mod._guard_date("yesterday fixed the bug") is not None
def test_block_date_jin_tian(self):
assert self.mod._guard_date("今天修復了 bug") is not None
def test_block_date_ben_zhou(self):
assert self.mod._guard_date("本週進度") is not None
def test_block_date_weekday(self):
assert self.mod._guard_date("本週一完成") is not None
assert self.mod._guard_date("上週五進度") is not None
assert self.mod._guard_date("下週三開始") is not None
def test_block_date_week_reference(self):
assert self.mod._guard_date("本星期") is not None
assert self.mod._guard_date("上星期") is not None
assert self.mod._guard_date("下星期") is not None
# Fix 2: Relative date pattern ordering — specific matches before broad
def test_date_matched_text_weekday_specific(self):
"""本週一 should match full 本週一, not just 本週."""
matched = self.mod._guard_date("本週一")
assert matched is not None
assert matched == "本週一"
def test_date_matched_text_previous_weekday(self):
"""上週五的會議 should match 上週五, not just 上週."""
matched = self.mod._guard_date("上週五的會議")
assert matched is not None
assert matched == "上週五"
def test_date_matched_text_next_month_start(self):
"""下個月初 should match full 下個月初, not just 下個月."""
matched = self.mod._guard_date("下個月初")
assert matched is not None
assert matched == "下個月初"
# ═══════════════════════════════════════════════════════════════════
# Hard Guard 2 — Placeholder / temp / TODO
# ═══════════════════════════════════════════════════════════════════
class TestPlaceholderGuard(unittest.TestCase):
"""_guard_placeholder — always hard block."""
def setUp(self):
self.mod = _load_mod()
def test_block_todo(self):
assert self.mod._guard_placeholder("TODO: fix this") is not None
def test_block_placeholder(self):
assert self.mod._guard_placeholder("placeholder entry") is not None
def test_block_temp(self):
assert self.mod._guard_placeholder("temp check") is not None
def test_block_dummy(self):
assert self.mod._guard_placeholder("dummy entry") is not None
assert self.mod._guard_placeholder("dummy to read") is not None
assert self.mod._guard_placeholder("this is a dummy") is not None
def test_block_phase_done(self):
assert self.mod._guard_placeholder("phase 3 done") is not None
def test_block_session_note(self):
assert self.mod._guard_placeholder("session note: refactored") is not None
def test_block_current_task(self):
assert self.mod._guard_placeholder("current task: refactor") is not None
def test_block_proc_xxx(self):
assert self.mod._guard_placeholder("proc_a1b2c3d4e5f6 session") is not None
# A — Commit SHA
def test_block_full_sha(self):
assert (
self.mod._guard_placeholder("commit abcdef1234567890abcdef1234567890abcdef12")
is not None
)
def test_block_short_sha_with_label(self):
assert self.mod._guard_placeholder("sha: a1b2c3d4e5f6") is not None
def test_block_commit_with_short_sha(self):
assert self.mod._guard_placeholder("commit a1b2c3d") is not None
def test_block_probe_state(self):
assert self.mod._guard_placeholder("probe current state") is not None
def test_block_probe_state_short(self):
assert self.mod._guard_placeholder("probe state") is not None
def test_block_bare_probe(self):
assert self.mod._guard_placeholder("temp probe") is not None
assert self.mod._guard_placeholder("probe entry") is not None
assert self.mod._guard_placeholder("probe") is not None
assert self.mod._guard_placeholder("this is a probe test") is not None
assert self.mod._guard_placeholder("PROBE") is not None
def test_allow_probe_substring(self):
assert self.mod._guard_placeholder("probing") is None
assert self.mod._guard_placeholder("probed") is None
assert self.mod._guard_placeholder("probes") is None
def test_allow_plain_text(self):
assert self.mod._guard_placeholder("user prefers concise") is None
def test_block_placeholder_variants(self):
"""Without \\b boundary, placeholder substrings are also blocked."""
assert self.mod._guard_placeholder("placeholder_check") is not None
assert self.mod._guard_placeholder("_placeholder") is not None
assert self.mod._guard_placeholder("placeholder_") is not None
assert self.mod._guard_placeholder("placeholders") is not None
assert self.mod._guard_placeholder("placeholder_entry") is not None
# ═══════════════════════════════════════════════════════════════════
# Soft Guard 3 — Work verbs
# ═══════════════════════════════════════════════════════════════════
class TestWorkVerbGuard(unittest.TestCase):
"""_guard_work_verb — soft block, retry passes."""
def setUp(self):
self.mod = _load_mod()
def test_block_fixed_bug(self):
assert self.mod._guard_work_verb("fixed the bug") is not None
def test_block_submitted_pr(self):
assert self.mod._guard_work_verb("submitted PR") is not None
def test_block_pr_number(self):
assert self.mod._guard_work_verb("PR#42") is not None
def test_block_currently_working(self):
assert self.mod._guard_work_verb("currently working on auth") is not None
def test_block_next_step(self):
assert self.mod._guard_work_verb("next step: deploy") is not None
def test_block_chinese_status(self):
assert self.mod._guard_work_verb("正在處理 auth") is not None
def test_block_chinese_done(self):
assert self.mod._guard_work_verb("已修復 bug") is not None
def test_block_chinese_bu(self):
assert self.mod._guard_work_verb("已補上 missing dep") is not None
def test_block_chinese_que_ren(self):
assert self.mod._guard_work_verb("已確認權限正確") is not None
def test_block_chinese_wan_cheng(self):
assert self.mod._guard_work_verb("已完成部署測試") is not None
def test_block_chinese_she_ding(self):
assert self.mod._guard_work_verb("已設定環境變數") is not None
def test_block_done_with(self):
assert self.mod._guard_work_verb("done with debugging") is not None
def test_block_cron(self):
assert self.mod._guard_work_verb("cron job failed") is not None
def test_block_session_search(self):
assert self.mod._guard_work_verb("session_search coverage") is not None
def test_allow_plain_text(self):
assert self.mod._guard_work_verb("user prefers concise") is None
def test_allow_user_preference(self):
assert self.mod._guard_work_verb("uses pytest with xdist") is None
# C — Status snapshots
def test_block_progress_label(self):
assert self.mod._guard_work_verb("progress: auth module") is not None
def test_block_status_label(self):
assert self.mod._guard_work_verb("status: investigating") is not None
def test_block_jin_du_label(self):
assert self.mod._guard_work_verb("進度:已完成 CI") is not None
def test_block_zhuang_tai_label(self):
assert self.mod._guard_work_verb("狀態:調查中") is not None
# ═══════════════════════════════════════════════════════════════════
# Soft Guard 4 — User quote / incident narrative
# ═══════════════════════════════════════════════════════════════════
class TestUserQuoteGuard(unittest.TestCase):
"""_guard_user_quote — soft block, retry passes."""
def setUp(self):
self.mod = _load_mod()
def test_block_user_said_tw(self):
assert self.mod._guard_user_quote("主人說「先確認再動作」") is not None
def test_block_user_replied_tw(self):
assert self.mod._guard_user_quote("主人回「這個方向不對」") is not None
def test_block_user_required_tw(self):
assert self.mod._guard_user_quote("主人要求以 Codex 審查時 scope 嚴格限制") is not None
def test_block_user_said_en(self):
assert self.mod._guard_user_quote('User said "check first"') is not None
def test_block_ta_shuo(self):
assert self.mod._guard_user_quote("他說先等一下") is not None
def test_block_ni_shuo(self):
assert self.mod._guard_user_quote("你說「不對」") is not None
def test_allow_plain_text(self):
assert self.mod._guard_user_quote("user prefers concise") is None
# D — Incident markers
def test_block_incident(self):
assert self.mod._guard_user_quote("incident timeline") is not None
def test_block_root_cause(self):
assert self.mod._guard_user_quote("root cause: timeout") is not None
def test_block_shi_gu(self):
assert self.mod._guard_user_quote("事故時間線") is not None
def test_block_fu_pan(self):
assert self.mod._guard_user_quote("復盤結果") is not None
# E — Reflexive lessons
def test_block_lesson_learned(self):
assert self.mod._guard_user_quote("lesson learned: check first") is not None
def test_block_xue_dao_le(self):
assert self.mod._guard_user_quote("學到了要先確認") is not None
def test_block_xia_ci_yao_ji_de(self):
assert self.mod._guard_user_quote("下次要記得先讀 skill") is not None
# ═══════════════════════════════════════════════════════════════════
# Soft Guard 5 — Cron / parallel session artifacts
# ═══════════════════════════════════════════════════════════════════
class TestCronSessionGuard(unittest.TestCase):
"""_guard_cron_session — soft block, retry passes."""
def setUp(self):
self.mod = _load_mod()
def test_block_parallel_session_tw(self):
assert self.mod._guard_cron_session("平行 session 覆蓋機制") is not None
def test_block_parallel_session_en(self):
assert self.mod._guard_cron_session("parallel session coverage") is not None
def test_block_parallel_kuri(self):
assert self.mod._guard_cron_session("parallel Kuri dispatch") is not None
def test_block_coverage_edge(self):
assert self.mod._guard_cron_session("coverage edge detected") is not None
def test_block_silent(self):
assert self.mod._guard_cron_session("不要回 [SILENT]") is not None
def test_block_shou_dong_trigger(self):
assert self.mod._guard_cron_session("手動 trigger cron") is not None
def test_allow_plain_text(self):
assert self.mod._guard_cron_session("user prefers concise") is None
# ═══════════════════════════════════════════════════════════════════
# Soft Guard 6 — Version snapshot & memory cleanup meta
# ═══════════════════════════════════════════════════════════════════
class TestMetaGuard(unittest.TestCase):
"""_guard_meta — soft block, retry passes."""
def setUp(self):
self.mod = _load_mod()
def test_block_version_number(self):
assert self.mod._guard_meta("version 3.14") is not None
def test_block_short_version(self):
assert self.mod._guard_meta("v1.2") is not None
def test_block_full_semver(self):
assert self.mod._guard_meta("v9.1.1") is not None
def test_block_memory_cleanup(self):
assert self.mod._guard_meta("memory cleanup 完成") is not None
def test_block_memory_clean(self):
assert self.mod._guard_meta("memory clean up") is not None
def test_block_ji_yi_tiao_mu(self):
assert self.mod._guard_meta("記憶條目偏好") is not None
def test_block_skill_bloat(self):
assert self.mod._guard_meta("skill bloat detected") is not None
def test_block_you_hua_fang_xiang(self):
assert self.mod._guard_meta("軟封鎖優化方向") is not None
def test_block_gai_shan_fang_xiang(self):
assert self.mod._guard_meta("改善方向:合併重複 guard") is not None
def test_block_housekeeping(self):
assert self.mod._guard_meta("housekeeping cron") is not None
# F — Re-fetchable from source
def test_block_git_log(self):
assert self.mod._guard_meta("see git log for details") is not None
def test_block_source_code(self):
assert self.mod._guard_meta("in the source code") is not None
def test_block_yuan_shi_ma(self):
assert self.mod._guard_meta("原始碼已有實作") is not None
def test_block_official_docs(self):
assert self.mod._guard_meta("official docs explain it") is not None
def test_block_release_notes(self):
assert self.mod._guard_meta("release notes v2.0") is not None
def test_allow_plain_text(self):
assert self.mod._guard_meta("user prefers concise") is None
# ═══════════════════════════════════════════════════════════════════
# Soft block tracking
# ═══════════════════════════════════════════════════════════════════
class TestSoftBlockTracking(unittest.TestCase):
"""_consume_retry_if_allowed / _mark_soft_blocked — atomic one-time retry with scope-aware fingerprint."""
def setUp(self):
self.mod = _load_mod()
self.mod._pending_retries.clear()
self.mod._session_state.clear()
def test_first_block_then_allow(self):
"""First soft block creates pending retry; second identical op passes atomically."""
assert not self.mod._consume_retry_if_allowed(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", _SID
)
self.mod._mark_soft_blocked(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", _SID
)
assert self.mod._consume_retry_if_allowed(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", _SID
)
def test_different_content_not_affected(self):
self.mod._mark_soft_blocked(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", _SID
)
assert not self.mod._consume_retry_if_allowed(
self.mod._SCOPE_SINGLE, "add", "memory", "submitted PR", "", _SID
)
def test_different_session_not_affected(self):
self.mod._mark_soft_blocked(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", "session-a"
)
assert not self.mod._consume_retry_if_allowed(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", "session-b"
)
def test_whitespace_insensitive(self):
self.mod._mark_soft_blocked(
self.mod._SCOPE_SINGLE, "add", "memory", " fixed the bug ", "", _SID
)
assert self.mod._consume_retry_if_allowed(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", _SID
)
def test_different_action_not_affected(self):
self.mod._mark_soft_blocked(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", _SID
)
assert not self.mod._consume_retry_if_allowed(
self.mod._SCOPE_SINGLE, "replace", "memory", "fixed the bug", "", _SID
)
def test_different_target_not_affected(self):
self.mod._mark_soft_blocked(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", _SID
)
assert not self.mod._consume_retry_if_allowed(
self.mod._SCOPE_SINGLE, "add", "user", "fixed the bug", "", _SID
)
def test_different_old_text_not_affected(self):
self.mod._mark_soft_blocked(
self.mod._SCOPE_SINGLE, "replace", "memory", "fixed the bug", "old1", _SID
)
assert not self.mod._consume_retry_if_allowed(
self.mod._SCOPE_SINGLE, "replace", "memory", "fixed the bug", "old2", _SID
)
def test_consume_retry_makes_next_attempt_block(self):
"""Atomic consume: after one successful retry, next attempt blocks."""
self.mod._mark_soft_blocked(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", _SID
)
assert self.mod._consume_retry_if_allowed(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", _SID
)
assert not self.mod._consume_retry_if_allowed(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", _SID
)
def test_single_scope_does_not_authorize_batch(self):
"""Single scope fingerprint must not authorize batch scope retry."""
self.mod._mark_soft_blocked(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", _SID
)
assert not self.mod._consume_retry_if_allowed(
self.mod._SCOPE_BATCH, "add", "memory", "fixed the bug", "", _SID
)
def test_batch_scope_does_not_authorize_single(self):
"""Batch scope fingerprint must not authorize single scope retry."""
self.mod._mark_soft_blocked(
self.mod._SCOPE_BATCH, "add", "memory", "fixed the bug", "", _SID
)
assert not self.mod._consume_retry_if_allowed(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", _SID
)
# ═══════════════════════════════════════════════════════════════════
# _scan_content — orchestration
# ═══════════════════════════════════════════════════════════════════
class TestScanContent(unittest.TestCase):
"""_scan_content routes through hard then soft guards."""
def setUp(self):
self.mod = _load_mod()
self.mod._pending_retries.clear()
self.mod._session_state.clear()
def test_hard_date_blocks_first(self):
name, msg = self.mod._scan_content(
"2026-07-05 session note", _SID, action="add", target="memory"
)
assert name == "date"
assert msg is not None
def test_hard_placeholder_blocks(self):
name, msg = self.mod._scan_content(
"TODO: fix session note", _SID, action="add", target="memory"
)
assert name == "placeholder"
assert msg is not None
def test_soft_blocks_first_time(self):
name, msg = self.mod._scan_content(
"fixed the bug in cron", _SID, action="add", target="memory"
)
assert name == "work_verb"
assert msg is not None
def test_soft_allows_second_time(self):
self.mod._scan_content("fixed the bug", _SID, action="add", target="memory")
name, msg = self.mod._scan_content("fixed the bug", _SID, action="add", target="memory")
assert name == "" and msg is None
def test_soft_still_blocks_different_content(self):
self.mod._scan_content("fixed the bug", _SID, action="add", target="memory")
name, msg = self.mod._scan_content("submitted PR", _SID, action="add", target="memory")
assert name == "work_verb"
def test_hard_always_blocks(self):
self.mod._scan_content("fixed the bug", _SID, action="add", target="memory")
name, msg = self.mod._scan_content("2026-07-05 test", _SID, action="add", target="memory")
assert name == "date"
def test_soft_respects_session_boundary(self):
self.mod._scan_content("fixed the bug", "session-a", action="add", target="memory")
name, msg = self.mod._scan_content(
"fixed the bug", "session-b", action="add", target="memory"
)
assert name == "work_verb"
def test_allow_clean(self):
name, msg = self.mod._scan_content(
"user prefers concise", _SID, action="add", target="memory"
)
assert name == "" and msg is None
# ═══════════════════════════════════════════════════════════════════
# _get_block_msg — memory call interface
# ═══════════════════════════════════════════════════════════════════
class TestGetBlockMsg(unittest.TestCase):
"""_get_block_msg with one-time retry tracking."""
def setUp(self):
self.mod = _load_mod()
self.mod._pending_retries.clear()
self.mod._session_state.clear()
def test_block_hard_single(self):
msg = self.mod._get_block_msg(
{"action": "add", "target": "memory", "content": "2026-07-05 note"}, _SID
)
assert msg is not None
def test_block_soft_first_time(self):
msg = self.mod._get_block_msg(
{"action": "add", "target": "memory", "content": "fixed the bug"}, _SID
)
assert msg is not None
def test_allow_soft_second_time(self):
self.mod._get_block_msg(
{"action": "add", "target": "memory", "content": "fixed the bug"}, _SID
)
msg = self.mod._get_block_msg(
{"action": "add", "target": "memory", "content": "fixed the bug"}, _SID
)
assert msg is None
def test_block_batch_with_hard(self):
msg = self.mod._get_block_msg(
{
"operations": [
{"action": "add", "target": "memory", "content": "clean"},
{"action": "add", "target": "memory", "content": "2026-07-05 dirty"},
],
},
_SID,
)
assert msg is not None
def test_block_batch_with_soft_first(self):
msg = self.mod._get_block_msg(
{
"operations": [
{"action": "add", "target": "memory", "content": "fixed the bug"},
],
},
_SID,
)
assert msg is not None
def test_allow_batch_soft_second(self):
ops = [{"action": "add", "target": "memory", "content": "fixed the bug"}]
self.mod._get_block_msg({"operations": ops}, _SID)
msg = self.mod._get_block_msg({"operations": ops}, _SID)
assert msg is None
def test_allow_clean(self):
msg = self.mod._get_block_msg(
{"action": "add", "target": "memory", "content": "user prefers concise"}, _SID
)
assert msg is None
# ═══════════════════════════════════════════════════════════════════
# _on_pre_tool_call — hook interface
# ═══════════════════════════════════════════════════════════════════
class TestOnPreToolCall(unittest.TestCase):
"""pre_tool_call hook with session_id."""
def setUp(self):
self.mod = _load_mod()
self.mod._pending_retries.clear()
self.mod._session_state.clear()
def test_block_hard(self):
r = self.mod._on_pre_tool_call(
tool_name="memory",
args={"action": "add", "target": "memory", "content": "2026-07-05 note"},
session_id=_SID,
)
assert r is not None and r["action"] == "block"
def test_block_soft_first_time(self):
r = self.mod._on_pre_tool_call(
tool_name="memory",
args={"action": "add", "target": "memory", "content": "fixed the bug"},
session_id=_SID,
)
assert r is not None and r["action"] == "block"
def test_allow_soft_second_time(self):
self.mod._on_pre_tool_call(
tool_name="memory",
args={"action": "add", "target": "memory", "content": "fixed the bug"},
session_id=_SID,
)
r = self.mod._on_pre_tool_call(
tool_name="memory",
args={"action": "add", "target": "memory", "content": "fixed the bug"},
session_id=_SID,
)
assert r is None
def test_hard_still_blocks_after_soft(self):
self.mod._on_pre_tool_call(
tool_name="memory",
args={"action": "add", "target": "memory", "content": "fixed the bug"},
session_id=_SID,
)
r = self.mod._on_pre_tool_call(
tool_name="memory",
args={
"action": "add",
"target": "memory",
"content": "2026-07-05 fixed bug",
},
session_id=_SID,
)
assert r is not None and r["action"] == "block"
def test_allow_clean(self):
r = self.mod._on_pre_tool_call(
tool_name="memory",
args={
"action": "add",
"target": "memory",
"content": "user prefers concise",
},
session_id=_SID,
)
assert r is None
def test_allow_non_memory(self):
r = self.mod._on_pre_tool_call(tool_name="patch", args={})
assert r is None
# ═══════════════════════════════════════════════════════════════════
# Normalize / hash
# ═══════════════════════════════════════════════════════════════════
class TestHelpers(unittest.TestCase):
"""_normalize and _operation_fingerprint."""
def setUp(self):
self.mod = _load_mod()
def test_normalize_strips_whitespace(self):
assert self.mod._normalize(" hello ") == "hello"
def test_normalize_preserves_inner_space(self):
assert self.mod._normalize("hello world") == "hello world"
def test_fingerprint_stable(self):
h1 = self.mod._operation_fingerprint("single", "add", "memory", "fixed the bug", "")
h2 = self.mod._operation_fingerprint("single", "add", "memory", "fixed the bug", "")
assert h1 == h2
def test_fingerprint_different_content(self):
h1 = self.mod._operation_fingerprint("single", "add", "memory", "fixed the bug", "")
h2 = self.mod._operation_fingerprint("single", "add", "memory", "submitted PR", "")
assert h1 != h2
def test_fingerprint_different_action(self):
h1 = self.mod._operation_fingerprint("single", "add", "memory", "fixed the bug", "")
h2 = self.mod._operation_fingerprint("single", "replace", "memory", "fixed the bug", "")
assert h1 != h2
def test_fingerprint_different_target(self):
h1 = self.mod._operation_fingerprint("single", "add", "memory", "fixed the bug", "")
h2 = self.mod._operation_fingerprint("single", "add", "user", "fixed the bug", "")
assert h1 != h2
def test_fingerprint_different_old_text(self):
h1 = self.mod._operation_fingerprint("single", "replace", "memory", "fixed the bug", "old1")
h2 = self.mod._operation_fingerprint("single", "replace", "memory", "fixed the bug", "old2")
assert h1 != h2
def test_fingerprint_different_scope(self):
h1 = self.mod._operation_fingerprint("single", "add", "memory", "fixed the bug", "")
h2 = self.mod._operation_fingerprint("batch", "add", "memory", "fixed the bug", "")
assert h1 != h2
# ═══════════════════════════════════════════════════════════════════
# register
# ═══════════════════════════════════════════════════════════════════
class TestRegister(unittest.TestCase):
"""register() registers the correct hook."""
def test_register_pre_tool_call_hook(self):
mod = _load_mod()
ctx = MagicMock()
mod.register(ctx)
names = [c.args[0] for c in ctx.register_hook.call_args_list]
assert "pre_tool_call" in names
def test_register_with_correct_callback(self):
mod = _load_mod()
ctx = MagicMock()
mod.register(ctx)
nf = {c.args[0]: c.args[1] for c in ctx.register_hook.call_args_list}
assert nf["pre_tool_call"] is mod._on_pre_tool_call
# ═══════════════════════════════════════════════════════════════════
# Length Guard
# ═══════════════════════════════════════════════════════════════════
class TestLengthGuard(unittest.TestCase):
"""_guard_length — three-stage soft block (90/140/220)."""
def setUp(self):
self.mod = _load_mod()
def test_s1_blocks_at_80(self):
assert self.mod._guard_length("x" * 80) is not None
def test_s1_allows_below_80(self):
assert self.mod._guard_length("x" * 79) is None
def test_s1_message_contains_refine(self):
msg = self.mod._guard_length("x" * 85)
assert "精煉" in msg
def test_s2_blocks_at_120(self):
msg = self.mod._guard_length("x" * 120)
assert msg is not None
assert "拆分" in msg
def test_s3_blocks_at_150(self):
msg = self.mod._guard_length("x" * 150)
assert msg is not None
assert "敘事" in msg or "文件" in msg
def test_early_s2_with_markers(self):
"""Content in S1 range (80-119 chars) with 3+ split markers triggers early S2 (Fix 6)."""
# 12 chars + 80 x's = 92 chars, which is >= S1 (80) and < S2 (120)
msg = self.mod._guard_length("不要同時而且另外還有必須不能" + "x" * 80)
assert msg is not None
assert "拆分" in msg
def test_early_s2_not_below_80(self):
"""Below S1 should not trigger even with markers."""
msg = self.mod._guard_length("不要同時而且另外還有必須不能應該")
assert msg is None
def test_clean_under_80(self):
assert self.mod._guard_length("user prefers concise") is None
# ═══════════════════════════════════════════════════════════════════
# Multi-Hit (extra_hits in _scan_content)
# ═══════════════════════════════════════════════════════════════════
class TestMultiHit(unittest.TestCase):
"""_scan_content collects extra soft guard hits."""
def setUp(self):
self.mod = _load_mod()
self.mod._pending_retries.clear()
self.mod._session_state.clear()
def test_extra_hits_appended_to_msg(self):
"""Content hitting multiple soft guards shows them all."""
name, msg = self.mod._scan_content(
"被糾正時不要先跑 git log", _SID, action="add", target="memory"
)
assert "同時也會命中以下" in msg, (
f"Expected multi-hit message, got: {msg[:100] if msg else 'None'}"
)
def test_extra_hits_lists_names(self):
name, msg = self.mod._scan_content(
"被糾正時不要先跑 git log", _SID, action="add", target="memory"
)
assert "user_quote" in msg or "meta" in msg
def test_clean_no_extra_hits(self):
name, msg = self.mod._scan_content(
"user prefers concise", _SID, action="add", target="memory"
)
assert name == "" and msg is None
def test_hard_still_blocks_immediately(self):
"""Hard guard returns immediately, no extra_hits collected."""
name, msg = self.mod._scan_content(
"2026-07-05 被糾正時不要先跑 git log", _SID, action="add", target="memory"
)
assert name == "date"
assert "同時也會命中以下" not in msg
class TestPolicyFixtures(unittest.TestCase):
"""Representative allow/block and retry-regression policy fixtures."""
def setUp(self):
self.mod = _load_mod()
self.mod._pending_retries.clear()
self.mod._session_state.clear()
def test_allowed_fixtures_have_no_hits(self):
for content in POLICY_FIXTURES["allowed"]:
with self.subTest(content=content):
assert self.mod._classify_content(content) == []
def test_hard_fixtures_block_as_hard(self):
for content in POLICY_FIXTURES["hard"]:
with self.subTest(content=content):
hits = self.mod._classify_content(content)
assert hits and hits[0][1] == self.mod._HARD
def test_soft_fixtures_block_once(self):
for content in POLICY_FIXTURES["soft"]:
with self.subTest(content=content):
assert (
self.mod._scan_content(content, _SID, action="add", target="memory")[1]
is not None
)
assert self.mod._scan_content(content, _SID, action="add", target="memory") == (
"",
None,
)
def test_normalized_retry_regression_passes_only_after_warning(self):
content = POLICY_FIXTURES["known_bypass"][0]
assert self.mod._scan_content(content, _SID, action="add", target="memory")[1] is not None
assert self.mod._scan_content("fixed the bug", _SID, action="add", target="memory") == (
"",
None,
)
class TestPhasesAndStateBounds(unittest.TestCase):
"""Classification/rendering stay pure; retry state has a TTL and cap."""
def setUp(self):
self.mod = _load_mod()
self.mod._pending_retries.clear()
self.mod._session_state.clear()
def test_classification_and_rendering_do_not_mutate_retry_state(self):
self.mod._mark_soft_blocked(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", _SID
)
before_retries = {sid: dict(retries) for sid, retries in self.mod._pending_retries.items()}
before_state = dict(self.mod._session_state)
hits = self.mod._classify_content("fixed the bug in cron")
name, message = self.mod._render_single_block(hits, action="add")
assert name == "work_verb"
assert message is not None
after_retries = {sid: dict(retries) for sid, retries in self.mod._pending_retries.items()}
after_state = dict(self.mod._session_state)
assert after_retries == before_retries
assert after_state == before_state
def test_expired_session_is_removed_lazily(self):
with patch.object(self.mod.time, "time", return_value=1_000.0):
self.mod._mark_soft_blocked(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", _SID
)
with patch.object(
self.mod.time,
"time",
return_value=1_000.0 + self.mod._STATE_TTL_SECONDS,
):
assert not self.mod._consume_retry_if_allowed(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", _SID
)
assert _SID not in self.mod._session_state
def test_session_cap_evicts_the_least_recently_used_session(self):
self.mod._MAX_TRACKED_SESSIONS = 2
with patch.object(self.mod.time, "time", side_effect=[1.0, 2.0, 3.0]):
self.mod._mark_soft_blocked(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", "oldest"
)
self.mod._mark_soft_blocked(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", "middle"
)
self.mod._mark_soft_blocked(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", "newest"
)
assert set(self.mod._session_state) == {"middle", "newest"}
def test_expired_retry_window_re_blocks(self):
"""Pending retry expires after _RETRY_WINDOW_SECONDS."""
with patch.object(self.mod.time, "time", return_value=1_000.0):
self.mod._mark_soft_blocked(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", _SID
)
with patch.object(
self.mod.time,
"time",
return_value=1_000.0 + self.mod._RETRY_WINDOW_SECONDS + 1,
):
assert not self.mod._consume_retry_if_allowed(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", _SID
)
def test_hard_ceiling_blocks_first_and_retry(self):
"""Hard ceiling blocks both first and second attempt; retry does not apply."""
content = "x" * 400
name1, msg1 = self.mod._scan_content(content, _SID, action="add", target="memory")
assert name1 == "hard_ceiling"
assert msg1 is not None
name2, msg2 = self.mod._scan_content(content, _SID, action="add", target="memory")
assert name2 == "hard_ceiling"
assert msg2 is not None
def test_hard_ceiling_message_mentions_ceiling_and_no_bypass(self):
content = "x" * 400
name, msg = self.mod._scan_content(content, _SID, action="add", target="memory")
assert "HARD BLOCK" in msg
assert "不會放行" in msg
assert "180 字絕對上限" in msg
def test_hard_ceiling_message_not_exclusively_exceeded(self):
"""New message uses 'N 字絕對上限' format (not '已達到或超過')."""
msg = self.mod._MSG_HARD_CEILING.format(n=180)
assert "180 字絕對上限" in msg
def test_hard_ceiling_blocks_exactly_at_180(self):
"""n == 180 (the ceiling value) must hard block."""
content = "x" * 180
name, msg = self.mod._scan_content(content, _SID, action="add", target="memory")
assert name == "hard_ceiling"
assert msg is not None
assert "180" in msg
def test_hard_ceiling_at_180_retry_still_blocks(self):
"""Retry cannot bypass hard ceiling even at exactly 180."""
content = "x" * 180
self.mod._scan_content(content, _SID, action="add", target="memory")
name2, msg2 = self.mod._scan_content(content, _SID, action="add", target="memory")
assert name2 == "hard_ceiling"
assert msg2 is not None
def test_hard_ceiling_blocks_above_180(self):
"""n > 180 must hard block."""
content = "x" * 181
name, msg = self.mod._scan_content(content, _SID, action="add", target="memory")
assert name == "hard_ceiling"
assert msg is not None
def test_hard_ceiling_blocks_above_360(self):
"""n > 360 must still hard block."""
content = "x" * 400
name, msg = self.mod._scan_content(content, _SID, action="add", target="memory")
assert name == "hard_ceiling"
assert msg is not None
def test_length_message_shows_actual_and_threshold(self):
content = "x" * 107
name, msg = self.mod._scan_content(content, _SID, action="add", target="memory")
assert "107" in msg # actual length
assert "80 字精煉檢查" in msg
class TestBatchHygiene(unittest.TestCase):
"""Multiple guarded batch entries receive one summary without soft marks."""
def setUp(self):
self.mod = _load_mod()
self.mod._pending_retries.clear()
self.mod._session_state.clear()
def test_two_guarded_operations_return_indexed_summary(self):
msg = self.mod._get_block_msg(
{
"operations": [
{"action": "add", "target": "memory", "content": "fixed the bug"},
{"action": "add", "target": "memory", "content": "2026-07-05 note"},
]
},
_SID,
)
assert msg is not None
assert "第 1 筆" in msg and "第 2 筆" in msg
assert "work_verb" in msg and "date" in msg
assert "拆成單筆操作" in msg
assert "這看起來像當下工作狀態" not in msg
def test_batch_summary_does_not_mark_soft_retry_state(self):
operations = [
{"action": "add", "target": "memory", "content": "fixed the bug"},
{"action": "add", "target": "memory", "content": "submitted PR"},
]
assert self.mod._get_block_msg({"operations": operations}, _SID) is not None
assert not self.mod._consume_retry_if_allowed(
self.mod._SCOPE_BATCH, "add", "memory", "fixed the bug", "", _SID
)
assert (
self.mod._scan_content("fixed the bug", _SID, action="add", target="memory")[1]
is not None
)
def test_one_guarded_operation_keeps_full_single_entry_guidance(self):
operations = [{"action": "add", "target": "memory", "content": "fixed the bug"}]
msg = self.mod._get_block_msg({"operations": operations}, _SID)
assert msg is not None and "〔SOFT BLOCK" in msg
assert self.mod._get_block_msg({"operations": operations}, _SID) is None
def test_batch_one_op_retry_does_not_affect_another(self):
"""One operation's retry must not enable a different operation's retry."""
ops1 = [{"action": "add", "target": "memory", "content": "fixed the bug"}]
# First call: blocks and creates pending retry for op1
self.mod._get_block_msg({"operations": ops1}, _SID)
# Second call with same ops: should pass (retry)
assert self.mod._get_block_msg({"operations": ops1}, _SID) is None
# Now a different operation in the same session should still block
ops2 = [{"action": "add", "target": "memory", "content": "submitted PR"}]
msg = self.mod._get_block_msg({"operations": ops2}, _SID)
assert msg is not None
def test_batch_with_hard_ceiling_and_soft_still_shows_both(self):
"""Batch with hard ceiling + soft should show both in summary."""
msg = self.mod._get_block_msg(
{
"operations": [
{"action": "add", "target": "memory", "content": "x" * 400},
{"action": "add", "target": "memory", "content": "fixed the bug"},
]
},
_SID,
)
assert msg is not None
assert "hard_ceiling" in msg and "work_verb" in msg
class TestHermesNamespaceLoading(unittest.TestCase):
"""Relative messages import works with Hermes' namespace package layout."""
def test_loads_messages_relative_to_the_plugin_package(self):
mod = _load_mod()
assert mod.__package__ == _MODULE_NAME
assert f"{_MODULE_NAME}.messages" in sys.modules
class TestProjectMetadata(unittest.TestCase):
"""The package project and Hermes manifest keep the same release version."""
def test_manifest_uses_hermes_hook_field_and_matches_project_version(self):
manifest = (PLUGIN_DIR / "plugin.yaml").read_text(encoding="utf-8")
project = (PLUGIN_DIR / "pyproject.toml").read_text(encoding="utf-8")
manifest_version = next(
line.split(":", maxsplit=1)[1].strip().strip('"')
for line in manifest.splitlines()
if line.startswith("version:")
)
project_version = next(
line.split("=", maxsplit=1)[1].strip().strip('"')
for line in project.splitlines()
if line.startswith("version =")
)
assert "provides_hooks:" in manifest
assert "\nhooks:" not in manifest
assert manifest_version == project_version
def test_documentation_points_to_reproducible_verification(self):
for filename in ("README.md", "AGENTS.md"):
with self.subTest(filename=filename):
assert "just verify" in (PLUGIN_DIR / filename).read_text(encoding="utf-8")
# ═══════════════════════════════════════════════════════════════════
# Message constant integrity (Issue 1)
# ═══════════════════════════════════════════════════════════════════
class TestMessageNoLeadingBackslash(unittest.TestCase):
"""Message constants must not start with an isolated backslash."""
def setUp(self):
self.mod = _load_mod()
def test_add_intro_no_backslash(self):
assert not self.mod._MSG_ADD_INTRO.startswith("\\")
def test_replace_intro_no_backslash(self):
assert not self.mod._MSG_REPLACE_INTRO.startswith("\\")
def test_hard_ceiling_no_backslash(self):
assert not self.mod._MSG_HARD_CEILING.startswith("\\")
def test_soft_template_no_backslash(self):
assert not self.mod._MSG_SOFT_TEMPLATE.startswith("\\")
def test_rendered_soft_message_no_backslash(self):
"""Full rendered error message from a soft guard must not have leading backslash."""
self.mod._pending_retries.clear()
self.mod._session_state.clear()
_, msg = self.mod._scan_content("fixed the bug", _SID, action="add", target="memory")
assert msg is not None
assert not msg.startswith("\\")
def test_rendered_length_message_no_backslash(self):
"""Full rendered length message must not have leading backslash."""
_, msg = self.mod._scan_content("x" * 95, _SID, action="add", target="memory")
assert msg is not None
assert not msg.startswith("\\")
def test_rendered_hard_ceiling_no_backslash(self):
"""Full rendered hard ceiling message must not have leading backslash."""
_, msg = self.mod._scan_content("x" * 400, _SID, action="add", target="memory")
assert msg is not None
assert not msg.startswith("\\")
def test_rendered_replace_intro_no_backslash(self):
"""Replace intro in rendered message must not have leading backslash."""
self.mod._pending_retries.clear()
self.mod._session_state.clear()
_, msg = self.mod._scan_content("fixed the bug", _SID, action="replace", target="memory")
assert msg is not None
assert "〔replace〕" in msg
assert not msg.startswith("\\")
# ═══════════════════════════════════════════════════════════════════
# Atomic retry under concurrency (Issue 2)
# ═══════════════════════════════════════════════════════════════════
class TestAtomicRetryConsume(unittest.TestCase):
"""_consume_retry_if_allowed must be atomic under concurrent access."""
def setUp(self):
self.mod = _load_mod()
self.mod._pending_retries.clear()
self.mod._session_state.clear()
def test_concurrent_retries_only_one_succeeds(self):
"""Two threads racing to consume the same pending retry: exactly one wins."""
import threading
self.mod._mark_soft_blocked(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", _SID
)
barrier = threading.Barrier(2)
results: list[bool] = []
def attempt():
barrier.wait() # coordinate simultaneous release
result = self.mod._consume_retry_if_allowed(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", "", _SID
)
results.append(result)
t1 = threading.Thread(target=attempt)
t2 = threading.Thread(target=attempt)
t1.start()
t2.start()
t1.join()
t2.join()
wins = sum(results)
assert wins == 1, f"Expected exactly 1 winner, got {wins}"
# Pending fingerprint must be consumed (check BEFORE scan_content,
# which would re-create the pending retry)
retries = self.mod._pending_retries.get(_SID, {})
fp = self.mod._operation_fingerprint(
self.mod._SCOPE_SINGLE, "add", "memory", "fixed the bug", ""
)
assert fp not in retries, "Pending fingerprint should have been consumed"
# The losing thread should re-block on next scan
name, msg = self.mod._scan_content("fixed the bug", _SID, action="add", target="memory")
assert name == "work_verb"
assert msg is not None
# ═══════════════════════════════════════════════════════════════════
# Single vs batch scope isolation (Issue 3)
# ═══════════════════════════════════════════════════════════════════
class TestSingleBatchScopeIsolation(unittest.TestCase):
"""Single scope retry must not authorize batch and vice versa."""
def setUp(self):
self.mod = _load_mod()
self.mod._pending_retries.clear()
self.mod._session_state.clear()
def test_single_block_then_batch_still_blocks(self):
"""Single first block → same content as batch operation: still blocks."""
# Single scope block
self.mod._scan_content("fixed the bug", _SID, action="add", target="memory")
# Same content in batch scope
op = {"action": "add", "target": "memory", "content": "fixed the bug"}
msg = self.mod._operation_is_blocked(op, _SID)
assert msg is not None, "Batch scope should not use single scope retry"
def test_batch_block_then_single_still_blocks(self):
"""Batch first block → same content as single operation: still blocks."""
op = {"action": "add", "target": "memory", "content": "fixed the bug"}
self.mod._operation_is_blocked(op, _SID)
# Same content in single scope
name, msg = self.mod._scan_content("fixed the bug", _SID, action="add", target="memory")
assert name == "work_verb"
assert msg is not None, "Single scope should not use batch scope retry"
def test_batch_op_second_identical_passes(self):
"""Same batch operation submitted twice: second time passes (one-time retry)."""
ops = [{"action": "add", "target": "memory", "content": "fixed the bug"}]
msg1 = self.mod._get_block_msg({"operations": ops}, _SID)
assert msg1 is not None
msg2 = self.mod._get_block_msg({"operations": ops}, _SID)
assert msg2 is None
def test_batch_op_third_re_blocks(self):
"""Third identical batch submission re-blocks after retry consumed."""
ops = [{"action": "add", "target": "memory", "content": "fixed the bug"}]
self.mod._get_block_msg({"operations": ops}, _SID)
self.mod._get_block_msg({"operations": ops}, _SID)
msg3 = self.mod._get_block_msg({"operations": ops}, _SID)
assert msg3 is not None
def test_hard_guard_unaffected_by_scope(self):
"""Hard ceiling blocks regardless of single/batch scope."""
_, msg_single = self.mod._scan_content("x" * 400, _SID, action="add", target="memory")
assert msg_single is not None
op = {"action": "add", "target": "memory", "content": "x" * 400}
msg_batch = self.mod._operation_is_blocked(op, _SID)
assert msg_batch is not None
# ═══════════════════════════════════════════════════════════════════
# Path A/B message consistency (Issue 4)
# ═══════════════════════════════════════════════════════════════════
# ═══════════════════════════════════════════════════════════════════
# New message consistency
# ═══════════════════════════════════════════════════════════════════
class TestMessageConsistency(unittest.TestCase):
"""New message format consistency checks."""
def setUp(self):
self.mod = _load_mod()
def test_replace_intro_does_not_promise_length_exemption(self):
"""Replace intro is just a marker; no length-related phrasing."""
assert "〔replace〕" in self.mod._MSG_REPLACE_INTRO
assert "不論長度" not in self.mod._MSG_REPLACE_INTRO
def test_soft_block_contains_guard_name_placeholder(self):
"""SOFT TEMPLATE must contain {guard_name} for formatting."""
assert "{guard_name}" in self.mod._MSG_SOFT_TEMPLATE
def test_soft_block_contains_matched_text_placeholder(self):
assert "{matched_text}" in self.mod._MSG_SOFT_TEMPLATE
def test_hard_ceiling_denies_retry_override(self):
"""Hard ceiling message must say retry won't pass."""
msg = self.mod._MSG_HARD_CEILING.format(n=200)
assert "不會放行" in msg, "Hard ceiling should say retry won't pass"
def test_date_hard_block_contains_matched_placeholder(self):
assert "{matched}" in self.mod._MSG_DATE_HARD
def test_placeholder_block_contains_matched_placeholder(self):
assert "{matched}" in self.mod._MSG_PLACEHOLDER
assert "{list_warning}" in self.mod._MSG_PLACEHOLDER
def test_length_s1_contains_n_placeholder(self):
msg = self.mod._MSG_LENGTH_S1.format(n=80)
assert "80" in msg
def test_length_s2_contains_n_placeholder(self):
msg = self.mod._MSG_LENGTH_S2.format(n=120)
assert "120" in msg
def test_length_s3_contains_n_placeholder(self):
msg = self.mod._MSG_LENGTH_S3.format(n=150)
assert "150" in msg
# ═══════════════════════════════════════════════════════════════════
# Per-session pending retry cap (Issue 5)
# ═══════════════════════════════════════════════════════════════════
class TestPendingRetryCap(unittest.TestCase):
"""Per-session pending retry cap evicts oldest when exceeded."""
def setUp(self):
self.mod = _load_mod()
self.mod._pending_retries.clear()
self.mod._session_state.clear()
def test_cap_evicts_oldest_pending(self):
"""When cap is reached, oldest pending fingerprint is evicted."""
self.mod._MAX_PENDING_RETRIES_PER_SESSION = 3
# Fill to cap with distinct content
for i in range(3):
self.mod._mark_soft_blocked(
self.mod._SCOPE_SINGLE, "add", "memory", f"content_{i}", "", _SID
)
# Adding one more should evict the oldest (content_0)
self.mod._mark_soft_blocked(self.mod._SCOPE_SINGLE, "add", "memory", "content_3", "", _SID)
# content_0's retry should no longer be available
assert not self.mod._consume_retry_if_allowed(
self.mod._SCOPE_SINGLE, "add", "memory", "content_0", "", _SID
)
# content_2's retry should still be available
assert self.mod._consume_retry_if_allowed(
self.mod._SCOPE_SINGLE, "add", "memory", "content_2", "", _SID
)
def test_cap_does_not_affect_other_sessions(self):
"""Cap is per-session; another session's retries are unaffected."""
self.mod._MAX_PENDING_RETRIES_PER_SESSION = 2
self.mod._mark_soft_blocked(
self.mod._SCOPE_SINGLE, "add", "memory", "content_a", "", "session-1"
)
self.mod._mark_soft_blocked(
self.mod._SCOPE_SINGLE, "add", "memory", "content_b", "", "session-2"
)
# Both should still be available
assert self.mod._consume_retry_if_allowed(
self.mod._SCOPE_SINGLE, "add", "memory", "content_a", "", "session-1"
)
assert self.mod._consume_retry_if_allowed(
self.mod._SCOPE_SINGLE, "add", "memory", "content_b", "", "session-2"
)
# ═══════════════════════════════════════════════════════════════════
# Regression tests for new patterns and behavior
# ═══════════════════════════════════════════════════════════════════
class TestNewPatternRegression(unittest.TestCase):
"""Regression tests for new regex patterns and guard behavior."""
def setUp(self):
self.mod = _load_mod()
self.mod._pending_retries.clear()
self.mod._session_state.clear()
# ── Case-insensitive TODO ──
def test_todo_case_insensitive(self):
assert self.mod._guard_placeholder("TODO") is not None
assert self.mod._guard_placeholder("Todo") is not None
assert self.mod._guard_placeholder("todo") is not None
# ── SHA uppercase ──
def test_sha_uppercase(self):
sha = "ABCDEF1234567890ABCDEF1234567890ABCDEF12"
assert self.mod._guard_placeholder(f"commit {sha}") is not None
def test_sha_mixed_case(self):
sha = "AbCdEf1234567890AbCdEf1234567890AbCdEf12"
assert self.mod._guard_placeholder(f"hash {sha}") is not None
# ── New date patterns ──
def test_date_chinese_format(self):
assert self.mod._guard_date("3月15日更新") is not None
assert self.mod._guard_date("12月1日") is not None
assert self.mod._guard_date("3月5號") is not None
def test_date_slash_format(self):
assert self.mod._guard_date("2026/03/15") is not None
def test_date_dot_format(self):
assert self.mod._guard_date("03.15") is not None
def test_date_relative_chinese(self):
assert self.mod._guard_date("本週五前完成") is not None
assert self.mod._guard_date("月底前處理") is not None
assert self.mod._guard_date("下個月初確認") is not None
# ── New placeholder patterns ──
def test_block_wip(self):
assert self.mod._guard_placeholder("WIP refactor") is not None
def test_block_tbd(self):
assert self.mod._guard_placeholder("TBD value") is not None
assert self.mod._guard_placeholder("FIXME here") is not None
assert self.mod._guard_placeholder("XXX check") is not None
def test_block_chinese_placeholder(self):
assert self.mod._guard_placeholder("只是測試") is not None
assert self.mod._guard_placeholder("測試寫入看看") is not None
assert self.mod._guard_placeholder("暫存資料") is not None
assert self.mod._guard_placeholder("稍後刪除") is not None
def test_block_test_memory(self):
assert self.mod._guard_placeholder("test memory entry") is not None
assert self.mod._guard_placeholder("testing entry") is not None
def test_block_smoke_record(self):
assert self.mod._guard_placeholder("smoke record") is not None
def test_block_sentinel_state(self):
assert self.mod._guard_placeholder("sentinel state active") is not None
# ── Should NOT match ──
def test_allow_top_n(self):
"""'只列 top 3' should NOT trigger PLACEHOLDER or CRON patterns."""
assert self.mod._guard_placeholder("只列 top 3") is None
def test_allow_if_backup_restorable(self):
"""'只有在已確認備份可還原後' should NOT trigger work_verb."""
assert self.mod._guard_work_verb("只有在已確認備份可還原後") is None
def test_allow_tmp_substring(self):
"""'tmp' alone was NOT added as a placeholder pattern."""
assert self.mod._guard_placeholder("tmp file") is None
assert self.mod._guard_placeholder("TMP") is None
# ── Hard ceiling at new threshold ──
def test_hard_ceiling_at_181(self):
content = "x" * 181
name, msg = self.mod._scan_content(content, _SID, action="add", target="memory")
assert name == "hard_ceiling"
assert msg is not None
# ── Soft block message contains SOFT BLOCK and matched text ──
def test_soft_block_message_format(self):
name, msg = self.mod._scan_content("fixed the bug", _SID, action="add", target="memory")
assert name == "work_verb"
assert "SOFT BLOCK" in msg
assert "fixed the bug" in msg
assert "命中 guard" in msg
assert "觸發片段" in msg
# ── Hard retry cannot bypass hard ceiling ──
def test_hard_ceiling_retry_still_blocks(self):
content = "x" * 200
# First attempt blocks
self.mod._scan_content(content, _SID, action="add", target="memory")
# Second attempt still blocks (hard ceiling does not allow retry)
name2, msg2 = self.mod._scan_content(content, _SID, action="add", target="memory")
assert name2 == "hard_ceiling"
assert msg2 is not None
# ── Date message shows matched text ──
def test_date_message_shows_matched(self):
_, msg = self.mod._scan_content("2026-07-05 test", _SID, action="add", target="memory")
assert msg is not None
assert "2026-07-05" in msg
# ── Placeholder message shows matched text ──
def test_placeholder_message_shows_matched(self):
_, msg = self.mod._scan_content("TODO: fix this", _SID, action="add", target="memory")
assert msg is not None
assert "TODO" in msg
# ── target=user does not suggest '改放 USER' ──
def test_target_user_does_not_mention_rewrite_to_user(self):
"""When target=user, the message should not suggest putting content in USER."""
_, msg = self.mod._scan_content("x" * 200, _SID, action="add", target="user")
assert msg is not None
# The message should not contain "改放 USER" (it should say "另存至 skill 或 docs")
assert "改放 USER" not in msg
# ── Fix 7: Regression tests ──
def test_cron_session_allows_top_n(self):
"""'只列 top 3' should NOT trigger cron_session guard."""
assert self.mod._guard_cron_session("只列 top 3,並說明取捨") is None
def test_placeholder_wip_lowercase(self):
"""Lowercase wip should still block (IGNORECASE — Fix 4)."""
assert self.mod._guard_placeholder("wip entry") is not None
assert self.mod._guard_placeholder("Wip entry") is not None
def test_placeholder_tbd_lowercase(self):
"""Lowercase tbd should still block."""
assert self.mod._guard_placeholder("tbd value") is not None
def test_placeholder_fixme_lowercase(self):
"""Lowercase fixme should still block."""
assert self.mod._guard_placeholder("fixme here") is not None
def test_placeholder_xxx_lowercase(self):
"""Lowercase xxx should still block."""
assert self.mod._guard_placeholder("xxx check") is not None
def test_placeholder_fixme_case_mixed(self):
"""FixMe (mixed case) should block (Fix 4)."""
assert self.mod._guard_placeholder("FixMe entry") is not None
def test_placeholder_list_memory_en(self):
"""list memory / memory list / show memory — hard block (Fix 5)."""
assert self.mod._guard_placeholder("list memory") is not None
assert self.mod._guard_placeholder("list memories") is not None
assert self.mod._guard_placeholder("memory list") is not None
assert self.mod._guard_placeholder("show memory") is not None
def test_placeholder_list_memory_cn(self):
"""Chinese list-memory phrases — hard block (Fix 5)."""
assert self.mod._guard_placeholder("列出記憶") is not None
assert self.mod._guard_placeholder("記憶清單") is not None
assert self.mod._guard_placeholder("查看記憶") is not None
assert self.mod._guard_placeholder("取得最新記憶") is not None
def test_date_relative_retry_still_hard_blocked(self):
"""Relative dates are now HARD date, so retry still blocks (Fix 3)."""
name1, msg1 = self.mod._scan_content("today's status", _SID, action="add", target="memory")
assert name1 == "date"
assert msg1 is not None
# Hard block: second attempt still blocks
name2, msg2 = self.mod._scan_content("today's status", _SID, action="add", target="memory")
assert name2 == "date"
assert msg2 is not None
# Fix 1: List-memory warning appended via _scan_content
def test_list_warning_appears_for_list_memory_en(self):
"""list memory should include _MSG_LIST_WARNING in the final message."""
_, msg = self.mod._scan_content("list memory", _SID, action="add", target="memory")
assert msg is not None
assert self.mod._MSG_LIST_WARNING.rstrip() in msg
def test_list_warning_appears_for_list_memory_cn(self):
"""列出記憶 should include _MSG_LIST_WARNING in the final message."""
_, msg = self.mod._scan_content("列出記憶", _SID, action="add", target="memory")
assert msg is not None
assert self.mod._MSG_LIST_WARNING.rstrip() in msg