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/__init__.py +7 -0
- batonpass/__main__.py +3 -0
- batonpass/archive/__init__.py +4 -0
- batonpass/archive/adapters.py +616 -0
- batonpass/archive/export.py +71 -0
- batonpass/archive/runner.py +128 -0
- batonpass/cli.py +579 -0
- batonpass/discover/__init__.py +36 -0
- batonpass/discover/probe.py +1052 -0
- batonpass/doctor.py +314 -0
- batonpass/identity/__init__.py +9 -0
- batonpass/identity/artifacts.py +293 -0
- batonpass/identity/project.py +245 -0
- batonpass/identity/tasks.py +423 -0
- batonpass/mcp.py +273 -0
- batonpass/paths.py +26 -0
- batonpass/recall/__init__.py +45 -0
- batonpass/recall/index.py +147 -0
- batonpass/recall/query.py +215 -0
- batonpass/store/__init__.py +5 -0
- batonpass/store/codecs.py +31 -0
- batonpass/store/content.py +186 -0
- batonpass/store/db.py +95 -0
- batonpass/store/schema.py +152 -0
- batonpass/store/text.py +55 -0
- batonpass/store/write.py +92 -0
- batonpass/sync/__init__.py +15 -0
- batonpass/sync/channel.py +213 -0
- batonpass/sync/crypt.py +216 -0
- batonpass/sync/pull.py +186 -0
- batonpass/sync/push.py +276 -0
- batonpass/sync/status.py +56 -0
- batonpass/sync/wire.py +205 -0
- batonpass_cli-0.5.0.dist-info/METADATA +324 -0
- batonpass_cli-0.5.0.dist-info/RECORD +39 -0
- batonpass_cli-0.5.0.dist-info/WHEEL +5 -0
- batonpass_cli-0.5.0.dist-info/entry_points.txt +2 -0
- batonpass_cli-0.5.0.dist-info/licenses/LICENSE +21 -0
- batonpass_cli-0.5.0.dist-info/top_level.txt +1 -0
batonpass/mcp.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"""A small MCP server: three tools, because recall needs three verbs.
|
|
2
|
+
|
|
3
|
+
An agent does not need a hundred endpoints. It needs to *look something up*
|
|
4
|
+
(`memory_search`), to *write down what it just learned* (`memory_add`), and to
|
|
5
|
+
*be handed the baton* (`resume`). Everything else is a CLI subcommand, which is
|
|
6
|
+
the right shape for a human and the wrong shape for a model.
|
|
7
|
+
|
|
8
|
+
The transport is the standard one: newline-delimited JSON-RPC 2.0 on stdin and
|
|
9
|
+
stdout. No daemon, no port, no background process — the client starts this, and
|
|
10
|
+
when it exits there is nothing left running. Paths and ports are exactly the
|
|
11
|
+
things that break on a machine you just sat down at.
|
|
12
|
+
|
|
13
|
+
`memory_add` is the only tool that writes, and it appends an event. It never
|
|
14
|
+
rewrites history and never touches anyone else's data.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import sys
|
|
21
|
+
|
|
22
|
+
from . import __version__
|
|
23
|
+
|
|
24
|
+
PROTOCOL = "2024-11-05"
|
|
25
|
+
SERVER_NAME = "batonpass"
|
|
26
|
+
|
|
27
|
+
TOOLS = [
|
|
28
|
+
{
|
|
29
|
+
"name": "memory_search",
|
|
30
|
+
"description": (
|
|
31
|
+
"Search everything this person has ever done with an AI tool — on every "
|
|
32
|
+
"machine they own — by a vague phrase rather than an exact query. Use it "
|
|
33
|
+
"when you need to know whether something was already done, where a file "
|
|
34
|
+
"came from, or what the last state of a task was. Returns sessions, not "
|
|
35
|
+
"documents. An empty result is a real answer: report it as not found "
|
|
36
|
+
"instead of guessing."
|
|
37
|
+
),
|
|
38
|
+
"inputSchema": {
|
|
39
|
+
"type": "object",
|
|
40
|
+
"properties": {
|
|
41
|
+
"query": {"type": "string",
|
|
42
|
+
"description": "what you half-remember, e.g. 岗位表 or 反爬"},
|
|
43
|
+
"at": {"type": "string",
|
|
44
|
+
"description": "time window: 7d, 12h, today, 2026-09, "
|
|
45
|
+
"2026-09-01..2026-09-20"},
|
|
46
|
+
"project": {"type": "string",
|
|
47
|
+
"description": "restrict to one project (path, or part of its name)"},
|
|
48
|
+
"limit": {"type": "integer", "default": 5},
|
|
49
|
+
},
|
|
50
|
+
"required": ["query"],
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
"name": "memory_add",
|
|
55
|
+
"description": (
|
|
56
|
+
"Record a fact about the work in progress so the next machine inherits it: "
|
|
57
|
+
"a decision, a dead end, a path that matters. Appends an event to the "
|
|
58
|
+
"project's task; it never edits history. Use it when you learn something "
|
|
59
|
+
"the person would hate to repeat."
|
|
60
|
+
),
|
|
61
|
+
"inputSchema": {
|
|
62
|
+
"type": "object",
|
|
63
|
+
"properties": {
|
|
64
|
+
"text": {"type": "string", "description": "one sentence, in their language"},
|
|
65
|
+
"project": {"type": "string",
|
|
66
|
+
"description": "project path or name; defaults to the cwd"},
|
|
67
|
+
"kind": {"type": "string", "default": "note",
|
|
68
|
+
"enum": ["note", "decision", "blocked", "done"]},
|
|
69
|
+
},
|
|
70
|
+
"required": ["text"],
|
|
71
|
+
},
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
"name": "resume",
|
|
75
|
+
"description": (
|
|
76
|
+
"Hand over the baton for a project: the card with what it is, what was "
|
|
77
|
+
"produced, what was done, what is stuck and what is next, plus any fork "
|
|
78
|
+
"(the same task touched on two machines). Call this at the start of a "
|
|
79
|
+
"session when the person says 'where was I' or names a project."
|
|
80
|
+
),
|
|
81
|
+
"inputSchema": {
|
|
82
|
+
"type": "object",
|
|
83
|
+
"properties": {
|
|
84
|
+
"project": {"type": "string",
|
|
85
|
+
"description": "project path or name; defaults to the cwd"},
|
|
86
|
+
"sessions": {"type": "integer", "default": 4,
|
|
87
|
+
"description": "how many recent sessions to roll up"},
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
},
|
|
91
|
+
]
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _text(s: str) -> dict:
|
|
95
|
+
return {"content": [{"type": "text", "text": s}]}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _need(args, key):
|
|
99
|
+
v = args.get(key)
|
|
100
|
+
if v is None or (isinstance(v, str) and not v.strip()):
|
|
101
|
+
raise ValueError("missing required argument: %s" % key)
|
|
102
|
+
return v
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _project_key(conn, hint) -> str:
|
|
106
|
+
"""Turn a path, a name fragment, or nothing at all into a project key."""
|
|
107
|
+
from .identity import project as pj
|
|
108
|
+
from .identity import tasks as tk
|
|
109
|
+
|
|
110
|
+
hint = (hint or "").strip()
|
|
111
|
+
if not hint:
|
|
112
|
+
import os
|
|
113
|
+
hint = os.getcwd()
|
|
114
|
+
if "/" in hint or hint.startswith("~"):
|
|
115
|
+
key, _tier, _ = pj.derive(hint, "", None)
|
|
116
|
+
if key:
|
|
117
|
+
return key
|
|
118
|
+
hits = tk.resolve(conn, hint)
|
|
119
|
+
return hits[0]["project_key"] if hits else ""
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def tool_search(conn, args) -> str:
|
|
123
|
+
from .recall import ensure_index, search
|
|
124
|
+
|
|
125
|
+
q = _need(args, "query")
|
|
126
|
+
ensure_index(conn) # a search must never answer "nothing" out of neglect
|
|
127
|
+
hits = search(conn, q, at=args.get("at"), project=args.get("project"),
|
|
128
|
+
limit=int(args.get("limit") or 5))
|
|
129
|
+
if not hits:
|
|
130
|
+
# The silence contract: nothing found is said out loud, never papered over.
|
|
131
|
+
msg = ("not found — no session on this machine matches %r. Do not invent one; "
|
|
132
|
+
"say you could not find it." % q)
|
|
133
|
+
from .recall import undecodable_hint
|
|
134
|
+
|
|
135
|
+
hint = undecodable_hint(conn)
|
|
136
|
+
return msg + ("\n" + hint if hint else "")
|
|
137
|
+
out = ["%d session(s) match %r" % (len(hits), q)]
|
|
138
|
+
for h in hits:
|
|
139
|
+
out.append("")
|
|
140
|
+
out.append("%s %s %s %s" % (
|
|
141
|
+
(h.get("sid") or "")[:8], (h.get("updated_at") or "")[:16],
|
|
142
|
+
h.get("device") or "?", h.get("title") or ""))
|
|
143
|
+
if h.get("project"):
|
|
144
|
+
out.append(" project %s" % h["project"])
|
|
145
|
+
if h.get("snippet"):
|
|
146
|
+
out.append(" …%s" % h["snippet"])
|
|
147
|
+
if h.get("why"):
|
|
148
|
+
out.append(" matched %s" % ", ".join(h["why"]))
|
|
149
|
+
return "\n".join(out)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def tool_add(conn, args) -> str:
|
|
153
|
+
from .identity import artifacts as af # noqa: F401 (keeps ver constant importable)
|
|
154
|
+
from .identity import tasks as tk
|
|
155
|
+
from .sync.channel import device_name
|
|
156
|
+
from .store.db import set_meta
|
|
157
|
+
|
|
158
|
+
text = _need(args, "text")
|
|
159
|
+
kind = (args.get("kind") or "note").strip() or "note"
|
|
160
|
+
key = _project_key(conn, args.get("project"))
|
|
161
|
+
if not key:
|
|
162
|
+
return ("cannot record that: no project matches %r. Pass the project directory "
|
|
163
|
+
"or name, or run from it." % (args.get("project") or "the cwd"))
|
|
164
|
+
tid = tk.task_id(key)
|
|
165
|
+
conn.execute(
|
|
166
|
+
"INSERT OR IGNORE INTO task(tid,project_key,title,created_at) VALUES(?,?,?,?)",
|
|
167
|
+
(tid, key, key, tk._now_iso()),
|
|
168
|
+
)
|
|
169
|
+
lamport = conn.execute(
|
|
170
|
+
"SELECT COALESCE(MAX(lamport),0)+1 FROM task_event WHERE tid=?", (tid,)
|
|
171
|
+
).fetchone()[0]
|
|
172
|
+
import hashlib
|
|
173
|
+
eid = hashlib.sha256(("%s|%s|%s" % (tid, lamport, text)).encode("utf-8")).hexdigest()[:32]
|
|
174
|
+
conn.execute(
|
|
175
|
+
"INSERT OR IGNORE INTO task_event(eid,tid,device,lamport,kind,body,refs_json,created_at)"
|
|
176
|
+
" VALUES(?,?,?,?,?,?,?,?)",
|
|
177
|
+
(eid, tid, device_name(), lamport, kind, text, None, tk._now_iso()),
|
|
178
|
+
)
|
|
179
|
+
conn.commit()
|
|
180
|
+
return "recorded %s for %s (event %s)" % (kind, key, eid[:8])
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def tool_resume(conn, args) -> str:
|
|
184
|
+
from .identity import tasks as tk
|
|
185
|
+
|
|
186
|
+
key = _project_key(conn, args.get("project"))
|
|
187
|
+
if not key:
|
|
188
|
+
return ("nothing to hand over: no project matches %r. Try memory_search first."
|
|
189
|
+
% (args.get("project") or "the cwd"))
|
|
190
|
+
return tk.card(conn, key, int(args.get("sessions") or 4))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
_HANDLERS = {"memory_search": tool_search, "memory_add": tool_add, "resume": tool_resume}
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def handle(conn, method: str, params: dict):
|
|
197
|
+
"""One JSON-RPC call in, one result out. `None` means 'no response'."""
|
|
198
|
+
if method == "initialize":
|
|
199
|
+
return {
|
|
200
|
+
"protocolVersion": PROTOCOL,
|
|
201
|
+
"capabilities": {"tools": {}},
|
|
202
|
+
"serverInfo": {"name": SERVER_NAME, "version": __version__},
|
|
203
|
+
}
|
|
204
|
+
if method in ("notifications/initialized", "initialized"):
|
|
205
|
+
return None
|
|
206
|
+
if method == "ping":
|
|
207
|
+
return {}
|
|
208
|
+
if method == "tools/list":
|
|
209
|
+
return {"tools": TOOLS}
|
|
210
|
+
if method == "tools/call":
|
|
211
|
+
name = (params or {}).get("name")
|
|
212
|
+
args = (params or {}).get("arguments") or {}
|
|
213
|
+
fn = _HANDLERS.get(name)
|
|
214
|
+
if fn is None:
|
|
215
|
+
raise LookupError("unknown tool: %s" % name)
|
|
216
|
+
try:
|
|
217
|
+
return _text(fn(conn, args))
|
|
218
|
+
except ValueError as e: # bad arguments are the caller's fault
|
|
219
|
+
raise
|
|
220
|
+
except Exception as e: # a broken library must not kill the session
|
|
221
|
+
return {"content": [{"type": "text", "text": "error: %s" % e}],
|
|
222
|
+
"isError": True}
|
|
223
|
+
raise NotImplementedError("unknown method: %s" % method)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def serve(db_path=None, instream=None, outstream=None) -> int:
|
|
227
|
+
"""Read requests until stdin closes. Nothing is left running afterwards."""
|
|
228
|
+
from .store.db import connect
|
|
229
|
+
from .paths import db_path as default_db, ensure_home
|
|
230
|
+
|
|
231
|
+
inp = instream or sys.stdin
|
|
232
|
+
out = outstream or sys.stdout
|
|
233
|
+
path = str(db_path or default_db())
|
|
234
|
+
conn = None
|
|
235
|
+
for line in inp:
|
|
236
|
+
line = line.strip()
|
|
237
|
+
if not line:
|
|
238
|
+
continue
|
|
239
|
+
try:
|
|
240
|
+
msg = json.loads(line)
|
|
241
|
+
except ValueError:
|
|
242
|
+
continue
|
|
243
|
+
if not isinstance(msg, dict) or "method" not in msg:
|
|
244
|
+
continue # a response, not a request: ignore
|
|
245
|
+
rid = msg.get("id")
|
|
246
|
+
try:
|
|
247
|
+
if conn is None:
|
|
248
|
+
import os
|
|
249
|
+
if not os.path.exists(path):
|
|
250
|
+
ensure_home() # a first run creates an empty library
|
|
251
|
+
conn = connect(path)
|
|
252
|
+
result = handle(conn, msg["method"], msg.get("params") or {})
|
|
253
|
+
reply = None if msg["method"].startswith("notifications/") else \
|
|
254
|
+
{"jsonrpc": "2.0", "id": rid, "result": result}
|
|
255
|
+
except NotImplementedError as e:
|
|
256
|
+
reply = {"jsonrpc": "2.0", "id": rid,
|
|
257
|
+
"error": {"code": -32601, "message": str(e)}}
|
|
258
|
+
except LookupError as e:
|
|
259
|
+
reply = {"jsonrpc": "2.0", "id": rid,
|
|
260
|
+
"error": {"code": -32602, "message": str(e)}}
|
|
261
|
+
except ValueError as e:
|
|
262
|
+
reply = {"jsonrpc": "2.0", "id": rid,
|
|
263
|
+
"error": {"code": -32602, "message": str(e)}}
|
|
264
|
+
except Exception as e:
|
|
265
|
+
reply = {"jsonrpc": "2.0", "id": rid,
|
|
266
|
+
"error": {"code": -32603, "message": "%s: %s" % (type(e).__name__, e)}}
|
|
267
|
+
if reply is None:
|
|
268
|
+
continue
|
|
269
|
+
out.write(json.dumps(reply, ensure_ascii=False) + "\n")
|
|
270
|
+
out.flush()
|
|
271
|
+
if conn is not None:
|
|
272
|
+
conn.close()
|
|
273
|
+
return 0
|
batonpass/paths.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Where things live. One directory is ours; nothing else is written."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
ENV_HOME = "BATONPASS_HOME"
|
|
9
|
+
DB_NAME = "library.db"
|
|
10
|
+
DEFAULT_HOME = "~/.batonpass"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def home() -> Path:
|
|
14
|
+
return Path(os.path.expanduser(os.environ.get(ENV_HOME) or DEFAULT_HOME))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def ensure_home() -> Path:
|
|
18
|
+
h = home()
|
|
19
|
+
h.mkdir(parents=True, exist_ok=True)
|
|
20
|
+
return h
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def db_path(explicit=None) -> Path:
|
|
24
|
+
if explicit:
|
|
25
|
+
return Path(os.path.expanduser(str(explicit)))
|
|
26
|
+
return ensure_home() / DB_NAME
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Search: the index is local and disposable, the queries are not."""
|
|
2
|
+
|
|
3
|
+
from .index import build as build_index
|
|
4
|
+
from .index import ensure as ensure_tables
|
|
5
|
+
from .index import ensure_fresh as ensure_index
|
|
6
|
+
from .index import stats as index_stats
|
|
7
|
+
from .query import parse_window, search
|
|
8
|
+
|
|
9
|
+
__all__ = ["build_index", "ensure_index", "ensure_tables", "undecodable_hint", "index_stats", "parse_window", "search"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def undecodable_hint(conn) -> str:
|
|
13
|
+
"""Why a miss might not be a miss.
|
|
14
|
+
|
|
15
|
+
Two ways a library can be honest and still useless: its texts are stored under a
|
|
16
|
+
codec this machine cannot decode, or the text never travelled at all (a tier-1
|
|
17
|
+
pull carries summaries, not transcripts). In both cases "nothing matched" is
|
|
18
|
+
literally true and completely misleading, so the sentence says which one it is.
|
|
19
|
+
|
|
20
|
+
The test for the second case is *message rows*, not index documents: a summary
|
|
21
|
+
library is searchable — it has one document per session — and that is exactly
|
|
22
|
+
how a miss there stays silent when it should not.
|
|
23
|
+
"""
|
|
24
|
+
from ..store.content import HAVE_ZSTD
|
|
25
|
+
|
|
26
|
+
n = 0
|
|
27
|
+
try:
|
|
28
|
+
n = conn.execute(
|
|
29
|
+
"SELECT COUNT(*) FROM content WHERE codec LIKE 'zstd%'").fetchone()[0]
|
|
30
|
+
except Exception:
|
|
31
|
+
n = 0
|
|
32
|
+
if n and not HAVE_ZSTD:
|
|
33
|
+
return ('(%d stored texts cannot be read without zstandard — '
|
|
34
|
+
'pip install "batonpass-cli[zstd]")' % n)
|
|
35
|
+
try:
|
|
36
|
+
sess = conn.execute(
|
|
37
|
+
"SELECT COUNT(*) FROM session WHERE msg_count > 0").fetchone()[0]
|
|
38
|
+
bodies = conn.execute("SELECT COUNT(*) FROM message").fetchone()[0]
|
|
39
|
+
except Exception: # a library too young for these tables
|
|
40
|
+
return ""
|
|
41
|
+
if sess and not bodies:
|
|
42
|
+
return ("(%d session(s) are on record here, but not one message — this "
|
|
43
|
+
"library holds summaries only. Pull deeper: "
|
|
44
|
+
"batonpass sync pull PATH --tier 2)" % sess)
|
|
45
|
+
return ""
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""The search index, built locally and never synced.
|
|
2
|
+
|
|
3
|
+
One design decision worth stating up front: this index is *derived*, so it is
|
|
4
|
+
the only thing in the library that is allowed to be thrown away. It travels to
|
|
5
|
+
no other machine, it is not part of the channel, and a peer rebuilds its own
|
|
6
|
+
from the same immutable messages. That is why it can be aggressive — trigram
|
|
7
|
+
tokens over every word of every message — without bloating what you sync.
|
|
8
|
+
|
|
9
|
+
Incremental by construction: messages only ever get appended, so the watermark
|
|
10
|
+
is the last `seq` indexed per session. Re-running `index` costs nothing.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
|
|
17
|
+
from ..store.codecs import Codecs
|
|
18
|
+
from ..store.text import clean
|
|
19
|
+
|
|
20
|
+
FTS_VER = "1"
|
|
21
|
+
MAX_DOC_CHARS = 8000 # one pasted stack trace should not eat the disk
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _fts_ddl():
|
|
25
|
+
return [
|
|
26
|
+
"""CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
|
|
27
|
+
body, sid UNINDEXED, ref UNINDEXED, kind UNINDEXED, ts UNINDEXED,
|
|
28
|
+
tokenize='trigram')""",
|
|
29
|
+
"""CREATE TABLE IF NOT EXISTS search_state(
|
|
30
|
+
sid TEXT PRIMARY KEY, last_seq INTEGER, ver TEXT)""",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def ensure(conn) -> None:
|
|
35
|
+
for stmt in _fts_ddl():
|
|
36
|
+
try:
|
|
37
|
+
conn.execute(stmt)
|
|
38
|
+
except Exception as exc: # pragma: no cover - old sqlite
|
|
39
|
+
raise RuntimeError(
|
|
40
|
+
"this sqlite has no FTS5 trigram tokenizer (%s); batonpass find needs "
|
|
41
|
+
"sqlite >= 3.34" % exc)
|
|
42
|
+
conn.commit()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _clip(text: str) -> str:
|
|
46
|
+
text = clean(text or "")
|
|
47
|
+
if len(text) <= MAX_DOC_CHARS:
|
|
48
|
+
return text
|
|
49
|
+
head = MAX_DOC_CHARS * 2 // 3
|
|
50
|
+
return text[:head] + "\n…\n" + text[-MAX_DOC_CHARS // 3:]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def build(conn, force: bool = False, limit: int = None, progress=None) -> dict:
|
|
54
|
+
ensure(conn)
|
|
55
|
+
codecs = Codecs(conn)
|
|
56
|
+
if force:
|
|
57
|
+
conn.execute("DELETE FROM search_fts")
|
|
58
|
+
conn.execute("DELETE FROM search_state")
|
|
59
|
+
conn.commit()
|
|
60
|
+
|
|
61
|
+
stats = {"docs": 0, "sessions": 0, "skipped": 0}
|
|
62
|
+
sessions = conn.execute(
|
|
63
|
+
"SELECT sid, source, title, project_key FROM session").fetchall()
|
|
64
|
+
for s in sessions:
|
|
65
|
+
sid, source = s["sid"], s["source"]
|
|
66
|
+
st = conn.execute("SELECT last_seq, ver FROM search_state WHERE sid=?", (sid,)).fetchone()
|
|
67
|
+
last = -1
|
|
68
|
+
if st is not None and st["ver"] == FTS_VER and not force:
|
|
69
|
+
last = st["last_seq"] if st["last_seq"] is not None else -1
|
|
70
|
+
|
|
71
|
+
# The title is one doc, re-written only when it changes: it is the most
|
|
72
|
+
# common way a person names what they are looking for.
|
|
73
|
+
conn.execute("DELETE FROM search_fts WHERE sid=? AND kind='title'", (sid,))
|
|
74
|
+
title = (s["title"] or "").strip()
|
|
75
|
+
label = clean(title) + " " + (s["project_key"] or "")
|
|
76
|
+
if title:
|
|
77
|
+
conn.execute(
|
|
78
|
+
"INSERT INTO search_fts(body,sid,ref,kind,ts) VALUES(?,?,?,?,?)",
|
|
79
|
+
(_clip(label), sid, sid, "title", ""))
|
|
80
|
+
|
|
81
|
+
rows = conn.execute(
|
|
82
|
+
"""SELECT mid, seq, role, text_sha, ts FROM message
|
|
83
|
+
WHERE sid=? AND seq>? AND role IN ('user','assistant','unknown')
|
|
84
|
+
ORDER BY seq LIMIT ?""",
|
|
85
|
+
(sid, last, limit or -1),
|
|
86
|
+
).fetchall()
|
|
87
|
+
for r in rows:
|
|
88
|
+
body = _clip(codecs.get(r["text_sha"], source))
|
|
89
|
+
if body.strip():
|
|
90
|
+
conn.execute(
|
|
91
|
+
"INSERT INTO search_fts(body,sid,ref,kind,ts) VALUES(?,?,?,?,?)",
|
|
92
|
+
(body, sid, r["mid"], r["role"], r["ts"] or ""))
|
|
93
|
+
stats["docs"] += 1
|
|
94
|
+
else:
|
|
95
|
+
stats["skipped"] += 1
|
|
96
|
+
conn.execute(
|
|
97
|
+
"INSERT INTO search_state(sid,last_seq,ver) VALUES(?,?,?) "
|
|
98
|
+
"ON CONFLICT(sid) DO UPDATE SET last_seq=excluded.last_seq, ver=excluded.ver",
|
|
99
|
+
(sid, rows[-1]["seq"] if rows else last, FTS_VER))
|
|
100
|
+
stats["sessions"] += 1
|
|
101
|
+
if progress and stats["sessions"] % 100 == 0:
|
|
102
|
+
progress(stats)
|
|
103
|
+
conn.commit()
|
|
104
|
+
return stats
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def stale(conn) -> dict:
|
|
108
|
+
"""Sessions the index does not describe: never indexed, or behind."""
|
|
109
|
+
missing = conn.execute(
|
|
110
|
+
"SELECT COUNT(*) c FROM session s WHERE s.msg_count > 0 AND NOT EXISTS"
|
|
111
|
+
" (SELECT 1 FROM search_state st WHERE st.sid=s.sid)").fetchone()["c"]
|
|
112
|
+
behind = conn.execute(
|
|
113
|
+
"SELECT COUNT(*) c FROM search_state st WHERE st.ver<>? OR st.last_seq <"
|
|
114
|
+
" (SELECT COALESCE(MAX(seq),-1) FROM message m WHERE m.sid=st.sid)",
|
|
115
|
+
(FTS_VER,)).fetchone()["c"]
|
|
116
|
+
return {"missing": missing, "behind": behind}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def ensure_fresh(conn, progress=None) -> dict:
|
|
120
|
+
"""Tables, plus whatever has arrived since the last build.
|
|
121
|
+
|
|
122
|
+
`find` on a library nobody had indexed used to answer "nothing matched" —
|
|
123
|
+
the worst possible failure, because it is indistinguishable from the truth.
|
|
124
|
+
"""
|
|
125
|
+
ensure(conn)
|
|
126
|
+
counts = stale(conn)
|
|
127
|
+
if counts["missing"] or counts["behind"]:
|
|
128
|
+
return build(conn, progress=progress)
|
|
129
|
+
return {"docs": 0, "sessions": 0, "skipped": 0, "up_to_date": True}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def size_bytes(conn) -> int:
|
|
133
|
+
try:
|
|
134
|
+
row = conn.execute(
|
|
135
|
+
"SELECT SUM(pgsize) p FROM dbstat WHERE name LIKE 'search_fts%'").fetchone()
|
|
136
|
+
return int(row["p"] or 0)
|
|
137
|
+
except Exception:
|
|
138
|
+
return 0
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def stats(conn) -> dict:
|
|
142
|
+
ensure(conn)
|
|
143
|
+
n = conn.execute("SELECT count(*) c FROM search_fts").fetchone()["c"]
|
|
144
|
+
indexed = conn.execute("SELECT count(*) c FROM search_state").fetchone()["c"]
|
|
145
|
+
total = conn.execute("SELECT count(*) c FROM session").fetchone()["c"]
|
|
146
|
+
return {"docs": n, "sessions_indexed": indexed, "sessions_total": total,
|
|
147
|
+
"bytes": size_bytes(conn), "ver": FTS_VER}
|