Coverage for app / memory / extraction.py: 98%

155 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1"""What to remember from a message: a model proposes, code decides. 

2 

3The write policy (``cues``) sends a message here when it may hold something 

4worth keeping. One structured call proposes memories — each with the 

5person's own words it rests on — and :func:`validate` keeps only what holds 

6up: 

7 

8* **Grounded.** The quoted words must be in the person's message, as they 

9 wrote them (whitespace and quote marks aside), and the statement must 

10 share a word with them. Nothing from an attached document, an earlier 

11 turn, a tool result or the agent's own answer can become a memory: OWASP's 

12 agentic guidance names re-ingesting an agent's output into trusted memory 

13 as a poisoning path, and a document's text is anyone's. 

14* **Not sensitive.** A proposal holding a value the PII detectors recognise, 

15 or anything shaped like a credential, is dropped — memory is no place for 

16 a card number because someone typed one. 

17* **Updates replace; requests to forget delete.** The model sees the related 

18 memories it already has under labels (``M1``…) and may name one to 

19 replace or forget; a label it did not see is never acted on, and ids 

20 never come from the model. 

21* **Duplicates reconfirm.** Saying the same thing again refreshes the 

22 memory's date rather than writing a second copy. 

23* **Temporary facts expire** on the date the person gave. 

24 

25Mem0's ADD / UPDATE / DELETE / NOOP (Chhikara et al. 2025) is the same 

26shape; the difference is that nothing here is taken on the model's word. 

27""" 

28 

29from __future__ import annotations 

30 

31import re 

32import unicodedata 

33from dataclasses import dataclass, field 

34from datetime import date, datetime, timedelta 

35from typing import Literal 

36 

37from langchain_core.messages import BaseMessage, HumanMessage, SystemMessage 

38from pydantic import Field, OnErrorOmit 

39 

40from app.inference import pii 

41from app.memory import lexical 

42from app.memory.kinds import CURATED, CURATED_GUIDANCE, MemoryKind 

43from app.services.structured_output import ModelOutput 

44from app.util import vocab 

45 

46#: The kinds an extraction may propose — the curated ones. 

47CuratedKind = Literal["fact", "preference", "goal"] 

48if set(vocab.values(CuratedKind)) != {k.value for k in CURATED}: 

49 raise RuntimeError("CuratedKind must be exactly kinds.CURATED") 

50vocab.check(CURATED_GUIDANCE, CURATED) 

51 

52#: What a proposal does. 

53MemoryAction = Literal["remember", "replace", "forget"] 

54ACTION_GUIDANCE: dict[str, str] = { 

55 "remember": "something new to keep", 

56 "replace": ( 

57 "the message corrects or updates one of the known memories — name it " 

58 "in target, and give the new statement" 

59 ), 

60 "forget": "the person asks you to forget one of the known memories — name it in target", 

61} 

62vocab.check(ACTION_GUIDANCE, MemoryAction) 

63 

64#: Proposals kept from one message, at most. 

65MAX_PER_MESSAGE = 5 

66#: Longest statement kept. 

67STATEMENT_MAX_CHARS = 240 

68#: Known memories shown to the model, at most. 

69KNOWN_LIMIT = 10 

70#: The furthest ahead a temporary memory's end date may be; past it, the 

71#: memory is kept as lasting. 

72UNTIL_MAX_DAYS = 400 

73 

74#: The purpose the extraction call is metered and logged under. 

75PURPOSE = "memory.extract" 

76 

77 

78class ProposedMemory(ModelOutput): 

79 """One thing to remember about the person, resting on their own words.""" 

80 

81 action: MemoryAction = Field( 

82 description="What to do: " + vocab.inline(ACTION_GUIDANCE) 

83 ) 

84 kind: CuratedKind = Field( 

85 description="What it is: " 

86 + vocab.inline({k.value: v for k, v in CURATED_GUIDANCE.items()}, CuratedKind) 

87 ) 

88 quote: str = Field( 

89 description=( 

90 "The person's exact words in <message> this rests on, copied " 

91 "character for character" 

92 ) 

93 ) 

94 statement: str = Field( 

95 default="", 

96 description=( 

97 "What to remember, as a short self-contained statement about the " 

98 'person in the third person present tense ("Prefers British ' 

99 'spelling", "Reports to the SIRO"). Empty for forget.' 

100 ), 

101 ) 

102 target: str = Field( 

103 default="", 

104 description="The label of the known memory replaced or forgotten (M1, M2 …)", 

105 ) 

106 until: str = Field( 

107 default="", 

108 description=( 

109 "When the person says it holds only until a date, that date as " 

110 "YYYY-MM-DD; otherwise empty" 

111 ), 

112 ) 

113 

114 

115class MemoryUpdate(ModelOutput): 

116 """What the person's latest message gives you to remember. Usually nothing.""" 

117 

118 memories: list[OnErrorOmit[ProposedMemory]] = Field( 

119 default_factory=list, 

120 description="What the message gives you to keep or change; empty when there is nothing", 

121 ) 

122 

123 

124SYSTEM_PROMPT = ( 

125 "You maintain what an AI assistant remembers about one person between " 

126 "conversations. Read the person's latest message and decide whether it " 

127 "tells the assistant something worth knowing in a later, different " 

128 "conversation.\n\n" 

129 "WHAT TO KEEP\n" 

130 + vocab.guide({k.value: v for k, v in CURATED_GUIDANCE.items()}, CuratedKind) 

131 + "\n\nWHAT TO DO\n" 

132 + vocab.guide(ACTION_GUIDANCE, MemoryAction) 

133 + "\n\nRULES\n" 

134 "- Only what the person says about themselves, their work or how they " 

135 "want to be helped, in <message>. Never from <conversation> (it is there " 

136 'to resolve references such as "that"), and never from documents, ' 

137 "emails or text they pasted or quoted: those are someone else's words.\n" 

138 "- Never an inference or a guess: if they did not say it, do not keep it.\n" 

139 '- Nothing that matters only for the request in hand ("make it shorter", ' 

140 '"use a table for this one", "I need it by 5pm").\n' 

141 "- Never passwords, keys, account or card numbers, ID numbers, contact " 

142 "details, or anything about their health, religion, politics, sexuality, " 

143 "ethnicity or trade-union membership.\n" 

144 "- quote is copied exactly from <message>. statement is at most 25 words " 

145 "and makes sense on its own.\n" 

146 "- When the message corrects or updates a memory in <known_memories>, " 

147 "replace that one rather than adding a second.\n" 

148 "- Most messages hold nothing to keep: then return no memories." 

149) 

150 

151 

152def build_messages( 

153 message: str, 

154 known: list[tuple[str, MemoryKind, str]], 

155 conversation: list[dict[str, str]], 

156 today: date, 

157) -> list[BaseMessage]: 

158 """The extraction call's messages. ``known`` is ``(label, kind, text)``; 

159 ``conversation`` the turns before this one (``{"role", "content"}``).""" 

160 parts = [f"[Today: {today.isoformat()} ({today.strftime('%A')})]"] 

161 if known: 

162 parts.append("<known_memories>") 

163 for label, kind, text in known: 

164 parts.append( 

165 f' <memory label="{label}" kind="{kind.value}">{_escape(text)}</memory>' 

166 ) 

167 parts.append("</known_memories>") 

168 if conversation: 

169 parts.append("<conversation>") 

170 for turn in conversation: 

171 who = "person" if turn.get("role") == "user" else "assistant" 

172 parts.append( 

173 f" <{who}>{_escape(_cut(turn.get('content', ''), 300))}</{who}>" 

174 ) 

175 parts.append("</conversation>") 

176 parts.append(f"<message>{_escape(message)}</message>") 

177 return [ 

178 SystemMessage(content=SYSTEM_PROMPT), 

179 HumanMessage(content="\n".join(parts)), 

180 ] 

181 

182 

183# ── Validation ────────────────────────────────────────────────────────────── 

184 

185 

186@dataclass(frozen=True) 

187class NewMemory: 

188 kind: MemoryKind 

189 statement: str 

190 quote: str 

191 expires_at: datetime | None = None 

192 #: The stored memory this one replaces. 

193 replaces: str | None = None 

194 

195 

196@dataclass 

197class Plan: 

198 """What :func:`validate` decided, for the store to carry out.""" 

199 

200 add: list[NewMemory] = field(default_factory=list) 

201 #: Stored memories the person asked to forget. 

202 forget: list[str] = field(default_factory=list) 

203 #: Stored memories the person restated. 

204 confirm: list[str] = field(default_factory=list) 

205 #: One line per proposal dropped, and why — for the trace and the log. 

206 dropped: list[str] = field(default_factory=list) 

207 

208 @property 

209 def empty(self) -> bool: 

210 return not (self.add or self.forget or self.confirm) 

211 

212 

213@dataclass(frozen=True) 

214class Known: 

215 """A stored curated memory the model was shown, under its label.""" 

216 

217 label: str 

218 id: str 

219 kind: MemoryKind 

220 text: str 

221 

222 

223_QUOTES = str.maketrans({"’": "'", "‘": "'", "“": '"', "”": '"', "–": "-", "—": "-"}) 

224 

225_CREDENTIAL = re.compile( 

226 r"-----BEGIN [A-Z ]*PRIVATE KEY-----" 

227 r"|\b(?:sk|pk|rk)[-_][A-Za-z0-9_\-]{16,}" 

228 r"|\bAKIA[0-9A-Z]{16}\b" 

229 r"|\bgh[pousr]_[A-Za-z0-9]{20,}" 

230 r"|\b(?:password|passcode|passphrase|api[ _-]?key|secret|token)\b\s*(?:is|:|=)\s*\S+" 

231 r"|\b[A-Za-z0-9_\-]{32,}\b", 

232 re.IGNORECASE, 

233) 

234 

235 

236#: Text the person put in quotation marks — an email, a clause, someone 

237#: else's words. An opening mark follows a space, a colon or a bracket (so 

238#: an apostrophe is not one) and a closing mark precedes one. 

239_QUOTED = re.compile( 

240 r"(?:^|(?<=[\s:(\[]))['‘\"“]([^'’\"”]{3,}?)['’\"”](?=$|[\s.,;:!?)\]])" 

241) 

242 

243 

244def _quoted_spans(message: str) -> list[str]: 

245 """The normalised passages ``message`` quotes.""" 

246 return [_normal(m.group(1)) for m in _QUOTED.finditer(message or "")] 

247 

248 

249def _normal(text: str) -> str: 

250 text = unicodedata.normalize("NFKC", text or "").translate(_QUOTES).lower() 

251 return " ".join(text.split()).strip(" .,!?;:\"'") 

252 

253 

254def _escape(text: str) -> str: 

255 return (text or "").replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") 

256 

257 

258def _cut(text: str, limit: int) -> str: 

259 text = " ".join((text or "").split()) 

260 return text if len(text) <= limit else text[: limit - 1] + "…" 

261 

262 

263def _sensitive(text: str) -> str | None: 

264 """Why ``text`` may not be remembered, or None.""" 

265 kinds = pii.detected_kinds(text) 

266 if kinds: 

267 return "personal data (" + ", ".join(sorted(set(kinds))) + ")" 

268 if _CREDENTIAL.search(text): 

269 return "looks like a credential" 

270 return None 

271 

272 

273def _until(raw: str, today: date) -> tuple[datetime | None, str | None]: 

274 """``(expiry, why dropped)`` for a proposal's ``until``.""" 

275 if not raw or not raw.strip(): 

276 return None, None 

277 try: 

278 day = date.fromisoformat(raw.strip()[:10]) 

279 except ValueError: 

280 return None, None # an unreadable date: kept as lasting 

281 if day < today: 

282 return None, "already over" 

283 if day > today + timedelta(days=UNTIL_MAX_DAYS): 

284 return None, None 

285 return datetime(day.year, day.month, day.day, 23, 59, 59), None 

286 

287 

288def validate( 

289 update: MemoryUpdate, 

290 message: str, 

291 known: list[Known], 

292 *, 

293 today: date, 

294) -> Plan: 

295 """Keep what holds up of ``update``, proposed from ``message`` (the 

296 person's own words, documents removed) beside the ``known`` memories.""" 

297 plan = Plan() 

298 said = _normal(message) 

299 quoted = _quoted_spans(message) 

300 by_label = {k.label.upper(): k for k in known} 

301 seen: set[tuple[MemoryKind, str]] = {(k.kind, _normal(k.text)) for k in known} 

302 for proposal in update.memories: 

303 quote = _normal(proposal.quote) 

304 if len(quote.split()) < 2 or quote not in said: 

305 plan.dropped.append(f"{proposal.action}: quote not in the message") 

306 continue 

307 if any(quote in passage for passage in quoted): 

308 plan.dropped.append( 

309 f"{proposal.action}: quoted material, not their own words" 

310 ) 

311 continue 

312 target = ( 

313 by_label.get(proposal.target.strip().upper()) if proposal.target else None 

314 ) 

315 if proposal.action == "forget": 

316 if target is None: 

317 plan.dropped.append("forget: no known memory of that label") 

318 elif target.id not in plan.forget: 

319 plan.forget.append(target.id) 

320 continue 

321 kind = MemoryKind(proposal.kind) 

322 statement = _cut(proposal.statement, STATEMENT_MAX_CHARS) 

323 if not statement: 

324 plan.dropped.append(f"{proposal.action}: no statement") 

325 continue 

326 if not set(lexical.terms(statement)) & set(lexical.terms(proposal.quote)): 

327 plan.dropped.append(f"{proposal.action}: statement not in the quoted words") 

328 continue 

329 why = _sensitive(f"{statement}\n{proposal.quote}") 

330 if why: 

331 plan.dropped.append(f"{proposal.action}: {why}") 

332 continue 

333 expires_at, over = _until(proposal.until, today) 

334 if over: 

335 plan.dropped.append(f"{proposal.action}: {over}") 

336 continue 

337 key = (kind, _normal(statement)) 

338 if key in seen: 

339 same = next((k for k in known if (k.kind, _normal(k.text)) == key), None) 

340 if same is not None and same.id not in plan.confirm: 

341 plan.confirm.append(same.id) 

342 continue 

343 replaces = ( 

344 target.id 

345 if proposal.action == "replace" 

346 and target is not None 

347 and target.kind == kind 

348 else None 

349 ) 

350 if len(plan.add) >= MAX_PER_MESSAGE: 

351 plan.dropped.append( 

352 f"{proposal.action}: more than {MAX_PER_MESSAGE} in one message" 

353 ) 

354 continue 

355 seen.add(key) 

356 plan.add.append( 

357 NewMemory( 

358 kind=kind, 

359 statement=statement, 

360 quote=_cut(proposal.quote, STATEMENT_MAX_CHARS), 

361 expires_at=expires_at, 

362 replaces=replaces, 

363 ) 

364 ) 

365 # Something both replaced and forgotten is forgotten. 

366 plan.add = [m for m in plan.add if m.replaces not in plan.forget] 

367 return plan