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/cli.py ADDED
@@ -0,0 +1,582 @@
1
+ """forgetproof command line."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import sqlite3
9
+ import sys
10
+ from datetime import datetime, timezone
11
+ from pathlib import Path
12
+
13
+ from . import __version__, copies as copies_mod, discovery, forget as forget_mod, postgres, receipt, remembered, safety
14
+ from .erase_live import LiveEraseError
15
+ from .fixer import FixError, Options, fix, plan
16
+ from .report import Report
17
+ from .scanner import KINDS, UnsupportedStore, scan
18
+ from .subject import subject as make_subject
19
+
20
+ EXIT_CLEAN, EXIT_RESIDUE, EXIT_ERROR = 0, 1, 2
21
+
22
+
23
+ def _style(code: str):
24
+ def apply(text: str) -> str:
25
+ return f"\033[{code}m{text}\033[0m" if sys.stdout.isatty() else text
26
+ return apply
27
+
28
+
29
+ red, green, bold, dim = _style("31"), _style("32"), _style("1"), _style("2")
30
+
31
+
32
+ def _pinned() -> list[tuple[str, discovery.Found, Path]]:
33
+ """Every pinned store visible from here: the project config found by walking up, then the
34
+ user's home config. Each with the root its paths must stay inside."""
35
+ out: list[tuple[str, discovery.Found, Path]] = []
36
+ config = discovery.find_config(Path.cwd())
37
+ if config is not None:
38
+ out += [(name, f, config.parent) for name, f in discovery.load_config(config).items()]
39
+ out += [(name, f, Path.home()) for name, f in discovery.load_home_config().items()]
40
+ return out
41
+
42
+
43
+ def _target(arg: str) -> Path | str:
44
+ if postgres.is_postgres(arg):
45
+ return arg
46
+ path = Path(arg)
47
+ # A bare name (no "/" and no existing file there) may be a store pinned by `forgetproof init`.
48
+ if not path.exists() and os.sep not in arg and "/" not in arg:
49
+ for name, pinned, root in _pinned():
50
+ if name == arg:
51
+ return discovery.resolve(pinned, root=root)
52
+ return path.resolve()
53
+
54
+
55
+ def _canaries(args) -> list[str]:
56
+ values = list(args.canary or [])
57
+ if args.canary_file:
58
+ values += [line.strip() for line in Path(args.canary_file).read_text().splitlines() if line.strip()]
59
+ return values
60
+
61
+
62
+ def _print_report(r: Report) -> None:
63
+ print(f"{bold('forgetproof')} {dim(__version__)} {KINDS.get(r.store, r.store)} store at {r.target}")
64
+ if r.stats:
65
+ print(dim(" " + ", ".join(f"{k.replace('_', ' ')}: {v}" for k, v in r.stats.items())))
66
+ print()
67
+ for w in r.warnings:
68
+ print(f"{bold('!')} {w}\n")
69
+ if r.incomplete:
70
+ print(f"{red('!')} {bold('Incomplete scan:')} {r.incomplete}\n")
71
+ for f in r.findings:
72
+ print(f"{red('✗')} {bold(f.title)}")
73
+ print(f" {f.records} {f.unit} in {f.location}")
74
+ if f.pii:
75
+ print(" patterns: " + ", ".join(f"{n} {k}" for k, n in sorted(f.pii.items())))
76
+ for s in f.samples:
77
+ print(dim(f" {s}"))
78
+ print(dim(f" why it matters: {f.why}"))
79
+ print()
80
+ for i, c in enumerate(r.canaries, 1):
81
+ if c.found_in:
82
+ print(f"{red('✗')} canary #{i} still on disk in: {', '.join(c.found_in)}")
83
+ else:
84
+ print(f"{green('✓')} canary #{i} not found anywhere in the store's files")
85
+ if r.canaries:
86
+ print()
87
+ if r.clean:
88
+ print(green("✓ No deleted data found on disk."))
89
+ elif r.incomplete and not r.findings:
90
+ print(red("Not verified clean: see the incomplete-scan note above."))
91
+ elif r.store == "files" and not r.findings:
92
+ print(red("Text files keep no deleted data, so a value found here is still live content: the agent "
93
+ "never removed it. `forgetproof forget --also-live` removes the lines that carry it."))
94
+ else:
95
+ print(red(f"Deleted data is still recoverable. Run `forgetproof fix {r.target}` to erase it."))
96
+
97
+
98
+ def _markdown(r: Report) -> str:
99
+ """For CI job summaries. Counts only: no samples, even redacted ones, since CI logs can be public."""
100
+ status = "✅ No deleted data found on disk" if r.clean else (
101
+ "⚠️ Not verified clean" if r.incomplete and not r.findings else "❌ Deleted data is still recoverable")
102
+ lines = [f"### forgetproof: {status}", "", f"`{r.store}` store · " + ", ".join(
103
+ f"{k.replace('_', ' ')}: {v}" for k, v in r.stats.items()), ""]
104
+ if r.findings:
105
+ lines += ["| Check | What's left | Amount | Patterns |", "|---|---|---|---|"]
106
+ for f in r.findings:
107
+ pii = ", ".join(f"{n} {k}" for k, n in sorted(f.pii.items())) or "–"
108
+ lines.append(f"| `{f.check}` | {f.title} | {f.records} {f.unit} | {pii} |")
109
+ lines.append("")
110
+ for c in r.canaries:
111
+ lines.append(f"- canary #{c.number}: " + (f"**still on disk** in {', '.join(c.found_in)}" if c.found_in else "not found"))
112
+ for w in r.warnings:
113
+ lines.append(f"- ⚠️ {w}")
114
+ if r.incomplete:
115
+ lines.append(f"- ⚠️ **Incomplete scan:** {r.incomplete}")
116
+ if not r.clean and r.findings:
117
+ lines += ["", "Run `forgetproof fix` on the store to erase it ([how fix works](https://github.com/Sharathvc23/forgetproof#how-fix-works))."]
118
+ return "\n".join(lines) + "\n"
119
+
120
+
121
+ def cmd_scan(args) -> int:
122
+ r = scan(_target(args.path), _canaries(args), show=args.show)
123
+ fmt = "json" if args.json else args.format
124
+ if fmt == "json":
125
+ print(json.dumps(r.to_dict(), indent=2))
126
+ elif fmt == "markdown":
127
+ print(_markdown(r), end="")
128
+ else:
129
+ _print_report(r)
130
+ return EXIT_CLEAN if r.clean else EXIT_RESIDUE
131
+
132
+
133
+ def cmd_fix(args) -> int:
134
+ target = _target(args.path)
135
+ canaries = _canaries(args)
136
+ if args.dry_run:
137
+ r = scan(target, canaries)
138
+ _print_report(r)
139
+ print(f"\n{bold('fix would:')}")
140
+ for step in plan(r):
141
+ print(f" • {step}")
142
+ print(dim("Dry run: nothing was changed."))
143
+ return EXIT_CLEAN if r.clean else EXIT_RESIDUE
144
+ if not args.yes and postgres.is_postgres(target):
145
+ print(
146
+ f"This runs VACUUM FULL on every table with a pgvector column in {postgres.display(target)}.\n"
147
+ " - Each table is locked while it is rewritten: your app's reads and writes on it wait.\n"
148
+ " - It needs free disk space on the server about the size of the largest table.\n"
149
+ " Run with --dry-run to see the plan first."
150
+ )
151
+ if input("Continue? [y/N] ").strip().lower() not in ("y", "yes"):
152
+ print("Aborted.")
153
+ return EXIT_ERROR
154
+ elif not args.yes:
155
+ print(
156
+ f"This rewrites the store at {target} in place.\n"
157
+ " - Stop every process using it first.\n"
158
+ " - No backup is kept: a backup would defeat the erasure. Make your own if you need one.\n"
159
+ " - Chroma collections are rebuilt and get new internal IDs (names are kept).\n"
160
+ " Run with --dry-run to see the plan first."
161
+ )
162
+ if input("Continue? [y/N] ").strip().lower() not in ("y", "yes"):
163
+ print("Aborted.")
164
+ return EXIT_ERROR
165
+ result = fix(target, canaries, Options(force=args.force, allow_upgrade=args.allow_upgrade))
166
+ before, after = result.before.summary(), result.after.summary()
167
+ for a in result.actions:
168
+ print(f" • {a}")
169
+ canary_results = [{"canary": c.number, "found_in": c.found_in} for c in result.after.canaries]
170
+ rec = receipt.issue(target, before, after, result.actions, canary_results, label=result.before.target,
171
+ correlation_id=args.correlation)
172
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
173
+ out = Path(args.receipt or f"forgetproof-receipt-{stamp}.json")
174
+ out.write_text(json.dumps(rec, indent=2) + "\n")
175
+ resolved = len(set(before["findings"]) - set(after["findings"]))
176
+ for w in result.after.warnings:
177
+ print(f"{bold('!')} {w}")
178
+ if after["clean"]:
179
+ print(green(f"✓ Erased. {resolved} of {len(before['findings'])} finding(s) resolved; rescan is clean."))
180
+ else:
181
+ print(red("Residue remains after fix:"))
182
+ _print_report(result.after)
183
+ print(f"Signed receipt: {out} (key {receipt.fingerprint(rec['public_key'])})")
184
+ return EXIT_CLEAN if after["clean"] else EXIT_RESIDUE
185
+
186
+
187
+ def cmd_verify(args) -> int:
188
+ rec = json.loads(Path(args.receipt).read_text())
189
+ receipt.verify_signature(rec, args.key)
190
+ print(f"{green('✓')} signature valid — issued {rec['issued_at']} by key {receipt.fingerprint(rec['public_key'])}")
191
+ print(f" verdict at issue: {rec['verdict']}")
192
+ if not args.against:
193
+ return EXIT_CLEAN if rec["verdict"] == "CLEAN" else EXIT_RESIDUE
194
+ target = _target(args.against)
195
+ current = receipt.file_hashes(target)
196
+ if current != rec["files"]:
197
+ changed = sorted(set(current) ^ set(rec["files"]) | {k for k in current if rec["files"].get(k) != current[k]})
198
+ print(f"{dim('•')} store changed since the receipt was issued ({len(changed)} file(s)); rescanning")
199
+ else:
200
+ print(f"{green('✓')} store files are byte-identical to the receipt")
201
+ r = scan(target)
202
+ print(f"{green('✓') if r.clean else red('✗')} rescan now: {'clean' if r.clean else 'RESIDUE FOUND'}")
203
+ return EXIT_CLEAN if r.clean and rec["verdict"] == "CLEAN" else EXIT_RESIDUE
204
+
205
+
206
+ def cmd_key(args) -> int:
207
+ key = receipt.load_or_create_key()
208
+ pub = receipt.public_key_b64(key)
209
+ print(f"public key: {pub}\nfingerprint: {receipt.fingerprint(pub)}\nstored at: {receipt.key_path()}")
210
+ return EXIT_CLEAN
211
+
212
+
213
+ def _subject(args):
214
+ values = list(args.subject or [])
215
+ if getattr(args, "subject_file", None):
216
+ values += [line.strip() for line in Path(args.subject_file).read_text().splitlines() if line.strip()]
217
+ return make_subject(values)
218
+
219
+
220
+ def _print_copies(found: list[copies_mod.Copy]) -> None:
221
+ if not found:
222
+ print(dim(" no copies found in the places forgetproof knows to look"))
223
+ for c in found:
224
+ mark = green("scan") if c.scannable else dim("check")
225
+ print(f" {mark} {bold(c.kind)}: {c.where}\n {c.note}")
226
+
227
+
228
+ def cmd_forget(args) -> int:
229
+ target = _target(args.path)
230
+ subj = _subject(args)
231
+ queue_dir = Path(args.queue_dir).expanduser().resolve() if args.queue_dir else None
232
+ result = forget_mod.forget(target, subj, also_live=args.also_live, options=Options(allow_upgrade=args.allow_upgrade),
233
+ queue_dir=queue_dir, correlation_id=args.correlation)
234
+ if isinstance(result, forget_mod.Queued):
235
+ print(f"{bold('queued')}: {result.target} is open elsewhere right now (the store can't be rewritten while "
236
+ f"that's true).\nRun `forgetproof run-queued {args.path}` once nothing has it open, "
237
+ "typically at your app's next start before it reopens the store.")
238
+ return EXIT_RESIDUE
239
+ out = Path(args.receipt or f"forgetproof-receipt-{datetime.now(timezone.utc):%Y%m%dT%H%M%SZ}.json")
240
+ out.write_text(json.dumps(result, indent=2) + "\n")
241
+ for a in result["actions"]:
242
+ print(f" • {a}")
243
+ if result["verdict"] == "CLEAN":
244
+ print(green(f"✓ Erased {subj.count} value(s). Signed receipt: {out}"))
245
+ else:
246
+ found = [c for c in result["canaries"] if c["found_in"]]
247
+ print(red(f"{len(found)} of {len(result['canaries'])} value spelling(s) still on disk after erasing — see {out}"))
248
+ if not args.also_live:
249
+ print(dim(" A value that is still part of a live record stays until that record is deleted: "
250
+ "`--also-live` deletes live records that contain it."))
251
+ reachable = [c for c in result["copies"] if c["scannable"]]
252
+ if result["copies"]:
253
+ print(f"\n{bold('Copies of this store')} (not touched by this run):")
254
+ _print_copies([copies_mod.Copy(**c) for c in result["copies"]])
255
+ if reachable:
256
+ print(dim(" Run forget on each `scan` copy too, or `forgetproof sweep` to do all pinned stores."))
257
+ return EXIT_CLEAN if result["verdict"] == "CLEAN" else EXIT_RESIDUE
258
+
259
+
260
+ def cmd_copies(args) -> int:
261
+ target = _target(args.path)
262
+ if postgres.is_postgres(target):
263
+ print(dim("a database's copies are its backups and replicas; forgetproof can't see them from here"))
264
+ return EXIT_CLEAN
265
+ found = copies_mod.copies_of(target)
266
+ if args.json:
267
+ print(json.dumps([c.to_dict() for c in found], indent=2))
268
+ return EXIT_CLEAN
269
+ print(f"{bold('Copies of')} {target}:")
270
+ _print_copies(found)
271
+ return EXIT_CLEAN
272
+
273
+
274
+ def cmd_remembered(args) -> int:
275
+ target = _target(args.path)
276
+ rem = remembered.where_is(target, _subject(args), show=args.show)
277
+ if args.json:
278
+ print(json.dumps(rem.to_dict(), indent=2))
279
+ else:
280
+ print(f"{bold('forgetproof')} {dim(__version__)} {KINDS.get(rem.store, rem.store)} store at {rem.target}")
281
+ for v in rem.values:
282
+ if v.status == "absent":
283
+ print(f"{green('✓')} value #{v.value}: not in this store")
284
+ continue
285
+ print(f"{red('✗')} value #{v.value}: {v.status}")
286
+ for h in v.live:
287
+ print(f" live {h.where}" + (f"\n {dim(h.context)}" if h.context else ""))
288
+ for r in v.residue:
289
+ print(f" residue {r}")
290
+ return EXIT_CLEAN if rem.status == "absent" else EXIT_RESIDUE
291
+
292
+
293
+ def cmd_sweep(args) -> int:
294
+ """fix every pinned store that isn't open right now; one receipt each."""
295
+ pinned = _pinned()
296
+ if not pinned:
297
+ print(red("error: no pinned stores — run `forgetproof init` (a project) or `forgetproof init --home`"), file=sys.stderr)
298
+ return EXIT_ERROR
299
+ out_dir = Path(args.receipts_dir) if args.receipts_dir else receipt.key_path().parent / "receipts"
300
+ out_dir.mkdir(parents=True, exist_ok=True)
301
+ worst = EXIT_CLEAN
302
+ for name, found, root in pinned:
303
+ try:
304
+ target = discovery.resolve(found, root=root)
305
+ except ValueError as e:
306
+ print(f"{red('✗')} {bold(name)}: {e}")
307
+ worst = EXIT_ERROR
308
+ continue
309
+ label = f"{bold(name)} ({KINDS.get(found.kind, found.kind)}{', ' + found.agent if found.agent else ''})"
310
+ if not postgres.is_postgres(target) and found.kind != "files" and safety.open_by_other_processes(Path(target)):
311
+ print(f"{dim('–')} {label}: open in another process; skipped")
312
+ continue
313
+ try:
314
+ before = scan(target)
315
+ if before.clean:
316
+ print(f"{green('✓')} {label}: already clean")
317
+ continue
318
+ if args.dry_run:
319
+ print(f"{red('✗')} {label}: {len(before.findings)} finding(s); would fix")
320
+ worst = max(worst, EXIT_RESIDUE)
321
+ continue
322
+ result = fix(target, [], Options(allow_upgrade=args.allow_upgrade))
323
+ rec = receipt.issue(target, result.before.summary(), result.after.summary(), result.actions, [],
324
+ label=result.before.target, copies=forget_mod._copies(target))
325
+ path = out_dir / f"{name}.{datetime.now(timezone.utc):%Y%m%dT%H%M%S%fZ}.json"
326
+ path.write_text(json.dumps(rec, indent=2) + "\n")
327
+ mark = green("✓") if result.after.clean else red("✗")
328
+ print(f"{mark} {label}: {rec['verdict']} — receipt {path}")
329
+ if not result.after.clean:
330
+ worst = max(worst, EXIT_RESIDUE)
331
+ except (UnsupportedStore, FixError, postgres.PostgresError, ValueError, OSError, sqlite3.DatabaseError) as e:
332
+ print(f"{red('✗')} {label}: {e}")
333
+ worst = EXIT_ERROR
334
+ return worst
335
+
336
+
337
+ def cmd_run_queued(args) -> int:
338
+ target = _target(args.path)
339
+ queue_dir = Path(args.queue_dir).expanduser().resolve() if args.queue_dir else None
340
+ receipts = forget_mod.run_queued(target, options=Options(allow_upgrade=args.allow_upgrade), queue_dir=queue_dir)
341
+ if not receipts:
342
+ print(dim("nothing queued for this store."))
343
+ return EXIT_CLEAN
344
+ out_dir = Path(args.receipts_dir) if args.receipts_dir else Path.cwd()
345
+ out_dir.mkdir(parents=True, exist_ok=True)
346
+ stuck = 0
347
+ for i, rec in enumerate(receipts, 1):
348
+ path = out_dir / f"forgetproof-receipt-{datetime.now(timezone.utc):%Y%m%dT%H%M%S}-{i}.json"
349
+ path.write_text(json.dumps(rec, indent=2) + "\n")
350
+ clean = rec["verdict"] == "CLEAN"
351
+ stuck += 0 if clean else 1
352
+ print(f" • {(green if clean else red)(rec['verdict'])}: {path}")
353
+ if stuck:
354
+ print(red(f"{stuck} of {len(receipts)} queued erasure(s) still show residue — see the receipts above. "
355
+ f"They stay queued (up to {forget_mod.MAX_ATTEMPTS} attempts) rather than being dropped."))
356
+ return EXIT_RESIDUE
357
+ print(green(f"✓ {len(receipts)} queued erasure(s) finished."))
358
+ return EXIT_CLEAN
359
+
360
+
361
+ def cmd_purge_stale(args) -> int:
362
+ target = _target(args.path) if args.path else None
363
+ queue_dir = Path(args.queue_dir).expanduser().resolve() if args.queue_dir else None
364
+ purged = forget_mod.purge_stale(target, older_than_days=args.older_than_days, queue_dir=queue_dir)
365
+ print(f"purged {purged} parked entr{'y' if purged == 1 else 'ies'} "
366
+ f"older than {args.older_than_days} day(s).")
367
+ return EXIT_CLEAN
368
+
369
+
370
+ def cmd_mcp(args) -> int:
371
+ try:
372
+ from . import mcp_server
373
+ except ImportError:
374
+ print(red("error: the MCP server needs the mcp extra: pip install 'forgetproof[mcp]'"), file=sys.stderr)
375
+ return EXIT_ERROR
376
+ stores = [mcp_server.parse_store(spec) for spec in args.store]
377
+ if args.config:
378
+ config = Path(args.config).expanduser().resolve()
379
+ stores += [mcp_server.Store(name, discovery.resolve(found, root=config.parent), found.kind, found.agent)
380
+ for name, found in discovery.load_config(config).items()]
381
+ if args.home:
382
+ names = {s.name for s in stores}
383
+ stores += [s for s in mcp_server.home_stores() if s.name not in names]
384
+ if not stores:
385
+ print(red("error: no stores given — pass --store, --config or --home"), file=sys.stderr)
386
+ return EXIT_ERROR
387
+ if args.show and not args.owner:
388
+ print(red("error: --show only means something with --owner"), file=sys.stderr)
389
+ return EXIT_ERROR
390
+ receipts = Path(args.receipts).expanduser().resolve() if args.receipts else None
391
+ queue_dir = Path(args.queue_dir).expanduser().resolve() if args.queue_dir else None
392
+ mcp_server.build(stores, allow_fix=args.allow_fix, receipts_dir=receipts,
393
+ subject_file=args.subject_file, queue_dir=queue_dir, owner=args.owner, show=args.show).run()
394
+ return EXIT_CLEAN
395
+
396
+
397
+ def cmd_desktop(args) -> int:
398
+ from .desktop.app import main as desktop_main
399
+
400
+ argv = (["--browser"] if args.browser else []) + (["--no-open"] if args.no_open else []) + (["--port", str(args.port)] if args.port else [])
401
+ return desktop_main(argv)
402
+
403
+
404
+ def cmd_init(args) -> int:
405
+ if args.home:
406
+ root = Path.home()
407
+ found = discovery.discover_home(root, max_depth=args.max_depth)
408
+ out = discovery.home_config_path()
409
+ where_from = "in the places personal agents keep memory on this machine"
410
+ else:
411
+ root = Path(args.directory).expanduser().resolve()
412
+ found = discovery.discover(root, max_depth=args.max_depth)
413
+ out = discovery.config_path(root)
414
+ where_from = f"under {root}"
415
+ if not found:
416
+ print(dim(f"nothing that looks like a memory store was found {where_from}."))
417
+ return EXIT_CLEAN
418
+ print(f"Found {where_from}:")
419
+ for f in found:
420
+ where = f"the {f.where} environment variable" if f.kind == "postgres" else f.where
421
+ agent = f" — {f.agent}" if f.agent else ""
422
+ print(f" • {bold(f.name)} ({KINDS.get(f.kind, f.kind)}{agent}): {where}")
423
+ if not args.yes:
424
+ print(f"\nThis writes {out} so forgetproof only ever acts on these, by name, from here on.")
425
+ if input("Pin these stores? [y/N] ").strip().lower() not in ("y", "yes"):
426
+ print("Aborted; nothing was written.")
427
+ return EXIT_ERROR
428
+ discovery.write_config(root, found, path=out)
429
+ print(green(f"✓ pinned {len(found)} store(s) to {out}"))
430
+ hint = "from anywhere" if args.home else f"from {root}, or a subdirectory of it"
431
+ print(dim(f" e.g. forgetproof scan {found[0].name} ({hint})"))
432
+ return EXIT_CLEAN
433
+
434
+
435
+ def _utf8_output() -> None:
436
+ """Windows consoles and redirects default to a legacy code page that can't encode ✓ and ✗."""
437
+ for stream in (sys.stdout, sys.stderr):
438
+ if (getattr(stream, "encoding", "") or "").lower().replace("-", "") != "utf8" and hasattr(stream, "reconfigure"):
439
+ stream.reconfigure(encoding="utf-8", errors="replace")
440
+
441
+
442
+ def main(argv: list[str] | None = None) -> int:
443
+ _utf8_output()
444
+ p = argparse.ArgumentParser(prog="forgetproof", description="Detect and erase deleted records left on disk by agent memory stores.")
445
+ p.add_argument("--version", action="version", version=f"forgetproof {__version__}")
446
+ sub = p.add_subparsers(dest="cmd", required=True)
447
+
448
+ def canary_args(sp):
449
+ sp.add_argument("--canary", action="append", metavar="VALUE", help="a value you deleted (repeatable), e.g. a user's email")
450
+ sp.add_argument("--canary-file", metavar="FILE", help="file with one canary value per line")
451
+
452
+ s = sub.add_parser("scan", help="find deleted data still on disk (exit 1 if any)")
453
+ s.add_argument("path", help="Chroma persist directory, SQLite file, or postgresql:// URL (put the password in PGPASSWORD)")
454
+ canary_args(s)
455
+ s.add_argument("--format", choices=["text", "json", "markdown"], default="text",
456
+ help="markdown is for CI job summaries and leaves out samples")
457
+ s.add_argument("--json", action="store_true", help="same as --format json")
458
+ s.add_argument("--show", action="store_true",
459
+ help="owner mode: print samples unredacted (for a store you own on your own machine)")
460
+ s.set_defaults(func=cmd_scan)
461
+
462
+ f = sub.add_parser("fix", help="erase residue in place and issue a signed receipt")
463
+ f.add_argument("path")
464
+ canary_args(f)
465
+ f.add_argument("--yes", action="store_true", help="don't ask for confirmation")
466
+ f.add_argument("--receipt", metavar="FILE", help="where to write the receipt")
467
+ f.add_argument("--correlation", metavar="ID", help="an opaque id to carry into the receipt (e.g. a case or ticket id)")
468
+ f.add_argument("--dry-run", action="store_true", help="show what fix would do and change nothing")
469
+ f.add_argument("--force", action="store_true", help="skip the open-process and free-space checks")
470
+ f.add_argument("--allow-upgrade", action="store_true",
471
+ help="let the installed chromadb upgrade an older store to its own format")
472
+ f.set_defaults(func=cmd_fix)
473
+
474
+ g = sub.add_parser("forget", help="erase one subject's data now, or queue it if the store can't be rewritten yet")
475
+ g.add_argument("path")
476
+ g.add_argument("--subject", action="append", metavar="VALUE",
477
+ help="an exact value to erase (repeatable): a name, an email, a phone number, a pasted secret")
478
+ g.add_argument("--subject-file", metavar="FILE", help="file with one value per line")
479
+ g.add_argument("--also-live", action="store_true",
480
+ help="also delete live records that contain one of the values (a line, a row, a record); "
481
+ "off by default — normally the agent deletes, forgetproof erases what it leaves behind")
482
+ g.add_argument("--receipt", metavar="FILE", help="where to write the receipt")
483
+ g.add_argument("--correlation", metavar="ID",
484
+ help="an opaque id to carry into the receipt (e.g. a case or ticket id); kept even if the "
485
+ "request is queued and only drains later, possibly in another process")
486
+ g.add_argument("--queue-dir", metavar="DIR", help="where to queue an erasure that can't run yet (default: next to the signing key)")
487
+ g.add_argument("--allow-upgrade", action="store_true",
488
+ help="let the installed chromadb upgrade an older store to its own format")
489
+ g.set_defaults(func=cmd_forget)
490
+
491
+ rq = sub.add_parser("run-queued", help="finish forget() calls queued for a store (run before reopening it)")
492
+ rq.add_argument("path")
493
+ rq.add_argument("--receipts-dir", metavar="DIR", help="where to write the receipts (default: current directory)")
494
+ rq.add_argument("--queue-dir", metavar="DIR", help="where entries were queued (default: next to the signing key)")
495
+ rq.add_argument("--allow-upgrade", action="store_true",
496
+ help="let the installed chromadb upgrade an older store to its own format")
497
+ rq.set_defaults(func=cmd_run_queued)
498
+
499
+ ps = sub.add_parser("purge-stale", help="delete parked (repeatedly non-clean) queue entries older than N days")
500
+ ps.add_argument("path", nargs="?", help="only purge entries for this store (default: every store in the queue)")
501
+ ps.add_argument("--older-than-days", type=float, default=forget_mod.PARK_RETENTION_DAYS, metavar="N",
502
+ help=f"default: {forget_mod.PARK_RETENTION_DAYS} (run-queued also purges at this age on its own)")
503
+ ps.add_argument("--queue-dir", metavar="DIR", help="where entries were queued (default: next to the signing key)")
504
+ ps.set_defaults(func=cmd_purge_stale)
505
+
506
+ v = sub.add_parser("verify", help="check a receipt's signature, optionally against the store")
507
+ v.add_argument("receipt")
508
+ v.add_argument("--against", metavar="PATH", help="rescan this store and compare")
509
+ v.add_argument("--key", metavar="PUBKEY", help="require this signing key: its fingerprint or public key (from `forgetproof key`)")
510
+ v.set_defaults(func=cmd_verify)
511
+
512
+ k = sub.add_parser("key", help="show this machine's receipt signing key")
513
+ k.set_defaults(func=cmd_key)
514
+
515
+ i = sub.add_parser("init", help="find memory stores under a directory and pin them by name, once, after asking")
516
+ i.add_argument("directory", nargs="?", default=".", help="default: the current directory")
517
+ i.add_argument("--home", action="store_true",
518
+ help="instead: the stores personal agents keep on this machine (Claude Code, mem0, Letta, the memory "
519
+ "MCP server, Obsidian, and project folders), pinned for this user rather than one project")
520
+ i.add_argument("--max-depth", type=int, default=4, metavar="N", help="how far to search into subdirectories")
521
+ i.add_argument("--yes", action="store_true", help="don't ask for confirmation")
522
+ i.set_defaults(func=cmd_init)
523
+
524
+ c = sub.add_parser("copies", help="where else this store's bytes probably are: sync folders, git, backups")
525
+ c.add_argument("path")
526
+ c.add_argument("--json", action="store_true")
527
+ c.set_defaults(func=cmd_copies)
528
+
529
+ w = sub.add_parser("remembered", help="does this store still hold a value — live, or only as residue?")
530
+ w.add_argument("path")
531
+ w.add_argument("--subject", action="append", metavar="VALUE", help="an exact value (repeatable)")
532
+ w.add_argument("--subject-file", metavar="FILE", help="file with one value per line")
533
+ w.add_argument("--show", action="store_true", help="owner mode: show the text around each live occurrence")
534
+ w.add_argument("--json", action="store_true")
535
+ w.set_defaults(func=cmd_remembered)
536
+
537
+ sw = sub.add_parser("sweep", help="fix every pinned store that isn't open right now, one receipt each")
538
+ sw.add_argument("--receipts-dir", metavar="DIR", help="where receipts go (default: next to the signing key)")
539
+ sw.add_argument("--dry-run", action="store_true", help="report what would be fixed and change nothing")
540
+ sw.add_argument("--allow-upgrade", action="store_true",
541
+ help="let the installed chromadb upgrade an older store to its own format")
542
+ sw.set_defaults(func=cmd_sweep)
543
+
544
+ dk = sub.add_parser("desktop", help="open Memory Hygiene, the desktop app (pip install 'forgetproof[desktop]')")
545
+ dk.add_argument("--browser", action="store_true", help="open in the default browser instead of a window")
546
+ dk.add_argument("--port", type=int, default=0, help="loopback port (default: any free port)")
547
+ dk.add_argument("--no-open", action="store_true", help="start the local server, print its URL, open nothing")
548
+ dk.set_defaults(func=cmd_desktop)
549
+
550
+ m = sub.add_parser("mcp", help="run an MCP server (stdio) that lets an agent scan, fix and verify named stores")
551
+ m.add_argument("--store", action="append", default=[], metavar="NAME=PATH_OR_URL",
552
+ help="a store the agent may use (repeatable); the agent only ever sees NAME")
553
+ m.add_argument("--config", metavar="FILE",
554
+ help="also use every store pinned by `forgetproof init` in this file "
555
+ f"(default name: {discovery.CONFIG_NAME})")
556
+ m.add_argument("--home", action="store_true",
557
+ help="also serve the stores `forgetproof init --home` pinned for this user (or, if it was "
558
+ "never run, what discovery finds in the places personal agents keep memory)")
559
+ m.add_argument("--owner", action="store_true",
560
+ help="owner mode, for the agent you run yourself on your own machine: adds what_is_remembered "
561
+ "and (with --allow-fix) forget_value, which take the values the user names")
562
+ m.add_argument("--show", action="store_true",
563
+ help="with --owner: what_is_remembered also returns the text around each live match")
564
+ m.add_argument("--allow-fix", action="store_true", help="offer fix_store, sweep and forget_me/forget_value (off by default)")
565
+ m.add_argument("--receipts", metavar="DIR", help="where receipts are written (default: next to the signing key)")
566
+ m.add_argument("--subject-file", metavar="FILE",
567
+ help="file holding the current user's identity, kept current by your application; "
568
+ "enables check_if_forgotten and forget_me, scoped to that value only")
569
+ m.add_argument("--queue-dir", metavar="DIR", help="where forget_me queues a Chroma erasure it can't do yet")
570
+ m.set_defaults(func=cmd_mcp)
571
+
572
+ args = p.parse_args(argv)
573
+ try:
574
+ return args.func(args)
575
+ except (UnsupportedStore, FixError, LiveEraseError, postgres.PostgresError, ValueError, OSError,
576
+ sqlite3.DatabaseError) as e:
577
+ print(red(f"error: {e}"), file=sys.stderr)
578
+ return EXIT_ERROR
579
+
580
+
581
+ if __name__ == "__main__":
582
+ sys.exit(main())