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.
@@ -0,0 +1,69 @@
1
+ """Qdrant in local mode (`QdrantClient(path=...)`), the default vector store of mem0 and a common
2
+ choice for agents that want a vector database without running one.
3
+
4
+ On disk it is `meta.json` plus `collection/<name>/storage.sqlite`, a SQLite file with one row per
5
+ point: the id and the whole point (vector and payload) as a pickle. A delete removes the row, and
6
+ SQLite keeps the row's bytes in free space until the file is vacuumed — the payload's text is in
7
+ the pickle as plain UTF-8, so it carves out like any other deleted row. Each collection is checked
8
+ with the SQLite slack scanner and fixed with VACUUM and secure_delete on.
9
+
10
+ Qdrant local loads every point from storage.sqlite when the client opens, so this must run while
11
+ no client has the directory open (fix's open-process check covers it).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from pathlib import Path
17
+
18
+ from .report import Report
19
+ from .sqlite_residue import is_sqlite, slack_finding, vacuum
20
+
21
+ META = "meta.json"
22
+ STORAGE = "storage.sqlite"
23
+
24
+
25
+ def detect(target: Path) -> bool:
26
+ return target.is_dir() and (target / META).is_file() and (target / "collection").is_dir()
27
+
28
+
29
+ def collections(target: Path) -> list[tuple[str, Path]]:
30
+ out = []
31
+ for d in sorted((target / "collection").iterdir()):
32
+ db = d / STORAGE
33
+ if d.is_dir() and not d.is_symlink() and db.is_file() and is_sqlite(db):
34
+ out.append((d.name, db))
35
+ return out
36
+
37
+
38
+ def scan(target: Path, report: Report, show: bool = False, prefix: str = "") -> None:
39
+ points = 0
40
+ for name, db in collections(target):
41
+ location = f"{prefix}collection/{name}/{STORAGE}"
42
+ import sqlite3
43
+
44
+ conn = sqlite3.connect(f"{db.as_uri()}?mode=ro", uri=True)
45
+ try:
46
+ points += conn.execute("select count(*) from points").fetchone()[0]
47
+ except sqlite3.Error:
48
+ pass
49
+ finally:
50
+ conn.close()
51
+ finding = slack_finding(db, location, show)
52
+ if finding:
53
+ finding.why = ("Qdrant local stores each point as a pickle in SQLite and deletes by removing the row; "
54
+ "the row's bytes, payload text included, stay in free space until VACUUM")
55
+ report.findings.append(finding)
56
+ report.stats[f"{prefix}points" if prefix else "points"] = points
57
+ report.stats[f"{prefix}collections" if prefix else "collections"] = len(collections(target))
58
+
59
+
60
+ def plan(report: Report) -> list[str]:
61
+ return [f"VACUUM each collection's {STORAGE} with secure_delete on (rewrites the file without free pages)"]
62
+
63
+
64
+ def fix(target: Path) -> list[str]:
65
+ actions = []
66
+ for name, db in collections(target):
67
+ vacuum(db)
68
+ actions.append(f"vacuumed collection/{name}/{STORAGE} (secure_delete on)")
69
+ return actions
forgetproof/receipt.py ADDED
@@ -0,0 +1,135 @@
1
+ """Signed erasure receipts.
2
+
3
+ A receipt records what a scan found before the fix, what it found after, and
4
+ the SHA-256 of every file in the store afterwards — counts and hashes only,
5
+ never the erased values. It is signed with an Ed25519 key kept on this machine.
6
+
7
+ Signing proves the receipt hasn't been altered since it was issued and which
8
+ key issued it. It is the operator's attestation plus a check anyone can rerun
9
+ (`forgetproof verify --against`), not a third-party audit.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import base64
15
+ import hashlib
16
+ import json
17
+ import os
18
+ from datetime import datetime, timezone
19
+ from pathlib import Path
20
+
21
+ from cryptography.exceptions import InvalidSignature
22
+ from cryptography.hazmat.primitives import serialization
23
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
24
+
25
+ from . import __version__, keystore
26
+
27
+ FORMAT = "forgetproof-receipt/0.2"
28
+ PORTABLE_FORMAT = "forget-me-receipt/1" # the ForgetMe v1 portable projection (forgetme.py); same signing rule
29
+ FORMATS = ("forgetproof-receipt/0.1", FORMAT, PORTABLE_FORMAT) # 0.1 receipts still verify
30
+ VERDICTS = ("CLEAN", "RESIDUE_REMAINS", "UNVERIFIABLE")
31
+
32
+
33
+ def key_path() -> Path:
34
+ home = os.environ.get("FORGETPROOF_HOME") or Path.home() / ".config" / "forgetproof"
35
+ return Path(home) / "signing_key.pem"
36
+
37
+
38
+ def _generate_pem() -> bytes:
39
+ key = Ed25519PrivateKey.generate()
40
+ return key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())
41
+
42
+
43
+ def load_or_create_key(path: Path | None = None) -> Ed25519PrivateKey:
44
+ """This machine's signing key, or the one at `path` (a hosted provider keeps its own)."""
45
+ path = Path(path) if path else key_path()
46
+ pem = keystore.get_or_create("signing_key" if path == key_path() else f"signing_key:{path}", path, _generate_pem)
47
+ key = serialization.load_pem_private_key(pem, password=None)
48
+ assert isinstance(key, Ed25519PrivateKey)
49
+ return key
50
+
51
+
52
+ def _b64(b: bytes) -> str:
53
+ return base64.urlsafe_b64encode(b).decode().rstrip("=")
54
+
55
+
56
+ def _unb64(s: str) -> bytes:
57
+ return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
58
+
59
+
60
+ def canonical(obj: dict) -> bytes:
61
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
62
+
63
+
64
+ def public_key_b64(key: Ed25519PrivateKey) -> str:
65
+ return _b64(key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw))
66
+
67
+
68
+ def fingerprint(public_b64: str) -> str:
69
+ return hashlib.sha256(_unb64(public_b64)).hexdigest()[:32]
70
+
71
+
72
+ def file_hashes(target: Path | str) -> dict[str, str]:
73
+ from . import postgres
74
+
75
+ if postgres.is_postgres(target):
76
+ return postgres.fingerprints(str(target))
77
+ target = Path(target)
78
+ files = sorted(p for p in target.rglob("*") if p.is_file()) if target.is_dir() else [target]
79
+ out = {}
80
+ for p in files:
81
+ h = hashlib.sha256()
82
+ with p.open("rb") as f:
83
+ for chunk in iter(lambda: f.read(1 << 20), b""):
84
+ h.update(chunk)
85
+ out[str(p.relative_to(target)) if target.is_dir() else p.name] = h.hexdigest()
86
+ return out
87
+
88
+
89
+ def issue(target: Path | str, before: dict, after: dict, actions: list[str], canaries: list[dict], label: str | None = None,
90
+ correlation_id: str | None = None, *, issuer: str | None = None, subject_values: int = 0,
91
+ copies: list[dict] | None = None, verdict: str | None = None, files: dict[str, str] | None = None,
92
+ key: Ed25519PrivateKey | None = None) -> dict:
93
+ """Sign a receipt. Counts and hashes only.
94
+
95
+ `issuer` names who signs (a hosted provider's name; by default this machine), `subject_values`
96
+ is how many exact values the subject had (never the values), `copies` is what the copies
97
+ report found, each marked reached or not, and `verdict` overrides the computed one — a
98
+ provider that can only delete through an API passes UNVERIFIABLE, which never reads as clean.
99
+ """
100
+ key = key or load_or_create_key()
101
+ if verdict is not None and verdict not in VERDICTS:
102
+ raise ValueError(f"verdict must be one of {VERDICTS}")
103
+ body = {
104
+ "format": FORMAT,
105
+ "tool": f"forgetproof {__version__}",
106
+ "issuer": issuer or "this machine",
107
+ "issued_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
108
+ "target": label or str(target), # for a database: the URL without its password
109
+ "verdict": verdict or ("CLEAN" if after["clean"] else "RESIDUE_REMAINS"),
110
+ "before": before,
111
+ "after": after,
112
+ "actions": actions,
113
+ "canaries": canaries, # per canary: where, if anywhere, it was still found; never the value or its hash
114
+ "subject_values": subject_values,
115
+ "copies": copies or [],
116
+ "correlation_id": correlation_id, # an opaque caller-supplied label; carried through a queued forget() too
117
+ "files": file_hashes(target) if files is None else files,
118
+ "public_key": public_key_b64(key),
119
+ }
120
+ body["signature"] = _b64(key.sign(canonical(body)))
121
+ return body
122
+
123
+
124
+ def verify_signature(receipt: dict, expected_key: str | None = None) -> None:
125
+ """Raise ValueError if the receipt was altered or signed by an unexpected key."""
126
+ body = {k: v for k, v in receipt.items() if k != "signature"}
127
+ if receipt.get("format") not in FORMATS:
128
+ raise ValueError(f"unknown receipt format {receipt.get('format')!r}")
129
+ if expected_key and expected_key not in (receipt["public_key"], fingerprint(receipt["public_key"])):
130
+ raise ValueError("receipt was signed by a different key than expected")
131
+ pub = Ed25519PublicKey.from_public_bytes(_unb64(receipt["public_key"]))
132
+ try:
133
+ pub.verify(_unb64(receipt["signature"]), canonical(body))
134
+ except InvalidSignature:
135
+ raise ValueError("signature does not match — the receipt was altered") from None
@@ -0,0 +1,257 @@
1
+ """What does this store still hold about a value — live, or only as residue?
2
+
3
+ The question a person asks first is not "is there residue" but "does my agent still know Alice's
4
+ email". The answer has three parts per store: records the agent can still read (live), bytes it
5
+ can no longer read but a file reader can (residue), and nothing. `where_is` answers it for one
6
+ subject, store by store, and in owner mode shows the line or cell the value sits in, because the
7
+ person owns the store. Outside owner mode no context is returned and the value itself is never
8
+ echoed back.
9
+
10
+ It never changes anything, and it reads stores the same read-only way the scanner does.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import sqlite3
16
+ from dataclasses import asdict, dataclass, field
17
+ from pathlib import Path
18
+
19
+ from . import files_store, lance_store, mem0_store, postgres, qdrant_store
20
+ from .scanner import check_canaries, detect
21
+ from .sqlite_residue import connect_ro, table_columns
22
+ from .subject import Subject
23
+
24
+ MAX_HITS = 50
25
+ CONTEXT = 60
26
+
27
+
28
+ @dataclass
29
+ class Hit:
30
+ where: str # table.column, collection/record, file:line
31
+ context: str | None = None # owner mode only: the text around the value, trimmed
32
+
33
+
34
+ @dataclass
35
+ class ValueReport:
36
+ value: int # 1-based position in the subject, never the value itself
37
+ live: list[Hit] = field(default_factory=list)
38
+ residue: list[str] = field(default_factory=list) # files that hold the value only as unreachable bytes
39
+
40
+ @property
41
+ def status(self) -> str:
42
+ if self.live:
43
+ return "live"
44
+ if self.residue:
45
+ return "residue"
46
+ return "absent"
47
+
48
+
49
+ @dataclass
50
+ class Remembered:
51
+ target: str
52
+ store: str
53
+ values: list[ValueReport]
54
+
55
+ @property
56
+ def status(self) -> str:
57
+ statuses = {v.status for v in self.values}
58
+ return "live" if "live" in statuses else "residue" if "residue" in statuses else "absent"
59
+
60
+ def to_dict(self) -> dict:
61
+ d = asdict(self)
62
+ d["status"] = self.status
63
+ for v, vd in zip(self.values, d["values"]):
64
+ vd["status"] = v.status
65
+ return d
66
+
67
+
68
+ def _snippet(text: str, needle: str) -> str:
69
+ i = text.lower().find(needle.lower())
70
+ if i < 0:
71
+ return text[:CONTEXT * 2]
72
+ start, end = max(0, i - CONTEXT), min(len(text), i + len(needle) + CONTEXT)
73
+ return ("…" if start else "") + text[start:end].replace("\n", " ") + ("…" if end < len(text) else "")
74
+
75
+
76
+ def _match(text: str, needles: list[str]) -> str | None:
77
+ low = text.lower()
78
+ for n in needles:
79
+ if n.lower() in low:
80
+ return n
81
+ return None
82
+
83
+
84
+ def _sqlite_hits(db: Path, needles_per_value: list[list[str]], show: bool, prefix: str = "",
85
+ tables: list[str] | None = None) -> list[list[Hit]]:
86
+ hits: list[list[Hit]] = [[] for _ in needles_per_value]
87
+ conn = connect_ro(db)
88
+ try:
89
+ for table, columns in table_columns(conn).items():
90
+ if tables is not None and table not in tables:
91
+ continue
92
+ quoted = '"' + table.replace('"', '""') + '"'
93
+ try:
94
+ rows = conn.execute(f"select rowid, * from {quoted}")
95
+ except sqlite3.Error:
96
+ continue
97
+ for row in rows:
98
+ rowid, cells = row[0], row[1:]
99
+ for col, cell in zip(columns, cells):
100
+ text = cell if isinstance(cell, str) else cell.decode("utf-8", "replace") if isinstance(cell, bytes) else None
101
+ if text is None:
102
+ continue
103
+ for i, needles in enumerate(needles_per_value):
104
+ if len(hits[i]) >= MAX_HITS:
105
+ continue
106
+ n = _match(text, needles)
107
+ if n:
108
+ hits[i].append(Hit(f"{prefix}{table}.{col} (row {rowid})", _snippet(text, n) if show else None))
109
+ finally:
110
+ conn.close()
111
+ return hits
112
+
113
+
114
+ def _chroma_hits(target: Path, needles_per_value: list[list[str]], show: bool) -> tuple[list[list[Hit]], list[int]]:
115
+ """Live hits from documents and metadata, plus per value the number of write-log rows that
116
+ carry it for records no longer live."""
117
+ hits: list[list[Hit]] = [[] for _ in needles_per_value]
118
+ write_log = [0] * len(needles_per_value)
119
+ conn = connect_ro(target / "chroma.sqlite3")
120
+ try:
121
+ collections = dict(conn.execute("select id, name from collections"))
122
+ seg_coll = dict(conn.execute("select id, collection from segments"))
123
+ live_ids: set[tuple[str, str]] = set()
124
+ for seg, emb_id in conn.execute("select segment_id, embedding_id from embeddings"):
125
+ live_ids.add((seg_coll.get(seg), emb_id))
126
+ rows = conn.execute(
127
+ "select e.segment_id, e.embedding_id, m.key, m.string_value from embedding_metadata m "
128
+ "join embeddings e on e.id = m.id where m.string_value is not null"
129
+ )
130
+ for seg, emb_id, key, value in rows:
131
+ coll = collections.get(seg_coll.get(seg), "?")
132
+ for i, needles in enumerate(needles_per_value):
133
+ if len(hits[i]) >= MAX_HITS:
134
+ continue
135
+ n = _match(value, needles)
136
+ if n:
137
+ what = "document" if key == "chroma:document" else f"metadata {key}"
138
+ hits[i].append(Hit(f"collection {coll}, record {emb_id} ({what})", _snippet(value, n) if show else None))
139
+ for topic, emb_id, metadata in conn.execute("select topic, id, metadata from embeddings_queue"):
140
+ coll_id = topic.rsplit("/", 1)[-1]
141
+ if (coll_id, emb_id) in live_ids or not metadata:
142
+ continue
143
+ text = metadata if isinstance(metadata, str) else metadata.decode("utf-8", "replace")
144
+ for i, needles in enumerate(needles_per_value):
145
+ if _match(text, needles):
146
+ write_log[i] += 1
147
+ finally:
148
+ conn.close()
149
+ return hits, write_log
150
+
151
+
152
+ def _lance_hits(target: Path, needles_per_value: list[list[str]], show: bool) -> list[list[Hit]] | None:
153
+ try:
154
+ import lancedb
155
+ import pyarrow as pa
156
+ except ImportError:
157
+ return None
158
+ hits: list[list[Hit]] = [[] for _ in needles_per_value]
159
+ for table in lance_store.tables(target):
160
+ t = lancedb.connect(str(table.parent)).open_table(table.stem)
161
+ row = 0
162
+ for batch in t.to_arrow().to_batches():
163
+ cols = [(f.name, batch.column(i).to_pylist()) for i, f in enumerate(batch.schema)
164
+ if pa.types.is_string(f.type) or pa.types.is_large_string(f.type)]
165
+ for r in range(batch.num_rows):
166
+ for name, values in cols:
167
+ text = values[r]
168
+ if not text:
169
+ continue
170
+ for i, needles in enumerate(needles_per_value):
171
+ if len(hits[i]) >= MAX_HITS:
172
+ continue
173
+ n = _match(text, needles)
174
+ if n:
175
+ hits[i].append(Hit(f"{table.name} row {row + r}, {name}", _snippet(text, n) if show else None))
176
+ row += batch.num_rows
177
+ return hits
178
+
179
+
180
+ def _file_hits(target: Path, needles_per_value: list[list[str]], show: bool) -> list[list[Hit]]:
181
+ hits: list[list[Hit]] = [[] for _ in needles_per_value]
182
+ for f in files_store.files(target):
183
+ rel = f.relative_to(target).as_posix() if target.is_dir() else f.name
184
+ try:
185
+ lines = f.read_text(encoding="utf-8", errors="replace").splitlines()
186
+ except OSError:
187
+ continue
188
+ for no, line in enumerate(lines, 1):
189
+ for i, needles in enumerate(needles_per_value):
190
+ if len(hits[i]) >= MAX_HITS:
191
+ continue
192
+ n = _match(line, needles)
193
+ if n:
194
+ hits[i].append(Hit(f"{rel}:{no}", _snippet(line, n) if show else None))
195
+ return hits
196
+
197
+
198
+ def _needles_per_value(subject: Subject) -> list[list[str]]:
199
+ from .subject import phone_spellings
200
+
201
+ return [[v, *sorted(phone_spellings(v))] for v in subject.values]
202
+
203
+
204
+ def where_is(target: Path | str, subject: Subject, show: bool = False) -> Remembered:
205
+ if postgres.is_postgres(target):
206
+ raise ValueError("where_is reads local stores only; for Postgres use scan with --canary")
207
+ target = Path(target).resolve()
208
+ kind = detect(target)
209
+ per_value = _needles_per_value(subject)
210
+ raw = check_canaries(target, [n for ns in per_value for n in ns])
211
+ # Raw hits per value: union over that value's spellings.
212
+ raw_files: list[set[str]] = []
213
+ k = 0
214
+ for ns in per_value:
215
+ files: set[str] = set()
216
+ for _ in ns:
217
+ files |= set(raw[k].found_in)
218
+ k += 1
219
+ raw_files.append(files)
220
+
221
+ notes: list[list[str]] = [[] for _ in per_value]
222
+ if kind == "sqlite":
223
+ hits = _sqlite_hits(target, per_value, show)
224
+ elif kind == "mem0":
225
+ hits = _sqlite_hits(mem0_store.history_db(target), per_value, show, prefix="history.db: ")
226
+ for sub in mem0_store.qdrant_dirs(target):
227
+ for name, sdb in qdrant_store.collections(sub):
228
+ for i, more in enumerate(_sqlite_hits(sdb, per_value, show, prefix=f"{sub.name}/collection/{name}: ", tables=["points"])):
229
+ hits[i] += more
230
+ elif kind == "qdrant":
231
+ hits = [[] for _ in per_value]
232
+ for name, sdb in qdrant_store.collections(target):
233
+ for i, more in enumerate(_sqlite_hits(sdb, per_value, show, prefix=f"collection/{name}: ", tables=["points"])):
234
+ hits[i] += more
235
+ elif kind == "chroma":
236
+ hits, write_log = _chroma_hits(target, per_value, show)
237
+ for i, n in enumerate(write_log):
238
+ if n:
239
+ notes[i].append(f"chroma.sqlite3 (write log: {n} deleted record(s))")
240
+ elif kind == "lancedb":
241
+ hits = _lance_hits(target, per_value, show) or [[] for _ in per_value]
242
+ else:
243
+ hits = _file_hits(target, per_value, show)
244
+
245
+ values = []
246
+ for i, (live, files) in enumerate(zip(hits, raw_files)):
247
+ residue = list(notes[i])
248
+ if kind == "files":
249
+ pass # a text file has no unreachable bytes: a raw hit is a live line, already listed
250
+ elif kind == "chroma":
251
+ residue += sorted(f for f in files if f != "chroma.sqlite3") # index files
252
+ if "chroma.sqlite3" in files and not live and not notes[i]:
253
+ residue.append("chroma.sqlite3 (free space)")
254
+ else:
255
+ residue += sorted(f"{f} (free space)" for f in files) if not live else []
256
+ values.append(ValueReport(i + 1, live, residue))
257
+ return Remembered(str(target), kind, values)
forgetproof/report.py ADDED
@@ -0,0 +1,59 @@
1
+ """Result types shared by the scanners, the fixer and the CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import asdict, dataclass, field
6
+
7
+
8
+ @dataclass
9
+ class Finding:
10
+ check: str # stable id, e.g. "chroma.write_log"
11
+ title: str
12
+ location: str # path relative to the scanned target
13
+ records: int # how many leftover units this finding covers
14
+ why: str # one line on why this matters
15
+ unit: str = "records" # what `records` counts: records, vectors, values, bytes
16
+ pii: dict[str, int] = field(default_factory=dict) # kind -> distinct values
17
+ samples: list[str] = field(default_factory=list) # redacted, safe to print
18
+
19
+
20
+ @dataclass
21
+ class CanaryResult:
22
+ number: int # 1-based position on the command line. The value itself is never stored or hashed:
23
+ found_in: list[str] # a hash of an email address can be confirmed by guessing.
24
+
25
+
26
+ @dataclass
27
+ class Report:
28
+ target: str
29
+ store: str
30
+ findings: list[Finding] = field(default_factory=list)
31
+ canaries: list[CanaryResult] = field(default_factory=list)
32
+ stats: dict[str, int] = field(default_factory=dict)
33
+ warnings: list[str] = field(default_factory=list) # problems that aren't residue, e.g. an interrupted fix
34
+ incomplete: str | None = None # why the scan couldn't check everything; such a store is never "clean"
35
+
36
+ @property
37
+ def clean(self) -> bool:
38
+ return not self.findings and not any(c.found_in for c in self.canaries) and self.incomplete is None
39
+
40
+ def summary(self) -> dict:
41
+ """Counts only — safe to put in a receipt. No samples, no values."""
42
+ return {
43
+ "store": self.store,
44
+ "clean": self.clean,
45
+ "findings": {f.check: f.records for f in self.findings},
46
+ "pii": {
47
+ kind: sum(f.pii.get(kind, 0) for f in self.findings)
48
+ for kind in sorted({k for f in self.findings for k in f.pii})
49
+ },
50
+ "canaries_found": sum(1 for c in self.canaries if c.found_in),
51
+ "incomplete": self.incomplete,
52
+ "warnings": self.warnings,
53
+ "stats": self.stats,
54
+ }
55
+
56
+ def to_dict(self) -> dict:
57
+ d = asdict(self)
58
+ d["clean"] = self.clean
59
+ return d
forgetproof/safety.py ADDED
@@ -0,0 +1,105 @@
1
+ """Pre-flight checks that keep `fix` from damaging a store it can't safely rewrite."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import subprocess
8
+ import sys
9
+ from pathlib import Path
10
+
11
+
12
+ _SQLITE_NAMES = (".sqlite3", ".sqlite3-wal", ".sqlite3-shm", ".sqlite3-journal")
13
+
14
+
15
+ def store_files(target: Path) -> list[Path]:
16
+ """Every file belonging to the store: the directory's files, or a SQLite file and its sidecars."""
17
+ if target.is_dir():
18
+ return sorted(p for p in target.rglob("*") if p.is_file())
19
+ sidecars = (target.with_name(target.name + s) for s in ("-wal", "-shm", "-journal"))
20
+ return [target, *(p for p in sidecars if p.exists())]
21
+
22
+
23
+ def _proc_holders(target: Path) -> list[str]:
24
+ """Linux: processes with a store file open or mapped (only those this user can inspect)."""
25
+ wanted = {str(p) for p in store_files(target)}
26
+ prefix = str(target) + os.sep if target.is_dir() else None
27
+ me = str(os.getpid())
28
+
29
+ def ours(path: str, pid: str) -> bool:
30
+ path = path.removesuffix(" (deleted)")
31
+ if pid == me and path.endswith(_SQLITE_NAMES):
32
+ # A chromadb client in this process keeps its SQLite pool open for the life of the process,
33
+ # which is harmless while idle. Its index files are what it can flush over our changes.
34
+ return False
35
+ return path in wanted or (prefix is not None and path.startswith(prefix))
36
+
37
+ holders = []
38
+ for proc in Path("/proc").iterdir():
39
+ if not proc.name.isdigit():
40
+ continue
41
+ try:
42
+ hit = any(ours(os.readlink(fd), proc.name) for fd in (proc / "fd").iterdir())
43
+ if not hit:
44
+ hit = any(ours(parts[5].strip(), proc.name) for line in (proc / "maps").read_text().splitlines()
45
+ if len(parts := line.split(maxsplit=5)) == 6)
46
+ except OSError:
47
+ continue # exited, or another user's process
48
+ if hit:
49
+ if proc.name == me:
50
+ holders.append("this process (close your Chroma client first, or run the forgetproof CLI)")
51
+ continue
52
+ try:
53
+ name = (proc / "comm").read_text().strip()
54
+ except OSError:
55
+ name = "?"
56
+ holders.append(f"pid {proc.name} ({name})")
57
+ return holders
58
+
59
+
60
+ def _lsof_holders(target: Path) -> list[str]:
61
+ """macOS and other Unixes: ask lsof."""
62
+ if not shutil.which("lsof"):
63
+ return []
64
+ args = ["lsof", "-F", "pc", "+D", str(target)] if target.is_dir() else ["lsof", "-F", "pc", "--", *map(str, store_files(target))]
65
+ out = subprocess.run(args, capture_output=True, text=True).stdout
66
+ holders, pid = [], None
67
+ for line in out.splitlines():
68
+ if line.startswith("p"):
69
+ pid = line[1:]
70
+ elif line.startswith("c") and pid and int(pid) != os.getpid():
71
+ holders.append(f"pid {pid} ({line[1:]})")
72
+ return sorted(set(holders))
73
+
74
+
75
+ def _windows_holders(target: Path) -> list[str]:
76
+ """Windows refuses to rename a file another process has open."""
77
+ busy = []
78
+ for p in store_files(target):
79
+ probe = p.with_name(p.name + ".forgetproof-probe")
80
+ try:
81
+ p.rename(probe)
82
+ except PermissionError:
83
+ busy.append(f"a process holding {p.name}")
84
+ continue
85
+ probe.rename(p)
86
+ return busy
87
+
88
+
89
+ def open_by_other_processes(target: Path) -> list[str]:
90
+ """Best effort: describe processes that have the store open. Empty when none are found."""
91
+ if sys.platform.startswith("linux") and Path("/proc/self/fd").exists():
92
+ return _proc_holders(target)
93
+ if sys.platform == "win32":
94
+ return _windows_holders(target)
95
+ return _lsof_holders(target)
96
+
97
+
98
+ def space_needed(target: Path) -> int:
99
+ """Rebuilding copies the data once and VACUUM writes a second copy of the SQLite file."""
100
+ total = sum(p.stat().st_size for p in store_files(target))
101
+ return 2 * total + (64 << 20)
102
+
103
+
104
+ def free_space(target: Path) -> int:
105
+ return shutil.disk_usage(target if target.is_dir() else target.parent).free