batonpass-cli 0.5.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,1052 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ batonpass discover — v0.1
5
+
6
+ Read-only inventory of the AI history already sitting on this machine.
7
+
8
+ It answers three questions and nothing else:
9
+ 1. What is here?
10
+ 2. How much of it can I actually read?
11
+ 3. What am I silently failing to read, and why?
12
+
13
+ Guarantees
14
+ * never writes to any source (sqlite opened with mode=ro)
15
+ * never opens a socket (no urllib.request, no http, no socket in this file)
16
+ * the only file it creates is the report you ask for
17
+
18
+ Usage
19
+ python3 discover.py # report -> ./batonpass-report.html
20
+ python3 discover.py --report ~/r.html # choose output
21
+ python3 discover.py --json out.json # machine readable too
22
+ python3 discover.py --deep # also measure payload bytes (slower)
23
+ python3 discover.py --explain # print detection reasoning
24
+ python3 discover.py --only zcode,billion # limit sources
25
+
26
+ Python 3.9+. No third-party packages.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import argparse
32
+ import datetime as dt
33
+ import json
34
+ import os
35
+ import sqlite3
36
+ import sys
37
+ from pathlib import Path
38
+
39
+ try:
40
+ from .. import __version__ as VERSION
41
+ except Exception: # run as a loose script
42
+ VERSION = "0.2.0"
43
+
44
+ # --------------------------------------------------------------------------
45
+ # Known shapes.
46
+ #
47
+ # Detection is by *shape*, not by path: we look at which tables exist and
48
+ # which columns they have. Paths change between versions, shapes are stable.
49
+ #
50
+ # required : tables that must all be present
51
+ # forbidden : tables that must all be absent (used to tell siblings apart)
52
+ # sessions : (table, timestamp column) — one row per conversation
53
+ # messages : (table, timestamp column) — one row per message
54
+ # parts : (table, timestamp column) — tool calls / reasoning / images
55
+ # --------------------------------------------------------------------------
56
+
57
+ KNOWN = [
58
+ {
59
+ "adapter": "zcode",
60
+ "role": "transcripts",
61
+ "label": "ZCode",
62
+ "required": {"session", "message", "part"},
63
+ "forbidden": {"project", "session_share"},
64
+ "sessions": ("session", "time_created"),
65
+ "messages": ("message", "time_created"),
66
+ "parts": ("part", "time_created"),
67
+ "title_col": ("session", "title"),
68
+ "path_col": ("session", "directory"),
69
+ "counters": ["session", "message", "part", "todo", "session_entry",
70
+ "tool_usage", "turn_usage", "model_usage", "session_task_link"],
71
+ "notes": "sessions may fork (parent_id); payload sits in .data JSON columns",
72
+ },
73
+ {
74
+ "adapter": "zcode-tasks",
75
+ "role": "index",
76
+ "label": "ZCode task index",
77
+ "required": {"tasks", "projects", "hosts"},
78
+ "forbidden": {"session", "message"},
79
+ "sessions": None,
80
+ "messages": None,
81
+ "parts": None,
82
+ "title_col": ("tasks", "title"),
83
+ "path_col": ("tasks", "workspace_path"),
84
+ "counters": ["tasks", "projects", "hosts", "automations",
85
+ "automation_runs", "off_peak_tasks", "session_creation_commands"],
86
+ "notes": "the map, not the transcript: task → workspace → session id",
87
+ },
88
+ {
89
+ "adapter": "zhanlu",
90
+ "role": "transcripts",
91
+ "label": "Zhanlu",
92
+ "required": {"project", "session", "message", "part"},
93
+ "forbidden": {"session_entry"},
94
+ "sessions": ("session", "time_created"),
95
+ "messages": ("message", "time_created"),
96
+ "parts": ("part", "time_created"),
97
+ "title_col": ("session", "title"),
98
+ "path_col": ("session", "directory"),
99
+ "counters": ["project", "session", "message", "part", "todo"],
100
+ "notes": "same shape as ZCode minus the extra tables; usually empty",
101
+ },
102
+ {
103
+ "adapter": "billion",
104
+ "role": "transcripts",
105
+ "label": "billion-context",
106
+ "required": {"sessions", "messages", "content"},
107
+ "forbidden": set(),
108
+ "sessions": ("sessions", "created_at"),
109
+ "messages": ("messages", "ts"),
110
+ "parts": None,
111
+ "title_col": ("sessions", "title"),
112
+ "path_col": None,
113
+ "counters": ["sessions", "messages", "content", "blocks", "refs",
114
+ "message_media", "conversations"],
115
+ "notes": "content is content-addressed; duplicates stored once",
116
+ },
117
+ {
118
+ "adapter": "dsh-chat",
119
+ "role": "transcripts",
120
+ "label": "dsh chat index",
121
+ "required": {"messages", "lines"},
122
+ "forbidden": {"calls"},
123
+ "sessions": None,
124
+ "messages": ("messages", "time"),
125
+ "parts": None,
126
+ "title_col": None,
127
+ "path_col": None,
128
+ "counters": ["messages", "lines", "marks"],
129
+ "notes": "one row per message; session id is a plain string, no session table",
130
+ },
131
+ {
132
+ "adapter": "dsh-usage",
133
+ "role": "usage",
134
+ "label": "dsh usage ledger",
135
+ "required": {"calls", "marks"},
136
+ "forbidden": {"lines"},
137
+ "sessions": None,
138
+ "messages": None,
139
+ "parts": None,
140
+ "title_col": None,
141
+ "path_col": None,
142
+ "counters": ["calls", "marks", "owners", "call_slots"],
143
+ "notes": "token accounting only — no transcripts here",
144
+ },
145
+ {
146
+ "adapter": "dsh-state",
147
+ "role": "state",
148
+ "label": "dsh orchestrator state",
149
+ "required": {"kv", "trigger", "outbox"},
150
+ "forbidden": set(),
151
+ "sessions": None,
152
+ "messages": None,
153
+ "parts": None,
154
+ "title_col": None,
155
+ "path_col": None,
156
+ "counters": ["kv", "trigger", "thread", "decision", "outbox", "ticket"],
157
+ "notes": "control state, not conversation content",
158
+ },
159
+ {
160
+ "adapter": "alma",
161
+ "role": "transcripts",
162
+ "label": "Alma",
163
+ "required": {"chat_threads", "chat_messages"},
164
+ "forbidden": set(),
165
+ "sessions": ("chat_threads", "created_at"),
166
+ "messages": ("chat_messages", "timestamp"),
167
+ "parts": None,
168
+ "title_col": ("chat_threads", "title"),
169
+ "path_col": None,
170
+ "counters": ["chat_threads", "chat_messages", "agent_op_traces",
171
+ "agent_op_trace_steps", "activity_sessions", "activity_events",
172
+ "activity_ocr_frames", "memories", "crystals", "thread_briefs"],
173
+ "notes": "message bodies live in chat_messages.message (JSON)",
174
+ },
175
+ {
176
+ "adapter": "pinky",
177
+ "role": "transcripts",
178
+ "label": "Pinky",
179
+ "required": {"tasks", "steps", "devices"},
180
+ "forbidden": set(),
181
+ "sessions": ("tasks", "started_at"),
182
+ "messages": ("steps", "started_at"),
183
+ "parts": None,
184
+ "title_col": ("tasks", "title"),
185
+ "path_col": None,
186
+ "counters": ["tasks", "steps", "sessions", "approvals", "media", "recordings"],
187
+ "notes": "agent run traces; steps carry tool args + screen text",
188
+ },
189
+ ]
190
+
191
+ # Where to look. Globs allowed. A hit may be a sqlite file or a directory.
192
+ CANDIDATES = [
193
+ "~/.zcode/**/*.sqlite",
194
+ "~/.zcode/**/*.db",
195
+ "~/.local/share/billion-context/**/index.db",
196
+ "~/.dsh/**/*.sqlite",
197
+ "~/.dsh/**/*.db",
198
+ "~/Library/Application Support/alma/*.db",
199
+ "~/Library/Application Support/Pinky/*.db",
200
+ "~/.local/share/zhanlu/*.db",
201
+ "~/.claude/**/*.db",
202
+ "~/.codex/**/*.db",
203
+ "~/.cursor/**/*.db",
204
+ "~/.config/**/chat*.db",
205
+ ]
206
+
207
+ # Directories that look like AI tooling but may hold history we do not parse yet.
208
+ PROBE_ROOTS = [
209
+ "~/.claude", "~/.codex", "~/.cursor", "~/.gemini", "~/.continue",
210
+ "~/.aider", "~/.zcode", "~/.dsh", "~/.local/share", "~/.config",
211
+ "~/Library/Application Support",
212
+ ]
213
+
214
+ SKIP_DIR_NAMES = {"node_modules", ".git", "__pycache__", "Cache", "Caches",
215
+ "GPUCache", "Code Cache", "logs", "tmp", "temp"}
216
+
217
+ # Files that are definitely not transcripts. Skipped by reason, and the reasons
218
+ # are counted in the report — a skip you can see is not a silent skip.
219
+ NOISE_FRAGMENTS = {
220
+ "browser-cache": ("/code cache/", "/gpucache/", "/dawn", "/shadercache/",
221
+ "/grshadercache/", "/service worker/", "/local storage/",
222
+ "/session storage/", "/cache/"),
223
+ "browser-profile": ("chromium", "bsk-chrome", "chrome-publish", "baidu-profile",
224
+ "google/chrome", "/firefox/", "/safari/"),
225
+ "browser-internal": ("first_party_sets", "heavy_ad_intervention",
226
+ "criticalactions", "top_sites", "web data",
227
+ "network persistent state", "/cookies", "/history",
228
+ "/favorites", "/login data"),
229
+ "backup-copy": (".bak-", ".backup", "/backup/", "-backup-"),
230
+ "nested-artifact": ("/workspace/draft-", "/node_modules/", "/site-packages/"),
231
+ }
232
+
233
+ TEXTISH = {".jsonl", ".json", ".md", ".txt", ".log", ".ndjson"}
234
+
235
+ # Magic bytes of the compression formats these tools actually use. A blob is
236
+ # only called "compressed" when its first bytes say so — never because a column
237
+ # is named `algo`.
238
+ CODEC_MAGIC = [
239
+ (b"\x28\xb5\x2f\xfd", "zstd"),
240
+ (b"\x1f\x8b", "gzip"),
241
+ (b"BZh", "bzip2"),
242
+ (b"\xfd7zXZ\x00", "xz"),
243
+ (b"\x04\x22\x4d\x18", "lz4"),
244
+ (b"\x00\x00\x00\x0dJXL", "jxl"),
245
+ ]
246
+
247
+
248
+ # --------------------------------------------------------------------------
249
+ # helpers
250
+ # --------------------------------------------------------------------------
251
+
252
+ def now_iso() -> str:
253
+ return dt.datetime.now().astimezone().isoformat(timespec="seconds")
254
+
255
+
256
+ def human(n) -> str:
257
+ if n is None:
258
+ return "—"
259
+ n = float(n)
260
+ for unit in ("B", "KB", "MB", "GB", "TB"):
261
+ if n < 1024 or unit == "TB":
262
+ return f"{n:.0f} {unit}" if unit == "B" else f"{n:.1f} {unit}"
263
+ n /= 1024
264
+ return f"{n:.1f} TB"
265
+
266
+
267
+ def norm_ts(v):
268
+ """Turn whatever a database calls a timestamp into an aware datetime, or None."""
269
+ if v is None:
270
+ return None
271
+ if isinstance(v, (int, float)):
272
+ x = float(v)
273
+ if x > 1e17: # nanoseconds
274
+ x /= 1e9
275
+ elif x > 1e14: # microseconds
276
+ x /= 1e6
277
+ elif x > 1e11: # milliseconds
278
+ x /= 1e3
279
+ if x < 1e8 or x > 4e9: # implausible
280
+ return None
281
+ try:
282
+ return dt.datetime.fromtimestamp(x, dt.timezone.utc).astimezone()
283
+ except (OverflowError, OSError, ValueError):
284
+ return None
285
+ s = str(v).strip()
286
+ if not s:
287
+ return None
288
+ if s.isdigit():
289
+ return norm_ts(int(s))
290
+ s2 = s.replace("Z", "+00:00").replace(" ", "T", 1)
291
+ for cand in (s2, s[:19]):
292
+ try:
293
+ d = dt.datetime.fromisoformat(cand)
294
+ return d if d.tzinfo else d.replace(tzinfo=dt.timezone.utc).astimezone()
295
+ except ValueError:
296
+ continue
297
+ return None
298
+
299
+
300
+ def day(v) -> str:
301
+ if not v:
302
+ return "—"
303
+ return v.strftime("%Y-%m-%d")
304
+
305
+
306
+ def dir_size(path: Path, budget=40000):
307
+ """Rough size + file count, bounded so a huge directory cannot hang the scan."""
308
+ total, files, seen = 0, 0, 0
309
+ for root, dirs, names in os.walk(path):
310
+ dirs[:] = [d for d in dirs if d not in SKIP_DIR_NAMES]
311
+ for name in names:
312
+ seen += 1
313
+ if seen > budget:
314
+ return total, files, True
315
+ try:
316
+ total += (Path(root) / name).stat().st_size
317
+ files += 1
318
+ except OSError:
319
+ pass
320
+ return total, files, False
321
+
322
+
323
+ # --------------------------------------------------------------------------
324
+ # probing
325
+ # --------------------------------------------------------------------------
326
+
327
+ def open_ro(path: Path):
328
+ """Read-only sqlite connection.
329
+
330
+ Returns (conn, mode). mode is "ro" normally; "immutable" when the database is
331
+ in WAL mode and the sidecar files are not readable for us — `immutable=1`
332
+ tells sqlite to touch nothing at all, at the cost of possibly seeing a
333
+ snapshot that is mid-write. Both are strictly read-only; neither can modify
334
+ the source.
335
+ """
336
+ try:
337
+ conn = sqlite3.connect(path.as_uri() + "?mode=ro", uri=True, timeout=2.0)
338
+ conn.text_factory = lambda b: b.decode("utf-8", "replace")
339
+ conn.execute("select 1").fetchone()
340
+ return conn, "ro"
341
+ except sqlite3.OperationalError:
342
+ conn = sqlite3.connect(path.as_uri() + "?immutable=1", uri=True, timeout=2.0)
343
+ conn.text_factory = lambda b: b.decode("utf-8", "replace")
344
+ conn.execute("select 1").fetchone()
345
+ return conn, "immutable"
346
+
347
+
348
+ def table_names(conn) -> set:
349
+ rows = conn.execute(
350
+ "select name from sqlite_master where type='table' and name not like 'sqlite_%'"
351
+ ).fetchall()
352
+ return {r[0] for r in rows}
353
+
354
+
355
+ def match_adapter(tables: set, columns: dict):
356
+ """Exact fingerprint first, then a looser column-set match, then give up."""
357
+ for spec in KNOWN:
358
+ if spec["required"] <= tables and not (spec["forbidden"] & tables):
359
+ return spec, "high", "fingerprint"
360
+ # loose: how many required tables are present at all?
361
+ best, best_score = None, 0.0
362
+ for spec in KNOWN:
363
+ overlap = len(spec["required"] & tables) / max(1, len(spec["required"]))
364
+ if overlap > best_score:
365
+ best, best_score = spec, overlap
366
+ if best and best_score >= 0.6:
367
+ return best, "medium", "table-overlap"
368
+ # content heuristic: does any table smell like a conversation?
369
+ for t, cols in columns.items():
370
+ low = {c.lower() for c in cols}
371
+ if "role" in low and ({"content", "text", "message", "data"} & low):
372
+ return None, "low", "content-heuristic"
373
+ return None, "none", "unknown"
374
+
375
+
376
+ def count_rows(conn, table) -> int | None:
377
+ try:
378
+ return int(conn.execute(f'select count(*) from "{table}"').fetchone()[0])
379
+ except sqlite3.Error:
380
+ return None
381
+
382
+
383
+ def ts_range(conn, table, col):
384
+ try:
385
+ lo, hi = conn.execute(f'select min("{col}"), max("{col}") from "{table}"').fetchone()
386
+ except sqlite3.Error:
387
+ return None, None
388
+ return norm_ts(lo), norm_ts(hi)
389
+
390
+
391
+ def payload_bytes(conn, table, cols) -> int:
392
+ """Sum of blob/text lengths for the payload-ish columns. Slow: --deep only."""
393
+ total = 0
394
+ existing = {c.lower() for c in cols}
395
+ for col in ("data", "bytes", "message", "text", "content", "body", "payload"):
396
+ if col in existing:
397
+ try:
398
+ total += int(conn.execute(
399
+ f'select coalesce(sum(length("{col}")),0) from "{table}"'
400
+ ).fetchone()[0] or 0)
401
+ except sqlite3.Error:
402
+ pass
403
+ return total
404
+
405
+
406
+ def probe_sqlite(path: Path, deep: bool, explain: bool) -> dict:
407
+ res = {
408
+ "kind": "sqlite",
409
+ "path": str(path),
410
+ "size": path.stat().st_size,
411
+ "adapter": None,
412
+ "role": None,
413
+ "label": None,
414
+ "confidence": "none",
415
+ "detected_by": None,
416
+ "tables": 0,
417
+ "counters": {},
418
+ "sessions": None,
419
+ "messages": None,
420
+ "parts": None,
421
+ "first": None,
422
+ "last": None,
423
+ "payload_bytes": None,
424
+ "notes": "",
425
+ "degradations": [],
426
+ }
427
+ try:
428
+ conn, ro_mode = open_ro(path)
429
+ if ro_mode == "immutable":
430
+ res["degradations"].append(
431
+ ("readonly-immutable",
432
+ "no lock possible (WAL sidecars unreadable); opened immutable so the "
433
+ "source stays untouched — a snapshot taken mid-write may be torn"))
434
+ except sqlite3.DatabaseError as e:
435
+ msg = str(e).lower()
436
+ if "locked" in msg or "busy" in msg:
437
+ res["degradations"].append(("locked", f"database is in use: {e}"))
438
+ elif "not a database" in msg or "file is encrypted" in msg:
439
+ res["degradations"].append(("not-a-database", "file is not a readable SQLite database"))
440
+ else:
441
+ res["degradations"].append(("open-failed", str(e)[:200]))
442
+ return res
443
+ except OSError as e:
444
+ res["degradations"].append(("permission-denied", str(e)[:200]))
445
+ return res
446
+
447
+ try:
448
+ tables = table_names(conn)
449
+ res["tables"] = len(tables)
450
+ columns = {}
451
+ for t in sorted(tables):
452
+ try:
453
+ columns[t] = [r[1] for r in conn.execute(f'pragma table_info("{t}")')]
454
+ except sqlite3.Error:
455
+ columns[t] = []
456
+
457
+ spec, confidence, how = match_adapter(tables, columns)
458
+ if explain:
459
+ print(f" tables({len(tables)}): {', '.join(sorted(tables))[:400]}")
460
+ print(f" -> {spec['adapter'] if spec else '(none)'} "
461
+ f"confidence={confidence} by={how}")
462
+ res["confidence"] = confidence
463
+ res["detected_by"] = how
464
+
465
+ if spec is None:
466
+ if confidence == "low":
467
+ res["degradations"].append(
468
+ ("schema-unknown",
469
+ "conversation-shaped tables found but no adapter matches yet"))
470
+ return res
471
+
472
+ res["adapter"] = spec["adapter"]
473
+ res["role"] = spec.get("role", "transcripts")
474
+ res["label"] = spec["label"]
475
+ res["notes"] = spec.get("notes", "")
476
+
477
+ for t in spec.get("counters", []):
478
+ if t in tables:
479
+ n = count_rows(conn, t)
480
+ if n is not None:
481
+ res["counters"][t] = n
482
+
483
+ for slot in ("sessions", "messages", "parts"):
484
+ spec_slot = spec.get(slot)
485
+ if not spec_slot:
486
+ continue
487
+ t, col = spec_slot
488
+ if t not in tables:
489
+ continue
490
+ res[slot] = count_rows(conn, t)
491
+ if col in columns.get(t, []):
492
+ lo, hi = ts_range(conn, t, col)
493
+ if lo and (res["first"] is None or lo < res["first"]):
494
+ res["first"] = lo
495
+ if hi and (res["last"] is None or hi > res["last"]):
496
+ res["last"] = hi
497
+ else:
498
+ res["degradations"].append(
499
+ ("no-timestamp", f'{t} has no "{col}" column — date range unknown'))
500
+
501
+ if deep:
502
+ buf = 0
503
+ for t in spec.get("counters", []):
504
+ if t in tables:
505
+ buf += payload_bytes(conn, t, columns.get(t, []))
506
+ res["payload_bytes"] = buf or None
507
+
508
+ # source-specific facts worth reporting
509
+ if spec["adapter"] == "zcode" and "session" in tables:
510
+ if "parent_id" in columns.get("session", []):
511
+ try:
512
+ forks = conn.execute(
513
+ "select count(*) from session where parent_id is not null "
514
+ "and parent_id <> ''").fetchone()[0]
515
+ if forks:
516
+ res["counters"]["forked_sessions"] = int(forks)
517
+ except sqlite3.Error:
518
+ pass
519
+ if spec["adapter"] == "billion" and "content" in tables:
520
+ # Do not trust the column called "algo": in this schema it names the
521
+ # hash, not the codec. Look at the bytes themselves.
522
+ codec = None
523
+ try:
524
+ sample = conn.execute(
525
+ "select substr(bytes,1,4) from content "
526
+ "where bytes is not null limit 5").fetchall()
527
+ for (head,) in sample:
528
+ if isinstance(head, str):
529
+ head = head.encode("utf-8", "replace")
530
+ for magic, name in CODEC_MAGIC:
531
+ if head and head.startswith(magic):
532
+ codec = name
533
+ break
534
+ if codec:
535
+ break
536
+ if not codec and sample:
537
+ res["notes"] += " · content decodes as plain text, no decoder needed"
538
+ except sqlite3.Error:
539
+ pass
540
+ if codec:
541
+ res["degradations"].append(
542
+ ("compressed-payload", f"content blobs are {codec} frames — needs a decoder"))
543
+ if spec["adapter"] == "billion" and "message_media" in tables:
544
+ n = res["counters"].get("message_media")
545
+ if n:
546
+ res["degradations"].append(
547
+ ("media-by-reference", f"{n} media rows reference files, not copied"))
548
+
549
+ if res["sessions"] == 0 and res["messages"] in (0, None) and not res["counters"].get("messages"):
550
+ res["degradations"].append(("empty-source", "recognised, but contains no rows yet"))
551
+
552
+ if (res["messages"] or 0) > 0 and res["first"] is None:
553
+ res["degradations"].append(("date-range-unknown", "no usable timestamps"))
554
+
555
+ except sqlite3.Error as e:
556
+ res["degradations"].append(("query-failed", str(e)[:200]))
557
+ finally:
558
+ try:
559
+ conn.close()
560
+ except sqlite3.Error:
561
+ pass
562
+ return res
563
+
564
+
565
+ def probe_dir(path: Path, deep: bool) -> dict:
566
+ """A directory of loose files (jsonl / md / json) — the fallback shape."""
567
+ total, files, truncated = dir_size(path)
568
+ exts, samples = {}, []
569
+ for root, dirs, names in os.walk(path):
570
+ dirs[:] = [d for d in dirs if d not in SKIP_DIR_NAMES]
571
+ for name in names:
572
+ ext = Path(name).suffix.lower()
573
+ exts[ext] = exts.get(ext, 0) + 1
574
+ if ext in TEXTISH and len(samples) < 3:
575
+ samples.append(str(Path(root) / name))
576
+ res = {
577
+ "kind": "dir",
578
+ "path": str(path),
579
+ "size": total,
580
+ "adapter": None,
581
+ "label": path.name,
582
+ "confidence": "low",
583
+ "detected_by": "path",
584
+ "tables": 0,
585
+ "counters": {"files": files},
586
+ "sessions": None,
587
+ "messages": None,
588
+ "parts": None,
589
+ "first": None,
590
+ "last": None,
591
+ "payload_bytes": None,
592
+ "notes": ", ".join(f"{k or '(none)'}={v}" for k, v in
593
+ sorted(exts.items(), key=lambda x: -x[1])[:5]),
594
+ "degradations": [],
595
+ }
596
+ if truncated:
597
+ res["degradations"].append(
598
+ ("scan-truncated", "directory too large; counts are a lower bound"))
599
+ if not (TEXTISH & set(exts)):
600
+ res["degradations"].append(
601
+ ("no-transcripts", "no .jsonl/.json/.md files — probably caches or binaries"))
602
+ return res
603
+
604
+
605
+ # --------------------------------------------------------------------------
606
+ # discovery
607
+ # --------------------------------------------------------------------------
608
+
609
+ def skip_reason(path: Path):
610
+ """Why this file cannot possibly hold transcripts. None = worth probing."""
611
+ p = str(path).lower()
612
+ for reason, frags in NOISE_FRAGMENTS.items():
613
+ if any(f in p for f in frags):
614
+ return reason
615
+ return None
616
+
617
+
618
+ def resolve(patterns):
619
+ import glob as _glob
620
+ seen, out = set(), []
621
+ for pat in patterns:
622
+ for hit in _glob.glob(os.path.expanduser(pat), recursive=True):
623
+ rp = Path(hit)
624
+ if rp.is_file() and rp.suffix.lower() not in (".db", ".sqlite", ".sqlite3", ""):
625
+ continue
626
+ if rp.name.endswith(("-wal", "-shm", ".tmp")):
627
+ continue
628
+ key = str(rp)
629
+ if key in seen:
630
+ continue
631
+ seen.add(key)
632
+ out.append(rp)
633
+ return out
634
+
635
+
636
+ def looks_like_ai_dir(name: str) -> bool:
637
+ low = name.lower()
638
+ keys = ("claude", "codex", "cursor", "gemini", "zcode", "dsh", "aider",
639
+ "continue", "copilot", "cline", "goose", "windsurf", "trae",
640
+ "opencode", "crush", "zed", "chat", "agent", "llm", "ai-", "-ai")
641
+ return any(k in low for k in keys)
642
+
643
+
644
+ # A directory that looks like AI tooling but is structurally not history: a
645
+ # bundled runtime, an Electron profile's caches, a system dir. These sat in the
646
+ # "unclaimed" list forever — which reads like a promise to collect them, and is
647
+ # really just noise. Name the reason and close the ticket.
648
+ _NOT_HISTORY = (
649
+ ("dsh-runtime", "a bundled Node runtime, not transcripts"),
650
+ ("Application Support/ZCode", "an Electron profile — caches and IndexedDB, "
651
+ "the chat db lives in ~/.zcode"),
652
+ ("ContextStoreAgent", "an Apple system directory"),
653
+ ("/dsh-usage", "a token-usage ledger, not a transcript"),
654
+ ("/dsh-session-archive", "an empty archive — only a state marker inside"),
655
+ )
656
+ _TRANSCRIPT_SUFFIXES = (".db", ".sqlite", ".sqlite3", ".jsonl", ".json")
657
+
658
+
659
+ def _transcript_files(root, depth: int = 3) -> int:
660
+ n, base = 0, str(root).count(os.sep)
661
+ for dirpath, dirnames, filenames in os.walk(root):
662
+ if dirpath.count(os.sep) - base >= depth:
663
+ dirnames[:] = []
664
+ n += sum(1 for f in filenames if f.endswith(_TRANSCRIPT_SUFFIXES))
665
+ return n
666
+
667
+
668
+ def not_history_reason(path) -> str:
669
+ """Why this directory cannot hold what we archive — or "" if we don't know."""
670
+ text = str(path)
671
+ for frag, reason in _NOT_HISTORY:
672
+ if frag in text:
673
+ return reason
674
+ try:
675
+ if _transcript_files(path) == 0:
676
+ return "no file that could hold a transcript inside"
677
+ except OSError:
678
+ return ""
679
+ return ""
680
+
681
+
682
+ def probe_roots(claimed: set, explain: bool):
683
+ """Directories that look like AI tooling but hold nothing we parse.
684
+
685
+ Returns (unclaimed, ignored): things we cannot explain, and things we can.
686
+ """
687
+ found, ignored = [], []
688
+ for pattern in PROBE_ROOTS:
689
+ base = Path(os.path.expanduser(pattern))
690
+ if not base.exists():
691
+ continue
692
+ try:
693
+ children = [c for c in base.iterdir() if c.is_dir()]
694
+ except (PermissionError, OSError):
695
+ continue
696
+ for child in children:
697
+ if child.name in SKIP_DIR_NAMES:
698
+ continue
699
+ key = str(child.resolve())
700
+ if key in claimed or not looks_like_ai_dir(child.name):
701
+ continue
702
+ size, files, trunc = dir_size(child)
703
+ if files == 0:
704
+ continue
705
+ reason = not_history_reason(child)
706
+ if reason:
707
+ ignored.append({"path": str(child), "size": size, "files": files,
708
+ "reason": reason})
709
+ if explain:
710
+ print(f" not history: {child} ({reason})")
711
+ continue
712
+ found.append({"path": str(child), "size": size, "files": files,
713
+ "truncated": trunc})
714
+ if explain:
715
+ print(f" unclaimed? {child} files={files} size={human(size)}")
716
+ found.sort(key=lambda x: -x["size"])
717
+ ignored.sort(key=lambda x: -x["size"])
718
+ return found, ignored
719
+
720
+
721
+ def run(args):
722
+ sources, claimed = [], set()
723
+ skipped = {}
724
+ targets = resolve(CANDIDATES)
725
+ keep = {s.strip() for s in args.only.split(",") if s.strip()} if args.only else None
726
+
727
+ for path in targets:
728
+ try:
729
+ if path.is_dir():
730
+ continue
731
+ reason = skip_reason(path)
732
+ if reason:
733
+ skipped[reason] = skipped.get(reason, 0) + 1
734
+ if args.explain:
735
+ print(f" skip {reason:16} {path}")
736
+ continue
737
+ if path.stat().st_size < 4096:
738
+ skipped["too-small"] = skipped.get("too-small", 0) + 1
739
+ continue
740
+ if args.explain:
741
+ print(f" probe {path}")
742
+ res = probe_sqlite(path, args.deep, args.explain)
743
+ claimed.add(str(path.parent.resolve()))
744
+ claimed.add(str(path.resolve()))
745
+ if keep is not None and res["adapter"] not in keep:
746
+ continue
747
+ sources.append(res)
748
+ except (OSError, PermissionError) as e:
749
+ sources.append({"kind": "sqlite", "path": str(path), "size": 0,
750
+ "adapter": None, "label": None, "confidence": "none",
751
+ "detected_by": None, "tables": 0, "counters": {},
752
+ "sessions": None, "messages": None, "parts": None,
753
+ "first": None, "last": None, "payload_bytes": None,
754
+ "notes": "", "degradations": [("permission-denied", str(e)[:200])]})
755
+
756
+ if keep:
757
+ unclaimed, ignored = [], []
758
+ else:
759
+ unclaimed, ignored = probe_roots(claimed, args.explain)
760
+
761
+ # identical copies (a .bak sibling, a cloned profile) must not be counted twice
762
+ seen_sig, deduped = set(), []
763
+ for s in sources:
764
+ sig = (s["adapter"], s["size"], s["sessions"], s["messages"])
765
+ if s["adapter"] and sig in seen_sig:
766
+ skipped["duplicate-copy"] = skipped.get("duplicate-copy", 0) + 1
767
+ continue
768
+ seen_sig.add(sig)
769
+ deduped.append(s)
770
+ sources = deduped
771
+
772
+ role_rank = {"transcripts": 0, "index": 1, "usage": 2, "state": 3}
773
+ sources.sort(key=lambda s: (s["adapter"] is None,
774
+ role_rank.get(s.get("role"), 9),
775
+ -(s["messages"] or 0), -(s["size"] or 0)))
776
+
777
+ tot_msgs = sum(s["messages"] or 0 for s in sources)
778
+ tot_sess = sum(s["sessions"] or 0 for s in sources)
779
+ tot_bytes = sum(s["size"] or 0 for s in sources)
780
+ tot_payload = sum(s["payload_bytes"] or 0 for s in sources)
781
+ recognised = [s for s in sources if s["adapter"]]
782
+ readable = [s for s in recognised if (s["messages"] or 0) > 0]
783
+ deg_count = {}
784
+ for s in sources:
785
+ for code, _ in s["degradations"]:
786
+ deg_count[code] = deg_count.get(code, 0) + 1
787
+
788
+ summary = {
789
+ "batonpass": VERSION,
790
+ "generated_at": now_iso(),
791
+ "host": os.uname().nodename if hasattr(os, "uname") else os.environ.get("COMPUTERNAME", "?"),
792
+ "platform": sys.platform,
793
+ "python": sys.version.split()[0],
794
+ "sources": sources,
795
+ "unclaimed": unclaimed,
796
+ "ignored": ignored,
797
+ "skipped": skipped,
798
+ "totals": {
799
+ "sources": len(sources),
800
+ "recognised": len(recognised),
801
+ "with_messages": len(readable),
802
+ "sessions": tot_sess,
803
+ "messages": tot_msgs,
804
+ "bytes_on_disk": tot_bytes,
805
+ "payload_bytes": tot_payload or None,
806
+ "degradation_kinds": len(deg_count),
807
+ "skipped_files": sum(skipped.values()),
808
+ "unclaimed_dirs": len(unclaimed),
809
+ "ignored_dirs": len(ignored),
810
+ },
811
+ }
812
+ return summary
813
+
814
+
815
+ # --------------------------------------------------------------------------
816
+ # report
817
+ # --------------------------------------------------------------------------
818
+
819
+ CSS = """
820
+ :root{--bg:#0f1115;--fg:#e6e8ee;--mut:#8b93a7;--card:#161923;--line:#252a37;
821
+ --ok:#3ecf8e;--warn:#e2b93b;--bad:#e2605c;--acc:#6aa6ff}
822
+ @media(prefers-color-scheme:light){:root{--bg:#fbfbfd;--fg:#15171c;--mut:#6b7280;
823
+ --card:#fff;--line:#e5e7eb;--ok:#12885b;--warn:#a1740a;--bad:#b03a36;--acc:#2557c7}}
824
+ *{box-sizing:border-box}
825
+ body{margin:0;background:var(--bg);color:var(--fg);
826
+ font:15px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC",
827
+ "Hiragino Sans GB","Microsoft YaHei",sans-serif}
828
+ .wrap{max-width:1080px;margin:0 auto;padding:40px 24px 80px}
829
+ h1{font-size:26px;margin:0 0 4px;letter-spacing:-.02em}
830
+ h2{font-size:17px;margin:38px 0 12px;letter-spacing:-.01em}
831
+ .sub{color:var(--mut);font-size:13px}
832
+ .hero{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));
833
+ gap:12px;margin:26px 0 8px}
834
+ .kpi{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:14px 16px}
835
+ .kpi .n{font-size:24px;font-weight:600;letter-spacing:-.02em}
836
+ .kpi .l{color:var(--mut);font-size:12px;margin-top:2px}
837
+ .card{background:var(--card);border:1px solid var(--line);border-radius:10px;
838
+ padding:16px 18px;margin:10px 0}
839
+ .card h3{margin:0 0 2px;font-size:15px}
840
+ .path{color:var(--mut);font-size:12px;word-break:break-all;font-family:ui-monospace,
841
+ SFMono-Regular,Menlo,monospace}
842
+ .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(110px,1fr));
843
+ gap:10px;margin:12px 0}
844
+ .grid div{font-size:12px;color:var(--mut)}
845
+ .grid b{display:block;font-size:15px;color:var(--fg);font-weight:600}
846
+ .pill{display:inline-block;font-size:11px;padding:2px 8px;border-radius:99px;
847
+ border:1px solid var(--line);color:var(--mut);margin-left:6px}
848
+ .pill.high{color:var(--ok);border-color:var(--ok)}
849
+ .pill.medium{color:var(--warn);border-color:var(--warn)}
850
+ .pill.low,.pill.none{color:var(--bad);border-color:var(--bad)}
851
+ table{width:100%;border-collapse:collapse;font-size:13px}
852
+ th,td{text-align:left;padding:7px 10px;border-bottom:1px solid var(--line);
853
+ vertical-align:top}
854
+ th{color:var(--mut);font-weight:500;font-size:12px}
855
+ code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px}
856
+ .deg{color:var(--bad)}
857
+ .note{color:var(--mut);font-size:12px;margin-top:8px}
858
+ .foot{margin-top:48px;color:var(--mut);font-size:12px;border-top:1px solid var(--line);
859
+ padding-top:16px}
860
+ .bar{height:6px;background:var(--line);border-radius:3px;overflow:hidden;margin-top:10px}
861
+ .bar i{display:block;height:100%;background:var(--ok)}
862
+ """
863
+
864
+
865
+ def esc(v) -> str:
866
+ import html as _h
867
+ return _h.escape(str(v if v is not None else "—"))
868
+
869
+
870
+ def render(summary) -> str:
871
+ t = summary["totals"]
872
+ rows = []
873
+
874
+ rows.append(f"""<div class="wrap">
875
+ <h1>batonpass <span class="sub">discover v{esc(summary['batonpass'])}</span></h1>
876
+ <div class="sub">{esc(summary['host'])} · {esc(summary['platform'])} · python {esc(summary['python'])}
877
+ · generated {esc(summary['generated_at'])}</div>
878
+
879
+ <div class="hero">
880
+ <div class="kpi"><div class="n">{t['messages']:,}</div><div class="l">messages found</div></div>
881
+ <div class="kpi"><div class="n">{t['sessions']:,}</div><div class="l">conversations</div></div>
882
+ <div class="kpi"><div class="n">{t['recognised']}</div><div class="l">sources recognised</div></div>
883
+ <div class="kpi"><div class="n">{human(t['bytes_on_disk'])}</div><div class="l">readable on disk</div></div>
884
+ <div class="kpi"><div class="n">{t['unclaimed_dirs']}</div><div class="l">dirs in the queue</div></div>
885
+ <div class="kpi"><div class="n">{t.get('ignored_dirs', 0)}</div><div class="l">left alone on purpose</div></div>
886
+ </div>""")
887
+
888
+ recognised = [s for s in summary["sources"] if s["adapter"]]
889
+ unknown = [s for s in summary["sources"]
890
+ if not s["adapter"] and (s["size"] or 0) > 262144]
891
+
892
+ rows.append("<h2>What can be archived today</h2>")
893
+ for s in recognised:
894
+ conf = s["confidence"]
895
+ bits = []
896
+ if s["sessions"] is not None:
897
+ bits.append(f"<div><b>{s['sessions']:,}</b>conversations</div>")
898
+ if s["messages"] is not None:
899
+ bits.append(f"<div><b>{s['messages']:,}</b>messages</div>")
900
+ if s["parts"] is not None:
901
+ bits.append(f"<div><b>{s['parts']:,}</b>parts / tool calls</div>")
902
+ extra = [(k, v) for k, v in s["counters"].items()
903
+ if k not in ("session", "sessions", "message", "messages", "part",
904
+ "chat_threads", "chat_messages", "tasks", "steps")]
905
+ for k, v in extra[:4]:
906
+ bits.append(f"<div><b>{v:,}</b>{esc(k)}</div>")
907
+ bits.append(f"<div><b>{human(s['size'])}</b>file size</div>")
908
+ if s["payload_bytes"]:
909
+ bits.append(f"<div><b>{human(s['payload_bytes'])}</b>payload bytes</div>")
910
+ span = "—"
911
+ if s["first"] or s["last"]:
912
+ span = f"{day(s['first'])} → {day(s['last'])}"
913
+ bits.append(f"<div><b>{esc(span)}</b>date range</div>")
914
+
915
+ degs = "".join(
916
+ f'<tr><td class="deg">{esc(c)}</td><td>{esc(d)}</td></tr>'
917
+ for c, d in s["degradations"])
918
+ deg_html = (f'<table><tr><th>degradation</th><th>why</th></tr>{degs}</table>'
919
+ if degs else '<div class="note">no degradation</div>')
920
+
921
+ rows.append(f"""<div class="card">
922
+ <h3>{esc(s['label'] or 'unrecognised')}
923
+ <span class="pill {esc(conf)}">{esc(conf)}</span>
924
+ <span class="pill">{esc(s.get('role') or s['detected_by'])}</span></h3>
925
+ <div class="path">{esc(s['path'])}</div>
926
+ <div class="grid">{''.join(bits)}</div>
927
+ {deg_html}
928
+ {f'<div class="note">{esc(s["notes"])}</div>' if s["notes"] else ''}
929
+ </div>""")
930
+
931
+ if t["messages"]:
932
+ covered = sum(s["messages"] or 0 for s in recognised
933
+ if s["confidence"] in ("high", "medium"))
934
+ pct = min(100, round(100 * covered / max(1, t["messages"])))
935
+ verified = "100%" if pct == 100 else f"{pct}%"
936
+ rows.append(f"""<div class="card">
937
+ <div><b>{verified}</b> of the messages on this machine sit in sources with a known
938
+ shape — those are archivable today, at the confidence shown above.</div>
939
+ <div class="bar"><i style="width:{pct}%"></i></div></div>""")
940
+
941
+ if unknown:
942
+ ur = "".join(
943
+ f"<tr><td><code>{esc(u['path'])}</code></td><td>{human(u['size'])}</td>"
944
+ f"<td>{u['tables']}</td><td>{u['confidence']}</td></tr>"
945
+ for u in unknown[:40])
946
+ rows.append(f"""<h2>Databases with no adapter yet ({len(unknown)})</h2>
947
+ <div class="card">
948
+ <table><tr><th>file</th><th>size</th><th>tables</th><th>confidence</th></tr>{ur}</table>
949
+ <div class="note">Most of these are browser caches and app settings. The ones worth a
950
+ second look are the ones with 10+ tables and no obvious browser in the path.
951
+ Open an issue with the path and table names — never with conversation content.</div>
952
+ </div>""")
953
+
954
+ if summary["unclaimed"]:
955
+ ur = "".join(
956
+ f"<tr><td><code>{esc(u['path'])}</code></td><td>{u['files']:,}"
957
+ f"{'+' if u['truncated'] else ''}</td><td>{human(u['size'])}</td></tr>"
958
+ for u in summary["unclaimed"][:40])
959
+ rows.append(f"""<h2>Looks like AI tooling, but no readable history yet</h2>
960
+ <div class="card">
961
+ <table><tr><th>directory</th><th>files</th><th>size</th></tr>{ur}</table>
962
+ <div class="note">These are not bugs. They are the queue. If one of them is yours,
963
+ open an issue with the directory name — do not paste conversation content.</div>
964
+ </div>""")
965
+
966
+ if summary.get("ignored"):
967
+ ur = "".join(
968
+ f"<tr><td><code>{esc(u['path'])}</code></td><td>{human(u['size'])}</td>"
969
+ f"<td>{esc(u['reason'])}</td></tr>" for u in summary["ignored"][:20])
970
+ rows.append(f"""<h2>Looked at, and deliberately not touched</h2>
971
+ <div class="card">
972
+ <table><tr><th>directory</th><th>size</th><th>why</th></tr>{ur}</table>
973
+ <div class="note">A runtime, a browser profile, or a system folder holds no
974
+ transcript. Listing them as "unclaimed" would be a promise to collect something
975
+ that does not exist, so they are named once and closed.</div>
976
+ </div>""")
977
+
978
+ if summary["totals"]["degradation_kinds"]:
979
+ rows.append(f"""<h2>What this report does not see</h2>
980
+ <div class="card">
981
+ <p style="margin:0 0 8px">Every degradation above is deliberate: rather than writing
982
+ a placeholder that looks like data, batonpass names the gap so you can judge it.</p>
983
+ <ul style="margin:0;padding-left:20px;color:var(--mut);font-size:13px">
984
+ <li><b>locked</b> — the tool was mid-write; close it and re-run.</li>
985
+ <li><b>compressed-payload / reasoning-encrypted</b> — the tool stored it in a form
986
+ that needs a decoder we have not written.</li>
987
+ <li><b>media-by-reference</b> — files are pointed at, not copied. By design.</li>
988
+ <li><b>schema-unknown</b> — conversation-shaped tables with no adapter. The queue.</li>
989
+ </ul></div>""")
990
+
991
+ skipped = summary.get("skipped") or {}
992
+ if skipped:
993
+ sk = ", ".join(f"{esc(k)} × {v}" for k, v in sorted(skipped.items(), key=lambda x: -x[1]))
994
+ rows.append(f"""<div class="card"><div class="note">
995
+ <b>{sum(skipped.values())} files were skipped on purpose:</b> {sk}.<br>
996
+ Browser caches, backup copies and nested build artifacts cannot hold transcripts,
997
+ so probing them would only add noise — but the count stays here so you can see
998
+ that the skip happened.</div></div>""")
999
+
1000
+ rows.append(f"""<div class="foot">
1001
+ <p><b>This report was produced read-only.</b> Every database was opened with
1002
+ <code>mode=ro</code>; nothing was written outside this file; no network call was made;
1003
+ no telemetry exists.</p>
1004
+ <p>Re-run any time: <code>python3 discover.py</code></p>
1005
+ </div></div>""")
1006
+
1007
+ return f"""<!doctype html><html lang="en"><head><meta charset="utf-8">
1008
+ <meta name="viewport" content="width=device-width,initial-scale=1">
1009
+ <title>batonpass discover — {esc(summary['host'])}</title>
1010
+ <style>{CSS}</style></head><body>{''.join(rows)}</body></html>"""
1011
+
1012
+
1013
+ def main(argv=None):
1014
+ ap = argparse.ArgumentParser(
1015
+ prog="batonpass",
1016
+ description="Read-only inventory of local AI history (batonpass v%s)" % VERSION,
1017
+ epilog="archive / find / resume are designed but not shipped yet — "
1018
+ "see docs/design-v1.md")
1019
+ ap.add_argument("command", nargs="?", default="discover", choices=["discover"],
1020
+ help="what to do (default: discover)")
1021
+ ap.add_argument("--report", default="batonpass-report.html", help="HTML output path")
1022
+ ap.add_argument("--json", dest="json_path", help="also write machine-readable JSON here")
1023
+ ap.add_argument("--deep", action="store_true",
1024
+ help="measure payload bytes (slower, reads full tables)")
1025
+ ap.add_argument("--only", help="comma separated adapters, e.g. zcode,billion")
1026
+ ap.add_argument("--explain", action="store_true", help="print detection reasoning")
1027
+ args = ap.parse_args(argv)
1028
+
1029
+ print(f"batonpass discover v{VERSION} — read-only scan")
1030
+ summary = run(args)
1031
+
1032
+ out = Path(os.path.expanduser(args.report))
1033
+ out.write_text(render(summary), encoding="utf-8")
1034
+ if args.json_path:
1035
+ Path(os.path.expanduser(args.json_path)).write_text(
1036
+ json.dumps(summary, ensure_ascii=False, indent=2, default=str),
1037
+ encoding="utf-8")
1038
+
1039
+ t = summary["totals"]
1040
+ print(f"\n {t['messages']:,} messages · {t['sessions']:,} conversations · "
1041
+ f"{t['recognised']} sources recognised · {human(t['bytes_on_disk'])}")
1042
+ print(f" {t['skipped_files']} files skipped (browser caches, backups) · "
1043
+ f"{t['unclaimed_dirs']} dirs in the queue · "
1044
+ f"{t.get('ignored_dirs', 0)} left alone on purpose")
1045
+ print(f" report → {out}")
1046
+ if args.json_path:
1047
+ print(f" json → {args.json_path}")
1048
+ return 0
1049
+
1050
+
1051
+ if __name__ == "__main__":
1052
+ sys.exit(main())