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
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""Finding the thing you half-remember.
|
|
2
|
+
|
|
3
|
+
You will arrive with a vague concept, not a query: "那个岗位表", "the ppt for
|
|
4
|
+
the exam thing", "what was I doing last Tuesday". So a search here is four
|
|
5
|
+
searches — title, project name, filename, message body — fused by reciprocal
|
|
6
|
+
rank, because each one alone fails on a different half of that sentence:
|
|
7
|
+
|
|
8
|
+
title the session was *named* after it
|
|
9
|
+
project the folder was named after it
|
|
10
|
+
file the deliverable was named after it
|
|
11
|
+
body it was only ever mentioned in passing
|
|
12
|
+
|
|
13
|
+
And the silence contract: when nothing matches, return nothing and say so. An
|
|
14
|
+
invented answer to "where is my spreadsheet" costs more than "not found",
|
|
15
|
+
because you would go looking for a file that does not exist.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import re
|
|
21
|
+
from datetime import datetime, timedelta, timezone
|
|
22
|
+
|
|
23
|
+
RRF_K = 60
|
|
24
|
+
SNIPPET_CHARS = 220
|
|
25
|
+
|
|
26
|
+
_REL = re.compile(r"^(\d+)\s*(h|d|w|m|y)$", re.I)
|
|
27
|
+
_DAY = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
|
28
|
+
_MONTH = re.compile(r"^\d{4}-\d{2}$")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _now() -> datetime:
|
|
32
|
+
return datetime.now(timezone.utc)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _iso(d: datetime) -> str:
|
|
36
|
+
return d.strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def parse_window(spec: str):
|
|
40
|
+
"""`7d` `12h` `today` `2026-09` `2026-09-20` `2026-09-01..2026-09-20` -> (since, until)."""
|
|
41
|
+
if not spec:
|
|
42
|
+
return None, None
|
|
43
|
+
s = spec.strip().lower()
|
|
44
|
+
now = _now()
|
|
45
|
+
if s in ("today", "今天"):
|
|
46
|
+
start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
|
47
|
+
return _iso(start), None
|
|
48
|
+
if s in ("yesterday", "昨天"):
|
|
49
|
+
end = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
|
50
|
+
return _iso(end - timedelta(days=1)), _iso(end)
|
|
51
|
+
m = _REL.match(s)
|
|
52
|
+
if m:
|
|
53
|
+
n, unit = int(m.group(1)), m.group(2)
|
|
54
|
+
delta = {"h": timedelta(hours=n), "d": timedelta(days=n), "w": timedelta(weeks=n),
|
|
55
|
+
"m": timedelta(days=30 * n), "y": timedelta(days=365 * n)}[unit]
|
|
56
|
+
return _iso(now - delta), None
|
|
57
|
+
if ".." in s:
|
|
58
|
+
a, _, b = s.partition("..")
|
|
59
|
+
return _bound(a, end=False), _bound(b, end=True)
|
|
60
|
+
if _MONTH.match(s):
|
|
61
|
+
y, mo = int(s[:4]), int(s[5:7])
|
|
62
|
+
start = datetime(y, mo, 1, tzinfo=timezone.utc)
|
|
63
|
+
end = datetime(y + (mo == 12), (mo % 12) + 1, 1, tzinfo=timezone.utc)
|
|
64
|
+
return _iso(start), _iso(end)
|
|
65
|
+
if _DAY.match(s):
|
|
66
|
+
return _bound(s, end=False), _bound(s, end=True)
|
|
67
|
+
return None, None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _bound(text: str, end: bool):
|
|
71
|
+
text = text.strip()
|
|
72
|
+
try:
|
|
73
|
+
if _DAY.match(text):
|
|
74
|
+
d = datetime.strptime(text, "%Y-%m-%d").replace(tzinfo=timezone.utc)
|
|
75
|
+
return _iso(d + timedelta(days=1) if end else d)
|
|
76
|
+
if _MONTH.match(text):
|
|
77
|
+
y, mo = int(text[:4]), int(text[5:7])
|
|
78
|
+
if end:
|
|
79
|
+
return _iso(datetime(y + (mo == 12), (mo % 12) + 1, 1, tzinfo=timezone.utc))
|
|
80
|
+
return _iso(datetime(y, mo, 1, tzinfo=timezone.utc))
|
|
81
|
+
except ValueError:
|
|
82
|
+
return None
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _like(term: str) -> str:
|
|
87
|
+
return "%" + term.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _fts_phrase(q: str) -> str:
|
|
91
|
+
"""Trigram MATCH wants a plain phrase; the user's punctuation is not syntax."""
|
|
92
|
+
return '"%s"' % q.replace('"', " ")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _snippet(body: str, q: str) -> str:
|
|
96
|
+
body = " ".join((body or "").split())
|
|
97
|
+
idx = body.lower().find(q.lower())
|
|
98
|
+
if idx < 0:
|
|
99
|
+
return body[:SNIPPET_CHARS] + ("…" if len(body) > SNIPPET_CHARS else "")
|
|
100
|
+
start = max(0, idx - SNIPPET_CHARS // 3)
|
|
101
|
+
end = min(len(body), start + SNIPPET_CHARS)
|
|
102
|
+
return ("…" if start else "") + body[start:end] + ("…" if end < len(body) else "")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _session_filters(at, project, device):
|
|
106
|
+
where, args = [], []
|
|
107
|
+
since, until = parse_window(at) if at else (None, None)
|
|
108
|
+
if since:
|
|
109
|
+
where.append("COALESCE(updated_at,'') >= ?")
|
|
110
|
+
args.append(since)
|
|
111
|
+
if until:
|
|
112
|
+
where.append("COALESCE(updated_at,'') < ?")
|
|
113
|
+
args.append(until)
|
|
114
|
+
if project:
|
|
115
|
+
where.append("(project_key LIKE ? ESCAPE '\\' OR cwd LIKE ? ESCAPE '\\')")
|
|
116
|
+
args += [_like(project), _like(project)]
|
|
117
|
+
if device:
|
|
118
|
+
where.append("device = ?")
|
|
119
|
+
args.append(device)
|
|
120
|
+
return (" AND " + " AND ".join(where)) if where else "", args
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def search(conn, q: str, at: str = None, project: str = None, device: str = None,
|
|
124
|
+
limit: int = 5, explain: bool = False) -> list:
|
|
125
|
+
"""Return ranked sessions. Empty list is a valid, honest answer."""
|
|
126
|
+
q = (q or "").strip()
|
|
127
|
+
if len(q) < 2:
|
|
128
|
+
return []
|
|
129
|
+
clauses, cargs = _session_filters(at, project, device)
|
|
130
|
+
allowed = {r["sid"] for r in conn.execute(
|
|
131
|
+
"SELECT sid FROM session WHERE 1=1" + clauses, cargs)}
|
|
132
|
+
if not allowed:
|
|
133
|
+
return []
|
|
134
|
+
|
|
135
|
+
lists = {}
|
|
136
|
+
# ① the session was named after it
|
|
137
|
+
rows = conn.execute(
|
|
138
|
+
"SELECT sid FROM search_fts WHERE kind='title' AND body LIKE ? ESCAPE '\\' "
|
|
139
|
+
"ORDER BY rank LIMIT 40", (_like(q),)).fetchall()
|
|
140
|
+
lists["title"] = [r["sid"] for r in rows]
|
|
141
|
+
# ② the folder was named after it
|
|
142
|
+
rows = conn.execute(
|
|
143
|
+
"SELECT sid FROM session WHERE project_key LIKE ? ESCAPE '\\' "
|
|
144
|
+
"ORDER BY COALESCE(updated_at,'') DESC LIMIT 40", (_like(q),)).fetchall()
|
|
145
|
+
lists["project"] = [r["sid"] for r in rows]
|
|
146
|
+
# ③ the deliverable was named after it
|
|
147
|
+
rows = conn.execute(
|
|
148
|
+
"SELECT sid FROM session WHERE artifact_refs LIKE ? ESCAPE '\\' "
|
|
149
|
+
"ORDER BY COALESCE(updated_at,'') DESC LIMIT 40", (_like(q),)).fetchall()
|
|
150
|
+
lists["file"] = [r["sid"] for r in rows]
|
|
151
|
+
# ④ it was only ever mentioned in passing
|
|
152
|
+
if len(q) >= 3:
|
|
153
|
+
try:
|
|
154
|
+
rows = conn.execute(
|
|
155
|
+
"SELECT sid FROM search_fts WHERE kind<>'title' AND search_fts MATCH ? "
|
|
156
|
+
"ORDER BY rank LIMIT 60", (_fts_phrase(q),)).fetchall()
|
|
157
|
+
except Exception:
|
|
158
|
+
rows = []
|
|
159
|
+
else:
|
|
160
|
+
rows = conn.execute(
|
|
161
|
+
"SELECT sid FROM search_fts WHERE kind<>'title' AND body LIKE ? ESCAPE '\\' "
|
|
162
|
+
"ORDER BY rank LIMIT 60", (_like(q),)).fetchall()
|
|
163
|
+
lists["body"] = [r["sid"] for r in rows]
|
|
164
|
+
|
|
165
|
+
scores, why = {}, {}
|
|
166
|
+
for name, sids in lists.items():
|
|
167
|
+
seen = set()
|
|
168
|
+
for rank, sid in enumerate(sids):
|
|
169
|
+
if sid not in allowed or sid in seen:
|
|
170
|
+
continue
|
|
171
|
+
seen.add(sid)
|
|
172
|
+
scores[sid] = scores.get(sid, 0.0) + 1.0 / (RRF_K + rank + 1)
|
|
173
|
+
why.setdefault(sid, []).append(name)
|
|
174
|
+
|
|
175
|
+
if not scores:
|
|
176
|
+
return []
|
|
177
|
+
|
|
178
|
+
top = sorted(scores.items(), key=lambda kv: -kv[1])[:max(limit, 1)]
|
|
179
|
+
out = []
|
|
180
|
+
for sid, score in top:
|
|
181
|
+
s = conn.execute(
|
|
182
|
+
"""SELECT sid, source, device, title, project_key, cwd, updated_at,
|
|
183
|
+
msg_count FROM session WHERE sid=?""", (sid,)).fetchone()
|
|
184
|
+
if s is None:
|
|
185
|
+
continue
|
|
186
|
+
body, ts = "", ""
|
|
187
|
+
try:
|
|
188
|
+
r = conn.execute(
|
|
189
|
+
"SELECT body, ts FROM search_fts WHERE sid=? AND kind<>'title' "
|
|
190
|
+
"AND search_fts MATCH ? ORDER BY rank LIMIT 1",
|
|
191
|
+
(sid, _fts_phrase(q))).fetchone()
|
|
192
|
+
if r:
|
|
193
|
+
body, ts = r["body"], r["ts"] or ""
|
|
194
|
+
except Exception:
|
|
195
|
+
pass
|
|
196
|
+
if not body:
|
|
197
|
+
r = conn.execute("SELECT body FROM search_fts WHERE sid=? AND kind='title' LIMIT 1",
|
|
198
|
+
(sid,)).fetchone()
|
|
199
|
+
body = r["body"] if r else ""
|
|
200
|
+
item = {
|
|
201
|
+
"sid": sid,
|
|
202
|
+
"title": (s["title"] or "").strip(),
|
|
203
|
+
"project": s["project_key"] or "",
|
|
204
|
+
"device": s["device"] or "",
|
|
205
|
+
"source": s["source"] or "",
|
|
206
|
+
"updated_at": s["updated_at"] or "",
|
|
207
|
+
"score": round(score, 5),
|
|
208
|
+
"snippet": _snippet(body, q),
|
|
209
|
+
"snippet_at": ts,
|
|
210
|
+
"messages": s["msg_count"] or 0,
|
|
211
|
+
}
|
|
212
|
+
if explain:
|
|
213
|
+
item["why"] = why.get(sid, [])
|
|
214
|
+
out.append(item)
|
|
215
|
+
return out
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
from .db import connect, source_ro, file_signature, get_meta, set_meta
|
|
2
|
+
from .content import Codec, sha256_text, get_content, put_content, HAVE_ZSTD
|
|
3
|
+
|
|
4
|
+
__all__ = ["connect", "source_ro", "file_signature", "get_meta", "set_meta",
|
|
5
|
+
"Codec", "sha256_text", "get_content", "put_content", "HAVE_ZSTD"]
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""One codec per source, resolved lazily.
|
|
2
|
+
|
|
3
|
+
Every source gets its own compression dictionary because the training data is
|
|
4
|
+
its own history — a zcode dictionary does nothing for billion-context rows and
|
|
5
|
+
vice versa. Readers therefore cannot pick a codec out of the air; they have to
|
|
6
|
+
ask which source a row came from first. This object is that "ask once, cache
|
|
7
|
+
forever" cache, so callers stop rediscovering it.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from .content import Codec, get_content, get_dict
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Codecs:
|
|
16
|
+
def __init__(self, conn):
|
|
17
|
+
self.conn = conn
|
|
18
|
+
self._cache = {}
|
|
19
|
+
|
|
20
|
+
def for_source(self, source: str) -> Codec:
|
|
21
|
+
key = source or ""
|
|
22
|
+
codec = self._cache.get(key)
|
|
23
|
+
if codec is None:
|
|
24
|
+
codec = Codec(get_dict(self.conn, key))
|
|
25
|
+
self._cache[key] = codec
|
|
26
|
+
return codec
|
|
27
|
+
|
|
28
|
+
def get(self, sha: str, source: str) -> str:
|
|
29
|
+
if not sha:
|
|
30
|
+
return ""
|
|
31
|
+
return get_content(self.conn, sha, self.for_source(source))
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Content-addressed compressed text.
|
|
2
|
+
|
|
3
|
+
Three decisions worth writing down:
|
|
4
|
+
|
|
5
|
+
1. The key is sha256 of the plaintext. The codec lives in its own column, so
|
|
6
|
+
swapping zstd for lzma (or for 3.14's stdlib zstd) never invalidates a
|
|
7
|
+
library that already exists.
|
|
8
|
+
2. Identical text is stored once. The sources are full of duplicates.
|
|
9
|
+
3. Foreign blobs may be several concatenated zstd frames. Decoding only the
|
|
10
|
+
first silently loses the tail, so decode_all() walks the unused_data.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import bz2
|
|
16
|
+
import gzip
|
|
17
|
+
import hashlib
|
|
18
|
+
import lzma
|
|
19
|
+
import sqlite3
|
|
20
|
+
|
|
21
|
+
try:
|
|
22
|
+
import zstandard as _zstd
|
|
23
|
+
HAVE_ZSTD = True
|
|
24
|
+
except Exception: # pragma: no cover
|
|
25
|
+
_zstd = None
|
|
26
|
+
HAVE_ZSTD = False
|
|
27
|
+
|
|
28
|
+
ZSTD_MAGIC = b"\x28\xb5\x2f\xfd"
|
|
29
|
+
DICT_SIZE = 112_640
|
|
30
|
+
LEVEL = 19
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def sha256_bytes(data: bytes) -> str:
|
|
34
|
+
return hashlib.sha256(data).hexdigest()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def sha256_text(text: str) -> str:
|
|
38
|
+
return sha256_bytes(text.encode("utf-8"))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def short(*parts) -> str:
|
|
42
|
+
return sha256_text("|".join(str(p) for p in parts))[:32]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
# ── dictionary ──────────────────────────────────────────────────
|
|
46
|
+
|
|
47
|
+
def train_dict(samples, size=DICT_SIZE):
|
|
48
|
+
if not HAVE_ZSTD:
|
|
49
|
+
return None
|
|
50
|
+
uniq, seen = [], set()
|
|
51
|
+
for s in samples:
|
|
52
|
+
if not s or len(s) < 8:
|
|
53
|
+
continue
|
|
54
|
+
h = sha256_bytes(s)
|
|
55
|
+
if h in seen:
|
|
56
|
+
continue
|
|
57
|
+
seen.add(h)
|
|
58
|
+
uniq.append(bytes(s))
|
|
59
|
+
if len(uniq) >= 3000:
|
|
60
|
+
break
|
|
61
|
+
if len(uniq) < 8:
|
|
62
|
+
return None
|
|
63
|
+
try:
|
|
64
|
+
return _zstd.train_dictionary(size, uniq).as_bytes()
|
|
65
|
+
except Exception:
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Codec:
|
|
70
|
+
def __init__(self, dict_bytes=None):
|
|
71
|
+
self.dict_bytes = dict_bytes
|
|
72
|
+
self._c = self._d = None
|
|
73
|
+
if HAVE_ZSTD:
|
|
74
|
+
try:
|
|
75
|
+
dd = _zstd.ZstdCompressionDict(dict_bytes) if dict_bytes else None
|
|
76
|
+
kw = {"level": LEVEL}
|
|
77
|
+
if dd:
|
|
78
|
+
kw["dict_data"] = dd
|
|
79
|
+
self._c = _zstd.ZstdCompressor(**kw)
|
|
80
|
+
self._d = _zstd.ZstdDecompressor(dict_data=dd) if dd else _zstd.ZstdDecompressor()
|
|
81
|
+
except Exception:
|
|
82
|
+
self._c = self._d = None
|
|
83
|
+
if self._c is not None:
|
|
84
|
+
self.name = "zstd19+dict" if dict_bytes else "zstd19"
|
|
85
|
+
else:
|
|
86
|
+
self.name = "lzma6"
|
|
87
|
+
|
|
88
|
+
def compress(self, data: bytes):
|
|
89
|
+
if self._c is not None:
|
|
90
|
+
try:
|
|
91
|
+
return self._c.compress(data), self.name
|
|
92
|
+
except Exception:
|
|
93
|
+
pass
|
|
94
|
+
return lzma.compress(data, preset=6), "lzma6"
|
|
95
|
+
|
|
96
|
+
def decompress(self, blob: bytes, codec: str) -> bytes:
|
|
97
|
+
if not blob:
|
|
98
|
+
return b""
|
|
99
|
+
if codec.startswith("zstd"):
|
|
100
|
+
if not HAVE_ZSTD:
|
|
101
|
+
raise RuntimeError("library needs zstandard installed to read: pip install zstandard")
|
|
102
|
+
return decode_all(blob, self._d)
|
|
103
|
+
if codec.startswith("lzma"):
|
|
104
|
+
return lzma.decompress(blob)
|
|
105
|
+
if codec == "none":
|
|
106
|
+
return blob
|
|
107
|
+
raise ValueError("unknown codec %r" % codec)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def decode_all(blob: bytes, dctx=None) -> bytes:
|
|
111
|
+
"""Decompress one or more concatenated zstd frames."""
|
|
112
|
+
dctx = dctx or _zstd.ZstdDecompressor()
|
|
113
|
+
out, data = bytearray(), blob
|
|
114
|
+
while data:
|
|
115
|
+
obj = dctx.decompressobj()
|
|
116
|
+
out += obj.decompress(data)
|
|
117
|
+
rest = obj.unused_data
|
|
118
|
+
if not rest or rest == data:
|
|
119
|
+
break
|
|
120
|
+
data = rest
|
|
121
|
+
return bytes(out)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def sniff_and_decode(blob: bytes) -> tuple[bytes, str]:
|
|
125
|
+
"""Decode a foreign blob by magic bytes — never trust a column called `algo`."""
|
|
126
|
+
if blob[:4] == ZSTD_MAGIC:
|
|
127
|
+
if not HAVE_ZSTD:
|
|
128
|
+
return blob, "zstd-unavailable"
|
|
129
|
+
try:
|
|
130
|
+
return decode_all(blob), "zstd"
|
|
131
|
+
except Exception:
|
|
132
|
+
return blob, "zstd-failed"
|
|
133
|
+
if blob[:2] == b"\x1f\x8b":
|
|
134
|
+
try:
|
|
135
|
+
return gzip.decompress(blob), "gzip"
|
|
136
|
+
except Exception:
|
|
137
|
+
return blob, "gzip-failed"
|
|
138
|
+
if blob[:3] == b"BZh":
|
|
139
|
+
try:
|
|
140
|
+
return bz2.decompress(blob), "bzip2"
|
|
141
|
+
except Exception:
|
|
142
|
+
return blob, "bzip2-failed"
|
|
143
|
+
return blob, "plain"
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# ── storage ─────────────────────────────────────────────────────
|
|
147
|
+
|
|
148
|
+
def put_content(conn: sqlite3.Connection, text, codec: Codec) -> tuple[str, bool]:
|
|
149
|
+
"""Store text once, bumping refcount on repeats. Returns (sha, was_new)."""
|
|
150
|
+
if text is None:
|
|
151
|
+
return "", False
|
|
152
|
+
data = text.encode("utf-8", "replace") if isinstance(text, str) else bytes(text)
|
|
153
|
+
sha = sha256_bytes(data)
|
|
154
|
+
row = conn.execute("SELECT 1 FROM content WHERE sha256=?", (sha,)).fetchone()
|
|
155
|
+
if row:
|
|
156
|
+
conn.execute("UPDATE content SET refcount=refcount+1 WHERE sha256=?", (sha,))
|
|
157
|
+
return sha, False
|
|
158
|
+
body, cname = codec.compress(data)
|
|
159
|
+
conn.execute("INSERT INTO content(sha256,byte_len,refcount,codec,body) VALUES(?,?,?,?,?)",
|
|
160
|
+
(sha, len(data), 1, cname, body))
|
|
161
|
+
return sha, True
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def get_content(conn: sqlite3.Connection, sha: str, codec: Codec) -> str:
|
|
165
|
+
if not sha:
|
|
166
|
+
return ""
|
|
167
|
+
row = conn.execute("SELECT body,codec FROM content WHERE sha256=?", (sha,)).fetchone()
|
|
168
|
+
if row is None:
|
|
169
|
+
return ""
|
|
170
|
+
return codec.decompress(row["body"], row["codec"]).decode("utf-8", "replace")
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def get_dict(conn, adapter: str):
|
|
174
|
+
from .db import get_meta
|
|
175
|
+
hexed = get_meta(conn, "dict:" + adapter)
|
|
176
|
+
if not hexed:
|
|
177
|
+
return None
|
|
178
|
+
try:
|
|
179
|
+
return bytes.fromhex(hexed)
|
|
180
|
+
except ValueError:
|
|
181
|
+
return None
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def save_dict(conn, adapter: str, data: bytes) -> None:
|
|
185
|
+
from .db import set_meta
|
|
186
|
+
set_meta(conn, "dict:" + adapter, data.hex())
|
batonpass/store/db.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Connections.
|
|
2
|
+
|
|
3
|
+
Two kinds, with a hard wall between them:
|
|
4
|
+
connect() our library, read-write
|
|
5
|
+
source_ro() somebody else's database, read-only, no escape hatch
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import sqlite3
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from ..paths import db_path
|
|
16
|
+
from .schema import DDL, SCHEMA_VERSION
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def connect(path=None) -> sqlite3.Connection:
|
|
20
|
+
p = db_path(path)
|
|
21
|
+
Path(p).parent.mkdir(parents=True, exist_ok=True)
|
|
22
|
+
conn = sqlite3.connect(str(p))
|
|
23
|
+
conn.row_factory = sqlite3.Row
|
|
24
|
+
conn.execute("PRAGMA journal_mode=WAL")
|
|
25
|
+
conn.execute("PRAGMA synchronous=NORMAL")
|
|
26
|
+
conn.execute("PRAGMA busy_timeout=5000")
|
|
27
|
+
for stmt in DDL:
|
|
28
|
+
conn.execute(stmt)
|
|
29
|
+
stored = get_meta(conn, "schema_version")
|
|
30
|
+
if stored is None:
|
|
31
|
+
set_meta(conn, "schema_version", str(SCHEMA_VERSION))
|
|
32
|
+
elif stored.isdigit() and int(stored) < SCHEMA_VERSION:
|
|
33
|
+
# Every upgrade so far has been additive, and the DDL above has just
|
|
34
|
+
# run with IF NOT EXISTS — so the library is already at this version.
|
|
35
|
+
set_meta(conn, "schema_version", str(SCHEMA_VERSION))
|
|
36
|
+
conn.commit()
|
|
37
|
+
return conn
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def source_ro(path):
|
|
41
|
+
"""Open a source strictly read-only. Returns (conn, mode)."""
|
|
42
|
+
for uri, mode in (("file:%s?mode=ro" % path, "readonly"),
|
|
43
|
+
("file:%s?mode=ro&immutable=1" % path, "readonly-immutable")):
|
|
44
|
+
try:
|
|
45
|
+
conn = sqlite3.connect(uri, uri=True, timeout=10)
|
|
46
|
+
conn.row_factory = sqlite3.Row
|
|
47
|
+
conn.execute("SELECT count(*) FROM sqlite_master").fetchone()
|
|
48
|
+
return conn, mode
|
|
49
|
+
except sqlite3.OperationalError:
|
|
50
|
+
continue
|
|
51
|
+
raise sqlite3.OperationalError("cannot open %s read-only" % path)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def set_meta(conn, key, value) -> None:
|
|
55
|
+
conn.execute("INSERT INTO meta(key,value) VALUES(?,?) "
|
|
56
|
+
"ON CONFLICT(key) DO UPDATE SET value=excluded.value", (key, value))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def get_meta(conn, key, default=None):
|
|
60
|
+
try:
|
|
61
|
+
row = conn.execute("SELECT value FROM meta WHERE key=?", (key,)).fetchone()
|
|
62
|
+
except sqlite3.OperationalError:
|
|
63
|
+
return default
|
|
64
|
+
return row[0] if row else default
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def file_signature(path) -> dict:
|
|
68
|
+
"""Size+mtime of the database and its sidecars — the read-only receipt.
|
|
69
|
+
|
|
70
|
+
Kept as separate keys on purpose. The main file must not move while we read
|
|
71
|
+
it; the -wal file legitimately does when the *owning application* is running
|
|
72
|
+
(Alma writes its chat log while the user is chatting). Treating those two as
|
|
73
|
+
one fingerprint produces a false "source changed" alarm on every live source.
|
|
74
|
+
"""
|
|
75
|
+
out = {}
|
|
76
|
+
for suffix, key in (("", "main"), ("-wal", "wal"), ("-shm", "shm")):
|
|
77
|
+
try:
|
|
78
|
+
st = Path(str(path) + suffix).stat()
|
|
79
|
+
out[key] = "%d:%d" % (st.st_size, st.st_mtime_ns)
|
|
80
|
+
except OSError:
|
|
81
|
+
out[key] = None
|
|
82
|
+
return out
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def dumps(obj) -> str:
|
|
86
|
+
return json.dumps(obj, ensure_ascii=False, separators=(",", ":"), default=str)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class Timer:
|
|
90
|
+
def __init__(self):
|
|
91
|
+
self.t0 = time.time()
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def done(self) -> float:
|
|
95
|
+
return time.time() - self.t0
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Schema, version 2.
|
|
2
|
+
|
|
3
|
+
raw_* append-only compressed source payloads — the parser's undo button.
|
|
4
|
+
content content-addressed plaintext, refcounted.
|
|
5
|
+
session/message/part the canonical model, rebuildable from raw at any time.
|
|
6
|
+
sync_state local bookkeeping: how far this library has pushed/pulled.
|
|
7
|
+
session_head the summary layer, so a new machine is useful before it
|
|
8
|
+
has a single message row.
|
|
9
|
+
|
|
10
|
+
1 → 2 is additive: two new tables, no column changed, so the DDL alone upgrades
|
|
11
|
+
an existing library and no migration pass is needed.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
SCHEMA_VERSION = 2
|
|
17
|
+
|
|
18
|
+
DDL = [
|
|
19
|
+
"""
|
|
20
|
+
CREATE TABLE IF NOT EXISTS raw_source (
|
|
21
|
+
source_sha TEXT PRIMARY KEY,
|
|
22
|
+
device TEXT NOT NULL,
|
|
23
|
+
adapter TEXT NOT NULL,
|
|
24
|
+
adapter_ver TEXT NOT NULL,
|
|
25
|
+
path TEXT,
|
|
26
|
+
bytes INTEGER,
|
|
27
|
+
first_seen TEXT NOT NULL
|
|
28
|
+
)
|
|
29
|
+
""",
|
|
30
|
+
"""
|
|
31
|
+
CREATE TABLE IF NOT EXISTS raw_record (
|
|
32
|
+
id INTEGER PRIMARY KEY,
|
|
33
|
+
source_sha TEXT NOT NULL REFERENCES raw_source(source_sha),
|
|
34
|
+
seq INTEGER NOT NULL,
|
|
35
|
+
kind TEXT NOT NULL,
|
|
36
|
+
payload BLOB,
|
|
37
|
+
payload_sha TEXT NOT NULL,
|
|
38
|
+
codec TEXT NOT NULL DEFAULT 'none',
|
|
39
|
+
UNIQUE(source_sha, seq, kind)
|
|
40
|
+
)
|
|
41
|
+
""",
|
|
42
|
+
"CREATE INDEX IF NOT EXISTS raw_record_sha ON raw_record(payload_sha)",
|
|
43
|
+
"""
|
|
44
|
+
CREATE TABLE IF NOT EXISTS content (
|
|
45
|
+
sha256 TEXT PRIMARY KEY,
|
|
46
|
+
byte_len INTEGER NOT NULL,
|
|
47
|
+
refcount INTEGER NOT NULL DEFAULT 1,
|
|
48
|
+
codec TEXT NOT NULL DEFAULT 'none',
|
|
49
|
+
body BLOB NOT NULL
|
|
50
|
+
)
|
|
51
|
+
""",
|
|
52
|
+
"""
|
|
53
|
+
CREATE TABLE IF NOT EXISTS session (
|
|
54
|
+
sid TEXT PRIMARY KEY,
|
|
55
|
+
source TEXT NOT NULL,
|
|
56
|
+
source_sid TEXT NOT NULL,
|
|
57
|
+
device TEXT NOT NULL,
|
|
58
|
+
project_key TEXT,
|
|
59
|
+
project_key_tier INTEGER,
|
|
60
|
+
cwd TEXT,
|
|
61
|
+
title TEXT,
|
|
62
|
+
created_at TEXT,
|
|
63
|
+
updated_at TEXT,
|
|
64
|
+
msg_count INTEGER DEFAULT 0,
|
|
65
|
+
first_msg_at TEXT,
|
|
66
|
+
last_msg_at TEXT,
|
|
67
|
+
forked_from TEXT,
|
|
68
|
+
artifact_refs TEXT,
|
|
69
|
+
adapter_ver TEXT,
|
|
70
|
+
content_hash TEXT,
|
|
71
|
+
UNIQUE(source, source_sid, device)
|
|
72
|
+
)
|
|
73
|
+
""",
|
|
74
|
+
"""
|
|
75
|
+
CREATE TABLE IF NOT EXISTS message (
|
|
76
|
+
mid TEXT PRIMARY KEY,
|
|
77
|
+
sid TEXT NOT NULL REFERENCES session(sid),
|
|
78
|
+
seq INTEGER NOT NULL,
|
|
79
|
+
role TEXT NOT NULL,
|
|
80
|
+
text_sha TEXT,
|
|
81
|
+
model TEXT,
|
|
82
|
+
ts TEXT,
|
|
83
|
+
meta_json TEXT,
|
|
84
|
+
UNIQUE(sid, seq)
|
|
85
|
+
)
|
|
86
|
+
""",
|
|
87
|
+
# no separate indexes on (sid,seq) / (mid,seq): the UNIQUE constraints
|
|
88
|
+
# already create exactly those b-trees. Measured on a 745k-row library the
|
|
89
|
+
# redundant copies cost 35 MB and speed nothing up.
|
|
90
|
+
"""
|
|
91
|
+
CREATE TABLE IF NOT EXISTS part (
|
|
92
|
+
pid TEXT PRIMARY KEY,
|
|
93
|
+
mid TEXT NOT NULL REFERENCES message(mid),
|
|
94
|
+
seq INTEGER NOT NULL,
|
|
95
|
+
kind TEXT NOT NULL,
|
|
96
|
+
name TEXT,
|
|
97
|
+
args_sha TEXT,
|
|
98
|
+
result_sha TEXT,
|
|
99
|
+
is_error INTEGER DEFAULT 0,
|
|
100
|
+
ts TEXT,
|
|
101
|
+
UNIQUE(mid, seq)
|
|
102
|
+
)
|
|
103
|
+
""",
|
|
104
|
+
|
|
105
|
+
"""
|
|
106
|
+
CREATE TABLE IF NOT EXISTS task (
|
|
107
|
+
tid TEXT PRIMARY KEY,
|
|
108
|
+
project_key TEXT NOT NULL,
|
|
109
|
+
title TEXT NOT NULL,
|
|
110
|
+
created_at TEXT NOT NULL,
|
|
111
|
+
UNIQUE(project_key, title)
|
|
112
|
+
)
|
|
113
|
+
""",
|
|
114
|
+
"""
|
|
115
|
+
CREATE TABLE IF NOT EXISTS task_event (
|
|
116
|
+
eid TEXT PRIMARY KEY,
|
|
117
|
+
tid TEXT NOT NULL REFERENCES task(tid),
|
|
118
|
+
device TEXT NOT NULL,
|
|
119
|
+
lamport INTEGER NOT NULL,
|
|
120
|
+
kind TEXT NOT NULL,
|
|
121
|
+
body TEXT,
|
|
122
|
+
refs_json TEXT,
|
|
123
|
+
created_at TEXT NOT NULL
|
|
124
|
+
)
|
|
125
|
+
""",
|
|
126
|
+
"CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT)",
|
|
127
|
+
|
|
128
|
+
# How far this library has pushed to / pulled from each channel. Local
|
|
129
|
+
# bookkeeping only — never itself synced, because it describes *this*
|
|
130
|
+
# machine's progress, not the data.
|
|
131
|
+
"""
|
|
132
|
+
CREATE TABLE IF NOT EXISTS sync_state (
|
|
133
|
+
channel TEXT NOT NULL,
|
|
134
|
+
key TEXT NOT NULL,
|
|
135
|
+
value TEXT,
|
|
136
|
+
PRIMARY KEY (channel, key)
|
|
137
|
+
)
|
|
138
|
+
""",
|
|
139
|
+
|
|
140
|
+
# The summary layer, stored apart from `session` so that tier-1 can be
|
|
141
|
+
# pulled and read without touching a single message row.
|
|
142
|
+
"""
|
|
143
|
+
CREATE TABLE IF NOT EXISTS session_head (
|
|
144
|
+
sid TEXT PRIMARY KEY,
|
|
145
|
+
device TEXT,
|
|
146
|
+
one_line TEXT,
|
|
147
|
+
head_json TEXT,
|
|
148
|
+
msg_total INTEGER DEFAULT 0,
|
|
149
|
+
updated_at TEXT
|
|
150
|
+
)
|
|
151
|
+
""",
|
|
152
|
+
]
|