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.
batonpass/doctor.py ADDED
@@ -0,0 +1,314 @@
1
+ """`doctor` — the answer to "why isn't it working", before you have to ask.
2
+
3
+ Every check here earned its place by being something that actually went wrong
4
+ once: a missing compressor, an archive written by an older extractor, an index
5
+ built before the messages grew, a channel whose folder moved, a disk that could
6
+ not take another gigabyte. Each one prints one line it can act on, and never a
7
+ stack trace.
8
+
9
+ Nothing here writes to a library, a channel, or a source. Doctor is read-only,
10
+ like everything else that is allowed to touch other people's data.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import platform
17
+ import shutil
18
+ import sqlite3
19
+ import sys
20
+
21
+ from . import __version__
22
+
23
+ OK, WARN, FAIL, INFO = "OK", "WARN", "FAIL", "--"
24
+ _LABEL = {OK: "OK ", WARN: "WARN", FAIL: "FAIL", INFO: " · "}
25
+
26
+
27
+ def _check(level, name, detail, fix=None) -> dict:
28
+ return {"level": level, "name": name, "detail": detail, "fix": fix}
29
+
30
+
31
+ def _human(n) -> str:
32
+ n = float(n or 0)
33
+ for unit in ("B", "KB", "MB", "GB", "TB"):
34
+ if n < 1024 or unit == "TB":
35
+ return ("%d %s" % (n, unit)) if unit == "B" else ("%.1f %s" % (n, unit))
36
+ n /= 1024.0
37
+ return "%.1f TB" % n
38
+
39
+
40
+ def _dir_bytes(path, limit=200000) -> float:
41
+ total, seen = 0, 0
42
+ for root, _dirs, files in os.walk(path):
43
+ for f in files:
44
+ seen += 1
45
+ if seen > limit:
46
+ return total
47
+ try:
48
+ total += os.path.getsize(os.path.join(root, f))
49
+ except OSError:
50
+ pass
51
+ return total
52
+
53
+
54
+ # ── checks ─────────────────────────────────────────────────────
55
+
56
+
57
+ def check_python():
58
+ v = "%d.%d.%d" % sys.version_info[:3]
59
+ if sys.version_info < (3, 9):
60
+ return _check(FAIL, "python", "%s — batonpass needs 3.9 or newer" % v,
61
+ "install python 3.9+ and run it with that interpreter")
62
+ return _check(OK, "python", v)
63
+
64
+
65
+ def check_sqlite():
66
+ v = sqlite3.sqlite_version
67
+ try:
68
+ c = sqlite3.connect(":memory:")
69
+ c.execute("CREATE VIRTUAL TABLE t USING fts5(body)")
70
+ except sqlite3.Error as e:
71
+ return _check(FAIL, "sqlite", "%s without fts5 (%s)" % (v, e),
72
+ "use a python built with sqlite 3.34+ (python.org or Homebrew)")
73
+ try:
74
+ c.execute("CREATE VIRTUAL TABLE g USING fts5(body, tokenize='trigram')")
75
+ trigram = True
76
+ except sqlite3.Error:
77
+ trigram = False
78
+ c.close()
79
+ if not trigram:
80
+ # Chinese has no spaces; trigram is how a search for 「岗位表」 ever matches.
81
+ return _check(WARN, "sqlite", "%s with fts5 but no trigram tokenizer" % v,
82
+ "search still works for latin words; use sqlite 3.34+ for CJK")
83
+ return _check(OK, "sqlite", "%s, fts5 + trigram" % v)
84
+
85
+
86
+ def check_zstd():
87
+ try:
88
+ import zstandard # noqa: F401
89
+ except Exception:
90
+ return _check(WARN, "zstd", "not installed — archives stay readable, "
91
+ "2.50x becomes 2.04x",
92
+ 'pip install "batonpass-cli[zstd]"')
93
+ return _check(OK, "zstd", getattr(__import__("zstandard"), "__version__", "installed"))
94
+
95
+
96
+ def check_disk(path):
97
+ try:
98
+ os.makedirs(path, exist_ok=True)
99
+ free = shutil.disk_usage(path).free
100
+ except OSError as e:
101
+ return _check(FAIL, "disk", "%s is not writable (%s)" % (path, e),
102
+ "point BATONPASS_HOME at a writable directory")
103
+ if free < 2 * 1024 ** 3:
104
+ return _check(WARN, "disk", "%s free at %s — a big archive may not fit"
105
+ % (_human(free), path), "free space, or archive elsewhere with --db")
106
+ return _check(OK, "disk", "%s free at %s" % (_human(free), path))
107
+
108
+
109
+ def check_library(db_path):
110
+ from .store.db import get_meta
111
+ from .store.schema import SCHEMA_VERSION
112
+
113
+ out = []
114
+ if not os.path.exists(db_path):
115
+ return [_check(INFO, "library", "no library yet at %s" % db_path,
116
+ "batonpass archive # or point --db somewhere else")]
117
+ try:
118
+ conn = sqlite3.connect("file:%s?mode=ro" % db_path, uri=True)
119
+ conn.row_factory = sqlite3.Row
120
+ conn.execute("SELECT COUNT(*) FROM session").fetchone()
121
+ except sqlite3.Error as e:
122
+ return [_check(FAIL, "library", "%s: %s" % (db_path, e),
123
+ "if it was written by an older batonpass, run "
124
+ "`batonpass archive` again into a new --db")]
125
+
126
+ sessions = conn.execute("SELECT COUNT(*) FROM session").fetchone()[0]
127
+ messages = conn.execute("SELECT COUNT(*) FROM message").fetchone()[0]
128
+ size = os.path.getsize(db_path)
129
+ ver = get_meta(conn, "schema_version")
130
+ if str(ver or "") != str(SCHEMA_VERSION):
131
+ out.append(_check(WARN, "schema", "library is v%s, this build is v%s"
132
+ % (ver, SCHEMA_VERSION), "re-run `batonpass archive`"))
133
+ out.append(_check(OK, "library", "%s, %s sessions, %s messages"
134
+ % (_human(size), format(sessions, ","), format(messages, ","))))
135
+ integrity = conn.execute("PRAGMA quick_check").fetchone()[0]
136
+ if integrity != "ok":
137
+ out.append(_check(FAIL, "integrity", integrity,
138
+ "copy the file aside and re-run `batonpass archive`"))
139
+
140
+ # identity: stale extractors are silent otherwise
141
+ from .identity import artifacts as af
142
+ have = get_meta(conn, "artifact_ver")
143
+ if sessions and str(have or "") and str(have) != af.ARTIFACT_VER:
144
+ out.append(_check(WARN, "identity", "built by artifact extractor v%s, current is v%s"
145
+ % (have, af.ARTIFACT_VER), "batonpass identity"))
146
+ elif sessions and not have:
147
+ out.append(_check(WARN, "identity", "never built for this library",
148
+ "batonpass identity"))
149
+ else:
150
+ ok = conn.execute(
151
+ "SELECT COUNT(*) FROM session WHERE project_key IS NOT NULL AND project_key<>''"
152
+ ).fetchone()[0]
153
+ ungrouped = sessions - ok
154
+ out.append(_check(OK, "identity", "%d named project key(s), %d honestly ungrouped"
155
+ % (len(set(r[0] for r in conn.execute(
156
+ "SELECT project_key FROM session WHERE project_key IS NOT NULL"
157
+ " AND project_key<>''"))), ungrouped)))
158
+
159
+ # index: does it still describe the messages that are there?
160
+ try:
161
+ docs = conn.execute("SELECT COUNT(*) FROM search_fts").fetchone()[0]
162
+ from .recall.index import FTS_VER
163
+
164
+ vers = sorted(r[0] or "" for r in conn.execute(
165
+ "SELECT DISTINCT ver FROM search_state"))
166
+ stale = conn.execute(
167
+ "SELECT COUNT(*) FROM session s WHERE s.msg_count > 0 AND NOT EXISTS"
168
+ " (SELECT 1 FROM search_state d WHERE d.sid=s.sid)"
169
+ ).fetchone()[0]
170
+ behind = conn.execute(
171
+ "SELECT COUNT(*) FROM search_state st WHERE st.last_seq <"
172
+ " (SELECT COALESCE(MAX(seq),-1) FROM message m WHERE m.sid=st.sid)"
173
+ ).fetchone()[0]
174
+ if FTS_VER not in vers:
175
+ out.append(_check(INFO, "index", "not built with this version",
176
+ "batonpass index"))
177
+ elif stale or behind:
178
+ # Not a warning: every search catches the index up before it runs.
179
+ out.append(_check(INFO, "index", "%d session(s) not indexed yet, %d behind"
180
+ % (stale, behind),
181
+ "batonpass index # or just run a find — it catches up"))
182
+ else:
183
+ out.append(_check(OK, "index", "%s documents" % format(docs, ",")))
184
+ except sqlite3.Error:
185
+ out.append(_check(INFO, "index", "not built yet — find has nothing to read",
186
+ "batonpass index"))
187
+ conn.close()
188
+
189
+ return out
190
+
191
+
192
+ def check_channel(channel):
193
+ from .sync import channel as ch
194
+ from .sync import wire
195
+
196
+ channel = os.path.abspath(os.path.expanduser(channel))
197
+ if not ch.is_channel(channel):
198
+ return [_check(FAIL, "channel", "no %s at %s" % (ch.MARKER, channel),
199
+ "batonpass sync init %s" % channel)]
200
+ out = []
201
+ marker = {}
202
+ try:
203
+ import json
204
+ with open(os.path.join(channel, ch.MARKER), encoding="utf-8") as fh:
205
+ marker = json.load(fh)
206
+ except (OSError, ValueError):
207
+ pass
208
+ if int(marker.get("schema") or 0) > ch.SCHEMA:
209
+ out.append(_check(FAIL, "channel", "schema %s is newer than this build (%s)"
210
+ % (marker.get("schema"), ch.SCHEMA),
211
+ "upgrade batonpass on this machine"))
212
+ devs = ch.devices(channel)
213
+ out.append(_check(OK, "channel", "id %s, %d device(s), %s"
214
+ % ((marker.get("id") or "")[:12], len(devs),
215
+ _human(_dir_bytes(os.path.join(channel, "blobs"))))))
216
+ for d in devs:
217
+ when = d.get("last_seen") or ""
218
+ ver = d.get("batonpass") or "?"
219
+ if ver and ver != __version__:
220
+ out.append(_check(INFO, "channel", "%s last seen %s, on batonpass %s"
221
+ % (d.get("device"), when, ver), None))
222
+ if marker.get("enc"):
223
+ from .sync import crypt
224
+
225
+ try:
226
+ out.append(_check(OK, "encryption", "%s, key %s"
227
+ % (marker["enc"], crypt.fingerprint(channel))))
228
+ except RuntimeError:
229
+ out.append(_check(WARN, "encryption",
230
+ "channel is sealed, but this machine has no key",
231
+ "export BATONPASS_KEY=… (or ~/.batonpass/key)"))
232
+ except Exception as exc: # cryptography missing
233
+ out.append(_check(WARN, "encryption", "channel is sealed; %s" % exc,
234
+ 'pip install "batonpass-cli[crypto]"'))
235
+ sizes = sum(_streams(channel))
236
+ out.append(_check(INFO, "channel", "%s of streams — `sync status` says how much is new"
237
+ % _human(sizes)))
238
+ return out
239
+
240
+
241
+ def _streams(channel):
242
+ """Total bytes of every stream file, per device directory."""
243
+ sdir = os.path.join(channel, "stream")
244
+ if not os.path.isdir(sdir):
245
+ return
246
+ for dev in sorted(os.listdir(sdir)):
247
+ ddir = os.path.join(sdir, dev)
248
+ if not os.path.isdir(ddir):
249
+ continue
250
+ total = 0
251
+ for name in os.listdir(ddir):
252
+ if name.endswith(".jsonl"):
253
+ try:
254
+ total += os.path.getsize(os.path.join(ddir, name))
255
+ except OSError:
256
+ pass
257
+ yield total
258
+
259
+
260
+ def check_sources():
261
+ from .discover import summary
262
+
263
+ try:
264
+ s = summary()
265
+ except Exception as e: # a scan must never be what breaks doctor
266
+ return [_check(WARN, "sources", "scan failed: %s" % e, "batonpass discover --explain")]
267
+ t = s["totals"]
268
+ out = [_check(OK if t["recognised"] else INFO, "sources",
269
+ "%d recognised, %s conversations, %s messages, %s on disk"
270
+ % (t["recognised"], format(t["sessions"], ","),
271
+ format(t["messages"], ","), _human(t["bytes_on_disk"])))]
272
+ if s.get("unclaimed"):
273
+ names = ", ".join(u["path"].split("/")[-1] if isinstance(u, dict) else str(u)
274
+ for u in s["unclaimed"][:5])
275
+ out.append(_check(INFO, "sources", "%d dir(s) in the queue: %s"
276
+ % (len(s["unclaimed"]), names),
277
+ "batonpass discover --explain # or open an issue with the name"))
278
+ return out
279
+
280
+
281
+ def run(db_path=None, channel=None, sources=False) -> dict:
282
+ from .paths import db_path as default_db
283
+
284
+ db = str(db_path or default_db())
285
+ checks = [check_python(), check_sqlite(), check_zstd(),
286
+ check_disk(os.path.dirname(os.path.abspath(db)) or ".")]
287
+ checks.extend(check_library(db))
288
+ if channel:
289
+ checks.extend(check_channel(channel))
290
+ else:
291
+ checks.append(_check(INFO, "channel", "not asked about (--channel PATH)",
292
+ "batonpass sync status PATH"))
293
+ if sources:
294
+ checks.extend(check_sources())
295
+ return {"version": __version__, "platform": "%s %s" % (platform.system(),
296
+ platform.release()),
297
+ "db": db, "channel": channel, "checks": checks}
298
+
299
+
300
+ def render(result) -> str:
301
+ lines = ["batonpass doctor %s · %s · %s"
302
+ % (result["version"], result["platform"], result["db"]), ""]
303
+ for c in result["checks"]:
304
+ lines.append("%s %-12s %s" % (_LABEL.get(c["level"], c["level"]),
305
+ c["name"], c["detail"]))
306
+ if c.get("fix"):
307
+ lines.append(" → %s" % c["fix"])
308
+ bad = [c for c in result["checks"] if c["level"] == FAIL]
309
+ lines.append("")
310
+ if bad:
311
+ lines.append("%d thing(s) need a hand. Nothing was changed." % len(bad))
312
+ else:
313
+ lines.append("Nothing broken. Nothing was changed.")
314
+ return "\n".join(lines)
@@ -0,0 +1,9 @@
1
+ """Identity: what was this session about, on any machine."""
2
+
3
+ from .project import derive, display, is_candidate, key_from_path, remote_to_key
4
+ from .tasks import build, card, card_for_session, projects, resolve, resume_hint
5
+
6
+ __all__ = [
7
+ "build", "card", "card_for_session", "derive", "display", "is_candidate",
8
+ "key_from_path", "projects", "remote_to_key", "resolve", "resume_hint",
9
+ ]
@@ -0,0 +1,293 @@
1
+ """What did this task actually produce?
2
+
3
+ A transcript is mostly talk. The one thing you want when you come back to a
4
+ task a week later is the file it left behind — and that file is almost never
5
+ mentioned in the first message. Measured on a real session: 79 filename
6
+ candidates, the first six were `SOUL.md / AGENTS.md / bootstrap.md`. Take the
7
+ *last* mention, not the first, and filter out the files every project has.
8
+
9
+ Two rules, and both are needed:
10
+
11
+ whitelist a deliverable has a deliverable extension — .xlsx .docx .pdf .zip
12
+ blacklist the eighteen files that exist in every repo are never "the output"
13
+
14
+ Skipping either one produces a card pointing at `README.md`, which is worse
15
+ than a card pointing at nothing, because it looks like an answer.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import re
22
+
23
+ DELIVERABLE_EXT = {
24
+ ".xlsx", ".xlsm", ".xls", ".csv", ".numbers",
25
+ ".docx", ".doc", ".pages", ".pdf",
26
+ ".pptx", ".ppt", ".key",
27
+ ".zip", ".tar", ".gz",
28
+ ".md", ".html", ".ipynb",
29
+ ".png", ".jpg", ".jpeg", ".svg",
30
+ }
31
+
32
+ # The files that exist in every repository. They are not wrong, they are just
33
+ # never the answer to "where is my work".
34
+ NOISE_NAMES = {
35
+ "readme.md", "changelog.md", "license", "license.md", "license.txt",
36
+ "skill.md", "agents.md", "soul.md", "memory.md", "user.md", "claude.md",
37
+ "agents", "contributing.md", "code_of_conduct.md", "security.md",
38
+ "requirements.txt", "pyproject.toml", "package.json", "package-lock.json",
39
+ "tsconfig.json", "mcp.json", "settings.json", ".gitignore", "makefile",
40
+ "dockerfile", "docker-compose.yml", "index.html", "index.js", "index.ts",
41
+ "favicon.ico", "robots.txt", "setup.py", "manifest.json",
42
+ }
43
+
44
+ # Tool arguments arrive as JSON containing JSON, so a "path" can be three
45
+ # levels down. These are the keys that hold a destination, across the naming
46
+ # conventions of the tools actually on this machine.
47
+ PATH_KEYS = {
48
+ "path", "file_path", "filepath", "target_file", "filename", "file",
49
+ "output", "output_path", "save_as", "destination", "dest", "to",
50
+ }
51
+
52
+ NAME_RE = re.compile(
53
+ r"""(?<![\w.\-\\]) # not mid-word, not mid-extension
54
+ ( # a name starts and ends on a word
55
+ [\w\u4e00-\u9fff] # character — "existing .xlsx" is
56
+ (?:[\w\u4e00-\u9fff .\-_]{0,68} # prose, "报告 2026.xlsx" is not
57
+ [\w\u4e00-\u9fff\-_])?
58
+ \.(?:xlsx|xlsm|xls|csv|numbers|docx|doc|pages|pdf|pptx|ppt|key|
59
+ zip|tar|gz|md|html|ipynb|png|jpe?g|svg))
60
+ (?![\w])""",
61
+ re.I | re.X,
62
+ )
63
+
64
+ # Not all deliverables are equal. A spreadsheet is the thing you were making;
65
+ # a markdown note is usually the thing you were reading. Without this, every
66
+ # card's top line is `index.md`.
67
+ EXT_RANK = {
68
+ ".xlsx": 3, ".xlsm": 3, ".xls": 3, ".numbers": 3, ".docx": 3, ".doc": 3,
69
+ ".pages": 3, ".pdf": 3, ".pptx": 3, ".ppt": 3, ".key": 3, ".zip": 3,
70
+ ".tar": 3, ".gz": 3, ".csv": 2, ".html": 2, ".ipynb": 2, ".png": 2,
71
+ ".jpg": 2, ".jpeg": 2, ".svg": 2, ".md": 1,
72
+ }
73
+
74
+
75
+ def rank(name: str) -> int:
76
+ low = (name or "").lower()
77
+ return EXT_RANK.get("." + low.rsplit(".", 1)[-1] if "." in low else "", 0)
78
+
79
+
80
+ # Chinese prose glues itself to the filename: "产出 xueji_岗位表_2026.xlsx".
81
+ # The space is the only seam there is, so drop the words that are never part of
82
+ # a name and keep the token that is.
83
+ STOP_TOKENS = {
84
+ "产出", "见", "和", "与", "的", "在",
85
+ "保存到", "保存", "生成", "导出", "新建", "修改", "打开", "读取", "写入",
86
+ "输出", "附件", "下载", "上传", "已", "完成", "更新", "查看", "here", "file",
87
+ "the", "see", "and", "to", "into", "from", "for", "with", "saved", "saving",
88
+ "做了", "做到了", "存到", "保存为", "写入到", "文件是", "这里是",
89
+ "且", "并且", "还有", "另见", "详见", "参见", "参考", "注意", "继续读",
90
+ "save", "as", "new", "existing", "or", "and", "then", "with", "a", "an",
91
+ "creating", "editing", "restyling", "generating", "writing", "reading",
92
+ "saving", "uploading", "downloading", "fixing", "fix", "update", "updating",
93
+ "opening", "open", "exporting", "convert", "converting", "legacy", "files",
94
+ }
95
+
96
+ # Bumped whenever the extractor learns something. A rescan is cheap (713
97
+ # sessions in ~6 s) while a stale ref list is permanent — merging only ever
98
+ # adds, so an improved extractor would otherwise never be able to *remove* the
99
+ # `README.md` it used to believe in.
100
+ ARTIFACT_VER = "5"
101
+
102
+ MAX_REFS = 24
103
+ MAX_DEPTH = 6
104
+
105
+
106
+ def _ok_name(name: str) -> bool:
107
+ base = _strip_stopwords((name or "").strip())
108
+ base = base.strip("._-")
109
+ if not base or "/" in base or "\\" in base:
110
+ return False
111
+ low = base.lower()
112
+ if low in NOISE_NAMES:
113
+ return False
114
+ ext = "." + low.rsplit(".", 1)[-1] if "." in low else ""
115
+ if ext not in DELIVERABLE_EXT:
116
+ return False
117
+ # `streamlit.components.v1.html` is a module path, not a file you can open.
118
+ if base.count(".") > 2:
119
+ return False
120
+ # `state.json trades.csv` is two filenames separated by a space, and the
121
+ # space is allowed *inside* a name (`报告 2026.xlsx`), so the tell is the
122
+ # text that follows a complete extension: a real name never resumes after
123
+ # its own extension.
124
+ if re.search(r"\.[A-Za-z0-9]{1,5}\s+\S", base):
125
+ return False
126
+ # `1.png` / `a.md` are counters and headings, not deliverables.
127
+ if len(base.rsplit(".", 1)[0]) < 2:
128
+ return False
129
+ return True
130
+
131
+
132
+ # Words that join two names. They are separators, not part of a name, and the
133
+ # two sides are two deliverables: "岗位表 2026.xlsx 和 汇总表 2026.xlsx" is a pair,
134
+ # not a file called "岗位表 2026.xlsx 汇总表 2026.xlsx".
135
+ _REL_SPLIT = re.compile(
136
+ r"\s+(?:至|到|和|与|及|或|以及|然后|to|and|or|through|until|then|into)\s+", re.I)
137
+
138
+ _CJK_VERB = re.compile(
139
+ r"^(看|请|帮|把|给|要|想|能|可|让|叫|试|先|再|并|和|与|或|至|到|于|从|在|用|对|为|是|有|没|未|已|加|改|写|读|删|传|存|导|做|放|发|跑|禁止|不要|请勿|别|只|仅|继续|继续读|注意|且|并且|还有|另见|详见|参见|参考|重读|补|补充)"
140
+ )
141
+
142
+
143
+ def _strip_stopwords(name: str) -> str:
144
+ """Cut the Chinese sentence that grew around the filename.
145
+
146
+ "看能否上传 cover.png" and "加 card-1 至 card-5.png" are sentences, not files.
147
+ Only the tokens that are provably not part of a name are removed — a real
148
+ Chinese stem like `岗位表 2026.xlsx` keeps `岗位表`.
149
+ """
150
+ if " " not in name:
151
+ return name
152
+ parts = [p for p in name.split(" ") if p]
153
+ kept = []
154
+ for p in parts:
155
+ if p in STOP_TOKENS:
156
+ continue
157
+ if re.search(r"[A-Za-z]", p):
158
+ kept.append(p)
159
+ continue
160
+ if p.isdigit() and "." not in p:
161
+ continue # a row id, a price, a date fragment
162
+ if _CJK_VERB.match(p):
163
+ continue
164
+ kept.append(p)
165
+ return " ".join(kept) if kept else name
166
+
167
+
168
+ def names_in_text(text: str) -> list:
169
+ """Every filename in a blob of prose, in order, deduplicated.
170
+
171
+ `[2026-11-18.md](/Users/a/n/2026-11-18.md)` names the same file twice; the
172
+ label and the target are one mention, not two.
173
+ """
174
+ out, seen = [], set()
175
+ for m in NAME_RE.finditer(text or ""):
176
+ for piece in _REL_SPLIT.split(m.group(1).strip()):
177
+ name = _strip_stopwords(piece.strip())
178
+ if _ok_name(name) and name not in seen:
179
+ seen.add(name)
180
+ out.append(name)
181
+ return out
182
+
183
+
184
+ def _deep_paths(obj, out, depth=0):
185
+ if depth > MAX_DEPTH:
186
+ return
187
+ if isinstance(obj, dict):
188
+ for k, v in obj.items():
189
+ if isinstance(v, str):
190
+ if str(k).lower() in PATH_KEYS and _ok_name(v.rsplit("/", 1)[-1]):
191
+ out.append(v.strip())
192
+ else:
193
+ _deep_paths(v, out, depth + 1)
194
+ elif isinstance(obj, list):
195
+ for v in obj:
196
+ _deep_paths(v, out, depth + 1)
197
+ elif isinstance(obj, str):
198
+ s = obj.strip()
199
+ if s[:1] in "{[":
200
+ try:
201
+ _deep_paths(json.loads(s), out, depth + 1)
202
+ except (ValueError, TypeError):
203
+ pass
204
+
205
+
206
+ def paths_in_args(raw: str) -> list:
207
+ out = []
208
+ _deep_paths(raw if isinstance(raw, str) else str(raw), out)
209
+ return out
210
+
211
+
212
+ def _basename(p: str) -> str:
213
+ p = (p or "").replace("\\", "/").rstrip("/")
214
+ return p.rsplit("/", 1)[-1] if p else ""
215
+
216
+
217
+ def scan_session(conn, codecs, sid: str, source: str, limit_rows: int = 4000) -> list:
218
+ """Every deliverable this session mentions, with the last time it appeared.
219
+
220
+ Reads message prose, text parts and file-tool arguments — not tool results.
221
+ A directory listing mentions hundreds of files that are not the output;
222
+ `write({"path": "..."})` mentions exactly one.
223
+ """
224
+ seen = {}
225
+ order = 0
226
+
227
+ rows = conn.execute(
228
+ "SELECT seq, role, text_sha, ts FROM message WHERE sid=? ORDER BY seq LIMIT ?",
229
+ (sid, limit_rows),
230
+ ).fetchall()
231
+ for r in rows:
232
+ order += 1
233
+ text = codecs.get(r["text_sha"], source)
234
+ if text:
235
+ for name in names_in_text(text):
236
+ seen[name] = {"name": name, "ts": r["ts"], "via": "text", "order": order}
237
+
238
+ prows = conn.execute(
239
+ """SELECT p.kind, p.name, p.args_sha, p.result_sha, m.ts
240
+ FROM part p JOIN message m ON m.mid=p.mid
241
+ WHERE m.sid=? ORDER BY m.seq, p.seq LIMIT ?""",
242
+ (sid, limit_rows * 4),
243
+ ).fetchall()
244
+ for r in prows:
245
+ order += 1
246
+ ts = r["ts"]
247
+ kind = (r["kind"] or "").lower()
248
+ if kind in ("text", "tool_call", "file"):
249
+ body = codecs.get(r["args_sha"], source) if kind == "tool_call" else codecs.get(r["result_sha"], source)
250
+ if not body:
251
+ body = codecs.get(r["result_sha"], source) or codecs.get(r["args_sha"], source)
252
+ if kind == "tool_call":
253
+ for path in paths_in_args(body):
254
+ name = _basename(path)
255
+ if _ok_name(name):
256
+ seen[name] = {"name": name, "path": path, "ts": ts,
257
+ "via": "tool", "order": order}
258
+ continue
259
+ for name in names_in_text(body):
260
+ seen[name] = {"name": name, "ts": ts, "via": "text", "order": order}
261
+
262
+ # A path taken from `write({"path": ...})` outranks a filename spotted in
263
+ # prose: one of them the tool actually touched.
264
+ refs = sorted(seen.values(), key=lambda d: (rank(d["name"]), d["via"] == "tool", d["order"]))
265
+ # Newest first, and the cap keeps a card readable: 24 files is already more
266
+ # than anyone reads on a phone.
267
+ refs = refs[-MAX_REFS:]
268
+ refs.reverse()
269
+ for r in refs:
270
+ r.pop("order", None)
271
+ return refs
272
+
273
+
274
+ def merge_refs(existing_json: str, refs: list) -> str:
275
+ """Union by basename, newest wins. Used when a task spans sessions."""
276
+ merged = {}
277
+ if existing_json:
278
+ try:
279
+ for r in json.loads(existing_json):
280
+ if r.get("name"):
281
+ merged[r["name"]] = r
282
+ except (ValueError, TypeError):
283
+ pass
284
+ for r in refs:
285
+ name = r.get("name")
286
+ if not name:
287
+ continue
288
+ old = merged.get(name)
289
+ if old is None or str(r.get("ts") or "") >= str(old.get("ts") or ""):
290
+ merged[name] = r
291
+ out = sorted(merged.values(),
292
+ key=lambda d: (rank(d.get("name")), str(d.get("ts") or "")), reverse=True)
293
+ return json.dumps(out[:MAX_REFS], ensure_ascii=False)