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
|
@@ -0,0 +1,541 @@
|
|
|
1
|
+
"""MCP server: lets an agent scan the stores its operator allows, and ask to be forgotten.
|
|
2
|
+
|
|
3
|
+
forgetproof mcp --store memory=./chroma_dir --store pg=postgresql://app@db/agent \\
|
|
4
|
+
[--allow-fix] [--subject-file /run/forgetproof/current-user] # an application's agent
|
|
5
|
+
forgetproof mcp --home --owner --allow-fix # the agent you run yourself
|
|
6
|
+
|
|
7
|
+
Two ways to run it, for two situations.
|
|
8
|
+
|
|
9
|
+
**An application's agent** (0.1, unchanged). The agent names stores, never paths, so it can only
|
|
10
|
+
reach what the operator listed. It can never name an arbitrary value to check or erase — that would
|
|
11
|
+
turn this into a tool for looking people up ("is bob@example.com still in here?"). The one value a
|
|
12
|
+
`forget_me` or `check_if_forgotten` call acts on is read from --subject-file, which only the
|
|
13
|
+
operator's application controls and refreshes (typically with the identity of whoever is signed
|
|
14
|
+
in). forgetproof refuses to read it unless it's a regular file owned by this process's own user, not
|
|
15
|
+
a symlink, and not writable by anyone else — otherwise another local user or process could redirect
|
|
16
|
+
who `forget_me` acts for, or use it as a side channel to probe whether an arbitrary value is stored.
|
|
17
|
+
Generic `scan_store` reports counts only, never whether a specific value is present.
|
|
18
|
+
|
|
19
|
+
**The agent you run yourself** (0.2, `--owner`). On a personal machine the person talking to the
|
|
20
|
+
agent is the operator, and the stores are theirs: Claude Code's memory, a mem0 directory, a Chroma
|
|
21
|
+
folder under a project. `--home` finds those (or uses what `forgetproof init --home` pinned), and
|
|
22
|
+
`--owner` turns on the tools that take a value — `what_is_remembered`, `forget_value` — because
|
|
23
|
+
"forget Alice's number" is the whole point. The trade-off is explicit and on the command line: in
|
|
24
|
+
owner mode the agent can look a value up in the person's own stores. Text around a match is only
|
|
25
|
+
returned with `--show`, so by default even owner mode keeps other people's data out of the agent's
|
|
26
|
+
context. Owner mode never applies to a Postgres store, and never to a store the operator didn't list.
|
|
27
|
+
|
|
28
|
+
`fix` is not offered unless --allow-fix is given. Responses carry counts only (plus, in owner mode,
|
|
29
|
+
*where* a value is): no samples and no values, so nothing personal ends up in chat logs.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import json
|
|
35
|
+
import os
|
|
36
|
+
import re
|
|
37
|
+
import sqlite3
|
|
38
|
+
import stat
|
|
39
|
+
import sys
|
|
40
|
+
import threading
|
|
41
|
+
import time
|
|
42
|
+
from dataclasses import dataclass
|
|
43
|
+
from datetime import datetime, timezone
|
|
44
|
+
from pathlib import Path
|
|
45
|
+
from typing import Any
|
|
46
|
+
|
|
47
|
+
from mcp.server.mcpserver import MCPServer
|
|
48
|
+
from mcp.server.mcpserver.exceptions import ToolError
|
|
49
|
+
from mcp.types import ToolAnnotations
|
|
50
|
+
|
|
51
|
+
from . import __version__, copies as copies_mod, discovery, forget as forget_mod, postgres, receipt, remembered, safety
|
|
52
|
+
from .erase_live import LiveEraseError
|
|
53
|
+
from .fixer import FixError, Options, fix, plan
|
|
54
|
+
from .report import Report
|
|
55
|
+
from .scanner import KINDS, UnsupportedStore, detect, scan
|
|
56
|
+
from .subject import subject as make_subject
|
|
57
|
+
|
|
58
|
+
STORE_NAME = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
|
|
59
|
+
RECEIPT_ID = re.compile(r"^([A-Za-z0-9_-]{1,64})\.(\d{8}T\d{12}Z)$")
|
|
60
|
+
_EXPECTED = (UnsupportedStore, FixError, LiveEraseError, postgres.PostgresError, ValueError, OSError, sqlite3.DatabaseError)
|
|
61
|
+
_COOLDOWN = 1.0 # seconds between value-scoped calls on the same store, to blunt rapid probing
|
|
62
|
+
MAX_VALUES = 20 # exact values one owner-mode call may name
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _read_trustworthy(path: Path) -> str:
|
|
66
|
+
"""Read `path` only if its directory and the file itself are each owned by root or by this
|
|
67
|
+
process's own user (the rule OpenSSH applies to the path to authorized_keys: a root-owned
|
|
68
|
+
directory that nobody else can write to is the normal place for a service's runtime files), not
|
|
69
|
+
symlinks, and not writable by anyone else. Both are opened with openat-style directory
|
|
70
|
+
file descriptors (the file is opened by name *inside* the already-opened, already-checked parent
|
|
71
|
+
directory fd) so nothing between the two checks and the read can be swapped out from under them —
|
|
72
|
+
including the parent directory being used to unlink and recreate the file in place. The file is
|
|
73
|
+
also opened non-blocking and rejected unless it's a regular file with exactly one link, so a FIFO
|
|
74
|
+
or a hardlink planted at the path can't hang the call (and the store lock along with it) or stand
|
|
75
|
+
in for a file we've otherwise decided to trust. Returns "" if the file is missing, empty, or fails
|
|
76
|
+
any of this, same as a missing subject: the caller can't tell those apart, which keeps the check
|
|
77
|
+
itself from becoming a side channel."""
|
|
78
|
+
if path.is_symlink(): # cross-platform; the ownership/writability checks below are POSIX-only
|
|
79
|
+
return ""
|
|
80
|
+
if not hasattr(os, "getuid"):
|
|
81
|
+
try:
|
|
82
|
+
return path.read_text().strip() # no POSIX ownership/writability model to check (Windows)
|
|
83
|
+
except OSError:
|
|
84
|
+
return ""
|
|
85
|
+
|
|
86
|
+
def trustworthy(st: os.stat_result) -> bool:
|
|
87
|
+
return st.st_uid in (0, os.getuid()) and not st.st_mode & (stat.S_IWGRP | stat.S_IWOTH)
|
|
88
|
+
|
|
89
|
+
dir_fd = file_fd = None
|
|
90
|
+
try:
|
|
91
|
+
dir_fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
|
92
|
+
if not trustworthy(os.fstat(dir_fd)):
|
|
93
|
+
return ""
|
|
94
|
+
file_fd = os.open(path.name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_NOCTTY | os.O_CLOEXEC,
|
|
95
|
+
dir_fd=dir_fd)
|
|
96
|
+
st = os.fstat(file_fd)
|
|
97
|
+
if not (stat.S_ISREG(st.st_mode) and st.st_nlink == 1 and trustworthy(st)):
|
|
98
|
+
return ""
|
|
99
|
+
os.set_blocking(file_fd, True)
|
|
100
|
+
return os.read(file_fd, 1 << 20).decode(errors="replace").strip()
|
|
101
|
+
except OSError:
|
|
102
|
+
return ""
|
|
103
|
+
finally:
|
|
104
|
+
if file_fd is not None:
|
|
105
|
+
os.close(file_fd)
|
|
106
|
+
if dir_fd is not None:
|
|
107
|
+
os.close(dir_fd)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
INSTRUCTIONS = """\
|
|
111
|
+
forgetproof checks whether deleted data is really gone from a memory store's files on disk.
|
|
112
|
+
|
|
113
|
+
Call `scan_store` to see whether a store has deleted-but-recoverable data in general. It never
|
|
114
|
+
checks for one specific value: you cannot use it, or any other tool here, to ask whether a
|
|
115
|
+
particular person's data is present. Call `check_if_forgotten` / `forget_me` for the one person
|
|
116
|
+
this session is about — the operator's application identifies who that is, not you.
|
|
117
|
+
|
|
118
|
+
When a user asks to be forgotten: delete their records with your normal memory tools first, then
|
|
119
|
+
call `forget_me` (if available) and give the user the resulting receipt id.
|
|
120
|
+
|
|
121
|
+
`forget_me` can come back queued rather than done: for Chroma it can't rewrite the store while
|
|
122
|
+
the application still has it open, so it queues the erasure for the application's next start.
|
|
123
|
+
Tell the user it's scheduled, not failed.
|
|
124
|
+
"""
|
|
125
|
+
|
|
126
|
+
OWNER_INSTRUCTIONS = """\
|
|
127
|
+
forgetproof checks whether something the user asked you to forget is really gone from the memory
|
|
128
|
+
stores on this machine — theirs, listed by their operator — and erases what is left.
|
|
129
|
+
|
|
130
|
+
This server runs in owner mode: the user owns these stores, so when they name a value (a person's
|
|
131
|
+
name, an email, a phone number, something they pasted by mistake) you may pass it to
|
|
132
|
+
`what_is_remembered` to see which stores still hold it, live or as deleted-but-recoverable bytes,
|
|
133
|
+
and to `forget_value` to erase it. Only pass values the user gave you in this conversation; never
|
|
134
|
+
guess related values, and never use these tools to look up anyone the user didn't ask about.
|
|
135
|
+
|
|
136
|
+
A good "forget X" goes: delete X with your own memory tools if you have them, then call
|
|
137
|
+
`forget_value` with X's exact values (all of them: name, emails, phones), then tell the user the
|
|
138
|
+
receipt id(s) and what `copies_of` says about places this machine can't clean (a cloud sync folder,
|
|
139
|
+
git history). `forget_value` leaves live records alone unless `also_live` is true — ask the user
|
|
140
|
+
before setting it, since it deletes every record that contains one of the values.
|
|
141
|
+
|
|
142
|
+
A store that is open in another program (an agent running right now) can't be rewritten: the
|
|
143
|
+
erasure is queued and finishes at that program's next start. Tell the user it's scheduled, not
|
|
144
|
+
failed. `sweep` fixes every store that isn't open, with one receipt each.
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@dataclass(frozen=True)
|
|
149
|
+
class Store:
|
|
150
|
+
name: str
|
|
151
|
+
target: Path | str
|
|
152
|
+
kind: str = ""
|
|
153
|
+
agent: str = ""
|
|
154
|
+
|
|
155
|
+
@property
|
|
156
|
+
def location(self) -> str:
|
|
157
|
+
return postgres.display(self.target) if isinstance(self.target, str) else str(self.target)
|
|
158
|
+
|
|
159
|
+
@property
|
|
160
|
+
def is_postgres(self) -> bool:
|
|
161
|
+
return isinstance(self.target, str)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def parse_store(spec: str) -> Store:
|
|
165
|
+
name, sep, where = spec.partition("=")
|
|
166
|
+
if not sep or not STORE_NAME.match(name) or not where:
|
|
167
|
+
raise ValueError(f"--store expects NAME=PATH_OR_URL with NAME made of letters, digits, - and _: {spec!r}")
|
|
168
|
+
if postgres.is_postgres(where):
|
|
169
|
+
return Store(name, where, "postgres")
|
|
170
|
+
path = Path(where).expanduser().resolve()
|
|
171
|
+
if not path.exists():
|
|
172
|
+
raise ValueError(f"store {name!r}: {path} does not exist")
|
|
173
|
+
try:
|
|
174
|
+
kind = detect(path)
|
|
175
|
+
except UnsupportedStore:
|
|
176
|
+
kind = ""
|
|
177
|
+
return Store(name, path, kind)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def home_stores() -> list[Store]:
|
|
181
|
+
"""The stores `forgetproof init --home` pinned, or, if it was never run, what discovery finds now."""
|
|
182
|
+
pinned = discovery.load_home_config()
|
|
183
|
+
stores: list[Store] = []
|
|
184
|
+
if pinned:
|
|
185
|
+
for name, f in pinned.items():
|
|
186
|
+
try:
|
|
187
|
+
stores.append(Store(name, discovery.resolve(f, root=Path.home()), f.kind, f.agent))
|
|
188
|
+
except ValueError as e:
|
|
189
|
+
print(f"forgetproof: skipping pinned store {name!r}: {e}", file=sys.stderr)
|
|
190
|
+
return stores
|
|
191
|
+
for f in discovery.discover_home():
|
|
192
|
+
if f.kind == "postgres":
|
|
193
|
+
continue
|
|
194
|
+
stores.append(Store(f.name, Path(f.where), f.kind, f.agent))
|
|
195
|
+
return stores
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _findings(r: Report) -> dict[str, Any]:
|
|
199
|
+
return {
|
|
200
|
+
"clean": r.clean,
|
|
201
|
+
"store_type": r.store,
|
|
202
|
+
"incomplete": r.incomplete,
|
|
203
|
+
"findings": [
|
|
204
|
+
{"check": f.check, "what": f.title, "amount": f.records, "unit": f.unit,
|
|
205
|
+
"patterns": f.pii, "location": f.location}
|
|
206
|
+
for f in r.findings
|
|
207
|
+
],
|
|
208
|
+
"warnings": r.warnings,
|
|
209
|
+
"stats": r.stats,
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _open(s: Store) -> bool:
|
|
214
|
+
if s.is_postgres or s.kind == "files":
|
|
215
|
+
return False
|
|
216
|
+
try:
|
|
217
|
+
return bool(safety.open_by_other_processes(Path(s.target)))
|
|
218
|
+
except OSError:
|
|
219
|
+
return False
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def build(stores: list[Store], allow_fix: bool = False, receipts_dir: Path | None = None,
|
|
223
|
+
subject_file: Path | str | None = None, queue_dir: Path | str | None = None,
|
|
224
|
+
owner: bool = False, show: bool = False) -> MCPServer:
|
|
225
|
+
by_name = {s.name: s for s in stores}
|
|
226
|
+
if len(by_name) != len(stores):
|
|
227
|
+
raise ValueError("store names must be unique")
|
|
228
|
+
receipts = receipts_dir or receipt.key_path().parent / "receipts"
|
|
229
|
+
subject_path = Path(subject_file).expanduser().resolve() if subject_file else None
|
|
230
|
+
locks = {s.name: threading.Lock() for s in stores}
|
|
231
|
+
last_value_call: dict[str, float] = {}
|
|
232
|
+
|
|
233
|
+
def store(name: str) -> Store:
|
|
234
|
+
if name not in by_name:
|
|
235
|
+
raise ToolError(f"unknown store {name!r}; configured: {', '.join(by_name) or 'none'}")
|
|
236
|
+
return by_name[name]
|
|
237
|
+
|
|
238
|
+
def exclusive(name: str):
|
|
239
|
+
lock = locks[name]
|
|
240
|
+
if not lock.acquire(blocking=False):
|
|
241
|
+
raise ToolError(f"store {name!r} is busy with another forgetproof call; try again when it finishes")
|
|
242
|
+
return lock
|
|
243
|
+
|
|
244
|
+
def cooldown(name: str) -> None:
|
|
245
|
+
now = time.monotonic()
|
|
246
|
+
if now - last_value_call.get(name, 0.0) < _COOLDOWN:
|
|
247
|
+
raise ToolError("too many requests for this store in a row; wait a moment and try again")
|
|
248
|
+
last_value_call[name] = now
|
|
249
|
+
|
|
250
|
+
def current_subject() -> str:
|
|
251
|
+
if subject_path is None:
|
|
252
|
+
raise ToolError(
|
|
253
|
+
"this server wasn't started with --subject-file, so it has no signed-in user to act for. "
|
|
254
|
+
"The operator's application sets that file to the current user's identity; the agent cannot."
|
|
255
|
+
)
|
|
256
|
+
value = _read_trustworthy(subject_path)
|
|
257
|
+
if not value:
|
|
258
|
+
raise ToolError("no user is currently identified right now (the subject file is missing or empty)")
|
|
259
|
+
return value
|
|
260
|
+
|
|
261
|
+
def receipt_path(receipt_id: str) -> tuple[Store, Path]:
|
|
262
|
+
m = RECEIPT_ID.match(receipt_id)
|
|
263
|
+
if not m:
|
|
264
|
+
raise ToolError(f"not a receipt id: {receipt_id!r}")
|
|
265
|
+
path = receipts / f"{receipt_id}.json"
|
|
266
|
+
if not path.is_file():
|
|
267
|
+
raise ToolError(f"no receipt {receipt_id!r}")
|
|
268
|
+
return store(m.group(1)), path
|
|
269
|
+
|
|
270
|
+
def write_receipt(name: str, rec: dict) -> str:
|
|
271
|
+
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")
|
|
272
|
+
receipt_id = f"{name}.{stamp}"
|
|
273
|
+
receipts.mkdir(parents=True, exist_ok=True)
|
|
274
|
+
(receipts / f"{receipt_id}.json").write_text(json.dumps(rec, indent=2) + "\n")
|
|
275
|
+
return receipt_id
|
|
276
|
+
|
|
277
|
+
def owner_values(values: list[str]) -> Any:
|
|
278
|
+
if not owner:
|
|
279
|
+
raise ToolError("this server isn't in owner mode; a value can't be named here")
|
|
280
|
+
if not isinstance(values, list) or not values or len(values) > MAX_VALUES:
|
|
281
|
+
raise ToolError(f"give 1 to {MAX_VALUES} exact values")
|
|
282
|
+
try:
|
|
283
|
+
return make_subject([str(v) for v in values])
|
|
284
|
+
except ValueError as e:
|
|
285
|
+
raise ToolError(str(e)) from None
|
|
286
|
+
|
|
287
|
+
def owner_stores(store_name: str | None) -> list[Store]:
|
|
288
|
+
chosen = [store(store_name)] if store_name else list(stores)
|
|
289
|
+
return [s for s in chosen if not s.is_postgres] # owner mode never reaches a database
|
|
290
|
+
|
|
291
|
+
if allow_fix:
|
|
292
|
+
# Finish anything a previous forget queued (a store open elsewhere at the time) before this
|
|
293
|
+
# server starts offering fix on it. A failure here doesn't stop the server — it just means
|
|
294
|
+
# that queue is tried again on the next startup — and never reaches stdout.
|
|
295
|
+
for s in stores:
|
|
296
|
+
try:
|
|
297
|
+
for rec in forget_mod.run_queued(s.target, queue_dir=queue_dir):
|
|
298
|
+
receipt_id = write_receipt(s.name, rec)
|
|
299
|
+
if rec["verdict"] != "CLEAN":
|
|
300
|
+
print(f"forgetproof: a queued erasure for store {s.name!r} still shows residue "
|
|
301
|
+
f"(receipt {receipt_id}); it stays queued and is retried, up to "
|
|
302
|
+
f"{forget_mod.MAX_ATTEMPTS} attempts, rather than being dropped", file=sys.stderr)
|
|
303
|
+
except _EXPECTED as e:
|
|
304
|
+
print(f"forgetproof: couldn't finish a queued erasure for store {s.name!r}: {e}", file=sys.stderr)
|
|
305
|
+
|
|
306
|
+
server = MCPServer("forgetproof", version=__version__, instructions=OWNER_INSTRUCTIONS if owner else INSTRUCTIONS)
|
|
307
|
+
|
|
308
|
+
@server.tool(annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False))
|
|
309
|
+
def list_stores() -> dict[str, Any]:
|
|
310
|
+
"""List the stores this server may check, and which capabilities are enabled."""
|
|
311
|
+
return {
|
|
312
|
+
"stores": [{"name": s.name, "location": s.location, "kind": s.kind, "kind_label": KINDS.get(s.kind, s.kind),
|
|
313
|
+
"agent": s.agent, "open": _open(s)} for s in stores],
|
|
314
|
+
"fix_enabled": allow_fix,
|
|
315
|
+
"subject_configured": subject_path is not None,
|
|
316
|
+
"owner_mode": owner,
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
@server.tool(annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False))
|
|
320
|
+
def scan_store(store_name: str) -> dict[str, Any]:
|
|
321
|
+
"""Scan a store's files for deleted data that is still recoverable, as counts only.
|
|
322
|
+
|
|
323
|
+
This never checks for a specific value — use check_if_forgotten for the current user, or, in
|
|
324
|
+
owner mode, what_is_remembered.
|
|
325
|
+
"""
|
|
326
|
+
s = store(store_name)
|
|
327
|
+
lock = exclusive(s.name)
|
|
328
|
+
try:
|
|
329
|
+
return _findings(scan(s.target))
|
|
330
|
+
except _EXPECTED as e:
|
|
331
|
+
raise ToolError(str(e)) from None
|
|
332
|
+
finally:
|
|
333
|
+
lock.release()
|
|
334
|
+
|
|
335
|
+
@server.tool(annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False))
|
|
336
|
+
def plan_fix(store_name: str) -> dict[str, Any]:
|
|
337
|
+
"""Show what fix would change in a store, without changing anything."""
|
|
338
|
+
s = store(store_name)
|
|
339
|
+
lock = exclusive(s.name)
|
|
340
|
+
try:
|
|
341
|
+
r = scan(s.target)
|
|
342
|
+
return {"clean": r.clean, "steps": plan(r), "fix_enabled": allow_fix}
|
|
343
|
+
except _EXPECTED as e:
|
|
344
|
+
raise ToolError(str(e)) from None
|
|
345
|
+
finally:
|
|
346
|
+
lock.release()
|
|
347
|
+
|
|
348
|
+
@server.tool(annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False))
|
|
349
|
+
def copies_of(store_name: str) -> dict[str, Any]:
|
|
350
|
+
"""Where else this store's bytes probably are: a sync folder, git history, a backup file next to
|
|
351
|
+
it. Erasing the store doesn't reach these; the user has to."""
|
|
352
|
+
s = store(store_name)
|
|
353
|
+
if s.is_postgres:
|
|
354
|
+
return {"copies": [], "note": "a database's copies are its backups and replicas, not visible from here"}
|
|
355
|
+
return {"copies": [c.to_dict() for c in copies_mod.copies_of(s.target)]}
|
|
356
|
+
|
|
357
|
+
@server.tool(annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False))
|
|
358
|
+
def verify_receipt(receipt_id: str) -> dict[str, Any]:
|
|
359
|
+
"""Check a receipt was signed by this server and unaltered, and whether its store still matches it
|
|
360
|
+
and still scans clean."""
|
|
361
|
+
s, path = receipt_path(receipt_id)
|
|
362
|
+
lock = exclusive(s.name)
|
|
363
|
+
try:
|
|
364
|
+
rec = json.loads(path.read_text())
|
|
365
|
+
# Receipts in this directory were issued by this server, so pin its key: a receipt re-signed
|
|
366
|
+
# with some other key is rejected, not just checked for internal consistency.
|
|
367
|
+
receipt.verify_signature(rec, receipt.public_key_b64(receipt.load_or_create_key()))
|
|
368
|
+
now = scan(s.target)
|
|
369
|
+
return {
|
|
370
|
+
"signature_valid": True,
|
|
371
|
+
"issued_at": rec["issued_at"],
|
|
372
|
+
"signing_key": receipt.fingerprint(rec["public_key"]),
|
|
373
|
+
"verdict_at_issue": rec["verdict"],
|
|
374
|
+
"store_unchanged": receipt.file_hashes(s.target) == rec["files"],
|
|
375
|
+
"clean_now": now.clean,
|
|
376
|
+
}
|
|
377
|
+
except _EXPECTED as e:
|
|
378
|
+
raise ToolError(str(e)) from None
|
|
379
|
+
finally:
|
|
380
|
+
lock.release()
|
|
381
|
+
|
|
382
|
+
@server.tool(annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False))
|
|
383
|
+
def get_receipt(receipt_id: str) -> dict[str, Any]:
|
|
384
|
+
"""Return a signed receipt to hand to the user. It holds counts and file hashes, never erased values."""
|
|
385
|
+
_, path = receipt_path(receipt_id)
|
|
386
|
+
return json.loads(path.read_text())
|
|
387
|
+
|
|
388
|
+
if subject_path is not None:
|
|
389
|
+
@server.tool(annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False))
|
|
390
|
+
def check_if_forgotten(store_name: str) -> dict[str, Any]:
|
|
391
|
+
"""Check whether the current user (identified by the operator, not by you) still has
|
|
392
|
+
recoverable data in a store."""
|
|
393
|
+
s = store(store_name)
|
|
394
|
+
subject = current_subject() # before the lock: a slow or hung read can't hold up this store
|
|
395
|
+
lock = exclusive(s.name)
|
|
396
|
+
try:
|
|
397
|
+
cooldown(s.name)
|
|
398
|
+
r = scan(s.target, [subject])
|
|
399
|
+
return {"forgotten": not r.canaries[0].found_in, "store_type": r.store, "incomplete": r.incomplete}
|
|
400
|
+
except _EXPECTED as e:
|
|
401
|
+
raise ToolError(str(e)) from None
|
|
402
|
+
finally:
|
|
403
|
+
lock.release()
|
|
404
|
+
|
|
405
|
+
if owner:
|
|
406
|
+
@server.tool(annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False))
|
|
407
|
+
def what_is_remembered(values: list[str], store_name: str | None = None) -> dict[str, Any]:
|
|
408
|
+
"""Owner mode: which stores still hold these exact values — as live records the agent can
|
|
409
|
+
read, as deleted-but-recoverable bytes (residue), or not at all. Pass every spelling the
|
|
410
|
+
user gave (name, emails, phones). Only for values the user asked about."""
|
|
411
|
+
subj = owner_values(values)
|
|
412
|
+
out = []
|
|
413
|
+
for s in owner_stores(store_name):
|
|
414
|
+
lock = exclusive(s.name)
|
|
415
|
+
try:
|
|
416
|
+
cooldown(s.name)
|
|
417
|
+
rem = remembered.where_is(s.target, subj, show=show)
|
|
418
|
+
d = rem.to_dict()
|
|
419
|
+
out.append({"store": s.name, "kind": s.kind, "agent": s.agent, "status": d["status"],
|
|
420
|
+
"open": _open(s), "values": d["values"]})
|
|
421
|
+
except _EXPECTED as e:
|
|
422
|
+
out.append({"store": s.name, "kind": s.kind, "agent": s.agent, "status": "error", "error": str(e)})
|
|
423
|
+
finally:
|
|
424
|
+
lock.release()
|
|
425
|
+
overall = "live" if any(o["status"] == "live" for o in out) else \
|
|
426
|
+
"residue" if any(o["status"] == "residue" for o in out) else "absent"
|
|
427
|
+
return {"status": overall, "stores": out, "values": subj.count}
|
|
428
|
+
|
|
429
|
+
if allow_fix:
|
|
430
|
+
@server.tool(annotations=ToolAnnotations(destructive_hint=True, idempotent_hint=True, open_world_hint=False))
|
|
431
|
+
def fix_store(store_name: str) -> dict[str, Any]:
|
|
432
|
+
"""Erase every deleted-but-recoverable record from a store's files, rescan, and issue
|
|
433
|
+
a signed receipt. For a single user's request, prefer forget_me (or forget_value in owner mode).
|
|
434
|
+
|
|
435
|
+
Rewrites the store in place with no backup; live records are kept. Refuses while
|
|
436
|
+
another process has the store open. Postgres: locks each vector table while it is rewritten.
|
|
437
|
+
"""
|
|
438
|
+
s = store(store_name)
|
|
439
|
+
lock = exclusive(s.name)
|
|
440
|
+
try:
|
|
441
|
+
result = fix(s.target, [], Options())
|
|
442
|
+
rec = receipt.issue(s.target, result.before.summary(), result.after.summary(), result.actions, [],
|
|
443
|
+
label=s.location, copies=forget_mod._copies(s.target))
|
|
444
|
+
return {
|
|
445
|
+
"clean": result.after.clean,
|
|
446
|
+
"actions": result.actions,
|
|
447
|
+
"receipt_id": write_receipt(s.name, rec),
|
|
448
|
+
"signing_key": receipt.fingerprint(rec["public_key"]),
|
|
449
|
+
"after": _findings(result.after),
|
|
450
|
+
}
|
|
451
|
+
except _EXPECTED as e:
|
|
452
|
+
raise ToolError(str(e)) from None
|
|
453
|
+
finally:
|
|
454
|
+
lock.release()
|
|
455
|
+
|
|
456
|
+
@server.tool(annotations=ToolAnnotations(destructive_hint=True, idempotent_hint=True, open_world_hint=False))
|
|
457
|
+
def sweep() -> dict[str, Any]:
|
|
458
|
+
"""Fix every store that isn't open in another program right now, one signed receipt each.
|
|
459
|
+
Stores that are open are reported as skipped, not failed."""
|
|
460
|
+
out = []
|
|
461
|
+
for s in stores:
|
|
462
|
+
if _open(s):
|
|
463
|
+
out.append({"store": s.name, "status": "skipped", "why": "open in another program"})
|
|
464
|
+
continue
|
|
465
|
+
lock = exclusive(s.name)
|
|
466
|
+
try:
|
|
467
|
+
before = scan(s.target)
|
|
468
|
+
if before.clean:
|
|
469
|
+
out.append({"store": s.name, "status": "clean"})
|
|
470
|
+
continue
|
|
471
|
+
result = fix(s.target, [], Options())
|
|
472
|
+
rec = receipt.issue(s.target, result.before.summary(), result.after.summary(), result.actions, [],
|
|
473
|
+
label=s.location, copies=forget_mod._copies(s.target))
|
|
474
|
+
out.append({"store": s.name, "status": rec["verdict"].lower(), "receipt_id": write_receipt(s.name, rec),
|
|
475
|
+
"actions": result.actions})
|
|
476
|
+
except _EXPECTED as e:
|
|
477
|
+
out.append({"store": s.name, "status": "error", "why": str(e)})
|
|
478
|
+
finally:
|
|
479
|
+
lock.release()
|
|
480
|
+
return {"stores": out}
|
|
481
|
+
|
|
482
|
+
if subject_path is not None:
|
|
483
|
+
@server.tool(annotations=ToolAnnotations(destructive_hint=True, idempotent_hint=True, open_world_hint=False))
|
|
484
|
+
def forget_me(store_name: str) -> dict[str, Any]:
|
|
485
|
+
"""Erase the current user's data from a store and issue a signed receipt.
|
|
486
|
+
|
|
487
|
+
The user is the one the operator's application identified, not one you name. On
|
|
488
|
+
Chroma this can come back queued instead of done, if the application still has the
|
|
489
|
+
store open; it completes at the application's next start, before it reopens the store.
|
|
490
|
+
"""
|
|
491
|
+
s = store(store_name)
|
|
492
|
+
subject = current_subject() # before the lock: a slow or hung read can't hold up this store
|
|
493
|
+
lock = exclusive(s.name)
|
|
494
|
+
try:
|
|
495
|
+
cooldown(s.name)
|
|
496
|
+
result = forget_mod.forget(s.target, subject, queue_dir=queue_dir)
|
|
497
|
+
if isinstance(result, forget_mod.Queued):
|
|
498
|
+
return {"queued": True, "done": False, "queued_at": result.queued_at}
|
|
499
|
+
return {
|
|
500
|
+
"queued": False,
|
|
501
|
+
"done": True,
|
|
502
|
+
"clean": result["verdict"] == "CLEAN",
|
|
503
|
+
"receipt_id": write_receipt(s.name, result),
|
|
504
|
+
"signing_key": receipt.fingerprint(result["public_key"]),
|
|
505
|
+
}
|
|
506
|
+
except _EXPECTED as e:
|
|
507
|
+
raise ToolError(str(e)) from None
|
|
508
|
+
finally:
|
|
509
|
+
lock.release()
|
|
510
|
+
|
|
511
|
+
if owner:
|
|
512
|
+
@server.tool(annotations=ToolAnnotations(destructive_hint=True, idempotent_hint=True, open_world_hint=False))
|
|
513
|
+
def forget_value(values: list[str], store_name: str | None = None, also_live: bool = False,
|
|
514
|
+
correlation_id: str | None = None) -> dict[str, Any]:
|
|
515
|
+
"""Owner mode: erase these exact values from every store (or one), with a signed receipt
|
|
516
|
+
per store. Deleted-but-recoverable bytes are erased; live records are left alone unless
|
|
517
|
+
`also_live` is true, which deletes every record that contains one of the values — ask the
|
|
518
|
+
user before setting it. A store that is open in another program is queued and finishes at
|
|
519
|
+
that program's next start. Pass every spelling the user gave; never guess more."""
|
|
520
|
+
subj = owner_values(values)
|
|
521
|
+
out = []
|
|
522
|
+
for s in owner_stores(store_name):
|
|
523
|
+
lock = exclusive(s.name)
|
|
524
|
+
try:
|
|
525
|
+
cooldown(s.name)
|
|
526
|
+
result = forget_mod.forget(s.target, subj, also_live=also_live, queue_dir=queue_dir,
|
|
527
|
+
correlation_id=correlation_id)
|
|
528
|
+
if isinstance(result, forget_mod.Queued):
|
|
529
|
+
out.append({"store": s.name, "status": "queued", "queued_at": result.queued_at,
|
|
530
|
+
"why": "open in another program; finishes at its next start"})
|
|
531
|
+
continue
|
|
532
|
+
out.append({"store": s.name, "status": result["verdict"].lower(),
|
|
533
|
+
"receipt_id": write_receipt(s.name, result), "actions": result["actions"],
|
|
534
|
+
"copies_not_reached": [c for c in result["copies"] if not c["scannable"]]})
|
|
535
|
+
except _EXPECTED as e:
|
|
536
|
+
out.append({"store": s.name, "status": "error", "why": str(e)})
|
|
537
|
+
finally:
|
|
538
|
+
lock.release()
|
|
539
|
+
return {"stores": out, "values": subj.count}
|
|
540
|
+
|
|
541
|
+
return server
|