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,245 @@
1
+ """Machine-independent project identity.
2
+
3
+ The problem this solves, in one line of field data:
4
+
5
+ Mac mini /Users/lcpkof/Documents/xueji -> 49 sessions
6
+ laptop /home/luo/Documents/xueji -> the same 49 sessions
7
+ nobody .zcode/workspace/default -> 58 sessions of nothing
8
+
9
+ If identity is the path, those three are three different projects forever, and
10
+ "where is that spreadsheet I made" stays unanswerable across machines. So a
11
+ project is not a path — it is the *logical tail* of the path, with everything
12
+ machine-specific and everything disposable thrown away first.
13
+
14
+ Three tiers, best evidence first. A tier is stored with the key so the reader
15
+ can tell a git remote from a guess, and no tier is allowed to silently
16
+ impersonate another.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import os
22
+ import re
23
+ from pathlib import PurePosixPath
24
+
25
+ TIER_GIT = 1
26
+ TIER_PATH = 2
27
+ TIER_CANDIDATE = 3
28
+
29
+ CONFIDENCE = {TIER_GIT: "high", TIER_PATH: "medium", TIER_CANDIDATE: "low"}
30
+
31
+ UNKNOWN = "" # no project — sessions still searchable, just not groupable
32
+
33
+ # Home directories differ between machines, and so do the names inside them.
34
+ _HOME_PREFIX = re.compile(r"^(users|home|volumes|root|mnt|c)/", re.I)
35
+ _DRIVE = re.compile(r"^[a-z]:/", re.I)
36
+
37
+ # Directories that are disposable by construction. A task that lived in one of
38
+ # these was a run, not a project: `draft-42f3f9e1-...` is the same as `tmp`.
39
+ _NOISE_SEG = re.compile(
40
+ r"""^(
41
+ \..*| # a tool's own home, never a project
42
+ default|workspace|tmp|temp|output|outputs|out|dist|build|target|
43
+ node_modules|__pycache__|\.git|\.venv|venv|env|
44
+ draft[-\_]?[0-9a-f]{6,}[-\w]*|
45
+ [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|
46
+ .*[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|
47
+ [0-9]{8}[-\_]?[0-9]{4,6}|
48
+ [0-9]{4}-[0-9]{2}-[0-9]{2}([tT ][0-9:]+)?[-\w]*|
49
+ session[-\_]?\w*
50
+ )$""",
51
+ re.I | re.X,
52
+ )
53
+
54
+ # Sub-directories that belong to *some* project rather than being one. Without
55
+ # this, `xueji` and `xueji/frontend` are two projects and the 8 directories you
56
+ # actually work in become 20 clusters.
57
+ _GENERIC_TAIL = {
58
+ "src", "lib", "app", "apps", "web", "www", "site", "public", "static",
59
+ "assets", "docs", "doc", "scripts", "script", "test", "tests", "spec",
60
+ "frontend", "backend", "server", "client", "api", "core", "main",
61
+ "packages", "components", "pages", "views", "config", "tools",
62
+ }
63
+
64
+ # `~/Documents/xueji` on one machine is `~/projects/xueji` on the next. What
65
+ # they share is not the folder — it is the fact that the folder is *just a
66
+ # container*. Canonicalising it to `~` merges the two and keeps the leaf name,
67
+ # which is the only part a human ever says out loud.
68
+ _CONTAINER = {
69
+ "documents", "document", "desktop", "downloads", "projects", "project",
70
+ "work", "works", "workspace2", "code", "codes", "src", "source", "repos",
71
+ "repo", "git", "github", "gitlab", "gitee", "dev", "develop", "sites",
72
+ "apps", "projects2", "files", "user", "home",
73
+ }
74
+
75
+ _REMOTE_URL = re.compile(r"^\s*url\s*=\s*(.+?)\s*$", re.M)
76
+ _SCP_LIKE = re.compile(r"^[\w.-]+@([\w.-]+):(?!//)(.+)$")
77
+
78
+
79
+ def norm_path(path: str) -> str:
80
+ """Forward slashes, no trailing slash, no duplicate separators."""
81
+ p = (path or "").strip().replace("\\", "/")
82
+ p = re.sub(r"/{2,}", "/", p)
83
+ return p.rstrip("/")
84
+
85
+
86
+ def drop_machine_prefix(parts: list) -> list:
87
+ """Remove the part of a path that only makes sense on one machine."""
88
+ if parts and _DRIVE.match(parts[0] + "/"):
89
+ parts = parts[1:]
90
+ if parts and parts[0].lower() in ("users", "home", "volumes", "root", "mnt"):
91
+ parts = parts[1:]
92
+ # the account name itself
93
+ if parts and not _NOISE_SEG.match(parts[0]):
94
+ parts = parts[1:]
95
+ if parts and parts[0].lower() == "volumes":
96
+ parts = parts[1:]
97
+ if parts:
98
+ parts = parts[1:]
99
+ return parts
100
+
101
+
102
+ def logical_parts(cwd: str, home: str = None) -> list:
103
+ p = norm_path(cwd)
104
+ if not p:
105
+ return []
106
+ home = norm_path(home if home is not None else os.path.expanduser("~"))
107
+ if home and p.lower().startswith(home.lower() + "/"):
108
+ p = p[len(home) + 1:]
109
+ parts = [s for s in p.split("/") if s]
110
+ # Only strip a user/home prefix when the path actually started at a root.
111
+ if cwd.replace("\\", "/").startswith("/") or _DRIVE.match(norm_path(cwd)):
112
+ parts = drop_machine_prefix(parts)
113
+ else:
114
+ parts = drop_machine_prefix(parts)
115
+ return parts
116
+
117
+
118
+ def meaningful(parts: list) -> list:
119
+ """Drop noise everywhere, generic tails only at the end."""
120
+ kept = [s for s in parts if not _NOISE_SEG.match(s)]
121
+ while len(kept) > 1 and kept[-1].lower() in _GENERIC_TAIL:
122
+ kept.pop()
123
+ return kept
124
+
125
+
126
+ def key_from_path(cwd: str, home: str = None) -> tuple:
127
+ """Tier 2. Returns (key, tier, confidence) — key '' when there is no project."""
128
+ parts = meaningful(logical_parts(cwd, home))
129
+ if not parts:
130
+ return UNKNOWN, TIER_PATH, CONFIDENCE[TIER_PATH]
131
+ # Last two segments: deep enough to disambiguate `xueji` from `frontend`,
132
+ # shallow enough that a re-cloned copy still matches. A container parent
133
+ # collapses to `~`, so `/Users/a/Documents/xueji`, `/home/b/projects/xueji`
134
+ # and `C:/Users/c/Desktop/xueji` are one project.
135
+ if len(parts) == 1:
136
+ if parts[0].lower() in _CONTAINER:
137
+ return UNKNOWN, TIER_PATH, CONFIDENCE[TIER_PATH]
138
+ tail = parts[0].lower()
139
+ else:
140
+ parent, leaf = parts[-2].lower(), parts[-1].lower()
141
+ tail = ("~/" + leaf) if parent in _CONTAINER else (parent + "/" + leaf)
142
+ if len(tail) < 2:
143
+ return UNKNOWN, TIER_PATH, CONFIDENCE[TIER_PATH]
144
+ return tail, TIER_PATH, CONFIDENCE[TIER_PATH]
145
+
146
+
147
+ def remote_to_key(url: str) -> str:
148
+ """`git@github.com:Lcpkof/xueji.git` -> `github.com/lcpkof/xueji`."""
149
+ u = (url or "").strip()
150
+ if not u:
151
+ return ""
152
+ m = _SCP_LIKE.match(u)
153
+ if m:
154
+ host, path = m.group(1), m.group(2)
155
+ else:
156
+ u = re.sub(r"^[a-z]+://", "", u, flags=re.I)
157
+ u = u.split("?")[0].split("#")[0]
158
+ if "@" in u.split("/")[0]:
159
+ u = u.split("@", 1)[1]
160
+ host, _, path = u.partition("/")
161
+ path = path.strip("/")
162
+ if path.endswith(".git"):
163
+ path = path[:-4]
164
+ host = host.split(":")[0]
165
+ if not host or not path:
166
+ return ""
167
+ return ("%s/%s" % (host, path)).lower()
168
+
169
+
170
+ def read_git_remote(path: str) -> str:
171
+ """Tier 1, only when the directory is on *this* machine.
172
+
173
+ A git remote is the one identifier that is genuinely the same string on
174
+ every machine, which is why it outranks the path. We read `.git/config`
175
+ directly instead of shelling out — no subprocess, no network, no surprise.
176
+ """
177
+ base = norm_path(path)
178
+ if not base or not os.path.isdir(base):
179
+ return ""
180
+ for candidate in (os.path.join(base, ".git", "config"),
181
+ os.path.join(base, "config")):
182
+ if not os.path.isfile(candidate):
183
+ continue
184
+ try:
185
+ with open(candidate, "r", encoding="utf-8", errors="replace") as fh:
186
+ text = fh.read(20000)
187
+ except OSError:
188
+ continue
189
+ urls = _REMOTE_URL.findall(text)
190
+ for u in urls:
191
+ k = remote_to_key(u)
192
+ if k:
193
+ return k
194
+ return ""
195
+
196
+
197
+ def title_candidate(title: str) -> str:
198
+ """Tier 3: a *candidate*, never merged into a real cluster.
199
+
200
+ Marked with a leading `?` so `batonpass tasks` can show it as a guess and
201
+ nothing downstream can mistake it for a path-derived key.
202
+ """
203
+ t = (title or "").strip()
204
+ if len(t) < 4:
205
+ return UNKNOWN
206
+ t = re.sub(r"^(this is an automatically generated .*?|帮我|请|麻烦)\s*", "", t, flags=re.I)
207
+ t = re.sub(r"[^\w\u4e00-\u9fff]+", "-", t.lower()).strip("-")
208
+ slug = "-".join([s for s in t.split("-") if s][:6])[:40]
209
+ return "?" + slug if len(slug) >= 3 else UNKNOWN
210
+
211
+
212
+ def derive(cwd: str, title: str = "", home: str = None, guess: bool = False) -> tuple:
213
+ """Best available identity for one session: (key, tier, confidence).
214
+
215
+ `guess=False` by default, and that is a deliberate choice with a measured
216
+ reason: 409 sessions here have no working directory at all, and their
217
+ titles are sentences ("这道题我做错了,帮我讲讲"). Turning every sentence into
218
+ a project produced 400 clusters of one — noise pretending to be structure.
219
+ Ungrouped sessions are still fully searchable; they are just not lied about.
220
+ """
221
+ if cwd:
222
+ remote = read_git_remote(cwd)
223
+ rk = remote_to_key(remote) if remote else ""
224
+ if rk:
225
+ return rk, TIER_GIT, CONFIDENCE[TIER_GIT]
226
+ key, tier, conf = key_from_path(cwd, home)
227
+ if key:
228
+ return key, tier, conf
229
+ cand = title_candidate(title) if guess else UNKNOWN
230
+ if cand:
231
+ return cand, TIER_CANDIDATE, CONFIDENCE[TIER_CANDIDATE]
232
+ return UNKNOWN, TIER_CANDIDATE, "none"
233
+
234
+
235
+ def is_candidate(key: str) -> bool:
236
+ return bool(key) and key.startswith("?")
237
+
238
+
239
+ def display(key: str) -> str:
240
+ """Human label for a key — the candidate marker is noise in a table."""
241
+ if not key:
242
+ return "(no project)"
243
+ if key.startswith("?"):
244
+ return key[1:]
245
+ return key[2:] if key.startswith("~/") else key
@@ -0,0 +1,423 @@
1
+ """Grouping sessions into tasks, and rendering a card you can act on.
2
+
3
+ Everything on the card is *derived*, never written by a model: the tool calls
4
+ that happened, the files that were produced, the last thing that was said, the
5
+ session id to open. A card that guesses reads better and is useless — so where
6
+ there is no evidence, the line is omitted instead of filled in.
7
+
8
+ Two rules borrowed from the field and kept:
9
+
10
+ * the newest session of a project wins the title (an old session keeps the
11
+ old name forever otherwise)
12
+ * a task untouched for a week is marked stale — a stale workbench is more
13
+ dangerous than no workbench, because it is confidently wrong
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import time
20
+ from datetime import datetime, timedelta, timezone
21
+
22
+ from ..store.content import sha256_text
23
+ from . import artifacts as af
24
+ from . import project as pj
25
+
26
+ STALE_DAYS = 7
27
+
28
+ # Tool names that mean "this task moved forward", grouped so the card says
29
+ # "写了 31 个文件" instead of listing 2,000 calls.
30
+ TOOL_GROUPS = (
31
+ ("写", {"write", "edit", "str_replace_editor", "create_file", "apply_patch",
32
+ "multi_edit", "notebookedit"}),
33
+ ("读", {"read", "read_file", "view", "read_image", "readimage"}),
34
+ ("跑", {"bash", "run_code", "exec", "shell", "js", "python", "terminal"}),
35
+ ("查", {"websearch", "webfetch", "grep", "glob", "search", "list_dir"}),
36
+ ("查", {"job_output", "todo_write", "todowrite"}),
37
+ )
38
+
39
+
40
+ def _now_iso() -> str:
41
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
42
+
43
+
44
+ def _ago_iso(days: int) -> str:
45
+ return (datetime.now(timezone.utc) - timedelta(days=days)).strftime("%Y-%m-%dT%H:%M:%SZ")
46
+
47
+
48
+ def task_id(project_key: str) -> str:
49
+ return sha256_text("task|%s" % project_key)[:32]
50
+
51
+
52
+ # ── build ───────────────────────────────────────────────────────
53
+
54
+ def build(conn, extract_artifacts: bool = True, limit: int = None, home: str = None) -> dict:
55
+ """Recompute identity for every session. Idempotent: run it as often as you like."""
56
+ from ..store.codecs import Codecs
57
+
58
+ codecs = Codecs(conn)
59
+ if extract_artifacts:
60
+ from ..store.db import get_meta, set_meta
61
+ if get_meta(conn, "artifact_ver") != af.ARTIFACT_VER:
62
+ conn.execute("UPDATE session SET artifact_refs=NULL")
63
+ set_meta(conn, "artifact_ver", af.ARTIFACT_VER)
64
+
65
+ # Read rows *after* the reset: a row cached before it still carries the old
66
+ # refs, and merge_refs would faithfully resurrect every one of them.
67
+ rows = conn.execute(
68
+ "SELECT sid, source, source_sid, device, cwd, title, updated_at, "
69
+ "project_key, artifact_refs FROM session ORDER BY COALESCE(updated_at,'') DESC"
70
+ + (" LIMIT %d" % int(limit) if limit else "")
71
+ ).fetchall()
72
+
73
+ stats = {"sessions": 0, "keys_changed": 0, "artifacts": 0, "with_artifacts": 0,
74
+ "tiers": {}, "unknown": 0, "forks": 0, "merged_subprojects": 0,
75
+ "kept_remote": 0}
76
+
77
+ # Our paths say nothing about another machine's disk. A session that arrived
78
+ # through a channel already carries the answer the machine that owned it gave
79
+ # (t0 `pk`), so an empty local derivation must not erase it — otherwise
80
+ # "switch machines" silently loses exactly the grouping it was for.
81
+ from ..archive.runner import device_name
82
+ try:
83
+ local_device = device_name()
84
+ except Exception:
85
+ local_device = ""
86
+
87
+ derived = []
88
+ for r in rows:
89
+ key, tier, _conf = pj.derive(r["cwd"], r["title"], home)
90
+ derived.append((r, key, tier))
91
+
92
+ # A sub-directory of a project is not a second project. `documents/gp` had
93
+ # 48 sessions and `gp/stock_picker` had 2 — same work, two clusters, and the
94
+ # small one is unreachable in a list sorted by size.
95
+ remap = _subproject_remap([k for _r, k, _t in derived])
96
+ stats["merged_subprojects"] = len(remap)
97
+
98
+ for r, key, tier in derived:
99
+ stats["sessions"] += 1
100
+ key = remap.get(key, key)
101
+ stats["tiers"][tier] = stats["tiers"].get(tier, 0) + 1
102
+ if not key and (r["project_key"] or "") and (r["device"] or "") != local_device:
103
+ stats["kept_remote"] += 1
104
+ key = r["project_key"]
105
+ if not key:
106
+ stats["unknown"] += 1
107
+ if key != (r["project_key"] or ""):
108
+ stats["keys_changed"] += 1
109
+ conn.execute("UPDATE session SET project_key=?, project_key_tier=? WHERE sid=?",
110
+ (key or None, tier if key else None, r["sid"]))
111
+ if not extract_artifacts:
112
+ continue
113
+ refs = af.scan_session(conn, codecs, r["sid"], r["source"])
114
+ if not refs:
115
+ continue
116
+ stats["with_artifacts"] += 1
117
+ stats["artifacts"] += len(refs)
118
+ merged = af.merge_refs(r["artifact_refs"], refs)
119
+ if merged != (r["artifact_refs"] or ""):
120
+ conn.execute("UPDATE session SET artifact_refs=? WHERE sid=?", (merged, r["sid"]))
121
+
122
+ stats["forks"] = _link_forks(conn)
123
+ _sync_tasks(conn)
124
+ conn.commit()
125
+ return stats
126
+
127
+
128
+ def _subproject_remap(keys: list) -> dict:
129
+ """Fold a small `parent/child` cluster back into `*/parent`.
130
+
131
+ Deliberately conservative: the parent must already be a real cluster (>=5
132
+ sessions) and the child must be a rounding error next to it (<= max(2, 20%)),
133
+ otherwise a genuine second project sharing a folder name gets eaten.
134
+ """
135
+ counts = {}
136
+ for k in keys:
137
+ if k:
138
+ counts[k] = counts.get(k, 0) + 1
139
+ parents = {}
140
+ for k, n in counts.items():
141
+ tail = k.rsplit("/", 1)[-1]
142
+ if n >= 5:
143
+ parents.setdefault(tail, (k, n))
144
+ remap = {}
145
+ for k, n in counts.items():
146
+ if "/" not in k:
147
+ continue
148
+ head = k.split("/", 1)[0]
149
+ parent = parents.get(head)
150
+ if not parent or parent[0] == k:
151
+ continue
152
+ if n <= max(2, int(parent[1] * 0.2)):
153
+ remap[k] = parent[0]
154
+ return remap
155
+
156
+
157
+ def _link_forks(conn) -> int:
158
+ """Same source session on two machines = one was continued elsewhere.
159
+
160
+ We never merge them: the second copy keeps its own rows and points back at
161
+ the first. A visible fork can be dealt with; a silently merged one cannot.
162
+ """
163
+ rows = conn.execute(
164
+ """SELECT source, source_sid, sid, device, updated_at FROM session
165
+ WHERE source_sid IN (
166
+ SELECT source_sid FROM session GROUP BY source, source_sid
167
+ HAVING COUNT(*) > 1)
168
+ ORDER BY source, source_sid, COALESCE(updated_at,'') """
169
+ ).fetchall()
170
+ n, seen = 0, {}
171
+ for r in rows:
172
+ k = (r["source"], r["source_sid"])
173
+ first = seen.get(k)
174
+ if first is None:
175
+ seen[k] = r["sid"]
176
+ continue
177
+ if r["sid"] != first:
178
+ cur = conn.execute("SELECT forked_from FROM session WHERE sid=?", (r["sid"],)).fetchone()
179
+ if cur is not None and not cur["forked_from"]:
180
+ conn.execute("UPDATE session SET forked_from=? WHERE sid=?", (first, r["sid"]))
181
+ n += 1
182
+ return n
183
+
184
+
185
+ def _sync_tasks(conn) -> None:
186
+ """One task row per project that has sessions. Title follows the newest session."""
187
+ projects = conn.execute(
188
+ """SELECT project_key, COUNT(*) n FROM session
189
+ WHERE project_key IS NOT NULL AND project_key <> ''
190
+ GROUP BY project_key"""
191
+ ).fetchall()
192
+ for p in projects:
193
+ key = p["project_key"]
194
+ tid = task_id(key)
195
+ newest = conn.execute(
196
+ """SELECT title, updated_at FROM session WHERE project_key=?
197
+ ORDER BY COALESCE(updated_at,'') DESC LIMIT 1""", (key,)
198
+ ).fetchone()
199
+ title = pj.display(key)
200
+ conn.execute(
201
+ "INSERT OR IGNORE INTO task(tid,project_key,title,created_at) VALUES(?,?,?,?)",
202
+ (tid, key, title, _now_iso()),
203
+ )
204
+ if newest is not None:
205
+ conn.execute("UPDATE task SET title=? WHERE tid=?", (title, tid))
206
+
207
+
208
+ # ── read ────────────────────────────────────────────────────────
209
+
210
+ def projects(conn, min_sessions: int = 1, include_candidates: bool = False) -> list:
211
+ sql = """SELECT project_key,
212
+ COUNT(*) n,
213
+ MAX(COALESCE(updated_at,'')) last_at,
214
+ MIN(COALESCE(created_at, updated_at, '')) first_at,
215
+ COUNT(DISTINCT device) devices,
216
+ GROUP_CONCAT(DISTINCT device) device_list,
217
+ SUM(CASE WHEN artifact_refs IS NOT NULL AND artifact_refs<>'' THEN 1 ELSE 0 END) with_files
218
+ FROM session
219
+ WHERE project_key IS NOT NULL AND project_key <> ''
220
+ GROUP BY project_key HAVING n >= ?
221
+ ORDER BY last_at DESC"""
222
+ out = []
223
+ for r in conn.execute(sql, (min_sessions,)):
224
+ key = r["project_key"]
225
+ if pj.is_candidate(key) and not include_candidates:
226
+ continue
227
+ out.append({
228
+ "project_key": key,
229
+ "label": pj.display(key),
230
+ "sessions": r["n"],
231
+ "last_at": r["last_at"],
232
+ "first_at": r["first_at"],
233
+ "devices": r["devices"],
234
+ "device_list": (r["device_list"] or ""),
235
+ "with_files": r["with_files"],
236
+ "candidate": pj.is_candidate(key),
237
+ "stale": bool(r["last_at"] and r["last_at"] < _ago_iso(STALE_DAYS)),
238
+ })
239
+ return out
240
+
241
+
242
+ def resolve(conn, hint: str) -> list:
243
+ """Find the project a vague hint points at. Path, key fragment — best first."""
244
+ hint = (hint or "").strip()
245
+ if not hint:
246
+ return []
247
+ if "/" in hint or hint.startswith("~"):
248
+ key, tier, _ = pj.derive(hint, "", None)
249
+ if key:
250
+ return [p for p in projects(conn, include_candidates=True) if p["project_key"] == key]
251
+ low = hint.lower()
252
+ hits = [p for p in projects(conn, include_candidates=True)
253
+ if low in p["project_key"].lower() or low in p["label"].lower()]
254
+ return sorted(hits, key=lambda p: (-(p["sessions"] or 0), p["last_at"] or ""))
255
+
256
+
257
+ def sessions_of(conn, project_key: str, limit: int = 8) -> list:
258
+ rows = conn.execute(
259
+ """SELECT s.sid, s.source, s.device, s.title, s.cwd, s.updated_at,
260
+ s.msg_count, s.artifact_refs, s.forked_from,
261
+ (SELECT COUNT(*) FROM message m WHERE m.sid=s.sid) AS n_msg
262
+ FROM session s WHERE s.project_key=?
263
+ ORDER BY COALESCE(s.updated_at,'') DESC LIMIT ?""",
264
+ (project_key, limit),
265
+ ).fetchall()
266
+ return [dict(r) for r in rows]
267
+
268
+
269
+ def tool_histogram(conn, sid: str, top: int = 5) -> list:
270
+ rows = conn.execute(
271
+ """SELECT p.name, COUNT(*) n FROM part p JOIN message m ON m.mid=p.mid
272
+ WHERE m.sid=? AND p.kind='tool_call' AND p.name IS NOT NULL
273
+ GROUP BY LOWER(p.name) ORDER BY n DESC LIMIT ?""",
274
+ (sid, top),
275
+ ).fetchall()
276
+ return [{"name": r["name"], "count": r["n"]} for r in rows]
277
+
278
+
279
+ def _unwrap(text: str) -> str:
280
+ from ..store.text import clean
281
+ return clean(text or "")
282
+
283
+
284
+ def last_turns(conn, sid: str, source: str, roles=("assistant",), limit: int = 1) -> list:
285
+ from ..store.codecs import Codecs
286
+ codecs = Codecs(conn)
287
+ q = ("SELECT role, text_sha, ts FROM message WHERE sid=? AND role IN (%s) "
288
+ "ORDER BY seq DESC LIMIT ?" % ",".join("?" * len(roles)))
289
+ rows = conn.execute(q, (sid,) + tuple(roles) + (limit,)).fetchall()
290
+ out = []
291
+ for r in rows:
292
+ out.append({"role": r["role"], "ts": r["ts"],
293
+ "text": _unwrap(codecs.get(r["text_sha"], source))})
294
+ return out
295
+
296
+
297
+ def first_ask(conn, sid: str, source: str) -> str:
298
+ from ..store.codecs import Codecs
299
+ codecs = Codecs(conn)
300
+ r = conn.execute(
301
+ "SELECT text_sha FROM message WHERE sid=? AND role='user' ORDER BY seq LIMIT 1",
302
+ (sid,)).fetchone()
303
+ return _unwrap(codecs.get(r["text_sha"], source)) if r else ""
304
+
305
+
306
+ def artifact_list(row) -> list:
307
+ try:
308
+ return json.loads(row or "[]") or []
309
+ except (ValueError, TypeError):
310
+ return []
311
+
312
+
313
+ # ── render ──────────────────────────────────────────────────────
314
+
315
+ def _when(iso: str) -> str:
316
+ return (iso or "")[:16].replace("T", " ") or "—"
317
+
318
+
319
+ def _clip(text: str, n: int = 150) -> str:
320
+ text = " ".join((text or "").split())
321
+ return text if len(text) <= n else text[:n - 1] + "…"
322
+
323
+
324
+ def card(conn, project_key: str, sessions: int = 4) -> str:
325
+ """The handover card. Everything printed here is evidence, not inference."""
326
+ rows = sessions_of(conn, project_key, sessions)
327
+ if not rows:
328
+ return "no sessions for %s" % pj.display(project_key)
329
+ total = conn.execute("SELECT COUNT(*) c FROM session WHERE project_key=?",
330
+ (project_key,)).fetchone()["c"]
331
+ newest = rows[0]
332
+ lines = []
333
+ lines.append("任务 %s" % pj.display(project_key))
334
+ devices = sorted({(r["device"] or "?") for r in rows})
335
+ age = newest.get("updated_at") or ""
336
+ stale = bool(age and age < _ago_iso(STALE_DAYS))
337
+ lines.append("状态 %s%s" % (
338
+ "%d 个会话 · 最近 %s 由 %s 更新" % (total, _when(age), newest.get("device") or "?"),
339
+ " ⚠ 已 %s 天没动" % STALE_DAYS if stale else "",
340
+ ))
341
+ if len(devices) > 1:
342
+ lines.append("设备 %s" % " · ".join(devices))
343
+
344
+ # Roll up across the project's recent sessions: the newest session is often
345
+ # a question, and the file you want was made three sessions ago.
346
+ bag = {}
347
+ for row in rows:
348
+ for ref in artifact_list(row.get("artifact_refs")):
349
+ if ref.get("name") and ref["name"] not in bag:
350
+ bag[ref["name"]] = ref
351
+ refs = sorted(bag.values(),
352
+ key=lambda d: (af.rank(d.get("name")), str(d.get("ts") or "")), reverse=True)
353
+ if refs:
354
+ first = refs[0]
355
+ lines.append("产出 %s%s" % (first.get("name"),
356
+ " ← %s" % _when(first.get("ts")) if first.get("ts") else ""))
357
+ for r in refs[1:4]:
358
+ lines.append(" %s" % r.get("name"))
359
+ if len(refs) > 4:
360
+ lines.append(" …另外 %d 个" % (len(refs) - 4))
361
+
362
+ hist = tool_histogram(conn, newest["sid"], 4)
363
+ if hist:
364
+ lines.append("做过 %s" % " · ".join("%s×%d" % (h["name"], h["count"]) for h in hist))
365
+
366
+ # What someone wrote down on purpose. This is the only part of a card that
367
+ # is not inferred from a transcript, so it goes near the top.
368
+ try:
369
+ tid = task_id(project_key)
370
+ events = conn.execute(
371
+ "SELECT kind, body FROM task_event WHERE tid=? AND COALESCE(body,'')<>''"
372
+ " ORDER BY lamport DESC LIMIT 2", (tid,)
373
+ ).fetchall()
374
+ except Exception: # a library from before task_event
375
+ events = []
376
+ for e in reversed(events):
377
+ label = {"blocked": "卡住", "decision": "决定", "done": "完成"}.get(e["kind"], "笔记")
378
+ lines.append("备注 %s:%s" % (label, _clip(e["body"], 80)))
379
+
380
+ ask = first_ask(conn, newest["sid"], newest["source"])
381
+ if ask:
382
+ lines.append("原话 「%s」" % _clip(ask, 60))
383
+
384
+ tail = last_turns(conn, newest["sid"], newest["source"], ("assistant",), 1)
385
+ if tail:
386
+ lines.append("最后 助手 %s: %s" % (_when(tail[0]["ts"]), _clip(tail[0]["text"], 90)))
387
+
388
+ for r in rows[1:sessions]:
389
+ fork = " (fork of %s)" % (r["forked_from"] or "")[:8] if r.get("forked_from") else ""
390
+ lines.append("其他 %s %s %s 条%s" % (
391
+ (r["sid"] or "")[:8], _when(r.get("updated_at")), r.get("n_msg") or 0, fork))
392
+ return "\n".join(lines)
393
+
394
+
395
+ def card_for_session(conn, sid: str) -> str:
396
+ row = conn.execute(
397
+ "SELECT sid, source, device, title, cwd, project_key, updated_at, msg_count FROM session WHERE sid=?",
398
+ (sid,)).fetchone()
399
+ if row is None:
400
+ return "no such session: %s" % sid
401
+ if row["project_key"]:
402
+ return card(conn, row["project_key"])
403
+ return "\n".join([
404
+ "任务 (无项目·单次会话)",
405
+ "会话 %s %s %s" % (sid[:8], row["source"], _when(row["updated_at"])),
406
+ "原话 「%s」" % _clip(first_ask(conn, sid, row["source"]), 80),
407
+ ])
408
+
409
+
410
+ def resume_hint(conn, cwd: str, home: str = None) -> str:
411
+ """Proactive recall: the machine you just sat down at knows what you were doing."""
412
+ key, tier, _ = pj.derive(cwd, "", home or _home())
413
+ if not key:
414
+ return ""
415
+ rows = sessions_of(conn, key, 1)
416
+ if not rows:
417
+ return ""
418
+ return card(conn, key, 3)
419
+
420
+
421
+ def _home() -> str:
422
+ import os
423
+ return os.path.expanduser("~")