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,161 @@
1
+ """A daily sweep, scheduled with what the operating system already has.
2
+
3
+ macOS: a LaunchAgent plist in ~/Library/LaunchAgents, loaded with launchctl. Windows: a Task
4
+ Scheduler task. Both run `forgetproof sweep` as the signed-in user, so they see the same stores,
5
+ keys and receipts the desktop app does, and both are removed with one call. Linux isn't a target of
6
+ the desktop app; `status()` says so and gives the cron line to paste.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import plistlib
13
+ import re
14
+ import subprocess
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ TASK = "forgetproof-sweep"
19
+ LABEL = "ai.stellarminds.forgetproof.sweep"
20
+ _TIME = re.compile(r"^([01]\d|2[0-3]):([0-5]\d)$")
21
+
22
+
23
+ class ScheduleError(Exception):
24
+ pass
25
+
26
+
27
+ def command() -> list[str]:
28
+ """How to run `forgetproof sweep` from a scheduler: the frozen app itself, or this interpreter."""
29
+ if getattr(sys, "frozen", False):
30
+ return [sys.executable, "sweep"]
31
+ return [sys.executable, "-m", "forgetproof", "sweep"]
32
+
33
+
34
+ def _parse_time(time: str) -> tuple[int, int]:
35
+ m = _TIME.match(time)
36
+ if not m:
37
+ raise ScheduleError("time must be HH:MM, 24-hour")
38
+ return int(m.group(1)), int(m.group(2))
39
+
40
+
41
+ # --- macOS ----------------------------------------------------------------------------------------
42
+
43
+ def plist_path() -> Path:
44
+ return Path.home() / "Library" / "LaunchAgents" / f"{LABEL}.plist"
45
+
46
+
47
+ def launchd_plist(time: str = "03:00") -> dict:
48
+ hour, minute = _parse_time(time)
49
+ log_dir = Path.home() / "Library" / "Logs" / "forgetproof"
50
+ return {
51
+ "Label": LABEL,
52
+ "ProgramArguments": command(),
53
+ "StartCalendarInterval": {"Hour": hour, "Minute": minute},
54
+ "RunAtLoad": False,
55
+ "StandardOutPath": str(log_dir / "sweep.log"),
56
+ "StandardErrorPath": str(log_dir / "sweep.err"),
57
+ "EnvironmentVariables": {k: v for k, v in os.environ.items() if k in ("FORGETPROOF_HOME", "FORGETPROOF_USE_KEYRING", "PATH")},
58
+ }
59
+
60
+
61
+ def _launchctl(*args: str) -> subprocess.CompletedProcess:
62
+ return subprocess.run(["launchctl", *args], capture_output=True, text=True)
63
+
64
+
65
+ def _install_mac(time: str) -> None:
66
+ path = plist_path()
67
+ path.parent.mkdir(parents=True, exist_ok=True)
68
+ (Path.home() / "Library" / "Logs" / "forgetproof").mkdir(parents=True, exist_ok=True)
69
+ path.write_bytes(plistlib.dumps(launchd_plist(time)))
70
+ _launchctl("bootout", f"gui/{os.getuid()}", str(path)) # replace a previous one quietly
71
+ p = _launchctl("bootstrap", f"gui/{os.getuid()}", str(path))
72
+ if p.returncode != 0:
73
+ p = _launchctl("load", "-w", str(path)) # older launchctl
74
+ if p.returncode != 0:
75
+ raise ScheduleError(f"launchctl refused the agent: {p.stderr.strip() or p.stdout.strip()}")
76
+
77
+
78
+ def _uninstall_mac() -> None:
79
+ path = plist_path()
80
+ if path.exists():
81
+ _launchctl("bootout", f"gui/{os.getuid()}", str(path))
82
+ _launchctl("unload", str(path))
83
+ path.unlink()
84
+
85
+
86
+ def _status_mac() -> dict:
87
+ path = plist_path()
88
+ if not path.exists():
89
+ return {"installed": False}
90
+ try:
91
+ data = plistlib.loads(path.read_bytes())
92
+ cal = data.get("StartCalendarInterval", {})
93
+ time = f"{int(cal.get('Hour', 0)):02d}:{int(cal.get('Minute', 0)):02d}"
94
+ except Exception:
95
+ time = "?"
96
+ loaded = _launchctl("print", f"gui/{os.getuid()}/{LABEL}").returncode == 0
97
+ return {"installed": True, "time": time, "loaded": loaded, "detail": str(path)}
98
+
99
+
100
+ # --- Windows --------------------------------------------------------------------------------------
101
+
102
+ def _schtasks(*args: str) -> subprocess.CompletedProcess:
103
+ return subprocess.run(["schtasks", *args], capture_output=True, text=True)
104
+
105
+
106
+ def _quote(arg: str) -> str:
107
+ return f'"{arg}"' if " " in arg or '"' in arg else arg
108
+
109
+
110
+ def _install_windows(time: str) -> None:
111
+ _parse_time(time)
112
+ tr = " ".join(_quote(a) for a in command())
113
+ p = _schtasks("/Create", "/F", "/TN", TASK, "/SC", "DAILY", "/ST", time, "/TR", tr)
114
+ if p.returncode != 0:
115
+ raise ScheduleError(f"Task Scheduler refused the task: {p.stderr.strip() or p.stdout.strip()}")
116
+
117
+
118
+ def _uninstall_windows() -> None:
119
+ _schtasks("/Delete", "/F", "/TN", TASK)
120
+
121
+
122
+ def _status_windows() -> dict:
123
+ p = _schtasks("/Query", "/TN", TASK, "/FO", "LIST", "/V")
124
+ if p.returncode != 0:
125
+ return {"installed": False}
126
+ time = next((line.split(":", 1)[1].strip() for line in p.stdout.splitlines()
127
+ if line.strip().lower().startswith(("start time", "next run time"))), "?")
128
+ return {"installed": True, "time": time, "loaded": True, "detail": f"Task Scheduler task {TASK}"}
129
+
130
+
131
+ # --- the platform switch --------------------------------------------------------------------------
132
+
133
+ def supported() -> bool:
134
+ return sys.platform in ("darwin", "win32")
135
+
136
+
137
+ def status() -> dict:
138
+ base = {"platform": sys.platform, "supported": supported(), "command": " ".join(command())}
139
+ if sys.platform == "darwin":
140
+ return {**base, **_status_mac()}
141
+ if sys.platform == "win32":
142
+ return {**base, **_status_windows()}
143
+ return {**base, "installed": False, "hint": f"add to crontab: 0 3 * * * {' '.join(command())}"}
144
+
145
+
146
+ def install(time: str = "03:00") -> dict:
147
+ if sys.platform == "darwin":
148
+ _install_mac(time)
149
+ elif sys.platform == "win32":
150
+ _install_windows(time)
151
+ else:
152
+ raise ScheduleError("scheduling is set up on macOS and Windows; on Linux add the cron line from status()")
153
+ return status()
154
+
155
+
156
+ def uninstall() -> dict:
157
+ if sys.platform == "darwin":
158
+ _uninstall_mac()
159
+ elif sys.platform == "win32":
160
+ _uninstall_windows()
161
+ return status()
@@ -0,0 +1,298 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>Memory Hygiene</title>
7
+ <style>
8
+ :root { --bg:#f5f7fa; --panel:#ffffff; --ink:#111827; --body:#374151; --muted:#6b7280; --line:#e5e7eb; --accent:#2662d9; --accent-ink:#fff;
9
+ --warn:#c2410c; --warn-bg:#ffedd5; --ok:#1d4ed8; --ok-bg:#dbeafe; --good:#15803d; --good-bg:#dcfce7; --chip:#e8effc; --soft:#f9fafb; --dark:#1e293b; --dark-muted:#94a3b8;
10
+ --sans: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
11
+ @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { --bg:#0f172a; --panel:#111c33; --ink:#e5e7eb; --body:#cbd5e1; --muted:#94a3b8; --line:#243147; --chip:#1e2a44; --soft:#16213a; --ok-bg:#1e3a8a; --ok:#bfdbfe; --warn-bg:#7c2d12; --warn:#fed7aa; --good-bg:#14532d; --good:#bbf7d0; } }
12
+ * { box-sizing:border-box; }
13
+ body { margin:0; background:var(--bg); color:var(--ink); font:15px/1.5 var(--sans); display:grid; grid-template-columns:220px 1fr; min-height:100vh; }
14
+ a { color:var(--accent); }
15
+ code { font:12.5px/1.5 var(--mono); background:var(--soft); border:1px solid var(--line); border-radius:5px; padding:1px 5px; overflow-wrap:anywhere; }
16
+ nav { border-right:1px solid var(--line); background:var(--panel); padding:18px 14px; position:sticky; top:0; height:100vh; display:flex; flex-direction:column; gap:4px; }
17
+ nav .brand { display:flex; align-items:center; gap:9px; font-weight:750; font-size:16px; padding:4px 8px 16px; }
18
+ nav .brand .mark { width:24px; height:24px; border-radius:7px; background:var(--ink); display:inline-block; }
19
+ nav button { font:inherit; text-align:left; background:none; border:0; border-radius:9px; padding:9px 10px; color:var(--body); cursor:pointer; font-weight:600; }
20
+ nav button:hover { background:var(--soft); } nav button.active { background:var(--chip); color:var(--accent); }
21
+ nav .foot { margin-top:auto; font-size:12px; color:var(--muted); padding:8px; }
22
+ main { padding:28px 32px 60px; max-width:1100px; }
23
+ h1 { font-size:26px; letter-spacing:-0.02em; margin:0 0 4px; font-weight:750; } .lede { color:var(--muted); margin:0 0 20px; }
24
+ h2 { font-size:17px; margin:22px 0 8px; font-weight:700; } h3 { font-size:15px; margin:0 0 4px; font-weight:680; }
25
+ .card { background:var(--panel); border:1px solid var(--line); border-radius:14px; padding:16px 18px; box-shadow:0 1px 2px rgba(0,0,0,.04); margin-bottom:12px; }
26
+ .row { display:flex; gap:12px; align-items:center; flex-wrap:wrap; } .grow { flex:1 1 auto; min-width:0; }
27
+ .muted { color:var(--muted); } .small { font-size:13px; }
28
+ .btn { display:inline-flex; align-items:center; gap:8px; font:inherit; font-weight:650; font-size:14px; border-radius:9px; padding:8px 14px; min-height:36px; border:1px solid var(--accent); background:var(--accent); color:var(--accent-ink); cursor:pointer; white-space:nowrap; }
29
+ .btn.secondary { background:var(--panel); color:var(--ink); border-color:var(--line); } .btn.danger { background:var(--warn); border-color:var(--warn); }
30
+ .btn:disabled { opacity:.5; cursor:default; } .btn.small { padding:5px 10px; min-height:30px; font-size:13px; }
31
+ .badge { display:inline-block; border-radius:999px; padding:1px 9px; font-size:12px; font-weight:650; background:var(--soft); color:var(--muted); white-space:nowrap; }
32
+ .badge.clean { background:var(--good-bg); color:var(--good); } .badge.residue, .badge.bad { background:var(--warn-bg); color:var(--warn); } .badge.live { background:var(--ok-bg); color:var(--ok); } .badge.open { background:var(--chip); color:var(--accent); }
33
+ input[type=text], input[type=time], textarea { font:inherit; width:100%; border:1px solid var(--line); border-radius:9px; padding:9px 11px; background:var(--panel); color:var(--ink); }
34
+ textarea { min-height:84px; font-family:var(--mono); font-size:13px; }
35
+ label.check { display:flex; gap:8px; align-items:flex-start; font-size:14px; color:var(--body); } label.check input { margin-top:4px; }
36
+ table { width:100%; border-collapse:collapse; font-size:14px; } th { text-align:left; font-size:12px; letter-spacing:.06em; text-transform:uppercase; color:var(--muted); font-weight:700; padding:6px 8px; border-bottom:1px solid var(--line); } td { padding:9px 8px; border-bottom:1px solid var(--line); vertical-align:top; } tr:last-child td { border-bottom:0; }
37
+ .kv { display:grid; grid-template-columns:150px 1fr; gap:4px 12px; font-size:14px; } .kv b { color:var(--muted); font-weight:600; }
38
+ pre.log { background:var(--dark); color:var(--dark-muted); border-radius:10px; padding:12px 14px; font:12px/1.55 var(--mono); white-space:pre-wrap; overflow-wrap:anywhere; max-height:380px; overflow:auto; margin:10px 0 0; }
39
+ pre.log .ok { color:#86efac; } pre.log .bad { color:#fca5a5; } pre.log .dim { color:#64748b; }
40
+ .status { display:flex; gap:10px; align-items:center; font-size:14px; } .dot { width:9px; height:9px; border-radius:50%; background:var(--muted); flex:none; } .dot.run { background:var(--accent); animation:pulse 1s infinite; } .dot.ok { background:var(--good); } .dot.bad { background:var(--warn); }
41
+ @keyframes pulse { 50% { opacity:.3; } }
42
+ .toast { position:fixed; right:18px; bottom:18px; background:var(--dark); color:#fff; padding:10px 14px; border-radius:10px; font-size:14px; max-width:420px; box-shadow:0 6px 24px rgba(0,0,0,.25); display:none; }
43
+ .empty { padding:30px 10px; text-align:center; color:var(--muted); }
44
+ .grid2 { display:grid; grid-template-columns:1fr 1fr; gap:12px; } @media (max-width:900px) { .grid2 { grid-template-columns:1fr; } body { grid-template-columns:1fr; } nav { position:static; height:auto; flex-direction:row; flex-wrap:wrap; } nav .foot { display:none; } }
45
+ details summary { cursor:pointer; color:var(--accent); font-weight:600; font-size:14px; }
46
+ .hint { font-size:13px; color:var(--muted); margin-top:6px; }
47
+ </style>
48
+ </head>
49
+ <body>
50
+ <nav aria-label="Sections">
51
+ <div class="brand"><span class="mark"></span>Memory Hygiene</div>
52
+ <button data-tab="overview" class="active">Overview</button>
53
+ <button data-tab="remembered">What does it remember?</button>
54
+ <button data-tab="forget">Forget</button>
55
+ <button data-tab="receipts">Receipts</button>
56
+ <button data-tab="sweep">Sweep &amp; schedule</button>
57
+ <button data-tab="settings">Settings</button>
58
+ <div class="foot">forgetproof <span id="version"></span><br/>Nothing leaves this machine.</div>
59
+ </nav>
60
+ <main>
61
+
62
+ <section id="tab-overview">
63
+ <h1>Your agents' memory, on this machine</h1>
64
+ <p class="lede">Every store a personal agent keeps here, whether it still holds data that was deleted, whether it's open right now, and where copies of it live.</p>
65
+ <div id="unpinned"></div>
66
+ <div class="card">
67
+ <div class="row"><h3 class="grow">Stores</h3><button class="btn secondary small" id="scanAll">Scan all</button><button class="btn secondary small" id="rediscover">Look for new stores</button></div>
68
+ <div id="stores"></div>
69
+ </div>
70
+ <div class="grid2">
71
+ <div class="card"><h3>Queued erasures</h3><div id="queue" class="small muted">–</div></div>
72
+ <div class="card"><h3>Last sweep</h3><div id="lastSweep" class="small muted">–</div></div>
73
+ </div>
74
+ <div id="storeDetail"></div>
75
+ </section>
76
+
77
+ <section id="tab-remembered" hidden>
78
+ <h1>What does it remember about…</h1>
79
+ <p class="lede">A name, an email, a phone number, a thing you pasted. One value per line; every spelling you know. You own these stores, so the app can show you where a value sits.</p>
80
+ <div class="card">
81
+ <textarea id="remValues" placeholder="alice@example.com&#10;Alice Example&#10;415-555-0100"></textarea>
82
+ <div class="row" style="margin-top:10px"><label class="check"><input type="checkbox" id="remShow" /> Show the text around each match</label><span class="grow"></span><button class="btn" id="remGo">Look</button></div>
83
+ </div>
84
+ <div id="remOut"></div>
85
+ </section>
86
+
87
+ <section id="tab-forget" hidden>
88
+ <h1>Forget</h1>
89
+ <p class="lede">Erase these exact values from every store: what the agent already deleted but still holds, and, if you tick it, the live records that still carry them. One signed receipt per store.</p>
90
+ <div class="card">
91
+ <textarea id="fgValues" placeholder="alice@example.com&#10;Alice Example&#10;415-555-0100"></textarea>
92
+ <div style="margin-top:10px"><label class="check"><input type="checkbox" id="fgLive" /> <span><b>Also delete live records that contain one of these values.</b> A line in a text file, a row in a table, a record in a collection. Off, forgetproof only erases what the agent already deleted. There is no undo.</span></label></div>
93
+ <div class="row" style="margin-top:10px"><input type="text" id="fgCorr" placeholder="a label for the receipt, optional (not sensitive)" style="max-width:380px" /><span class="grow"></span><button class="btn danger" id="fgGo">Forget everywhere</button></div>
94
+ </div>
95
+ <div id="fgOut"></div>
96
+ </section>
97
+
98
+ <section id="tab-receipts" hidden>
99
+ <h1>Receipts</h1>
100
+ <p class="lede">Every erasure this machine signed. A receipt holds counts and file hashes, never the values. Verify any of them against the store as it is now.</p>
101
+ <div class="card small"><div class="kv"><b>Signing key</b><span><code id="fp"></code> <span class="muted">(fingerprint)</span></span><b>Public key</b><code id="pk"></code><b>Kept at</b><span id="keyPath" class="muted"></span></div></div>
102
+ <div class="card" id="receiptList"></div>
103
+ <div id="receiptDetail"></div>
104
+ </section>
105
+
106
+ <section id="tab-sweep" hidden>
107
+ <h1>Sweep &amp; schedule</h1>
108
+ <p class="lede">A sweep fixes every store that isn't open right now and keeps a receipt for each. Schedule one daily so residue never piles up.</p>
109
+ <div class="grid2">
110
+ <div class="card"><h3>Run now</h3><p class="small muted">Stores an agent has open are skipped and reported; run the sweep again after you quit the agent, or rely on the queue.</p><div class="row"><button class="btn secondary" id="sweepDry">Show what would change</button><button class="btn" id="sweepGo">Sweep now</button></div></div>
111
+ <div class="card"><h3>Daily sweep</h3><div id="schedState" class="small muted">–</div><div class="row" style="margin-top:10px"><input type="time" id="schedTime" value="03:00" style="max-width:140px" /><button class="btn" id="schedOn">Schedule</button><button class="btn secondary" id="schedOff">Remove</button></div><div class="hint" id="schedHint"></div></div>
112
+ </div>
113
+ <div id="sweepOut"></div>
114
+ </section>
115
+
116
+ <section id="tab-settings" hidden>
117
+ <h1>Settings</h1>
118
+ <p class="lede">Which stores this app may touch, and where its keys live.</p>
119
+ <div class="card"><h3>Pinned stores</h3><p class="small muted">The app only ever acts on stores pinned here. Unpinning forgets the entry, not the data.</p><div id="pinnedList"></div>
120
+ <details style="margin-top:12px"><summary>Pin a store by path</summary><div class="row" style="margin-top:8px"><input type="text" id="pinPath" placeholder="C:\Users\you\project\chroma_dir or /Users/you/.mem0" class="grow" /><input type="text" id="pinName" placeholder="name" style="max-width:160px" /><button class="btn secondary" id="pinGo">Pin</button></div><div class="hint">Inside your home directory only. Kind is detected from what's there.</div></details>
121
+ </div>
122
+ <div class="card"><h3>Keys</h3><div class="kv small"><b>Receipt signing key</b><span id="keyWhere"></span><b>OS keychain</b><span>Set <code>FORGETPROOF_USE_KEYRING=1</code> before launch to keep new keys in the macOS Keychain or Windows Credential Locker (<code>pip install 'forgetproof[keyring]'</code>). An existing file key is never moved.</span><b>Data folder</b><code id="homeDir"></code></div></div>
123
+ <div class="card small muted">Erasing rewrites a store's logical files, which is what sync, backups and other programs read. On an SSD an overwrite doesn't defeat wear levelling; full-disk encryption covers the rest. forgetproof keeps no copy of what it erases and makes no network requests.</div>
124
+ </section>
125
+
126
+ </main>
127
+ <div class="toast" id="toast"></div>
128
+
129
+ <script>
130
+ const TOKEN = new URLSearchParams(location.search).get("t") || sessionStorage.getItem("fp-token") || "";
131
+ try { if (TOKEN) sessionStorage.setItem("fp-token", TOKEN); } catch {}
132
+ if (location.search) history.replaceState(null, "", location.pathname);
133
+ const $ = (id) => document.getElementById(id);
134
+ const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
135
+ const when = (iso) => iso ? new Date(iso).toLocaleString(undefined, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }) : "never";
136
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
137
+ let toastTimer;
138
+ function toast(msg, bad = false) { const t = $("toast"); t.textContent = msg; t.style.display = "block"; t.style.background = bad ? "#7c2d12" : ""; clearTimeout(toastTimer); toastTimer = setTimeout(() => (t.style.display = "none"), bad ? 6000 : 3000); }
139
+ async function api(method, path, body) {
140
+ const res = await fetch(path, { method, headers: { "X-Forgetproof-Token": TOKEN, ...(body ? { "content-type": "application/json" } : {}) }, body: body ? JSON.stringify(body) : undefined });
141
+ const data = await res.json().catch(() => ({}));
142
+ if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
143
+ return data;
144
+ }
145
+ const busy = (btn, on) => { btn.disabled = on; btn.dataset.label ??= btn.textContent; btn.textContent = on ? "Working…" : btn.dataset.label; };
146
+ const lines = (el) => el.value.split("\n").map((s) => s.trim()).filter(Boolean);
147
+ const verdictBadge = (v) => `<span class="badge ${v === "clean" ? "clean" : v === "absent" ? "clean" : v === "live" ? "live" : v === "queued" || v === "skipped" ? "open" : "bad"}">${esc(v.replace("_", " "))}</span>`;
148
+
149
+ // -- tabs --------------------------------------------------------------------------------------------
150
+ document.querySelectorAll("nav [data-tab]").forEach((b) => (b.onclick = () => show(b.dataset.tab)));
151
+ function show(tab) {
152
+ document.querySelectorAll("nav [data-tab]").forEach((b) => b.classList.toggle("active", b.dataset.tab === tab));
153
+ document.querySelectorAll("main > section").forEach((s) => (s.hidden = s.id !== `tab-${tab}`));
154
+ if (tab === "overview") loadOverview();
155
+ if (tab === "receipts") loadReceipts();
156
+ if (tab === "sweep") loadSchedule();
157
+ if (tab === "settings") loadSettings();
158
+ }
159
+
160
+ // -- overview ------------------------------------------------------------------------------------------
161
+ let overview = null;
162
+ async function loadOverview() {
163
+ try { overview = await api("GET", "/api/overview"); } catch (e) { return toast(e.message, true); }
164
+ $("version").textContent = overview.version;
165
+ $("homeDir").textContent = overview.home;
166
+ const un = $("unpinned");
167
+ un.innerHTML = overview.unpinned.length ? `<div class="card" style="border-color:#bfdbfe"><div class="row"><div class="grow"><h3>${plural(overview.unpinned.length, "store")} found, not yet pinned</h3><p class="small muted" style="margin:0">The app only acts on stores you pin. These are the places personal agents keep memory on this machine.</p></div><button class="btn" id="pinAll">Pin all</button></div>
168
+ <table style="margin-top:10px"><tbody>${overview.unpinned.map((s) => `<tr><td><b>${esc(s.name)}</b></td><td>${esc(s.kind_label)}${s.agent ? ` · ${esc(s.agent)}` : ""}</td><td class="muted small">${esc(s.where)}</td></tr>`).join("")}</tbody></table></div>` : "";
169
+ const pinAll = $("pinAll");
170
+ if (pinAll) pinAll.onclick = async () => { busy(pinAll, true); try { await api("POST", "/api/stores", { stores: overview.unpinned }); toast("Pinned."); loadOverview(); } catch (e) { toast(e.message, true); busy(pinAll, false); } };
171
+ const st = $("stores");
172
+ if (!overview.stores.length) { st.innerHTML = `<div class="empty">No stores pinned yet.</div>`; }
173
+ else st.innerHTML = `<table><thead><tr><th>Store</th><th>Agent</th><th>Status</th><th>Copies</th><th></th></tr></thead><tbody>${overview.stores.map((s) => {
174
+ const ls = s.last_scan;
175
+ const status = !s.ok ? `<span class="badge bad">needs attention</span>` : ls ? (ls.clean ? `<span class="badge clean">clean</span>` : ls.incomplete ? `<span class="badge bad">unknown</span>` : `<span class="badge residue">${plural(ls.records, "recoverable item")}</span>`) : `<span class="badge">not scanned</span>`;
176
+ return `<tr><td><b>${esc(s.name)}</b><div class="small muted">${esc(s.kind_label)} · ${esc(s.where)}</div>${s.problem ? `<div class="small" style="color:var(--warn)">${esc(s.problem)}</div>` : ""}</td><td>${esc(s.agent || "–")}</td><td>${status}${s.open ? ` <span class="badge open">open now</span>` : ""}<div class="small muted">${ls ? `scanned ${when(ls.scanned_at)}` : ""}</div></td><td>${s.copies ? `<span class="badge">${s.copies}</span>` : "–"}</td><td><button class="btn secondary small" data-scan="${esc(s.name)}" ${s.ok ? "" : "disabled"}>Scan</button></td></tr>`;
177
+ }).join("")}</tbody></table>`;
178
+ st.querySelectorAll("[data-scan]").forEach((b) => (b.onclick = () => scanStore(b.dataset.scan, b)));
179
+ const q = overview.queue;
180
+ $("queue").innerHTML = q.pending || q.parked ? `${plural(q.pending, "erasure")} waiting for a store to close${q.parked ? `, ${q.parked} parked for you to look at` : ""}. <button class="btn secondary small" id="runQ">Run queued now</button>` : "None. An erasure on a store an agent has open waits here until the agent quits.";
181
+ const rq = $("runQ"); if (rq) rq.onclick = async () => { busy(rq, true); try { const r = await api("POST", "/api/queue/run"); toast(`${plural(r.drained.length, "erasure")} finished.`); loadOverview(); } catch (e) { toast(e.message, true); } };
182
+ $("lastSweep").innerHTML = overview.last_sweep ? `${when(overview.last_sweep)}${overview.schedule.installed ? ` · daily at ${esc(overview.schedule.time)}` : " · not scheduled"}` : `Never.${overview.schedule.installed ? ` Daily sweep scheduled at ${esc(overview.schedule.time)}.` : ""}`;
183
+ }
184
+ async function scanStore(name, btn) {
185
+ if (btn) busy(btn, true);
186
+ try {
187
+ const r = await api("POST", `/api/stores/${encodeURIComponent(name)}/scan`);
188
+ const d = $("storeDetail");
189
+ d.innerHTML = `<div class="card"><div class="row"><h3 class="grow">${esc(name)} <span class="muted small">${esc(r.store)} · ${esc(r.target)}</span></h3>${verdictBadge(r.clean ? "clean" : r.incomplete ? "unknown" : "residue")}</div>
190
+ ${r.incomplete ? `<p class="small" style="color:var(--warn)">Incomplete: ${esc(r.incomplete)}</p>` : ""}
191
+ ${r.warnings.map((w) => `<p class="small muted">! ${esc(w)}</p>`).join("")}
192
+ ${r.findings.length ? `<table><thead><tr><th>What's left</th><th>Where</th><th>Amount</th><th>Patterns</th></tr></thead><tbody>${r.findings.map((f) => `<tr><td><b>${esc(f.title)}</b><div class="small muted">${esc(f.why)}</div></td><td class="small">${esc(f.location)}</td><td>${f.records} ${esc(f.unit)}</td><td class="small">${Object.entries(f.pii).map(([k, n]) => `${n} ${esc(k)}`).join(", ") || "–"}</td></tr>`).join("")}</tbody></table>` : `<p class="small muted">Nothing deleted-but-recoverable in this store${r.store === "files" ? " (text files keep no deleted data)" : ""}.</p>`}
193
+ <h3 style="margin-top:14px">Fix would</h3><ul class="small">${r.plan.map((s) => `<li>${esc(s)}</li>`).join("")}</ul>
194
+ <h3 style="margin-top:14px">Copies of this store</h3>${r.copies.length ? `<ul class="small">${r.copies.map((c) => `<li><b>${esc(c.kind)}</b> ${esc(c.where)} <span class="muted">— ${esc(c.note)}</span>${c.scannable ? "" : " <span class='badge'>out of reach from here</span>"}</li>`).join("")}</ul>` : `<p class="small muted">None in the places the app knows to look.</p>`}
195
+ ${r.clean ? "" : `<div class="row" style="margin-top:12px"><button class="btn" id="fixOne">Fix this store now</button><span class="small muted">Rewrites the store in place, no undo. Stop the agent that uses it first.</span></div>`}</div>`;
196
+ d.scrollIntoView({ behavior: "smooth", block: "start" });
197
+ const fx = $("fixOne"); if (fx) fx.onclick = async () => { busy(fx, true); try { const s = await api("POST", "/api/sweep", {}); const me = s.stores.find((x) => x.store === name); toast(me ? `${name}: ${me.status.replace("_", " ")}${me.receipt_id ? ", receipt saved" : ""}` : "done"); loadOverview(); scanStore(name); } catch (e) { toast(e.message, true); busy(fx, false); } };
198
+ loadOverview();
199
+ } catch (e) { toast(e.message, true); if (btn) busy(btn, false); }
200
+ }
201
+ $("scanAll").onclick = async () => { const b = $("scanAll"); busy(b, true); for (const s of overview?.stores || []) { if (s.ok) try { await api("POST", `/api/stores/${encodeURIComponent(s.name)}/scan`); } catch {} } busy(b, false); loadOverview(); };
202
+ $("rediscover").onclick = async () => { const b = $("rediscover"); busy(b, true); try { const r = await api("POST", "/api/discover"); toast(r.new.length ? `${plural(r.new.length, "new store")} found.` : "Nothing new."); if (r.new.length) { await api("POST", "/api/stores", { stores: r.new }); } loadOverview(); } catch (e) { toast(e.message, true); } busy(b, false); };
203
+
204
+ // -- remembered ------------------------------------------------------------------------------------------
205
+ $("remGo").onclick = async () => {
206
+ const values = lines($("remValues")); if (!values.length) return toast("Type at least one value.", true);
207
+ busy($("remGo"), true);
208
+ try {
209
+ const r = await api("POST", "/api/remembered", { values, show: $("remShow").checked });
210
+ $("remOut").innerHTML = r.stores.map((s) => `<div class="card"><div class="row"><h3 class="grow">${esc(s.store)} <span class="muted small">${esc(s.kind)}${s.agent ? ` · ${esc(s.agent)}` : ""}</span></h3>${verdictBadge(s.status)}</div>
211
+ ${s.error ? `<p class="small" style="color:var(--warn)">${esc(s.error)}</p>` : (s.values || []).map((v, i) => `<div style="margin-top:8px"><div class="small"><b>Value ${v.value}</b> <span class="muted">${esc(values[i])}</span> ${verdictBadge(v.status)}</div>
212
+ ${v.live.length ? `<ul class="small">${v.live.map((h) => `<li>live in <code>${esc(h.where)}</code>${h.context ? `<div class="muted">${esc(h.context)}</div>` : ""}</li>`).join("")}</ul>` : ""}
213
+ ${v.residue.length ? `<ul class="small">${v.residue.map((x) => `<li>deleted but recoverable: <code>${esc(x)}</code></li>`).join("")}</ul>` : ""}</div>`).join("")}</div>`).join("") || `<div class="empty">No stores pinned.</div>`;
214
+ const summary = r.status === "absent" ? "Not found anywhere." : r.status === "live" ? "Still live somewhere: the agent hasn't deleted it." : "Deleted, but still recoverable somewhere.";
215
+ $("remOut").insertAdjacentHTML("afterbegin", `<p class="lede">${summary} <a href="#" id="toForget">Forget it →</a></p>`);
216
+ $("toForget").onclick = (e) => { e.preventDefault(); $("fgValues").value = values.join("\n"); show("forget"); };
217
+ } catch (e) { toast(e.message, true); }
218
+ busy($("remGo"), false);
219
+ };
220
+
221
+ // -- forget ----------------------------------------------------------------------------------------------
222
+ $("fgGo").onclick = async () => {
223
+ const values = lines($("fgValues")); if (!values.length) return toast("Type at least one value.", true);
224
+ const live = $("fgLive").checked;
225
+ if (!confirm(`Erase ${plural(values.length, "value")} from every pinned store${live ? ", INCLUDING live records that contain them" : ""}? There is no undo.`)) return;
226
+ busy($("fgGo"), true);
227
+ try {
228
+ const r = await api("POST", "/api/forget", { values, also_live: live, correlation_id: $("fgCorr").value.trim() || null });
229
+ $("fgOut").innerHTML = r.stores.map((s) => `<div class="card"><div class="row"><h3 class="grow">${esc(s.store)}</h3>${verdictBadge(s.status)}</div>
230
+ ${s.why ? `<p class="small muted">${esc(s.why)}</p>` : ""}
231
+ ${(s.actions || []).length ? `<ul class="small">${s.actions.map((a) => `<li>${esc(a)}</li>`).join("")}</ul>` : ""}
232
+ ${s.status === "residue_remains" ? `<p class="small" style="color:var(--warn)">${plural(s.canaries_found, "spelling")} still on disk. Usually a live record still carries the value${live ? "" : ": tick “also delete live records” to remove it"}.</p>` : ""}
233
+ ${(s.copies_not_reached || []).length ? `<p class="small"><b>Not reached from here:</b> ${s.copies_not_reached.map((c) => `${esc(c.kind)} ${esc(c.where)}`).join("; ")}</p>` : ""}
234
+ ${(s.copies_reachable || []).length ? `<p class="small"><b>Copies next to the store:</b> ${s.copies_reachable.map((c) => esc(c.where)).join("; ")} — pin them to clean them too.</p>` : ""}
235
+ ${s.receipt_id ? `<p class="small">Receipt <a href="#" data-rec="${esc(s.receipt_id)}">${esc(s.receipt_id)}</a></p>` : ""}</div>`).join("") || `<div class="empty">No stores pinned.</div>`;
236
+ $("fgOut").querySelectorAll("[data-rec]").forEach((a) => (a.onclick = (e) => { e.preventDefault(); show("receipts"); openReceipt(a.dataset.rec); }));
237
+ toast("Done.");
238
+ } catch (e) { toast(e.message, true); }
239
+ busy($("fgGo"), false);
240
+ };
241
+
242
+ // -- receipts -------------------------------------------------------------------------------------------
243
+ async function loadReceipts() {
244
+ try {
245
+ const r = await api("GET", "/api/receipts");
246
+ $("fp").textContent = r.fingerprint; $("pk").textContent = r.public_key; $("keyPath").textContent = r.key_path; $("keyWhere").textContent = r.key_path;
247
+ $("receiptList").innerHTML = r.receipts.length ? `<table><thead><tr><th>Issued</th><th>Store</th><th>Verdict</th><th>Values</th><th>Label</th><th></th></tr></thead><tbody>${r.receipts.map((x) => `<tr><td class="small">${when(x.issued_at)}</td><td><b>${esc(x.store)}</b><div class="small muted">${esc(x.target)}</div></td><td>${verdictBadge(x.verdict.toLowerCase())}</td><td>${x.subject_values || "–"}</td><td class="small muted">${esc(x.correlation_id || "")}</td><td><button class="btn secondary small" data-rec="${esc(x.receipt_id)}">Open</button></td></tr>`).join("")}</tbody></table>` : `<div class="empty">No receipts yet.</div>`;
248
+ $("receiptList").querySelectorAll("[data-rec]").forEach((b) => (b.onclick = () => openReceipt(b.dataset.rec)));
249
+ } catch (e) { toast(e.message, true); }
250
+ }
251
+ async function openReceipt(id) {
252
+ try {
253
+ const rec = await api("GET", `/api/receipts/${encodeURIComponent(id)}`);
254
+ $("receiptDetail").innerHTML = `<div class="card"><div class="row"><h3 class="grow">${esc(id)}</h3>${verdictBadge(rec.verdict.toLowerCase())}<button class="btn secondary small" id="verifyBtn">Verify now</button><button class="btn secondary small" id="copyBtn">Copy JSON</button></div>
255
+ <div class="kv small" style="margin-top:8px"><b>Issued</b><span>${esc(rec.issued_at)} by ${esc(rec.issuer || "this machine")}</span><b>Store</b><span>${esc(rec.target)}</span><b>Before</b><span>${Object.entries(rec.before.findings).map(([k, n]) => `${esc(k)}: ${n}`).join(", ") || "nothing found"}</span><b>After</b><span>${Object.entries(rec.after.findings).map(([k, n]) => `${esc(k)}: ${n}`).join(", ") || "nothing found"}${rec.after.canaries_found ? ` · ${plural(rec.after.canaries_found, "value")} still found` : ""}</span><b>Actions</b><span>${rec.actions.map(esc).join("<br/>") || "–"}</span><b>Copies</b><span>${(rec.copies || []).map((c) => `${esc(c.kind)} ${esc(c.where)}`).join("<br/>") || "none known"}</span><b>Files</b><span>${plural(Object.keys(rec.files).length, "file hash")}</span><b>Key</b><code>${esc(rec.public_key)}</code></div>
256
+ <div id="verifyOut" class="small" style="margin-top:10px"></div><details style="margin-top:8px"><summary>Raw receipt</summary><pre class="log">${esc(JSON.stringify(rec, null, 2))}</pre></details></div>`;
257
+ $("verifyBtn").onclick = async () => { busy($("verifyBtn"), true); try { const v = await api("POST", `/api/receipts/${encodeURIComponent(id)}/verify`); $("verifyOut").innerHTML = v.signature_valid ? `<span style="color:var(--good)">✓ Signature valid</span>, key ${esc(v.signing_key)}${v.ours ? " (this machine's)" : " (another key)"}. Store ${v.store_unchanged === null ? "not reachable to compare" : v.store_unchanged ? "unchanged since" : "changed since"}; ${v.clean_now === null ? "" : v.clean_now ? "scans clean now." : "shows residue now."}` : `<span style="color:var(--warn)">✗ ${esc(v.why)}</span>`; } catch (e) { toast(e.message, true); } busy($("verifyBtn"), false); };
258
+ $("copyBtn").onclick = async () => { try { await navigator.clipboard.writeText(JSON.stringify(rec, null, 2)); toast("Copied."); } catch { toast("Select the raw receipt and copy it.", true); } };
259
+ $("receiptDetail").scrollIntoView({ behavior: "smooth", block: "start" });
260
+ } catch (e) { toast(e.message, true); }
261
+ }
262
+
263
+ // -- sweep & schedule ------------------------------------------------------------------------------------
264
+ async function runSweep(dry) {
265
+ const b = dry ? $("sweepDry") : $("sweepGo"); busy(b, true);
266
+ try {
267
+ const r = await api("POST", "/api/sweep", { dry_run: dry });
268
+ $("sweepOut").innerHTML = `<div class="card"><h3>${dry ? "What a sweep would do" : "Sweep finished"}</h3><table><tbody>${r.stores.map((s) => `<tr><td><b>${esc(s.store)}</b></td><td>${verdictBadge(s.status)}</td><td class="small">${esc(s.why || "")}${(s.actions || []).map(esc).join("; ")}${(s.plan || []).map(esc).join("; ")}${s.receipt_id ? ` · receipt <code>${esc(s.receipt_id)}</code>` : ""}</td></tr>`).join("")}</tbody></table></div>`;
269
+ if (!dry) loadOverview();
270
+ } catch (e) { toast(e.message, true); }
271
+ busy(b, false);
272
+ }
273
+ $("sweepDry").onclick = () => runSweep(true); $("sweepGo").onclick = () => { if (confirm("Fix every pinned store that isn't open? Rewrites them in place; no undo.")) runSweep(false); };
274
+ async function loadSchedule() {
275
+ try {
276
+ const s = await api("GET", "/api/schedule");
277
+ $("schedState").textContent = !s.supported ? `Not available on ${s.platform}.` : s.installed ? `Scheduled daily at ${s.time}${s.loaded === false ? " (not loaded)" : ""}.` : "Not scheduled.";
278
+ $("schedHint").textContent = s.hint ? s.hint : `Runs: ${s.command}`;
279
+ $("schedOn").disabled = !s.supported; $("schedOff").disabled = !s.installed;
280
+ } catch (e) { toast(e.message, true); }
281
+ }
282
+ $("schedOn").onclick = async () => { busy($("schedOn"), true); try { await api("POST", "/api/schedule", { time: $("schedTime").value }); toast("Scheduled."); } catch (e) { toast(e.message, true); } busy($("schedOn"), false); loadSchedule(); };
283
+ $("schedOff").onclick = async () => { busy($("schedOff"), true); try { await api("DELETE", "/api/schedule"); toast("Removed."); } catch (e) { toast(e.message, true); } busy($("schedOff"), false); loadSchedule(); };
284
+
285
+ // -- settings -------------------------------------------------------------------------------------------
286
+ async function loadSettings() {
287
+ if (!overview) { try { overview = await api("GET", "/api/overview"); } catch (e) { return toast(e.message, true); } }
288
+ $("homeDir").textContent = overview.home;
289
+ $("pinnedList").innerHTML = overview.stores.length ? `<table><tbody>${overview.stores.map((s) => `<tr><td><b>${esc(s.name)}</b></td><td class="small">${esc(s.kind_label)}${s.agent ? ` · ${esc(s.agent)}` : ""}</td><td class="small muted">${esc(s.where)}</td><td><button class="btn secondary small" data-unpin="${esc(s.name)}">Unpin</button></td></tr>`).join("")}</tbody></table>` : `<div class="empty">Nothing pinned.</div>`;
290
+ $("pinnedList").querySelectorAll("[data-unpin]").forEach((b) => (b.onclick = async () => { try { await api("DELETE", `/api/stores/${encodeURIComponent(b.dataset.unpin)}`); overview = await api("GET", "/api/overview"); loadSettings(); } catch (e) { toast(e.message, true); } }));
291
+ loadReceipts();
292
+ }
293
+ $("pinGo").onclick = async () => { const where = $("pinPath").value.trim(); if (!where) return; busy($("pinGo"), true); try { await api("POST", "/api/stores", { where, name: $("pinName").value.trim() || undefined }); overview = await api("GET", "/api/overview"); $("pinPath").value = ""; loadSettings(); toast("Pinned."); } catch (e) { toast(e.message, true); } busy($("pinGo"), false); };
294
+
295
+ show("overview");
296
+ </script>
297
+ </body>
298
+ </html>