forgetproof 0.2.0__py3-none-any.whl
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.
- forgetproof/__init__.py +3 -0
- forgetproof/__main__.py +5 -0
- forgetproof/_chroma_rebuild.py +197 -0
- forgetproof/agent.py +342 -0
- forgetproof/cli.py +582 -0
- forgetproof/copies.py +155 -0
- forgetproof/desktop/__init__.py +1 -0
- forgetproof/desktop/__main__.py +26 -0
- forgetproof/desktop/api.py +549 -0
- forgetproof/desktop/app.py +59 -0
- forgetproof/desktop/schedule.py +161 -0
- forgetproof/desktop/ui/index.html +298 -0
- forgetproof/discovery.py +357 -0
- forgetproof/erase_live.py +180 -0
- forgetproof/files_store.py +69 -0
- forgetproof/fixer.py +274 -0
- forgetproof/forget.py +264 -0
- forgetproof/forgetme.py +270 -0
- forgetproof/hnsw.py +132 -0
- forgetproof/integrations/__init__.py +9 -0
- forgetproof/integrations/mem0.py +283 -0
- forgetproof/keystore.py +58 -0
- forgetproof/lance_store.py +191 -0
- forgetproof/mcp_server.py +541 -0
- forgetproof/mem0_store.py +189 -0
- forgetproof/pii.py +160 -0
- forgetproof/postgres.py +334 -0
- forgetproof/py.typed +0 -0
- forgetproof/qdrant_store.py +69 -0
- forgetproof/receipt.py +135 -0
- forgetproof/remembered.py +257 -0
- forgetproof/report.py +59 -0
- forgetproof/safety.py +105 -0
- forgetproof/scanner.py +288 -0
- forgetproof/sqlite_pages.py +245 -0
- forgetproof/sqlite_residue.py +226 -0
- forgetproof/subject.py +81 -0
- forgetproof-0.2.0.dist-info/METADATA +397 -0
- forgetproof-0.2.0.dist-info/RECORD +42 -0
- forgetproof-0.2.0.dist-info/WHEEL +4 -0
- forgetproof-0.2.0.dist-info/entry_points.txt +3 -0
- forgetproof-0.2.0.dist-info/licenses/LICENSE +21 -0
forgetproof/discovery.py
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
"""forgetproof init: find likely memory stores under a directory, confirm once, and pin them.
|
|
2
|
+
|
|
3
|
+
The point of pinning is that the *operator* decides what forgetproof may ever touch, not
|
|
4
|
+
whatever an automated scan happens to find lying around a directory tree later on — init only
|
|
5
|
+
proposes; it writes nothing without one confirmation. Once pinned, every command that resolves a
|
|
6
|
+
store by its name refuses it outright if what's actually there no longer matches what was pinned
|
|
7
|
+
(a file where a directory used to be, and the reverse), rather than silently acting on it.
|
|
8
|
+
|
|
9
|
+
A pinned Postgres store records the *name* of an environment variable, never the URL itself, so
|
|
10
|
+
a config file on disk never holds a password and a rotated credential needs no re-pinning.
|
|
11
|
+
|
|
12
|
+
Finding a config by walking up from the current directory, the way `init` makes that convenient,
|
|
13
|
+
means the directory it's found in isn't necessarily one `init` was ever run in on purpose — a
|
|
14
|
+
shared, world-writable directory (a bare `/tmp`, say) could hold one planted by someone else
|
|
15
|
+
entirely. find_config() only ever considers a candidate this user owns, isn't a symlink, and isn't
|
|
16
|
+
writable by anyone else, and stops climbing the moment an ancestor directory itself isn't owned by
|
|
17
|
+
this user — a directory nobody here owns is exactly where another user could have planted one.
|
|
18
|
+
resolve() narrows what a trusted config can still do: a path-kind entry must resolve inside the
|
|
19
|
+
directory the config file came from, and a postgres entry must name one of ENV_URL_VARS.
|
|
20
|
+
|
|
21
|
+
The ownership and writability checks are POSIX-only (Python's stat() can't see a real owner or
|
|
22
|
+
ACL on Windows); on Windows, every directory is treated as this user's own, same as before this
|
|
23
|
+
module existed. The containment and allowlist checks in resolve() hold on every platform.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import json
|
|
29
|
+
import os
|
|
30
|
+
import stat
|
|
31
|
+
from dataclasses import dataclass
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
|
|
34
|
+
from . import files_store, lance_store, mem0_store, qdrant_store
|
|
35
|
+
|
|
36
|
+
CONFIG_NAME = ".forgetproof.json"
|
|
37
|
+
HOME_CONFIG = "stores.json" # under FORGETPROOF_HOME: the stores `init --home` pinned for this user
|
|
38
|
+
ENV_URL_VARS = ("DATABASE_URL", "POSTGRES_URL", "PG_URL", "FORGETPROOF_PG_URL")
|
|
39
|
+
_SKIP_NAMES = {".git", ".hg", ".venv", "venv", "node_modules", "__pycache__", "site-packages", ".tox", ".mypy_cache"}
|
|
40
|
+
_SQLITE_SUFFIXES = (".db", ".sqlite", ".sqlite3")
|
|
41
|
+
_SQLITE_MAGIC = b"SQLite format 3\x00"
|
|
42
|
+
KINDS = ("chroma", "sqlite", "postgres", "mem0", "qdrant", "lancedb", "files")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class Found:
|
|
47
|
+
name: str
|
|
48
|
+
kind: str # one of KINDS
|
|
49
|
+
where: str # a resolved path, or (for postgres) the name of an environment variable
|
|
50
|
+
agent: str = "" # the agent runtime this store belongs to, when discovery knows ("Claude Code", "mem0", …)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _looks_like_sqlite(path: Path) -> bool:
|
|
54
|
+
try:
|
|
55
|
+
with path.open("rb") as f:
|
|
56
|
+
return f.read(len(_SQLITE_MAGIC)) == _SQLITE_MAGIC
|
|
57
|
+
except OSError:
|
|
58
|
+
return False
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _unique(name: str, taken: set[str]) -> str:
|
|
62
|
+
candidate, n = name, 2
|
|
63
|
+
while candidate in taken:
|
|
64
|
+
candidate, n = f"{name}-{n}", n + 1
|
|
65
|
+
taken.add(candidate)
|
|
66
|
+
return candidate
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _dir_kind(d: Path) -> str | None:
|
|
70
|
+
"""A directory that is a store in itself, by its marker files."""
|
|
71
|
+
if (d / "chroma.sqlite3").is_file():
|
|
72
|
+
return "chroma"
|
|
73
|
+
if mem0_store.detect(d):
|
|
74
|
+
return "mem0"
|
|
75
|
+
if qdrant_store.detect(d):
|
|
76
|
+
return "qdrant"
|
|
77
|
+
if lance_store.detect(d):
|
|
78
|
+
return "lancedb"
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def discover(root: Path, *, max_depth: int = 4, env: bool = True, taken: set[str] | None = None) -> list[Found]:
|
|
83
|
+
"""Chroma, mem0, Qdrant local and LanceDB directories and SQLite files under `root`, plus (with
|
|
84
|
+
`env`) any of ENV_URL_VARS that currently holds a postgresql:// URL. Doesn't follow symlinks, so
|
|
85
|
+
a planted one can't widen the search."""
|
|
86
|
+
root = root.resolve()
|
|
87
|
+
found: list[Found] = []
|
|
88
|
+
taken = set() if taken is None else taken
|
|
89
|
+
|
|
90
|
+
def walk(d: Path, depth: int) -> None:
|
|
91
|
+
if depth > max_depth:
|
|
92
|
+
return
|
|
93
|
+
try:
|
|
94
|
+
entries = sorted(d.iterdir())
|
|
95
|
+
except OSError:
|
|
96
|
+
return
|
|
97
|
+
kind = _dir_kind(d)
|
|
98
|
+
if kind:
|
|
99
|
+
found.append(Found(_unique(d.name, taken), kind, str(d)))
|
|
100
|
+
return # a store's own internals aren't a separate thing to find
|
|
101
|
+
for entry in entries:
|
|
102
|
+
if entry.is_symlink():
|
|
103
|
+
continue
|
|
104
|
+
if entry.is_dir():
|
|
105
|
+
if entry.name in _SKIP_NAMES or entry.name.startswith("."):
|
|
106
|
+
continue
|
|
107
|
+
walk(entry, depth + 1)
|
|
108
|
+
elif entry.suffix in _SQLITE_SUFFIXES and _looks_like_sqlite(entry):
|
|
109
|
+
kind = "mem0" if mem0_store.is_history_db(entry) else "sqlite"
|
|
110
|
+
found.append(Found(_unique(entry.stem, taken), kind, str(entry)))
|
|
111
|
+
|
|
112
|
+
walk(root, 0)
|
|
113
|
+
if env:
|
|
114
|
+
for var in ENV_URL_VARS:
|
|
115
|
+
url = os.environ.get(var, "")
|
|
116
|
+
if url.startswith(("postgresql://", "postgres://")):
|
|
117
|
+
found.append(Found(_unique(var.lower(), taken), "postgres", var))
|
|
118
|
+
return found
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
# --- the places known agent runtimes keep their memory -------------------------------------------
|
|
122
|
+
|
|
123
|
+
def _mcp_memory_files(home: Path) -> list[Path]:
|
|
124
|
+
"""Memory files named in MCP client configs: the reference memory server's MEMORY_FILE_PATH."""
|
|
125
|
+
configs = [
|
|
126
|
+
home / ".claude.json",
|
|
127
|
+
home / ".mcp.json",
|
|
128
|
+
home / ".cursor" / "mcp.json",
|
|
129
|
+
home / ".codeium" / "windsurf" / "mcp_config.json",
|
|
130
|
+
home / "AppData" / "Roaming" / "Claude" / "claude_desktop_config.json",
|
|
131
|
+
home / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json",
|
|
132
|
+
home / ".config" / "Claude" / "claude_desktop_config.json",
|
|
133
|
+
]
|
|
134
|
+
out: list[Path] = []
|
|
135
|
+
|
|
136
|
+
def servers(node) -> None:
|
|
137
|
+
if isinstance(node, dict):
|
|
138
|
+
if "mcpServers" in node and isinstance(node["mcpServers"], dict):
|
|
139
|
+
for s in node["mcpServers"].values():
|
|
140
|
+
env = s.get("env") if isinstance(s, dict) else None
|
|
141
|
+
p = env.get("MEMORY_FILE_PATH") if isinstance(env, dict) else None
|
|
142
|
+
if isinstance(p, str) and p:
|
|
143
|
+
out.append(Path(os.path.expanduser(p)))
|
|
144
|
+
for v in node.values():
|
|
145
|
+
servers(v)
|
|
146
|
+
|
|
147
|
+
for c in configs:
|
|
148
|
+
if not c.is_file() or c.is_symlink():
|
|
149
|
+
continue
|
|
150
|
+
try:
|
|
151
|
+
servers(json.loads(c.read_text(encoding="utf-8")))
|
|
152
|
+
except (OSError, ValueError):
|
|
153
|
+
continue
|
|
154
|
+
return out
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _project_label(slug: str) -> str:
|
|
158
|
+
"""Claude Code names a project directory after its path with the separators turned into dashes
|
|
159
|
+
(`C--Users-me-Documents-app`). The readable part is the end: the folder's own name, or the last
|
|
160
|
+
two pieces when that alone is too short to recognise."""
|
|
161
|
+
parts = [s for s in slug.lower().split("-") if s]
|
|
162
|
+
if not parts:
|
|
163
|
+
return slug.lower() or "project"
|
|
164
|
+
label = parts[-1]
|
|
165
|
+
if len(label) < 4 and len(parts) > 1:
|
|
166
|
+
label = "-".join(parts[-2:])
|
|
167
|
+
return label[:40]
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def known_stores(home: Path | None = None) -> list[Found]:
|
|
171
|
+
"""Stores at the paths known agent runtimes use, each tagged with its agent. Only what exists."""
|
|
172
|
+
home = (home or Path.home()).resolve()
|
|
173
|
+
taken: set[str] = set()
|
|
174
|
+
found: list[Found] = []
|
|
175
|
+
|
|
176
|
+
def add(name: str, kind: str, where: Path, agent: str) -> None:
|
|
177
|
+
if where.is_symlink() or not where.exists():
|
|
178
|
+
return
|
|
179
|
+
found.append(Found(_unique(name, taken), kind, str(where.resolve()), agent))
|
|
180
|
+
|
|
181
|
+
# Claude Code: memory as markdown, transcripts as JSONL, per project.
|
|
182
|
+
projects = home / ".claude" / "projects"
|
|
183
|
+
if projects.is_dir():
|
|
184
|
+
for p in sorted(projects.iterdir()):
|
|
185
|
+
if p.is_dir() and not p.is_symlink() and files_store.detect(p):
|
|
186
|
+
add("claude-" + _project_label(p.name), "files", p, "Claude Code")
|
|
187
|
+
if (home / ".claude" / "history.jsonl").is_file():
|
|
188
|
+
add("claude-history", "files", home / ".claude" / "history.jsonl", "Claude Code")
|
|
189
|
+
# mem0
|
|
190
|
+
mem0_dir = Path(os.environ.get("MEM0_DIR") or home / ".mem0")
|
|
191
|
+
if mem0_store.detect(mem0_dir):
|
|
192
|
+
add("mem0", "mem0", mem0_dir, "mem0")
|
|
193
|
+
# Letta
|
|
194
|
+
letta = home / ".letta" / "sqlite.db"
|
|
195
|
+
if letta.is_file() and _looks_like_sqlite(letta):
|
|
196
|
+
add("letta", "sqlite", letta, "Letta")
|
|
197
|
+
# The reference memory MCP server, wherever a client config points it
|
|
198
|
+
for f in _mcp_memory_files(home):
|
|
199
|
+
if f.is_file():
|
|
200
|
+
add("memory-server", "files", f, "memory MCP server")
|
|
201
|
+
# Obsidian vaults: a directory with .obsidian in it, one level under the usual places
|
|
202
|
+
for base in (home, home / "Documents", home / "Desktop", home / "iCloud Drive"):
|
|
203
|
+
if not base.is_dir():
|
|
204
|
+
continue
|
|
205
|
+
try:
|
|
206
|
+
for d in sorted(base.iterdir()):
|
|
207
|
+
if d.is_dir() and not d.is_symlink() and (d / ".obsidian").is_dir():
|
|
208
|
+
add("obsidian-" + d.name.lower().replace(" ", "-"), "files", d, "Obsidian")
|
|
209
|
+
except OSError:
|
|
210
|
+
continue
|
|
211
|
+
return found
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
HOME_ROOTS = ("Documents", "Desktop", "dev", "code", "projects", "Projects", "src", "repos", "work")
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def discover_home(home: Path | None = None, *, max_depth: int = 3) -> list[Found]:
|
|
218
|
+
"""Everything `known_stores` knows, plus a bounded search of the usual project folders. The
|
|
219
|
+
whole home directory is never walked."""
|
|
220
|
+
home = (home or Path.home()).resolve()
|
|
221
|
+
found = known_stores(home)
|
|
222
|
+
seen = {f.where for f in found}
|
|
223
|
+
taken = {f.name for f in found}
|
|
224
|
+
for name in HOME_ROOTS:
|
|
225
|
+
root = home / name
|
|
226
|
+
if root.is_dir() and not root.is_symlink():
|
|
227
|
+
for f in discover(root, max_depth=max_depth, env=False, taken=taken):
|
|
228
|
+
if f.where not in seen:
|
|
229
|
+
seen.add(f.where)
|
|
230
|
+
found.append(f)
|
|
231
|
+
return found
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def home_config_path() -> Path:
|
|
235
|
+
from .receipt import key_path
|
|
236
|
+
|
|
237
|
+
return key_path().parent / HOME_CONFIG
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def config_path(root: Path) -> Path:
|
|
241
|
+
return root.resolve() / CONFIG_NAME
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _owned_by_me(path: Path) -> bool:
|
|
245
|
+
if not hasattr(os, "getuid"):
|
|
246
|
+
return True # no POSIX ownership model to check (Windows)
|
|
247
|
+
try:
|
|
248
|
+
return path.stat().st_uid == os.getuid()
|
|
249
|
+
except OSError:
|
|
250
|
+
return False
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _trustworthy_config(path: Path) -> bool:
|
|
254
|
+
"""Would `init` itself plausibly have written this: this user's own, a real file (not a
|
|
255
|
+
symlink someone else could have swapped in), and not writable by anyone else."""
|
|
256
|
+
if path.is_symlink() or not _owned_by_me(path):
|
|
257
|
+
return False
|
|
258
|
+
if not hasattr(os, "getuid"):
|
|
259
|
+
return path.is_file()
|
|
260
|
+
try:
|
|
261
|
+
mode = path.stat().st_mode
|
|
262
|
+
except OSError:
|
|
263
|
+
return False
|
|
264
|
+
return stat.S_ISREG(mode) and not (mode & (stat.S_IWGRP | stat.S_IWOTH))
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def find_config(start: Path, *, max_up: int = 10) -> Path | None:
|
|
268
|
+
"""Walk upward from `start` (like git finds .git) for a trustworthy CONFIG_NAME.
|
|
269
|
+
|
|
270
|
+
Stops — rather than skipping past — the first ancestor this user doesn't own: nothing
|
|
271
|
+
above a directory nobody here owns should be treated as this user's own project.
|
|
272
|
+
"""
|
|
273
|
+
d = start.resolve()
|
|
274
|
+
for _ in range(max_up):
|
|
275
|
+
if not _owned_by_me(d):
|
|
276
|
+
return None
|
|
277
|
+
candidate = d / CONFIG_NAME
|
|
278
|
+
if candidate.exists() and _trustworthy_config(candidate):
|
|
279
|
+
return candidate
|
|
280
|
+
if d.parent == d:
|
|
281
|
+
break
|
|
282
|
+
d = d.parent
|
|
283
|
+
return None
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def write_config(root: Path, chosen: list[Found], *, path: Path | None = None) -> Path:
|
|
287
|
+
path = path or config_path(root)
|
|
288
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
289
|
+
data = {"stores": {f.name: {"kind": f.kind, "where": f.where, **({"agent": f.agent} if f.agent else {})}
|
|
290
|
+
for f in chosen}}
|
|
291
|
+
path.write_text(json.dumps(data, indent=2) + "\n")
|
|
292
|
+
try:
|
|
293
|
+
path.chmod(0o600)
|
|
294
|
+
except OSError:
|
|
295
|
+
pass
|
|
296
|
+
return path
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def load_config(path: Path) -> dict[str, Found]:
|
|
300
|
+
data = json.loads(path.read_text())
|
|
301
|
+
return {name: Found(name, v["kind"], v["where"], v.get("agent", "")) for name, v in data.get("stores", {}).items()}
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def load_home_config() -> dict[str, Found]:
|
|
305
|
+
"""The stores pinned by `init --home`, if that file is trustworthy; otherwise none."""
|
|
306
|
+
path = home_config_path()
|
|
307
|
+
if not path.exists() or not _trustworthy_config(path):
|
|
308
|
+
return {}
|
|
309
|
+
return load_config(path)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _kind_matches(kind: str, path: Path) -> bool:
|
|
313
|
+
if kind == "chroma":
|
|
314
|
+
return (path / "chroma.sqlite3").is_file()
|
|
315
|
+
if kind == "sqlite":
|
|
316
|
+
return _looks_like_sqlite(path)
|
|
317
|
+
if kind == "mem0":
|
|
318
|
+
return mem0_store.detect(path)
|
|
319
|
+
if kind == "qdrant":
|
|
320
|
+
return qdrant_store.detect(path)
|
|
321
|
+
if kind == "lancedb":
|
|
322
|
+
return lance_store.detect(path)
|
|
323
|
+
if kind == "files":
|
|
324
|
+
return files_store.detect(path)
|
|
325
|
+
return False
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def resolve(found: Found, root: Path | None = None) -> Path | str:
|
|
329
|
+
"""What this pinned entry currently points to — refusing if its kind no longer matches, if a
|
|
330
|
+
postgres entry names anything other than one of ENV_URL_VARS, or (when `root` is given — pass
|
|
331
|
+
the directory the config file came from) if it points outside that directory tree. That last
|
|
332
|
+
check matters even for a config this user does trust: nothing a pinned entry says should be
|
|
333
|
+
able to send forgetproof to touch a path outside the project `init` was run in.
|
|
334
|
+
"""
|
|
335
|
+
if found.kind == "postgres":
|
|
336
|
+
if found.where not in ENV_URL_VARS:
|
|
337
|
+
raise ValueError(f"store {found.name!r} names {found.where!r}, which isn't one of the "
|
|
338
|
+
f"recognized environment variables ({', '.join(ENV_URL_VARS)})")
|
|
339
|
+
url = os.environ.get(found.where, "")
|
|
340
|
+
if not url.startswith(("postgresql://", "postgres://")):
|
|
341
|
+
raise ValueError(
|
|
342
|
+
f"store {found.name!r} was pinned to the {found.where} environment variable, which "
|
|
343
|
+
"doesn't currently hold a postgresql:// URL"
|
|
344
|
+
)
|
|
345
|
+
return url
|
|
346
|
+
path = Path(found.where)
|
|
347
|
+
if root is not None:
|
|
348
|
+
try:
|
|
349
|
+
path.resolve().relative_to(root.resolve())
|
|
350
|
+
except ValueError:
|
|
351
|
+
raise ValueError(f"store {found.name!r} points to {path}, which is outside {root}") from None
|
|
352
|
+
if found.kind not in KINDS:
|
|
353
|
+
raise ValueError(f"store {found.name!r} has an unknown kind {found.kind!r}")
|
|
354
|
+
if not _kind_matches(found.kind, path):
|
|
355
|
+
raise ValueError(f"store {found.name!r} was pinned to a {found.kind} store at {path}, "
|
|
356
|
+
"which no longer looks like one")
|
|
357
|
+
return path
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Delete *live* records that carry a value — the owner's explicit choice, never the default.
|
|
2
|
+
|
|
3
|
+
`fix` and `forget` erase what a store has already deleted but still holds. Sometimes the person
|
|
4
|
+
wants more than that: "forget Alice" when the agent never deleted her in the first place. That
|
|
5
|
+
means removing live records, which is the agent's job through its own API — but on a personal
|
|
6
|
+
machine the person is the agent's operator, and the desktop app and the MCP server in owner mode
|
|
7
|
+
offer it with a separate, named switch (`--also-live`, "also delete live records that are exactly
|
|
8
|
+
this value").
|
|
9
|
+
|
|
10
|
+
The rule is deliberately blunt so it's predictable: a record is removed when it *contains* one of
|
|
11
|
+
the subject's exact values. For a text file that is the line; for a SQLite table the row; for a
|
|
12
|
+
Chroma collection the record whose document contains it; for LanceDB the row whose string column
|
|
13
|
+
contains it; for Qdrant local the point whose pickled payload contains it. A record that mentions
|
|
14
|
+
Alice without any of her exact values is not touched, and the receipt says how many records went.
|
|
15
|
+
|
|
16
|
+
Nothing here is offered for Postgres: that is an operator's store and its application owns its
|
|
17
|
+
rows.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import sqlite3
|
|
25
|
+
import tempfile
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
|
|
28
|
+
from . import files_store, mem0_store, postgres, qdrant_store
|
|
29
|
+
from .scanner import detect
|
|
30
|
+
from .sqlite_residue import table_columns, vacuum
|
|
31
|
+
from .subject import Subject
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class LiveEraseError(Exception):
|
|
35
|
+
pass
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _variants(subject: Subject) -> list[str]:
|
|
39
|
+
out: list[str] = []
|
|
40
|
+
for n in subject.needles:
|
|
41
|
+
for v in (n, n.lower()):
|
|
42
|
+
if v not in out:
|
|
43
|
+
out.append(v)
|
|
44
|
+
return out
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _erase_text_file(path: Path, variants: list[str]) -> int:
|
|
48
|
+
data = path.read_bytes()
|
|
49
|
+
newline = b"\r\n" if b"\r\n" in data else b"\n"
|
|
50
|
+
lines = data.split(b"\n")
|
|
51
|
+
needles = [v.encode() for v in variants]
|
|
52
|
+
kept = [line for line in lines if not any(n in line or n in line.lower() for n in needles)]
|
|
53
|
+
removed = len(lines) - len(kept)
|
|
54
|
+
if not removed:
|
|
55
|
+
return 0
|
|
56
|
+
out = b"\n".join(kept)
|
|
57
|
+
if newline == b"\r\n":
|
|
58
|
+
out = out.replace(b"\r\n", b"\n").replace(b"\n", b"\r\n")
|
|
59
|
+
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".forgetproof")
|
|
60
|
+
try:
|
|
61
|
+
with os.fdopen(fd, "wb") as f:
|
|
62
|
+
f.write(out)
|
|
63
|
+
try:
|
|
64
|
+
os.chmod(tmp, path.stat().st_mode & 0o777)
|
|
65
|
+
except OSError:
|
|
66
|
+
pass
|
|
67
|
+
os.replace(tmp, path)
|
|
68
|
+
except BaseException:
|
|
69
|
+
Path(tmp).unlink(missing_ok=True)
|
|
70
|
+
raise
|
|
71
|
+
return removed
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _erase_sqlite(db: Path, variants: list[str], *, tables: list[str] | None = None) -> dict[str, int]:
|
|
75
|
+
conn = sqlite3.connect(db)
|
|
76
|
+
removed: dict[str, int] = {}
|
|
77
|
+
try:
|
|
78
|
+
conn.execute("pragma secure_delete=on")
|
|
79
|
+
for table, columns in table_columns(conn).items():
|
|
80
|
+
if tables is not None and table not in tables:
|
|
81
|
+
continue
|
|
82
|
+
quoted = '"' + table.replace('"', '""') + '"'
|
|
83
|
+
clauses, params = [], []
|
|
84
|
+
for col in columns:
|
|
85
|
+
qc = '"' + col.replace('"', '""') + '"'
|
|
86
|
+
for v in variants:
|
|
87
|
+
clauses.append(f"(typeof({qc}) = 'text' and instr({qc}, ?) > 0)")
|
|
88
|
+
params.append(v)
|
|
89
|
+
clauses.append(f"(typeof({qc}) = 'blob' and instr({qc}, ?) > 0)")
|
|
90
|
+
params.append(v.encode())
|
|
91
|
+
if not clauses:
|
|
92
|
+
continue
|
|
93
|
+
try:
|
|
94
|
+
n = conn.execute(f"delete from {quoted} where {' or '.join(clauses)}", params).rowcount
|
|
95
|
+
except sqlite3.Error:
|
|
96
|
+
continue # a virtual table or one we can't query
|
|
97
|
+
if n:
|
|
98
|
+
removed[table] = n
|
|
99
|
+
conn.commit()
|
|
100
|
+
finally:
|
|
101
|
+
conn.close()
|
|
102
|
+
if removed:
|
|
103
|
+
vacuum(db)
|
|
104
|
+
return removed
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _erase_chroma(target: Path, variants: list[str]) -> list[str]:
|
|
108
|
+
# The chromadb client runs in a child process, as the fixer does, and the values go in on
|
|
109
|
+
# stdin: never on a command line another process could read.
|
|
110
|
+
from .fixer import _run_child
|
|
111
|
+
|
|
112
|
+
proc = _run_child("delete", str(target), input=json.dumps(variants))
|
|
113
|
+
if proc.returncode != 0:
|
|
114
|
+
raise LiveEraseError(f"deleting live Chroma records failed:\n{proc.stderr.strip()[-2000:]}")
|
|
115
|
+
return [line for line in proc.stderr.splitlines() if line.startswith("deleted ")]
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _erase_lance(target: Path, variants: list[str]) -> list[str]:
|
|
119
|
+
try:
|
|
120
|
+
import lancedb
|
|
121
|
+
import pyarrow as pa
|
|
122
|
+
except ImportError:
|
|
123
|
+
raise LiveEraseError("deleting live LanceDB rows needs lancedb: pip install 'forgetproof[lancedb]'") from None
|
|
124
|
+
from .lance_store import tables
|
|
125
|
+
|
|
126
|
+
actions = []
|
|
127
|
+
for table in tables(target):
|
|
128
|
+
t = lancedb.connect(str(table.parent)).open_table(table.stem)
|
|
129
|
+
string_cols = [f.name for f in t.schema if pa.types.is_string(f.type) or pa.types.is_large_string(f.type)]
|
|
130
|
+
if not string_cols:
|
|
131
|
+
continue
|
|
132
|
+
clauses = []
|
|
133
|
+
for col in string_cols:
|
|
134
|
+
for v in variants:
|
|
135
|
+
escaped = v.replace("'", "''").replace("%", "\\%").replace("_", "\\_")
|
|
136
|
+
clauses.append(f"`{col}` LIKE '%{escaped}%' ESCAPE '\\'")
|
|
137
|
+
before = t.count_rows()
|
|
138
|
+
t.delete(" OR ".join(clauses))
|
|
139
|
+
gone = before - t.count_rows()
|
|
140
|
+
if gone:
|
|
141
|
+
actions.append(f"deleted {gone} live row(s) from {table.name}")
|
|
142
|
+
return actions
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def erase_live(target: Path | str, subject: Subject) -> list[str]:
|
|
146
|
+
"""Remove every live record that contains one of `subject`'s values. Returns what was done, as
|
|
147
|
+
counts. Raises LiveEraseError for a Postgres target."""
|
|
148
|
+
if postgres.is_postgres(target):
|
|
149
|
+
raise LiveEraseError("live deletion isn't offered for Postgres: delete the rows through your application, "
|
|
150
|
+
"then run forget to erase what it leaves behind")
|
|
151
|
+
target = Path(target).resolve()
|
|
152
|
+
kind = detect(target)
|
|
153
|
+
variants = _variants(subject)
|
|
154
|
+
actions: list[str] = []
|
|
155
|
+
if kind == "files":
|
|
156
|
+
total = 0
|
|
157
|
+
for f in files_store.files(target):
|
|
158
|
+
total += _erase_text_file(f, variants)
|
|
159
|
+
if total:
|
|
160
|
+
actions.append(f"removed {total} line(s) containing the value from {len(files_store.files(target))} file(s)")
|
|
161
|
+
elif kind == "sqlite":
|
|
162
|
+
for table, n in _erase_sqlite(target, variants).items():
|
|
163
|
+
actions.append(f"deleted {n} live row(s) from {table}")
|
|
164
|
+
elif kind == "mem0":
|
|
165
|
+
db = mem0_store.history_db(target)
|
|
166
|
+
for table, n in _erase_sqlite(db, variants).items():
|
|
167
|
+
actions.append(f"deleted {n} live row(s) from {mem0_store.HISTORY} {table}")
|
|
168
|
+
for sub in mem0_store.qdrant_dirs(target):
|
|
169
|
+
for name, sdb in qdrant_store.collections(sub):
|
|
170
|
+
for table, n in _erase_sqlite(sdb, variants, tables=["points"]).items():
|
|
171
|
+
actions.append(f"deleted {n} live point(s) from {sub.name}/collection/{name}")
|
|
172
|
+
elif kind == "qdrant":
|
|
173
|
+
for name, sdb in qdrant_store.collections(target):
|
|
174
|
+
for table, n in _erase_sqlite(sdb, variants, tables=["points"]).items():
|
|
175
|
+
actions.append(f"deleted {n} live point(s) from collection/{name}")
|
|
176
|
+
elif kind == "chroma":
|
|
177
|
+
actions += _erase_chroma(target, variants)
|
|
178
|
+
elif kind == "lancedb":
|
|
179
|
+
actions += _erase_lance(target, variants)
|
|
180
|
+
return actions or ["no live record contained the value"]
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Plain-text memory: markdown and JSON Lines files.
|
|
2
|
+
|
|
3
|
+
Claude Code keeps its memory as markdown files and its transcripts as JSONL; the reference memory
|
|
4
|
+
MCP server keeps a knowledge graph as one JSONL file; Obsidian vaults and `CLAUDE.md`/`AGENTS.md`
|
|
5
|
+
are markdown. These files have no deleted-but-recoverable layer of their own: a tool that removes
|
|
6
|
+
an entry rewrites the file, and what isn't in the file isn't in the file. What forgetproof adds for
|
|
7
|
+
them is the rest of the picture — is a value still *in* them (the person asked the agent to forget
|
|
8
|
+
and it didn't), which copies of them exist, and, in owner mode, removing the lines that carry a
|
|
9
|
+
value (`forget --also-live`), written back atomically.
|
|
10
|
+
|
|
11
|
+
A canary found in a text store is therefore reported as still present, not as residue, and the
|
|
12
|
+
store is "clean" only in the sense that nothing hidden remains: the CLI says so.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from .report import Report
|
|
20
|
+
|
|
21
|
+
SUFFIXES = (".md", ".markdown", ".jsonl", ".json", ".txt")
|
|
22
|
+
MAX_DEPTH = 3
|
|
23
|
+
_SKIP = {".git", ".obsidian", "node_modules", ".venv", "__pycache__"}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def files(target: Path) -> list[Path]:
|
|
27
|
+
if target.is_file():
|
|
28
|
+
return [target]
|
|
29
|
+
out: list[Path] = []
|
|
30
|
+
|
|
31
|
+
def walk(d: Path, depth: int) -> None:
|
|
32
|
+
if depth > MAX_DEPTH:
|
|
33
|
+
return
|
|
34
|
+
try:
|
|
35
|
+
entries = sorted(d.iterdir())
|
|
36
|
+
except OSError:
|
|
37
|
+
return
|
|
38
|
+
for e in entries:
|
|
39
|
+
if e.is_symlink():
|
|
40
|
+
continue
|
|
41
|
+
if e.is_dir():
|
|
42
|
+
if e.name not in _SKIP:
|
|
43
|
+
walk(e, depth + 1)
|
|
44
|
+
elif e.suffix.lower() in SUFFIXES:
|
|
45
|
+
out.append(e)
|
|
46
|
+
|
|
47
|
+
walk(target, 0)
|
|
48
|
+
return out
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def detect(target: Path) -> bool:
|
|
52
|
+
if target.is_file():
|
|
53
|
+
return target.suffix.lower() in SUFFIXES
|
|
54
|
+
return target.is_dir() and bool(files(target))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def scan(target: Path, report: Report, show: bool = False) -> None:
|
|
58
|
+
fs = files(target)
|
|
59
|
+
report.stats["files"] = len(fs)
|
|
60
|
+
report.stats["bytes"] = sum(f.stat().st_size for f in fs)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def plan(report: Report) -> list[str]:
|
|
64
|
+
return ["nothing to rewrite: text files keep no deleted data. A value still present is live content; "
|
|
65
|
+
"`forget --also-live` removes the lines that carry it"]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def fix(target: Path) -> list[str]:
|
|
69
|
+
return ["nothing rewritten: text files keep no deleted data"]
|