833 lines
32 KiB
Python
833 lines
32 KiB
Python
"""
|
||
kuri-memory-guard — guards memory tool calls against stale content.
|
||
|
||
Two-tier system:
|
||
- **Hard block**: never allows the content through
|
||
- **Soft block**: first time blocks with explanation; same content retry passes
|
||
|
||
Only content that will still be useful next session belongs in memory.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import importlib.util
|
||
import logging
|
||
import re
|
||
import threading
|
||
import time
|
||
from collections.abc import Callable
|
||
from pathlib import Path
|
||
from typing import Any, cast
|
||
|
||
if __package__:
|
||
from .messages import ( # ty: ignore[unresolved-import] # Hermes loads this as a namespace package.
|
||
_MSG_ADD_INTRO,
|
||
_MSG_BATCH_FOOTER,
|
||
_MSG_BATCH_HEADER,
|
||
_MSG_CRON_SESSION_NOTE,
|
||
_MSG_DATE_HARD,
|
||
_MSG_HARD_CEILING,
|
||
_MSG_LENGTH_S1,
|
||
_MSG_LENGTH_S2,
|
||
_MSG_LENGTH_S3,
|
||
_MSG_LIST_WARNING,
|
||
_MSG_META_NOTE,
|
||
_MSG_PLACEHOLDER,
|
||
_MSG_REPLACE_INTRO,
|
||
_MSG_SOFT_TEMPLATE,
|
||
_MSG_USER_QUOTE_NOTE,
|
||
_MSG_WORK_VERB_NOTE,
|
||
)
|
||
else:
|
||
_messages_spec = importlib.util.spec_from_file_location(
|
||
"_kuri_memory_guard_messages",
|
||
Path(__file__).with_name("messages.py"),
|
||
)
|
||
if _messages_spec is None or _messages_spec.loader is None:
|
||
raise RuntimeError("Unable to load local memory-guard messages")
|
||
_messages = cast(Any, importlib.util.module_from_spec(_messages_spec))
|
||
_messages_spec.loader.exec_module(_messages)
|
||
_MSG_ADD_INTRO = _messages._MSG_ADD_INTRO
|
||
_MSG_BATCH_FOOTER = _messages._MSG_BATCH_FOOTER
|
||
_MSG_BATCH_HEADER = _messages._MSG_BATCH_HEADER
|
||
_MSG_CRON_SESSION_NOTE = _messages._MSG_CRON_SESSION_NOTE
|
||
_MSG_DATE_HARD = _messages._MSG_DATE_HARD
|
||
_MSG_HARD_CEILING = _messages._MSG_HARD_CEILING
|
||
_MSG_LENGTH_S1 = _messages._MSG_LENGTH_S1
|
||
_MSG_LENGTH_S2 = _messages._MSG_LENGTH_S2
|
||
_MSG_LENGTH_S3 = _messages._MSG_LENGTH_S3
|
||
_MSG_LIST_WARNING = _messages._MSG_LIST_WARNING
|
||
_MSG_META_NOTE = _messages._MSG_META_NOTE
|
||
_MSG_PLACEHOLDER = _messages._MSG_PLACEHOLDER
|
||
_MSG_REPLACE_INTRO = _messages._MSG_REPLACE_INTRO
|
||
_MSG_SOFT_TEMPLATE = _messages._MSG_SOFT_TEMPLATE
|
||
_MSG_USER_QUOTE_NOTE = _messages._MSG_USER_QUOTE_NOTE
|
||
_MSG_WORK_VERB_NOTE = _messages._MSG_WORK_VERB_NOTE
|
||
|
||
logger = logging.getLogger("kuri_memory_guard")
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Guard type tags
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
_HARD = "hard"
|
||
_SOFT = "soft"
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Hard Guard 1 — Dates (always stale)
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
# ISO date/time (longest/full patterns first — Fix 2)
|
||
_ISO_DATETIME = re.compile(r"\b\d{4}-\d{2}-\d{2}T")
|
||
_ISO_DATE = re.compile(r"\b\d{4}-\d{2}-\d{2}\b")
|
||
# Slash dates — full year before short M/D to avoid partial match
|
||
_SLASH_DATE_FULL = re.compile(r"\b\d{4}/\d{2}/\d{2}\b")
|
||
_SLASH_DATE_SHORT = re.compile(r"\b\d{1,2}/\d{1,2}\b")
|
||
# Chinese date format
|
||
_CHINESE_DATE = re.compile(r"\d{1,2}月\d{1,2}[日號]")
|
||
# Dot date — valid month/day ranges only, with digit-boundary lookarounds (Fix 1)
|
||
_DOT_DATE = re.compile(r"(?<!\d)(?:0[1-9]|1[0-2])\.(?:0[1-9]|[12]\d|3[01])(?!\d)")
|
||
# Relative temporal markers — moved from work-verb (soft) to date (hard) (Fix 3)
|
||
_RELATIVE_DATE_EN = re.compile(
|
||
r"\b(?:today|yesterday|tomorrow|this week|last week|next week|"
|
||
r"this month|last month|next month)\b",
|
||
re.IGNORECASE,
|
||
)
|
||
_RELATIVE_DATE_CN = re.compile(
|
||
r"(?:今天|昨天|明天|本週|這週|上週|下週|本月|這個月|"
|
||
r"上個月|下個月|剛剛|稍早)"
|
||
)
|
||
# Weekday range / week references
|
||
_WEEKDAY_RELATIVE = re.compile(
|
||
r"(?:本週[一二三四五六日天]|上週[一二三四五六日天]|下週[一二三四五六日天])"
|
||
)
|
||
_WEEK_REFERENCE = re.compile(r"(?:本星期|上星期|下星期)")
|
||
# Fixed Chinese relative markers
|
||
_CHINESE_RELATIVE = re.compile(r"(?:本週五|月底|下個月初)")
|
||
|
||
_ALL_DATE_PATTERNS: list[re.Pattern] = [
|
||
# Most specific first — ensures longer matches win over shorter sub-matches
|
||
_ISO_DATETIME,
|
||
_ISO_DATE,
|
||
_SLASH_DATE_FULL,
|
||
# Chinese weekday-specific patterns (本週一, 上週五, 下週三) before broad 本週/上週/下週
|
||
_WEEKDAY_RELATIVE,
|
||
# Chinese specific relative patterns (月底, 下個月初) before broad 下個月
|
||
_CHINESE_RELATIVE,
|
||
_WEEK_REFERENCE,
|
||
_CHINESE_DATE,
|
||
_DOT_DATE,
|
||
_RELATIVE_DATE_EN,
|
||
_RELATIVE_DATE_CN,
|
||
_SLASH_DATE_SHORT,
|
||
]
|
||
|
||
|
||
def _guard_date(content: str) -> str | None:
|
||
"""Return matched date text if content contains a date pattern, else None."""
|
||
for p in _ALL_DATE_PATTERNS:
|
||
m = p.search(content)
|
||
if m:
|
||
return m.group(0)
|
||
return None
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Hard Guard 2 — Placeholder / temp / TODO (always transient)
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
_PLACEHOLDER_PATTERNS: list[re.Pattern] = [
|
||
re.compile(r"\bTODO\b", re.IGNORECASE),
|
||
re.compile(r"placeholder", re.IGNORECASE),
|
||
re.compile(r"\btemp\b", re.IGNORECASE),
|
||
re.compile(r"\bdummy\b", re.IGNORECASE),
|
||
re.compile(r"\bphase\s+\d+\s+(?:done|complete|finished)\b", re.IGNORECASE),
|
||
# Session-specific labels — always session-bound
|
||
re.compile(
|
||
r"\b(?:session|current|today)(?:'s)?\s*"
|
||
r"(?:task|work|progress|update|log|note|status|goal|focus)",
|
||
re.IGNORECASE,
|
||
),
|
||
# Codex process session IDs — always execution artifacts
|
||
re.compile(r"\bproc_[a-f0-9]{12}\b"),
|
||
# Probe state — cleanup artifact
|
||
re.compile(r"\bprobe\s+(?:current\s+)?state\b", re.IGNORECASE),
|
||
# Bare "probe" — probe/temp placeholder
|
||
re.compile(r"\bprobe\b", re.IGNORECASE),
|
||
# Commit SHA — full 40-char standalone (case-insensitive hex)
|
||
re.compile(r"\b[a-fA-F0-9]{40}\b"),
|
||
re.compile(
|
||
r"\b(?:commit|sha|hash)\s*[:#]?\s*[a-f0-9]{7,39}\b",
|
||
re.IGNORECASE,
|
||
),
|
||
# New placeholder patterns (Fix 4: combined case-insensitive)
|
||
re.compile(r"\b(?:WIP|TBD|FIXME|XXX)\b", re.IGNORECASE),
|
||
re.compile(r"(?:只是測試|測試寫入|試寫|佔位|暫存|臨時內容|稍後刪除|請忽略)"),
|
||
re.compile(r"\btest memory\b", re.IGNORECASE),
|
||
re.compile(r"\btesting entry\b", re.IGNORECASE),
|
||
re.compile(r"\bsmoke record\b", re.IGNORECASE),
|
||
re.compile(r"\bsentinel state\b", re.IGNORECASE),
|
||
# List-memory probe matchers (Fix 5 — hard block)
|
||
re.compile(r"\blist (?:memory|memories)\b", re.IGNORECASE),
|
||
re.compile(r"\bmemory list\b", re.IGNORECASE),
|
||
re.compile(r"\bshow memory\b", re.IGNORECASE),
|
||
re.compile(r"(?:列出記憶|記憶清單|查看記憶|取得最新記憶)"),
|
||
]
|
||
|
||
|
||
def _has_list_indicator(matched_text: str) -> bool:
|
||
"""Check if matched text suggests user is probing for a memory list."""
|
||
indicators = [
|
||
"probe",
|
||
"dummy",
|
||
"placeholder",
|
||
"test",
|
||
"試",
|
||
"測試",
|
||
"佔位",
|
||
"暫存",
|
||
"list memory",
|
||
"list memories",
|
||
"memory list",
|
||
"show memory",
|
||
"列出記憶",
|
||
"記憶清單",
|
||
"查看記憶",
|
||
"取得最新記憶",
|
||
]
|
||
lower = matched_text.lower()
|
||
return any(ind in lower for ind in indicators)
|
||
|
||
|
||
def _guard_placeholder(content: str) -> str | None:
|
||
"""Return matched placeholder text if found, else None."""
|
||
for p in _PLACEHOLDER_PATTERNS:
|
||
m = p.search(content)
|
||
if m:
|
||
return m.group(0)
|
||
return None
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Soft Guard 3 — Work verbs (ambiguous; could be long-term lesson)
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
_WORK_VERB_PATTERNS: list[re.Pattern] = [
|
||
# Fix verbs
|
||
re.compile(
|
||
r"\b(?:fix|fixes|fixed|fixing)\s+(?:the\s+)?"
|
||
r"(?:bug|issue|problem|regression|edge\s*case)",
|
||
re.IGNORECASE,
|
||
),
|
||
# Submit/merge/push verbs
|
||
re.compile(
|
||
r"\b(?:submit|submitted|submitting|merge|merged|merging|"
|
||
r"push|pushed|pushing)\s+(?:a\s+)?"
|
||
r"(?:PR|patch|commit|branch|change|PRs)",
|
||
re.IGNORECASE,
|
||
),
|
||
# PR/issue numbers — fixed lookaround pattern
|
||
re.compile(
|
||
r"(?<!\w)(?:(?:PR|issue|patch|bug)\s*#?:?\s*\d+|#\d{3,})(?!\w)",
|
||
re.IGNORECASE,
|
||
),
|
||
# Current-status verbs
|
||
re.compile(
|
||
r"\b(?:currently|now)\s+"
|
||
r"(?:working|debugging|fixing|implementing|investigating|"
|
||
r"researching|refactoring|migrating)",
|
||
re.IGNORECASE,
|
||
),
|
||
# Next-step markers — English (with \b)
|
||
re.compile(r"\bnext\s+step\b", re.IGNORECASE),
|
||
# Next-step markers — Chinese (no \b)
|
||
re.compile(r"(?:^|[\n。;:])\s*(?:下一步|接下來)"),
|
||
# Chinese status verbs
|
||
re.compile(r"(?:正在|目前)\s*(?:處理|除錯|調查|研究|修復|開發|測試|部署)"),
|
||
# Chinese completion markers (fixed: requires start or line break)
|
||
re.compile(
|
||
r"(?:^|[\n。;:])\s*已(?:修復|提交|推送|合併|建立|刪除|更新|修改|"
|
||
r"解決|修正|關閉|開啟|補|上|記錄|標記|設定|"
|
||
r"檢查|確認|驗證|處理|完成)"
|
||
),
|
||
# "done with / completed with" style
|
||
re.compile(
|
||
r"\b(?:done|completed|finished)\s+(?:with|fixing|debugging|"
|
||
r"implementing|testing|migrating|investigating)",
|
||
re.IGNORECASE,
|
||
),
|
||
# cron/session_search/session_id (often sedimentary but can be legitimate)
|
||
re.compile(r"\b(?:cron|session_search|session_id)\b"),
|
||
# Standalone status/progress labels
|
||
re.compile(
|
||
r"\b(?:progress|status|update|work log|handoff|checkpoint)\s*[::\-]",
|
||
re.IGNORECASE,
|
||
),
|
||
re.compile(r"(?:進度|狀態|更新|工作紀錄|交接|checkpoint)\s*[::\-]"),
|
||
]
|
||
|
||
|
||
def _guard_work_verb(content: str) -> str | None:
|
||
"""Return matched work-verb text if found, else None."""
|
||
for p in _WORK_VERB_PATTERNS:
|
||
m = p.search(content)
|
||
if m:
|
||
return m.group(0)
|
||
return None
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Soft Guard 4 — User quote / incident narrative
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
_USER_QUOTE_PATTERNS: list[re.Pattern] = [
|
||
re.compile(
|
||
r"(?:主人說|主人回|主人要求|User said|使用者說|使用者回覆|"
|
||
r"user replied|user responded|他說|她說|你說)",
|
||
re.IGNORECASE,
|
||
),
|
||
# Incident/postmortem markers
|
||
re.compile(
|
||
r"\b(?:incident|postmortem|timeline|retrospective|root cause|rca)\b",
|
||
re.IGNORECASE,
|
||
),
|
||
re.compile(r"(?:事故|時間線|復盤|檢討|根因)"),
|
||
# Reflexive "lesson learned" — often sedimentary
|
||
re.compile(
|
||
r"\b(?:lesson learned|learned that|takeaway|note to self)\b",
|
||
re.IGNORECASE,
|
||
),
|
||
re.compile(r"(?:學到了|我學會|被糾正|被提醒|下次要記得|以後要記得|記取教訓)"),
|
||
]
|
||
|
||
|
||
def _guard_user_quote(content: str) -> str | None:
|
||
"""Return matched user-quote text if found, else None."""
|
||
for p in _USER_QUOTE_PATTERNS:
|
||
m = p.search(content)
|
||
if m:
|
||
return m.group(0)
|
||
return None
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Soft Guard 5 — Cron / parallel session artifacts
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
_CRON_SESSION_PATTERNS: list[re.Pattern] = [
|
||
re.compile(
|
||
r"(?:平行\s*session|parallel session|parallel Kuri|parallel kuri|"
|
||
r"coverage edge|手動\s*trigger|daily auto-commit|\[SILENT\])",
|
||
re.IGNORECASE,
|
||
),
|
||
]
|
||
|
||
|
||
def _guard_cron_session(content: str) -> str | None:
|
||
"""Return matched cron/session text if found, else None."""
|
||
for p in _CRON_SESSION_PATTERNS:
|
||
m = p.search(content)
|
||
if m:
|
||
return m.group(0)
|
||
return None
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Soft Guard 6 — Version snapshot & memory cleanup meta
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
_META_PATTERNS: list[re.Pattern] = [
|
||
# Version/project snapshot — specific version numbers are stale
|
||
re.compile(
|
||
r"\b(?:version|v)\s*\d+\.\d+(?:\.\d+)?\b",
|
||
re.IGNORECASE,
|
||
),
|
||
# Memory/skill cleanup meta — recursive sedimentation
|
||
re.compile(
|
||
r"(?:記憶條目|memory cleanup|memory clean|skill 肥大|skill bloat|"
|
||
r"cleanup|housekeeping|trim|sediment|sprawl|優化方向|改善方向)",
|
||
re.IGNORECASE,
|
||
),
|
||
# Re-fetchable from canonical source — don't duplicate
|
||
re.compile(
|
||
r"\b(?:git log|source code|repo code|official docs|"
|
||
r"release notes|changelog)\b",
|
||
re.IGNORECASE,
|
||
),
|
||
re.compile(r"(?:原始碼|程式碼|文件站|官方文件|變更紀錄|release note)"),
|
||
]
|
||
|
||
|
||
def _guard_meta(content: str) -> str | None:
|
||
"""Return matched meta text if found, else None."""
|
||
for p in _META_PATTERNS:
|
||
m = p.search(content)
|
||
if m:
|
||
return m.group(0)
|
||
return None
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Soft Guard 7 — Length (three-stage: refine / split / classify)
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
_S1_LIMIT = 80
|
||
_S2_LIMIT = 120
|
||
_S3_LIMIT = 150
|
||
|
||
# ── Hard ceiling — absolute upper limit, not overrideable by retry ──
|
||
_HARD_CEILING = 180
|
||
|
||
# Markers that suggest multiple independent rules in one entry.
|
||
# When >= S1_LIMIT and >= 3 markers are found, early-trigger S2 (before reaching S2_LIMIT).
|
||
_SPLIT_MARKERS = [
|
||
"另外",
|
||
"同時",
|
||
"而且",
|
||
"以及",
|
||
"還有",
|
||
"不要",
|
||
"不能",
|
||
"必須",
|
||
"應該",
|
||
]
|
||
|
||
|
||
def _split_marker_count(content: str) -> int:
|
||
"""Count occurrences of split markers that suggest bundled rules."""
|
||
return sum(content.count(m) for m in _SPLIT_MARKERS)
|
||
|
||
|
||
def _guard_length(content: str) -> str | None:
|
||
"""Three-stage length guard with early S2 trigger for bundled rules (80/120/150; hard ceiling 180)."""
|
||
n = len(content)
|
||
markers = _split_marker_count(content)
|
||
if n >= _S3_LIMIT:
|
||
return _MSG_LENGTH_S3.format(n=n)
|
||
if n >= _S2_LIMIT:
|
||
return _MSG_LENGTH_S2.format(n=n)
|
||
if n >= _S1_LIMIT and markers >= 3:
|
||
return _MSG_LENGTH_S2.format(n=n) # early S2: too many split markers for S1 range
|
||
if n >= _S1_LIMIT:
|
||
return _MSG_LENGTH_S1.format(n=n)
|
||
return None
|
||
|
||
|
||
def _is_hard_ceiling(content: str) -> str | None:
|
||
"""Return hard-ceiling block message if content exceeds absolute limit."""
|
||
n = len(content)
|
||
if n >= _HARD_CEILING:
|
||
return _MSG_HARD_CEILING.format(n=n)
|
||
return None
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Guard registry — first match wins (hard checked before soft)
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
_GuardFn = Callable[[str], str | None]
|
||
|
||
_GUARD_CONFIGS: list[tuple[str, str, _GuardFn, str]] = [
|
||
("hard_ceiling", _HARD, _is_hard_ceiling, _MSG_HARD_CEILING),
|
||
("date", _HARD, _guard_date, _MSG_DATE_HARD),
|
||
("placeholder", _HARD, _guard_placeholder, _MSG_PLACEHOLDER),
|
||
("work_verb", _SOFT, _guard_work_verb, _MSG_SOFT_TEMPLATE),
|
||
("user_quote", _SOFT, _guard_user_quote, _MSG_SOFT_TEMPLATE),
|
||
("cron_session", _SOFT, _guard_cron_session, _MSG_SOFT_TEMPLATE),
|
||
("meta", _SOFT, _guard_meta, _MSG_SOFT_TEMPLATE),
|
||
("length", _SOFT, _guard_length, ""),
|
||
]
|
||
|
||
|
||
def _normalize(value: str) -> str:
|
||
"""Normalize a string for fingerprinting."""
|
||
return value.strip()
|
||
|
||
|
||
# Scope tags for fingerprinting single vs batch operations.
|
||
_SCOPE_SINGLE = "single"
|
||
_SCOPE_BATCH = "batch"
|
||
|
||
|
||
def _operation_fingerprint(
|
||
scope: str,
|
||
action: str,
|
||
target: str,
|
||
content: str,
|
||
old_text: str = "",
|
||
) -> str:
|
||
"""Stable fingerprint of the full write intent.
|
||
|
||
Includes scope (single/batch), action, target, normalized content, and
|
||
(for replace) normalized old_text so that changing any field produces a
|
||
different fingerprint.
|
||
"""
|
||
parts = [
|
||
scope,
|
||
_normalize(action),
|
||
_normalize(target),
|
||
_normalize(content),
|
||
_normalize(old_text),
|
||
]
|
||
return hashlib.sha256("\x1f".join(parts).encode()).hexdigest()
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Soft-block tracking
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
# ── Two separate state concepts ────────────────────────────────────────
|
||
# 1. _pending_retries: short-lived one-time retry fingerprints (5 min TTL)
|
||
# Used to allow exactly one retry of the same operation after a soft block.
|
||
# 2. _session_state: general per-session soft guard tracking (24h TTL, LRU cap)
|
||
# Used for session-level metadata cleanup. NOT for retry authorization.
|
||
|
||
_RETRY_WINDOW_SECONDS = 5 * 60 # 5-minute one-time retry window
|
||
_STATE_TTL_SECONDS = 24 * 60 * 60 # general session state TTL
|
||
_MAX_TRACKED_SESSIONS = 1024
|
||
|
||
# session_id -> {fingerprint -> expiry_timestamp}
|
||
# A fingerprint here means the operation was soft-blocked; ONE retry of the
|
||
# exact same operation will pass. After passing (or expiry), it's consumed.
|
||
_pending_retries: dict[str, dict[str, float]] = {}
|
||
# session_id -> last_accessed_timestamp (for LRU/ TTL cleanup)
|
||
_session_state: dict[str, float] = {}
|
||
_soft_lock = threading.Lock()
|
||
|
||
|
||
def _clean_session_state(now: float) -> None:
|
||
"""Remove expired sessions and evict least-recently-used excess state."""
|
||
# Clean expired session-level state
|
||
expired = [
|
||
session_id
|
||
for session_id, last_seen in _session_state.items()
|
||
if now - last_seen >= _STATE_TTL_SECONDS
|
||
]
|
||
for session_id in expired:
|
||
_session_state.pop(session_id, None)
|
||
_pending_retries.pop(session_id, None)
|
||
|
||
excess = len(_session_state) - _MAX_TRACKED_SESSIONS
|
||
if excess > 0:
|
||
oldest = sorted(_session_state, key=lambda sid: _session_state[sid])
|
||
for session_id in oldest[:excess]:
|
||
_session_state.pop(session_id, None)
|
||
_pending_retries.pop(session_id, None)
|
||
|
||
|
||
def _clean_pending_retries(session_id: str, now: float) -> None:
|
||
"""Remove expired retry fingerprints for one session."""
|
||
retries = _pending_retries.get(session_id)
|
||
if not retries:
|
||
return
|
||
expired = [fp for fp, expiry in retries.items() if now >= expiry]
|
||
for fp in expired:
|
||
retries.pop(fp, None)
|
||
|
||
|
||
def _ensure_session_capacity(session_id: str) -> None:
|
||
"""Reserve one session slot, evicting the least recently used if needed."""
|
||
if session_id in _session_state:
|
||
return
|
||
if len(_session_state) >= _MAX_TRACKED_SESSIONS:
|
||
oldest = min(_session_state, key=lambda key: _session_state[key])
|
||
_session_state.pop(oldest, None)
|
||
_pending_retries.pop(oldest, None)
|
||
|
||
|
||
_MAX_PENDING_RETRIES_PER_SESSION = 128
|
||
|
||
|
||
def _consume_retry_if_allowed(
|
||
scope: str,
|
||
action: str,
|
||
target: str,
|
||
content: str,
|
||
old_text: str,
|
||
session_id: str,
|
||
) -> bool:
|
||
"""Atomically check and consume a pending one-time retry.
|
||
|
||
Returns True if the fingerprint was found and consumed; False otherwise.
|
||
The check and removal happen under a single lock acquisition so that
|
||
concurrent calls for the same fingerprint can succeed at most once.
|
||
"""
|
||
fp = _operation_fingerprint(scope, action, target, content, old_text)
|
||
now = time.time()
|
||
with _soft_lock:
|
||
_clean_session_state(now)
|
||
retries = _pending_retries.get(session_id)
|
||
if not retries:
|
||
return False
|
||
_clean_pending_retries(session_id, now)
|
||
if fp in retries:
|
||
retries.pop(fp, None)
|
||
_session_state[session_id] = now
|
||
return True
|
||
return False
|
||
|
||
|
||
def _mark_soft_blocked(
|
||
scope: str,
|
||
action: str,
|
||
target: str,
|
||
content: str,
|
||
old_text: str,
|
||
session_id: str,
|
||
) -> None:
|
||
"""Record a soft block, creating a short-lived pending retry fingerprint."""
|
||
fp = _operation_fingerprint(scope, action, target, content, old_text)
|
||
now = time.time()
|
||
expiry = now + _RETRY_WINDOW_SECONDS
|
||
with _soft_lock:
|
||
_clean_session_state(now)
|
||
_ensure_session_capacity(session_id)
|
||
_session_state[session_id] = now
|
||
retries = _pending_retries.setdefault(session_id, {})
|
||
_clean_pending_retries(session_id, now)
|
||
# Cap per-session pending retries (evict oldest expiry)
|
||
if len(retries) >= _MAX_PENDING_RETRIES_PER_SESSION:
|
||
oldest_fp = min(retries, key=lambda k: retries[k])
|
||
retries.pop(oldest_fp, None)
|
||
retries[fp] = expiry
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Content scanning
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
|
||
_GuardHit = tuple[str, str, str, str] # (name, guard_type, msg_template, matched_text)
|
||
|
||
|
||
def _build_soft_message(name: str, matched_text: str) -> str:
|
||
"""Build a soft block message from the shared template and guard-specific note."""
|
||
guard_notes = {
|
||
"user_quote": _MSG_USER_QUOTE_NOTE,
|
||
"work_verb": _MSG_WORK_VERB_NOTE,
|
||
"cron_session": _MSG_CRON_SESSION_NOTE,
|
||
"meta": _MSG_META_NOTE,
|
||
}
|
||
note = guard_notes.get(name, "")
|
||
return _MSG_SOFT_TEMPLATE.format(
|
||
guard_name=name,
|
||
matched_text=matched_text,
|
||
guard_specific_note=note,
|
||
)
|
||
|
||
|
||
def _build_date_message(matched_text: str) -> str:
|
||
"""Build a date hard block message with the matched text."""
|
||
return _MSG_DATE_HARD.format(matched=matched_text)
|
||
|
||
|
||
def _build_placeholder_message(matched_text: str) -> str:
|
||
"""Build a placeholder hard block message, optionally appending list warning."""
|
||
has_list = _has_list_indicator(matched_text)
|
||
list_warning = _MSG_LIST_WARNING if has_list else ""
|
||
return _MSG_PLACEHOLDER.format(matched=matched_text, list_warning=list_warning)
|
||
|
||
|
||
def _classify_content(content: str) -> list[_GuardHit]:
|
||
"""Purely classify guard hits, returning hard hits before soft hits.
|
||
|
||
Each hit is (name, guard_type, msg_template, matched_text).
|
||
For length/hard-ceiling guards, matched_text is the pre-formatted message.
|
||
"""
|
||
hits: list[_GuardHit] = []
|
||
for name, guard_type, guard_fn, default_msg in _GUARD_CONFIGS:
|
||
result = guard_fn(content)
|
||
if result is None:
|
||
continue
|
||
# For length & hard-ceiling, guard_fn returns the formatted message directly
|
||
if name in ("length", "hard_ceiling"):
|
||
hits.append((name, guard_type, "", result))
|
||
else:
|
||
hits.append((name, guard_type, default_msg, result))
|
||
if guard_type == _HARD:
|
||
return hits
|
||
return hits
|
||
|
||
|
||
def _render_single_block(
|
||
hits: list[_GuardHit],
|
||
*,
|
||
action: str = "",
|
||
target: str = "",
|
||
) -> tuple[str, str | None]:
|
||
"""Purely render one operation's classified guard hits."""
|
||
if not hits:
|
||
return "", None
|
||
name, guard_type, msg_template, matched_or_msg = hits[0]
|
||
|
||
if name == "hard_ceiling":
|
||
message = matched_or_msg # pre-formatted
|
||
if target == "user":
|
||
message = message.replace("或改放 skill/docs", "或另存至 skill 或 docs")
|
||
elif name == "date":
|
||
message = _build_date_message(matched_or_msg)
|
||
elif name == "placeholder":
|
||
message = _build_placeholder_message(matched_or_msg)
|
||
elif guard_type == _SOFT and name != "length":
|
||
message = _build_soft_message(name, matched_or_msg)
|
||
if action == "replace":
|
||
message = _MSG_REPLACE_INTRO + "\n" + message
|
||
elif action == "add":
|
||
message = _MSG_ADD_INTRO + "\n" + message
|
||
elif name == "length":
|
||
message = matched_or_msg # pre-formatted
|
||
if target == "user":
|
||
message = message.replace("或改放 skill/docs", "或另存至 skill 或 docs")
|
||
else:
|
||
message = matched_or_msg
|
||
|
||
extra_names = [extra_name for extra_name, _, _, _ in hits[1:]]
|
||
if extra_names:
|
||
message += (
|
||
f"\n\n同時也會命中以下 guard:{'、'.join(extra_names)}。"
|
||
"建議一併處理後重送,避免逐關被擋。"
|
||
)
|
||
return name, message
|
||
|
||
|
||
def _scan_content(
|
||
content: str,
|
||
session_id: str,
|
||
*,
|
||
action: str = "",
|
||
target: str = "",
|
||
old_text: str = "",
|
||
scope: str = _SCOPE_SINGLE,
|
||
) -> tuple[str, str | None]:
|
||
"""Classify, apply retry state, then render one content block if needed."""
|
||
hits = _classify_content(content)
|
||
if not hits:
|
||
return "", None
|
||
if hits[0][1] == _HARD:
|
||
return _render_single_block(hits, action=action, target=target)
|
||
# Soft guard: atomically check and consume one-time retry
|
||
if _consume_retry_if_allowed(scope, action, target, content, old_text, session_id):
|
||
return "", None
|
||
_mark_soft_blocked(scope, action, target, content, old_text, session_id)
|
||
return _render_single_block(hits, action=action, target=target)
|
||
|
||
|
||
def _operation_is_blocked(op: Any, session_id: str) -> str | None:
|
||
"""Return block msg if a single operation is blocked, else None."""
|
||
if not isinstance(op, dict):
|
||
return None
|
||
_, msg = _scan_content(
|
||
str(op.get("content", "")),
|
||
session_id,
|
||
action=str(op.get("action", "")),
|
||
target=str(op.get("target", "")),
|
||
old_text=str(op.get("old_text", "")),
|
||
scope=_SCOPE_BATCH,
|
||
)
|
||
return msg
|
||
|
||
|
||
def _batch_guard_hits(operations: list[Any]) -> list[tuple[int, list[_GuardHit]]]:
|
||
"""Purely classify all guarded operation entries for batch hygiene."""
|
||
hits: list[tuple[int, list[_GuardHit]]] = []
|
||
for index, operation in enumerate(operations, start=1):
|
||
if not isinstance(operation, dict):
|
||
continue
|
||
operation_hits = _classify_content(str(operation.get("content", "")))
|
||
if operation_hits:
|
||
hits.append((index, operation_hits))
|
||
return hits
|
||
|
||
|
||
def _render_batch_block(hits: list[tuple[int, list[_GuardHit]]]) -> str:
|
||
"""Purely render per-item breakdown for multiple guarded operations.
|
||
|
||
Format:
|
||
批次記憶操作中有多筆內容命中防護:
|
||
第 1 筆:date(觸發:「3/15 update」)
|
||
第 3 筆:placeholder(觸發:「TODO: test this」)
|
||
[footer]
|
||
"""
|
||
lines: list[str] = [_MSG_BATCH_HEADER]
|
||
for index, operation_hits in hits:
|
||
hit = operation_hits[0] # first hit for this operation
|
||
hit_name, _, _, hit_matched = hit
|
||
# For length/hard_ceiling, hit_matched is a formatted message; use name only
|
||
if hit_name in ("length", "hard_ceiling"):
|
||
item = f"第 {index} 筆:{hit_name}"
|
||
else:
|
||
item = f"第 {index} 筆:{hit_name}(觸發:「{hit_matched}」)"
|
||
lines.append(item)
|
||
# Add extra hit names if any operation has multiple hits
|
||
for index, operation_hits in hits:
|
||
extra_names = [n for n, _, _, _ in operation_hits[1:]]
|
||
if extra_names:
|
||
lines.append(f"(第 {index} 筆同時也會命中:{'、'.join(extra_names)})")
|
||
lines.append(_MSG_BATCH_FOOTER)
|
||
return "\n".join(lines)
|
||
|
||
|
||
def _get_block_msg(args: dict[str, Any], session_id: str) -> str | None:
|
||
"""Return one focused block or a compact multi-operation batch summary."""
|
||
_, msg = _scan_content(
|
||
str(args.get("content", "")),
|
||
session_id,
|
||
action=str(args.get("action", "")),
|
||
target=str(args.get("target", "")),
|
||
old_text=str(args.get("old_text", "")),
|
||
)
|
||
if msg is not None:
|
||
return msg
|
||
|
||
operations = args.get("operations", [])
|
||
if not isinstance(operations, list):
|
||
return None
|
||
|
||
batch_hits = _batch_guard_hits(operations)
|
||
if len(batch_hits) >= 2:
|
||
return _render_batch_block(batch_hits)
|
||
|
||
for op in operations:
|
||
msg = _operation_is_blocked(op, session_id)
|
||
if msg is not None:
|
||
return msg
|
||
|
||
return None
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Hook
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
|
||
def _on_pre_tool_call(
|
||
tool_name: str = "",
|
||
args: Any = None,
|
||
session_id: str = "",
|
||
**_: Any,
|
||
) -> dict[str, str] | None:
|
||
"""Block memory calls whose content matches any guard."""
|
||
if tool_name != "memory" or not isinstance(args, dict):
|
||
return None
|
||
|
||
msg = _get_block_msg(args, session_id)
|
||
if msg is not None:
|
||
logger.warning(
|
||
"kuri-memory-guard: blocked memory write (session=%s)",
|
||
session_id,
|
||
)
|
||
return {"action": "block", "message": msg}
|
||
|
||
return None
|
||
|
||
|
||
def register(ctx) -> None:
|
||
"""Register the pre_tool_call hook."""
|
||
ctx.register_hook("pre_tool_call", _on_pre_tool_call)
|
||
logger.info(
|
||
"kuri-memory-guard registered — %d guards (%d hard, %d soft)",
|
||
len(_GUARD_CONFIGS),
|
||
sum(1 for _, t, _, _ in _GUARD_CONFIGS if t == _HARD),
|
||
sum(1 for _, t, _, _ in _GUARD_CONFIGS if t == _SOFT),
|
||
)
|