agent-memory-hygiene 0.1.0__tar.gz

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 agent-memory-hygiene contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: agent-memory-hygiene
3
+ Version: 0.1.0
4
+ Summary: Pure-policy write-time hygiene for agent memory: what to store, what to drop, and whose fact it is.
5
+ Author: agent-memory-hygiene contributors
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/AirXsLink/agent-memory-hygiene
8
+ Project-URL: Repository, https://github.com/AirXsLink/agent-memory-hygiene
9
+ Project-URL: Issues, https://github.com/AirXsLink/agent-memory-hygiene/issues
10
+ Project-URL: Changelog, https://github.com/AirXsLink/agent-memory-hygiene/blob/main/CHANGELOG.md
11
+ Keywords: agent,memory,llm,hygiene,attribution
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: License :: OSI Approved :: MIT License
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Provides-Extra: test
25
+ Requires-Dist: pytest>=8; extra == "test"
26
+ Dynamic: license-file
27
+
28
+ # agent-memory-hygiene
29
+
30
+ [English](https://github.com/AirXsLink/agent-memory-hygiene/blob/main/README.md) | [简体中文](https://github.com/AirXsLink/agent-memory-hygiene/blob/main/README.zh-CN.md)
31
+
32
+ Pure-policy write-time hygiene for agent memory: what to store, what to drop, and whose fact it is.
33
+
34
+ ## Problem
35
+
36
+ Most agent-memory projects optimize retrieval: embeddings, re-ranking, recency, similarity thresholds. Very few ask the cheaper question first: **should this ever have been written?**
37
+
38
+ A store that accepts everything becomes a log. Tool output, stack traces, pasted links, questions and greetings all drift in, and the only remaining defense is a higher similarity threshold at read time. That is a patch on the retrieval side, not a decision on the write side.
39
+
40
+ The second failure is attribution. An extractor turns "小雨的妈妈是老师" into "the user is a teacher", or "豆豆特别能吃" into "the user eats a lot". The fact is real; the subject is wrong. Retrieval cannot detect this, because the stored sentence looks perfectly normal.
41
+
42
+ This library covers both, with pure functions and no model calls.
43
+
44
+ **At a glance:**
45
+
46
+ | Input | Decision |
47
+ | --- | --- |
48
+ | `""` / whitespace | `empty` |
49
+ | Shorter than 8 chars | `too_short` |
50
+ | Longer than 2000 chars | `too_long` |
51
+ | More than 12 non-empty lines | `too_many_lines` |
52
+ | Contains a traceback / `WinError` | `error_dump` |
53
+ | Only a URL, little else | `link_only` |
54
+ | Ends as a short question | `question` |
55
+ | Short greeting | `chitchat` |
56
+ | Everything else | `ok` |
57
+ | "我的妈妈是老师" | `relation_subject` flag |
58
+ | "豆豆特别能吃" (豆豆 is a known pet) | `pet_subject` flag |
59
+
60
+ ## Install
61
+
62
+ ```bash
63
+ pip install -e .
64
+ ```
65
+
66
+ ## Quick Start
67
+
68
+ ```python
69
+ from agent_memory_hygiene import MemoryHygieneConfig, assess_write, assess_attribution
70
+
71
+ verdict = assess_write("用户喜欢喝咖啡和茶")
72
+ print(verdict.ok, verdict.reason) # True ok
73
+
74
+ verdict = assess_write("明天下午的会议是几点?")
75
+ print(verdict.ok, verdict.reason) # False question
76
+
77
+ cfg = MemoryHygieneConfig(known_pets=("豆豆",))
78
+ risk = assess_attribution("豆豆特别能吃", cfg)
79
+ print(risk.shifted, risk.kind, risk.subject) # True pet 豆豆
80
+ ```
81
+
82
+ ## The Write Gate
83
+
84
+ The gate is deliberately simple. Each rule answers a question that does not need a model:
85
+
86
+ - **Process is not memory.** Stack traces and tool output can be re-derived. Store the symptom and the root cause, not the transcript.
87
+ - **Volume is a signal.** If a "memory" is longer than a screen, it is probably a transcript.
88
+ - **Questions are not facts.** "What time is the meeting tomorrow?" is a request. Remembering it only pollutes retrieval.
89
+ - **Greetings are not facts.** "ok", "嗯嗯", "好的好的" carry no information.
90
+
91
+ `assess_write` returns a `WriteVerdict` with `ok`, `reason`, the rule that fired and the metrics (`chars`, `meaningful_chars`, `lines`, `urls`). Log the reason; a silent drop is indistinguishable from a gate that never ran.
92
+
93
+ ## Subject Attribution
94
+
95
+ `assess_attribution` flags two shapes:
96
+
97
+ - **relation**: `X 的 <relation-noun> ...` — the fact belongs to the relation, not to the speaker.
98
+ - **pet**: a known pet name followed by a verb or adjective — the fact belongs to the pet.
99
+
100
+ It does **not** rewrite the text. A rewrite needs your extractor or a model, and a library should not silently change what gets stored. The flag is enough to stop the common failure.
101
+
102
+ ## Fail Open, Loudly
103
+
104
+ ```python
105
+ from agent_memory_hygiene import safe_assess_write
106
+
107
+ verdict = safe_assess_write(text)
108
+ if verdict.reason == "fail_open":
109
+ ... # the gate broke; the write was allowed and a warning was logged
110
+ ```
111
+
112
+ A write gate must not block the main flow when the gate itself breaks. But "the gate allowed everything" and "the gate never loaded" look identical in logs, so the wrapper always logs the exception before allowing the write.
113
+
114
+ ## What it does NOT do
115
+
116
+ - Calls no model.
117
+ - Stores no memory and owns no database.
118
+ - Connects to no vector store or embedding service.
119
+ - Rewrites nothing; it only returns verdicts.
120
+
121
+ ## Where this kit deliberately stops
122
+
123
+ - **Importance.** It cannot tell whether a fact matters to the user. That needs the caller's domain knowledge or a model.
124
+ - **Deduplication.** Near-duplicate detection needs embeddings; this kit is zero-dependency on purpose.
125
+ - **Multilingual rules.** The default patterns target Chinese text, which is where the attribution failures were observed. The thresholds are configurable, the phrase lists are not exhaustive.
126
+ - **Attribution rewriting.** Flagging is cheap and safe; rewriting needs the extractor.
127
+
128
+ ## Test
129
+
130
+ ```bash
131
+ pytest -q
132
+ ```
133
+
134
+ ## License
135
+
136
+ MIT
@@ -0,0 +1,109 @@
1
+ # agent-memory-hygiene
2
+
3
+ [English](https://github.com/AirXsLink/agent-memory-hygiene/blob/main/README.md) | [简体中文](https://github.com/AirXsLink/agent-memory-hygiene/blob/main/README.zh-CN.md)
4
+
5
+ Pure-policy write-time hygiene for agent memory: what to store, what to drop, and whose fact it is.
6
+
7
+ ## Problem
8
+
9
+ Most agent-memory projects optimize retrieval: embeddings, re-ranking, recency, similarity thresholds. Very few ask the cheaper question first: **should this ever have been written?**
10
+
11
+ A store that accepts everything becomes a log. Tool output, stack traces, pasted links, questions and greetings all drift in, and the only remaining defense is a higher similarity threshold at read time. That is a patch on the retrieval side, not a decision on the write side.
12
+
13
+ The second failure is attribution. An extractor turns "小雨的妈妈是老师" into "the user is a teacher", or "豆豆特别能吃" into "the user eats a lot". The fact is real; the subject is wrong. Retrieval cannot detect this, because the stored sentence looks perfectly normal.
14
+
15
+ This library covers both, with pure functions and no model calls.
16
+
17
+ **At a glance:**
18
+
19
+ | Input | Decision |
20
+ | --- | --- |
21
+ | `""` / whitespace | `empty` |
22
+ | Shorter than 8 chars | `too_short` |
23
+ | Longer than 2000 chars | `too_long` |
24
+ | More than 12 non-empty lines | `too_many_lines` |
25
+ | Contains a traceback / `WinError` | `error_dump` |
26
+ | Only a URL, little else | `link_only` |
27
+ | Ends as a short question | `question` |
28
+ | Short greeting | `chitchat` |
29
+ | Everything else | `ok` |
30
+ | "我的妈妈是老师" | `relation_subject` flag |
31
+ | "豆豆特别能吃" (豆豆 is a known pet) | `pet_subject` flag |
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ pip install -e .
37
+ ```
38
+
39
+ ## Quick Start
40
+
41
+ ```python
42
+ from agent_memory_hygiene import MemoryHygieneConfig, assess_write, assess_attribution
43
+
44
+ verdict = assess_write("用户喜欢喝咖啡和茶")
45
+ print(verdict.ok, verdict.reason) # True ok
46
+
47
+ verdict = assess_write("明天下午的会议是几点?")
48
+ print(verdict.ok, verdict.reason) # False question
49
+
50
+ cfg = MemoryHygieneConfig(known_pets=("豆豆",))
51
+ risk = assess_attribution("豆豆特别能吃", cfg)
52
+ print(risk.shifted, risk.kind, risk.subject) # True pet 豆豆
53
+ ```
54
+
55
+ ## The Write Gate
56
+
57
+ The gate is deliberately simple. Each rule answers a question that does not need a model:
58
+
59
+ - **Process is not memory.** Stack traces and tool output can be re-derived. Store the symptom and the root cause, not the transcript.
60
+ - **Volume is a signal.** If a "memory" is longer than a screen, it is probably a transcript.
61
+ - **Questions are not facts.** "What time is the meeting tomorrow?" is a request. Remembering it only pollutes retrieval.
62
+ - **Greetings are not facts.** "ok", "嗯嗯", "好的好的" carry no information.
63
+
64
+ `assess_write` returns a `WriteVerdict` with `ok`, `reason`, the rule that fired and the metrics (`chars`, `meaningful_chars`, `lines`, `urls`). Log the reason; a silent drop is indistinguishable from a gate that never ran.
65
+
66
+ ## Subject Attribution
67
+
68
+ `assess_attribution` flags two shapes:
69
+
70
+ - **relation**: `X 的 <relation-noun> ...` — the fact belongs to the relation, not to the speaker.
71
+ - **pet**: a known pet name followed by a verb or adjective — the fact belongs to the pet.
72
+
73
+ It does **not** rewrite the text. A rewrite needs your extractor or a model, and a library should not silently change what gets stored. The flag is enough to stop the common failure.
74
+
75
+ ## Fail Open, Loudly
76
+
77
+ ```python
78
+ from agent_memory_hygiene import safe_assess_write
79
+
80
+ verdict = safe_assess_write(text)
81
+ if verdict.reason == "fail_open":
82
+ ... # the gate broke; the write was allowed and a warning was logged
83
+ ```
84
+
85
+ A write gate must not block the main flow when the gate itself breaks. But "the gate allowed everything" and "the gate never loaded" look identical in logs, so the wrapper always logs the exception before allowing the write.
86
+
87
+ ## What it does NOT do
88
+
89
+ - Calls no model.
90
+ - Stores no memory and owns no database.
91
+ - Connects to no vector store or embedding service.
92
+ - Rewrites nothing; it only returns verdicts.
93
+
94
+ ## Where this kit deliberately stops
95
+
96
+ - **Importance.** It cannot tell whether a fact matters to the user. That needs the caller's domain knowledge or a model.
97
+ - **Deduplication.** Near-duplicate detection needs embeddings; this kit is zero-dependency on purpose.
98
+ - **Multilingual rules.** The default patterns target Chinese text, which is where the attribution failures were observed. The thresholds are configurable, the phrase lists are not exhaustive.
99
+ - **Attribution rewriting.** Flagging is cheap and safe; rewriting needs the extractor.
100
+
101
+ ## Test
102
+
103
+ ```bash
104
+ pytest -q
105
+ ```
106
+
107
+ ## License
108
+
109
+ MIT
@@ -0,0 +1,18 @@
1
+ """Write-time hygiene for agent memory: what to store, and whose fact it is."""
2
+
3
+ from .attribution import AttributionRisk, assess_attribution
4
+ from .config import MemoryHygieneConfig
5
+ from .fail_open import safe_assess_write
6
+ from .gate import WriteVerdict, assess_write, should_write
7
+
8
+ __version__ = "0.1.0"
9
+
10
+ __all__ = [
11
+ "AttributionRisk",
12
+ "MemoryHygieneConfig",
13
+ "WriteVerdict",
14
+ "assess_attribution",
15
+ "assess_write",
16
+ "safe_assess_write",
17
+ "should_write",
18
+ ]
@@ -0,0 +1,110 @@
1
+ """Subject attribution: whose fact is this?
2
+
3
+ LLM extraction often assigns a fact to the wrong subject. Two shapes recur in
4
+ production:
5
+
6
+ 1. **relation** - "小雨的妈妈是老师" or "我的妈妈是老师". The fact belongs to
7
+ the relation, not to the speaker. Storing "the user is a teacher" is wrong.
8
+ 2. **pet** - "豆豆特别能吃". If the speaker has a pet named "豆豆", the fact
9
+ belongs to the pet, not to the speaker.
10
+
11
+ The heuristics only *flag* the risk; they never rewrite the text. A rewrite
12
+ needs the caller's extractor or a model, and a library should not silently
13
+ change what gets stored. Flagging is enough to stop the common failure: a
14
+ fact silently attached to the wrong person.
15
+ """
16
+
17
+ import re
18
+ from dataclasses import dataclass
19
+ from typing import Optional
20
+
21
+ from .config import MemoryHygieneConfig
22
+
23
+ #: Nouns that introduce a relation subject after "X 的".
24
+ RELATION_NOUNS: tuple[str, ...] = (
25
+ "妈妈",
26
+ "爸爸",
27
+ "父母",
28
+ "母亲",
29
+ "父亲",
30
+ "老婆",
31
+ "老公",
32
+ "妻子",
33
+ "丈夫",
34
+ "儿子",
35
+ "女儿",
36
+ "孩子",
37
+ "哥哥",
38
+ "姐姐",
39
+ "弟弟",
40
+ "妹妹",
41
+ "朋友",
42
+ "同事",
43
+ "老板",
44
+ "老师",
45
+ "同学",
46
+ "室友",
47
+ )
48
+
49
+ _RELATION_RE = re.compile(
50
+ r"^(?P<subject>(?:我|用户|本人|[\u4e00-\u9fff]{2,4}))"
51
+ r"的(?P<relation>" + "|".join(RELATION_NOUNS) + r")"
52
+ )
53
+
54
+ #: Characters that commonly follow a pet name when the sentence is about the
55
+ #: pet rather than about the speaker.
56
+ _PET_FOLLOW_CHARS = frozenset("很特也能会在是有喜欢叫爱吃得")
57
+
58
+
59
+ @dataclass
60
+ class AttributionRisk:
61
+ """The result of checking whether a fact is attached to the wrong subject.
62
+
63
+ ``reason`` is ``"ok"`` when no risk was found; otherwise it is
64
+ ``"relation_subject"`` or ``"pet_subject"``.
65
+ """
66
+
67
+ shifted: bool
68
+ kind: Optional[str]
69
+ subject: Optional[str]
70
+ reason: str
71
+
72
+
73
+ def _relation_subject(text: str) -> Optional[str]:
74
+ match = _RELATION_RE.match(text)
75
+ if not match:
76
+ return None
77
+ return match.group(0).replace("的" + match.group("relation"), "")
78
+
79
+
80
+ def _pet_subject(text: str, cfg: MemoryHygieneConfig) -> Optional[str]:
81
+ for pet in cfg.known_pets:
82
+ if not pet or not text.startswith(pet):
83
+ continue
84
+ remainder = text[len(pet) :]
85
+ if remainder and remainder[0] in _PET_FOLLOW_CHARS:
86
+ return pet
87
+ return None
88
+
89
+
90
+ def assess_attribution(
91
+ text: Optional[str], cfg: Optional[MemoryHygieneConfig] = None
92
+ ) -> AttributionRisk:
93
+ """Return whether ``text`` looks like a fact about someone else.
94
+
95
+ This is a flag, not a correction: a ``True`` means the caller should keep
96
+ the relation/pet in the stored fact instead of collapsing it onto the user.
97
+ """
98
+ cfg = cfg or MemoryHygieneConfig()
99
+ if not cfg.check_attribution or not text:
100
+ return AttributionRisk(False, None, None, "ok")
101
+
102
+ relation = _relation_subject(text)
103
+ if relation:
104
+ return AttributionRisk(True, "relation", relation, "relation_subject")
105
+
106
+ pet = _pet_subject(text, cfg)
107
+ if pet:
108
+ return AttributionRisk(True, "pet", pet, "pet_subject")
109
+
110
+ return AttributionRisk(False, None, None, "ok")
@@ -0,0 +1,31 @@
1
+ """Configuration for write-time memory hygiene."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+
6
+ @dataclass
7
+ class MemoryHygieneConfig:
8
+ """Thresholds for deciding whether a piece of text is worth storing.
9
+
10
+ Defaults come from a production chat bot: ``min_chars`` blocks greetings
11
+ such as "ok" and "嗯嗯", ``max_chars`` / ``max_lines`` block pasted logs,
12
+ and ``question_max_chars`` keeps short questions out of the memory store.
13
+ """
14
+
15
+ #: Shorter texts are treated as noise (greetings, acknowledgements).
16
+ min_chars: int = 8
17
+ #: Longer texts are almost always tool output or pasted logs.
18
+ max_chars: int = 2000
19
+ #: Non-empty lines; a conclusion should fit on a screen.
20
+ max_lines: int = 12
21
+ #: Questions longer than this are not classified as questions.
22
+ question_max_chars: int = 80
23
+ #: Texts shorter than this are checked against the chitchat pattern.
24
+ chitchat_max_chars: int = 16
25
+ #: A URL-only text is dropped when less than this much content remains.
26
+ link_min_remaining_chars: int = 12
27
+ #: Names that should be attributed to a pet, not to the user.
28
+ known_pets: tuple[str, ...] = ()
29
+ #: Whether ``assess_attribution`` is applied by the caller. Kept as a flag
30
+ #: so an adapter can disable the heuristic without changing call sites.
31
+ check_attribution: bool = True
@@ -0,0 +1,34 @@
1
+ """Fail-open wrapper that never fails silently.
2
+
3
+ A write gate must not block the main flow when the gate itself breaks. But
4
+ "the gate allowed everything" and "the gate never loaded" look identical in
5
+ logs, so the wrapper always logs the exception before allowing the write.
6
+ """
7
+
8
+ import logging
9
+ from typing import Optional
10
+
11
+ from .config import MemoryHygieneConfig
12
+ from .gate import WriteVerdict, assess_write
13
+
14
+ _LOGGER = logging.getLogger("agent_memory_hygiene")
15
+
16
+
17
+ def safe_assess_write(
18
+ text: Optional[str],
19
+ cfg: Optional[MemoryHygieneConfig] = None,
20
+ *,
21
+ logger: Optional[logging.Logger] = None,
22
+ ) -> WriteVerdict:
23
+ """Assess a candidate memory, failing open and loud on internal errors.
24
+
25
+ Returns the normal verdict when the gate works. When it raises, returns a
26
+ permissive verdict with ``reason="fail_open"`` and logs a warning, so the
27
+ failure is visible without blocking the caller.
28
+ """
29
+ log = logger if logger is not None else _LOGGER
30
+ try:
31
+ return assess_write(text, cfg)
32
+ except Exception as exc: # noqa: BLE001 - this is the fail-open boundary
33
+ log.warning("memory hygiene gate failed open: %s", exc)
34
+ return WriteVerdict(ok=True, reason="fail_open", rule="exception", metrics={})
@@ -0,0 +1,132 @@
1
+ """Write gate: decide what deserves to enter a long-term memory store.
2
+
3
+ Every function is pure: no model calls, no I/O. The gate encodes four
4
+ observations from a production agent:
5
+
6
+ 1. **Process is not memory.** Tool output, stack traces and pasted links are
7
+ re-derivable; storing them turns the store into a log.
8
+ 2. **Volume is a signal.** A "memory" longer than a screen is usually a
9
+ transcript, and a transcript is not a conclusion.
10
+ 3. **Questions are not facts.** "What time is it tomorrow?" is a request, not
11
+ something to remember.
12
+ 4. **A write gate must fail open, but loudly.** If the gate itself breaks, the
13
+ caller should still be able to write; the failure must be logged, because
14
+ "the gate allowed everything" and "the gate never loaded" look identical.
15
+
16
+ The gate returns a :class:`WriteVerdict` with the reason and the metrics that
17
+ produced it, so a rejection can be logged instead of silently dropped.
18
+ """
19
+
20
+ import re
21
+ from dataclasses import dataclass, field
22
+ from typing import Any, Optional
23
+
24
+ from .config import MemoryHygieneConfig
25
+
26
+ _ERROR_RE = re.compile(
27
+ r"Traceback \(most recent call last\)"
28
+ r"|File \"[^\"]+\", line \d+"
29
+ r"|\bat [\w.$]+:\d+:\d+"
30
+ r"|^\s*Error[::]"
31
+ r"|Exception[::]"
32
+ r"|WinError \d+",
33
+ re.MULTILINE,
34
+ )
35
+ _URL_RE = re.compile(r"https?://\S+")
36
+ _CHITCHAT_RE = re.compile(
37
+ r"^[\s,。!?、~~…哈嗯哦啊呀吧呢了的是好好行可以收到明白okOK表情图片]*$"
38
+ )
39
+ _QUESTION_ENDINGS = ("?", "?")
40
+ _QUESTION_PHRASES = (
41
+ "是什么",
42
+ "是谁",
43
+ "在哪里",
44
+ "在哪儿",
45
+ "几点",
46
+ "怎么办",
47
+ "多少钱",
48
+ "哪一个",
49
+ "哪个",
50
+ )
51
+
52
+
53
+ @dataclass
54
+ class WriteVerdict:
55
+ """The result of assessing one candidate memory.
56
+
57
+ ``rule`` names the specific check that fired, which is what a log line
58
+ needs; ``reason`` is the stable category an adapter can switch on.
59
+ """
60
+
61
+ ok: bool
62
+ reason: str
63
+ rule: str
64
+ metrics: dict[str, Any] = field(default_factory=dict)
65
+
66
+
67
+ def _metrics(text: str) -> dict[str, Any]:
68
+ lines = [line for line in text.splitlines() if line.strip()]
69
+ return {
70
+ "chars": len(text),
71
+ "meaningful_chars": sum(1 for char in text if char.isalnum()),
72
+ "lines": len(lines),
73
+ "urls": len(_URL_RE.findall(text)),
74
+ }
75
+
76
+
77
+ def _is_question(text: str, cfg: MemoryHygieneConfig) -> bool:
78
+ if len(text) > cfg.question_max_chars:
79
+ return False
80
+ if text.endswith(_QUESTION_ENDINGS):
81
+ return True
82
+ # "吗" is an unambiguous question particle in Chinese.
83
+ if text.endswith("吗"):
84
+ return True
85
+ # Bare interrogatives ("谁", "呢") are deliberately not enough: they also
86
+ # end statements such as "本鱼在呢".
87
+ return any(text.endswith(phrase) for phrase in _QUESTION_PHRASES)
88
+
89
+
90
+ def assess_write(
91
+ text: Optional[str], cfg: Optional[MemoryHygieneConfig] = None
92
+ ) -> WriteVerdict:
93
+ """Assess one candidate memory and return the verdict plus its evidence."""
94
+ cfg = cfg or MemoryHygieneConfig()
95
+ raw = text or ""
96
+ stripped = raw.strip()
97
+ metrics = _metrics(stripped)
98
+
99
+ if not stripped:
100
+ return WriteVerdict(False, "empty", "empty", metrics)
101
+
102
+ if len(stripped) < cfg.min_chars:
103
+ return WriteVerdict(False, "too_short", "min_chars", metrics)
104
+
105
+ if len(stripped) > cfg.max_chars:
106
+ return WriteVerdict(False, "too_long", "max_chars", metrics)
107
+
108
+ if metrics["lines"] > cfg.max_lines:
109
+ return WriteVerdict(False, "too_many_lines", "max_lines", metrics)
110
+
111
+ if _ERROR_RE.search(stripped):
112
+ return WriteVerdict(False, "error_dump", "error_pattern", metrics)
113
+
114
+ if _URL_RE.search(stripped):
115
+ remainder = _URL_RE.sub("", stripped).strip(" \t\r\n,。、")
116
+ if len(remainder) < cfg.link_min_remaining_chars:
117
+ return WriteVerdict(False, "link_only", "url_only", metrics)
118
+
119
+ if _is_question(stripped, cfg):
120
+ return WriteVerdict(False, "question", "question_ending", metrics)
121
+
122
+ if len(stripped) < cfg.chitchat_max_chars and _CHITCHAT_RE.match(stripped):
123
+ return WriteVerdict(False, "chitchat", "chitchat_pattern", metrics)
124
+
125
+ return WriteVerdict(True, "ok", "ok", metrics)
126
+
127
+
128
+ def should_write(
129
+ text: Optional[str], cfg: Optional[MemoryHygieneConfig] = None
130
+ ) -> bool:
131
+ """Convenience wrapper: True when the text passes every write rule."""
132
+ return assess_write(text, cfg).ok
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: agent-memory-hygiene
3
+ Version: 0.1.0
4
+ Summary: Pure-policy write-time hygiene for agent memory: what to store, what to drop, and whose fact it is.
5
+ Author: agent-memory-hygiene contributors
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/AirXsLink/agent-memory-hygiene
8
+ Project-URL: Repository, https://github.com/AirXsLink/agent-memory-hygiene
9
+ Project-URL: Issues, https://github.com/AirXsLink/agent-memory-hygiene/issues
10
+ Project-URL: Changelog, https://github.com/AirXsLink/agent-memory-hygiene/blob/main/CHANGELOG.md
11
+ Keywords: agent,memory,llm,hygiene,attribution
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: License :: OSI Approved :: MIT License
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Provides-Extra: test
25
+ Requires-Dist: pytest>=8; extra == "test"
26
+ Dynamic: license-file
27
+
28
+ # agent-memory-hygiene
29
+
30
+ [English](https://github.com/AirXsLink/agent-memory-hygiene/blob/main/README.md) | [简体中文](https://github.com/AirXsLink/agent-memory-hygiene/blob/main/README.zh-CN.md)
31
+
32
+ Pure-policy write-time hygiene for agent memory: what to store, what to drop, and whose fact it is.
33
+
34
+ ## Problem
35
+
36
+ Most agent-memory projects optimize retrieval: embeddings, re-ranking, recency, similarity thresholds. Very few ask the cheaper question first: **should this ever have been written?**
37
+
38
+ A store that accepts everything becomes a log. Tool output, stack traces, pasted links, questions and greetings all drift in, and the only remaining defense is a higher similarity threshold at read time. That is a patch on the retrieval side, not a decision on the write side.
39
+
40
+ The second failure is attribution. An extractor turns "小雨的妈妈是老师" into "the user is a teacher", or "豆豆特别能吃" into "the user eats a lot". The fact is real; the subject is wrong. Retrieval cannot detect this, because the stored sentence looks perfectly normal.
41
+
42
+ This library covers both, with pure functions and no model calls.
43
+
44
+ **At a glance:**
45
+
46
+ | Input | Decision |
47
+ | --- | --- |
48
+ | `""` / whitespace | `empty` |
49
+ | Shorter than 8 chars | `too_short` |
50
+ | Longer than 2000 chars | `too_long` |
51
+ | More than 12 non-empty lines | `too_many_lines` |
52
+ | Contains a traceback / `WinError` | `error_dump` |
53
+ | Only a URL, little else | `link_only` |
54
+ | Ends as a short question | `question` |
55
+ | Short greeting | `chitchat` |
56
+ | Everything else | `ok` |
57
+ | "我的妈妈是老师" | `relation_subject` flag |
58
+ | "豆豆特别能吃" (豆豆 is a known pet) | `pet_subject` flag |
59
+
60
+ ## Install
61
+
62
+ ```bash
63
+ pip install -e .
64
+ ```
65
+
66
+ ## Quick Start
67
+
68
+ ```python
69
+ from agent_memory_hygiene import MemoryHygieneConfig, assess_write, assess_attribution
70
+
71
+ verdict = assess_write("用户喜欢喝咖啡和茶")
72
+ print(verdict.ok, verdict.reason) # True ok
73
+
74
+ verdict = assess_write("明天下午的会议是几点?")
75
+ print(verdict.ok, verdict.reason) # False question
76
+
77
+ cfg = MemoryHygieneConfig(known_pets=("豆豆",))
78
+ risk = assess_attribution("豆豆特别能吃", cfg)
79
+ print(risk.shifted, risk.kind, risk.subject) # True pet 豆豆
80
+ ```
81
+
82
+ ## The Write Gate
83
+
84
+ The gate is deliberately simple. Each rule answers a question that does not need a model:
85
+
86
+ - **Process is not memory.** Stack traces and tool output can be re-derived. Store the symptom and the root cause, not the transcript.
87
+ - **Volume is a signal.** If a "memory" is longer than a screen, it is probably a transcript.
88
+ - **Questions are not facts.** "What time is the meeting tomorrow?" is a request. Remembering it only pollutes retrieval.
89
+ - **Greetings are not facts.** "ok", "嗯嗯", "好的好的" carry no information.
90
+
91
+ `assess_write` returns a `WriteVerdict` with `ok`, `reason`, the rule that fired and the metrics (`chars`, `meaningful_chars`, `lines`, `urls`). Log the reason; a silent drop is indistinguishable from a gate that never ran.
92
+
93
+ ## Subject Attribution
94
+
95
+ `assess_attribution` flags two shapes:
96
+
97
+ - **relation**: `X 的 <relation-noun> ...` — the fact belongs to the relation, not to the speaker.
98
+ - **pet**: a known pet name followed by a verb or adjective — the fact belongs to the pet.
99
+
100
+ It does **not** rewrite the text. A rewrite needs your extractor or a model, and a library should not silently change what gets stored. The flag is enough to stop the common failure.
101
+
102
+ ## Fail Open, Loudly
103
+
104
+ ```python
105
+ from agent_memory_hygiene import safe_assess_write
106
+
107
+ verdict = safe_assess_write(text)
108
+ if verdict.reason == "fail_open":
109
+ ... # the gate broke; the write was allowed and a warning was logged
110
+ ```
111
+
112
+ A write gate must not block the main flow when the gate itself breaks. But "the gate allowed everything" and "the gate never loaded" look identical in logs, so the wrapper always logs the exception before allowing the write.
113
+
114
+ ## What it does NOT do
115
+
116
+ - Calls no model.
117
+ - Stores no memory and owns no database.
118
+ - Connects to no vector store or embedding service.
119
+ - Rewrites nothing; it only returns verdicts.
120
+
121
+ ## Where this kit deliberately stops
122
+
123
+ - **Importance.** It cannot tell whether a fact matters to the user. That needs the caller's domain knowledge or a model.
124
+ - **Deduplication.** Near-duplicate detection needs embeddings; this kit is zero-dependency on purpose.
125
+ - **Multilingual rules.** The default patterns target Chinese text, which is where the attribution failures were observed. The thresholds are configurable, the phrase lists are not exhaustive.
126
+ - **Attribution rewriting.** Flagging is cheap and safe; rewriting needs the extractor.
127
+
128
+ ## Test
129
+
130
+ ```bash
131
+ pytest -q
132
+ ```
133
+
134
+ ## License
135
+
136
+ MIT
@@ -0,0 +1,17 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ agent_memory_hygiene/__init__.py
5
+ agent_memory_hygiene/attribution.py
6
+ agent_memory_hygiene/config.py
7
+ agent_memory_hygiene/fail_open.py
8
+ agent_memory_hygiene/gate.py
9
+ agent_memory_hygiene/py.typed
10
+ agent_memory_hygiene.egg-info/PKG-INFO
11
+ agent_memory_hygiene.egg-info/SOURCES.txt
12
+ agent_memory_hygiene.egg-info/dependency_links.txt
13
+ agent_memory_hygiene.egg-info/requires.txt
14
+ agent_memory_hygiene.egg-info/top_level.txt
15
+ tests/test_attribution.py
16
+ tests/test_fail_open.py
17
+ tests/test_gate.py
@@ -0,0 +1 @@
1
+ agent_memory_hygiene
@@ -0,0 +1,43 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "agent-memory-hygiene"
7
+ version = "0.1.0"
8
+ description = "Pure-policy write-time hygiene for agent memory: what to store, what to drop, and whose fact it is."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "agent-memory-hygiene contributors" }]
13
+ keywords = ["agent", "memory", "llm", "hygiene", "attribution"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "License :: OSI Approved :: MIT License",
22
+ "Operating System :: OS Independent",
23
+ "Typing :: Typed",
24
+ ]
25
+ dependencies = []
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/AirXsLink/agent-memory-hygiene"
29
+ Repository = "https://github.com/AirXsLink/agent-memory-hygiene"
30
+ Issues = "https://github.com/AirXsLink/agent-memory-hygiene/issues"
31
+ Changelog = "https://github.com/AirXsLink/agent-memory-hygiene/blob/main/CHANGELOG.md"
32
+
33
+ [project.optional-dependencies]
34
+ test = ["pytest>=8"]
35
+
36
+ [tool.setuptools.packages.find]
37
+ include = ["agent_memory_hygiene*"]
38
+
39
+ [tool.setuptools.package-data]
40
+ agent_memory_hygiene = ["py.typed"]
41
+
42
+ [tool.pytest.ini_options]
43
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,42 @@
1
+ """Subject attribution: facts about relations and pets are not facts about the user."""
2
+
3
+ from agent_memory_hygiene import MemoryHygieneConfig, assess_attribution
4
+
5
+
6
+ def test_relation_with_pronoun() -> None:
7
+ risk = assess_attribution("我的妈妈是老师")
8
+ assert risk.shifted is True
9
+ assert risk.kind == "relation"
10
+ assert risk.subject == "我"
11
+
12
+
13
+ def test_relation_with_name() -> None:
14
+ risk = assess_attribution("小雨的妈妈是老师")
15
+ assert risk.shifted is True
16
+ assert risk.kind == "relation"
17
+ assert risk.subject == "小雨"
18
+
19
+
20
+ def test_non_relation_is_not_flagged() -> None:
21
+ assert assess_attribution("我的职业是后端开发").shifted is False
22
+
23
+
24
+ def test_known_pet_is_flagged() -> None:
25
+ cfg = MemoryHygieneConfig(known_pets=("豆豆",))
26
+ risk = assess_attribution("豆豆特别能吃", cfg)
27
+ assert risk.shifted is True
28
+ assert risk.kind == "pet"
29
+ assert risk.subject == "豆豆"
30
+
31
+
32
+ def test_pet_without_known_list_is_not_flagged() -> None:
33
+ assert assess_attribution("豆豆特别能吃").shifted is False
34
+
35
+
36
+ def test_plain_fact_is_not_flagged() -> None:
37
+ assert assess_attribution("用户喜欢喝咖啡和茶").shifted is False
38
+
39
+
40
+ def test_attribution_can_be_disabled() -> None:
41
+ cfg = MemoryHygieneConfig(check_attribution=False, known_pets=("豆豆",))
42
+ assert assess_attribution("豆豆特别能吃", cfg).shifted is False
@@ -0,0 +1,44 @@
1
+ """Fail-open behavior: permissive on errors, but never silent."""
2
+
3
+ import logging
4
+
5
+ from agent_memory_hygiene import MemoryHygieneConfig, safe_assess_write
6
+
7
+
8
+ class RecordingLogger(logging.Logger):
9
+ def __init__(self) -> None:
10
+ super().__init__("test")
11
+ self.messages: list[str] = []
12
+
13
+ def warning(self, msg: str, *args: object, **kwargs: object) -> None:
14
+ self.messages.append(msg % args)
15
+
16
+
17
+ def test_normal_path_returns_verdict() -> None:
18
+ verdict = safe_assess_write("用户喜欢喝咖啡和茶")
19
+ assert verdict.ok is True
20
+ assert verdict.reason == "ok"
21
+
22
+
23
+ def test_exception_fails_open(monkeypatch) -> None:
24
+ def boom(text, cfg=None):
25
+ raise RuntimeError("gate exploded")
26
+
27
+ monkeypatch.setattr("agent_memory_hygiene.fail_open.assess_write", boom)
28
+ verdict = safe_assess_write("用户喜欢喝咖啡和茶")
29
+ assert verdict.ok is True
30
+ assert verdict.reason == "fail_open"
31
+ assert verdict.rule == "exception"
32
+
33
+
34
+ def test_warning_is_logged(monkeypatch) -> None:
35
+ def boom(text, cfg=None):
36
+ raise RuntimeError("gate exploded")
37
+
38
+ monkeypatch.setattr("agent_memory_hygiene.fail_open.assess_write", boom)
39
+ recorder = RecordingLogger()
40
+ verdict = safe_assess_write(
41
+ "用户喜欢喝咖啡和茶", MemoryHygieneConfig(), logger=recorder
42
+ )
43
+ assert verdict.reason == "fail_open"
44
+ assert any("failed open" in message for message in recorder.messages)
@@ -0,0 +1,81 @@
1
+ """Write gate: every rule, plus the statements it must not reject."""
2
+
3
+ from agent_memory_hygiene import MemoryHygieneConfig, assess_write, should_write
4
+
5
+
6
+ def test_empty_is_empty() -> None:
7
+ assert assess_write("").reason == "empty"
8
+ assert should_write("") is False
9
+
10
+
11
+ def test_whitespace_is_empty() -> None:
12
+ assert assess_write(" \n\t").reason == "empty"
13
+
14
+
15
+ def test_too_short_is_rejected() -> None:
16
+ assert assess_write("嗯嗯").reason == "too_short"
17
+
18
+
19
+ def test_exactly_min_chars_passes() -> None:
20
+ assert should_write("用户喜欢喝咖啡和茶") is True
21
+
22
+
23
+ def test_too_long_is_rejected() -> None:
24
+ assert assess_write("字" * 2001).reason == "too_long"
25
+
26
+
27
+ def test_too_many_lines_is_rejected() -> None:
28
+ text = "\n".join(f"第 {i} 行的内容" for i in range(13))
29
+ assert assess_write(text).reason == "too_many_lines"
30
+
31
+
32
+ def test_traceback_is_rejected() -> None:
33
+ text = 'Traceback (most recent call last):\n File "app.py", line 3, in <module>'
34
+ assert assess_write(text).reason == "error_dump"
35
+
36
+
37
+ def test_winerror_is_rejected() -> None:
38
+ assert assess_write("OSError: WinError 10054 连接被重置").reason == "error_dump"
39
+
40
+
41
+ def test_link_only_is_rejected() -> None:
42
+ assert assess_write("https://example.com/a/b/c").reason == "link_only"
43
+
44
+
45
+ def test_url_with_content_passes() -> None:
46
+ text = "数据库迁移的完整说明文档在这里 https://example.com/a"
47
+ assert should_write(text) is True
48
+
49
+
50
+ def test_question_mark_is_rejected() -> None:
51
+ assert assess_write("明天下午的会议是几点?").reason == "question"
52
+
53
+
54
+ def test_question_particle_is_rejected() -> None:
55
+ assert assess_write("你今天中午吃饭了吗").reason == "question"
56
+
57
+
58
+ def test_statement_ending_with_ne_passes() -> None:
59
+ # "呢" alone is not a question marker; this is a statement.
60
+ assert should_write("本鱼一直都在这里呢") is True
61
+
62
+
63
+ def test_chitchat_is_rejected() -> None:
64
+ assert assess_write("好的好的好的好的").reason == "chitchat"
65
+
66
+
67
+ def test_normal_fact_passes() -> None:
68
+ assert should_write("用户养了一只橘猫叫年糕") is True
69
+
70
+
71
+ def test_verdict_reports_metrics() -> None:
72
+ verdict = assess_write("用户喜欢喝咖啡和茶")
73
+ assert verdict.ok is True
74
+ assert verdict.metrics["chars"] == 9
75
+ assert verdict.metrics["lines"] == 1
76
+ assert verdict.metrics["urls"] == 0
77
+
78
+
79
+ def test_min_chars_is_configurable() -> None:
80
+ cfg = MemoryHygieneConfig(min_chars=4)
81
+ assert assess_write("用户喜欢", cfg).ok is True