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,71 @@
|
|
|
1
|
+
"""Getting things back out.
|
|
2
|
+
|
|
3
|
+
The point of the raw layer is that it can be replayed. The point of `export` is
|
|
4
|
+
that you can prove it in one command: dump a session as plain text and diff it
|
|
5
|
+
against the source database with your own tools.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
|
|
12
|
+
from ..store.content import Codec, get_content, get_dict
|
|
13
|
+
from ..store.db import connect
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def export_session(sid, db=None, as_json=True):
|
|
17
|
+
conn = connect(db)
|
|
18
|
+
row = conn.execute("SELECT * FROM session WHERE sid LIKE ?||'%'", (sid,)).fetchone()
|
|
19
|
+
if row is None:
|
|
20
|
+
raise SystemExit("no session matching %r" % sid)
|
|
21
|
+
codec = Codec(get_dict(conn, row["source"]))
|
|
22
|
+
msgs = []
|
|
23
|
+
for m in conn.execute("SELECT * FROM message WHERE sid=? ORDER BY seq", (row["sid"],)):
|
|
24
|
+
parts = []
|
|
25
|
+
for p in conn.execute("SELECT * FROM part WHERE mid=? ORDER BY seq", (m["mid"],)):
|
|
26
|
+
parts.append({
|
|
27
|
+
"kind": p["kind"], "name": p["name"],
|
|
28
|
+
"args": get_content(conn, p["args_sha"], codec) or None,
|
|
29
|
+
"result": get_content(conn, p["result_sha"], codec) or None,
|
|
30
|
+
"is_error": bool(p["is_error"]), "ts": p["ts"],
|
|
31
|
+
})
|
|
32
|
+
msgs.append({"seq": m["seq"], "role": m["role"], "ts": m["ts"],
|
|
33
|
+
"text": get_content(conn, m["text_sha"], codec), "parts": parts})
|
|
34
|
+
doc = {"sid": row["sid"], "source": row["source"], "source_sid": row["source_sid"],
|
|
35
|
+
"device": row["device"], "title": row["title"], "cwd": row["cwd"],
|
|
36
|
+
"created_at": row["created_at"], "updated_at": row["updated_at"],
|
|
37
|
+
"messages": msgs}
|
|
38
|
+
if as_json:
|
|
39
|
+
return json.dumps(doc, ensure_ascii=False, indent=2, default=str)
|
|
40
|
+
lines = ["# %s" % (row["title"] or row["source_sid"])]
|
|
41
|
+
for m in msgs:
|
|
42
|
+
lines.append("\n## %s %s" % (m["role"], m["ts"] or ""))
|
|
43
|
+
if m["text"]:
|
|
44
|
+
lines.append(m["text"])
|
|
45
|
+
for p in m["parts"]:
|
|
46
|
+
lines.append(" [%s %s] %s" % (p["kind"], p["name"] or "",
|
|
47
|
+
(p["result"] or p["args"] or "").strip()[:400]))
|
|
48
|
+
return "\n".join(lines)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def stats(db=None):
|
|
52
|
+
conn = connect(db)
|
|
53
|
+
q = lambda sql: conn.execute(sql).fetchone()[0]
|
|
54
|
+
plain = q("SELECT COALESCE(sum(byte_len),0) FROM content")
|
|
55
|
+
stored = q("SELECT COALESCE(sum(length(body)),0) FROM content")
|
|
56
|
+
raw = q("SELECT COALESCE(sum(length(payload)),0) FROM raw_record")
|
|
57
|
+
return {
|
|
58
|
+
"sessions": q("SELECT count(*) FROM session"),
|
|
59
|
+
"messages": q("SELECT count(*) FROM message"),
|
|
60
|
+
"parts": q("SELECT count(*) FROM part"),
|
|
61
|
+
"raw_sources": q("SELECT count(*) FROM raw_source"),
|
|
62
|
+
"raw_records": q("SELECT count(*) FROM raw_record"),
|
|
63
|
+
"content_unique": q("SELECT count(*) FROM content"),
|
|
64
|
+
"plain_bytes": plain,
|
|
65
|
+
"stored_bytes": stored,
|
|
66
|
+
"raw_bytes": raw,
|
|
67
|
+
"ratio": round(plain / stored, 2) if stored else 0,
|
|
68
|
+
"db_bytes": q("SELECT page_count*page_size FROM pragma_page_count(), pragma_page_size()"),
|
|
69
|
+
"by_source": [dict(r) for r in conn.execute(
|
|
70
|
+
"SELECT source, count(*) n, sum(msg_count) msgs FROM session GROUP BY source ORDER BY n DESC")],
|
|
71
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Running an archive pass.
|
|
2
|
+
|
|
3
|
+
One source at a time, in its own transaction. A source that blows up is rolled
|
|
4
|
+
back and recorded; the rest of the run continues. Partial success is normal and
|
|
5
|
+
must never look like total failure.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import socket
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
|
|
14
|
+
from ..store.content import Codec, get_dict, save_dict, sha256_bytes, train_dict
|
|
15
|
+
from ..store.db import connect, file_signature, source_ro
|
|
16
|
+
from ..store.write import upsert_raw_source
|
|
17
|
+
from .adapters import ADAPTER_VER, ArchiveResult, get
|
|
18
|
+
from .adapters import _ingest
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def device_name() -> str:
|
|
22
|
+
return os.environ.get("BATONPASS_DEVICE") or socket.gethostname().split(".")[0]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def archive_one(conn_lib, adapter_name, path, device, level=1, dry_run=False, limit=None):
|
|
26
|
+
adapter = get(adapter_name)
|
|
27
|
+
result = ArchiveResult(adapter_name, os.path.abspath(path))
|
|
28
|
+
before = file_signature(path)
|
|
29
|
+
result.bytes_in = os.path.getsize(path)
|
|
30
|
+
result.source_sha = sha256_bytes(("%s|%s|%s" % (adapter_name, result.path,
|
|
31
|
+
before["main"])).encode())
|
|
32
|
+
|
|
33
|
+
if dry_run:
|
|
34
|
+
conn_src, mode = source_ro(path)
|
|
35
|
+
result.readonly_mode = mode
|
|
36
|
+
try:
|
|
37
|
+
ses = list(adapter.sessions(conn_src))
|
|
38
|
+
result.sessions = len(ses)
|
|
39
|
+
result.messages = sum(1 for s in ses for _ in adapter.messages(conn_src, s["source_sid"]))
|
|
40
|
+
finally:
|
|
41
|
+
conn_src.close()
|
|
42
|
+
result.note("dry-run: nothing written")
|
|
43
|
+
return result
|
|
44
|
+
|
|
45
|
+
codec = Codec(get_dict(conn_lib, adapter_name))
|
|
46
|
+
conn_src, mode = source_ro(path)
|
|
47
|
+
result.readonly_mode = mode
|
|
48
|
+
try:
|
|
49
|
+
upsert_raw_source(conn_lib, result.source_sha, device, adapter_name, ADAPTER_VER,
|
|
50
|
+
result.path, result.bytes_in)
|
|
51
|
+
if level >= 3 and not get_dict(conn_lib, adapter_name):
|
|
52
|
+
d = _train_from_source(adapter, conn_src)
|
|
53
|
+
if d:
|
|
54
|
+
save_dict(conn_lib, adapter_name, d)
|
|
55
|
+
codec = Codec(d)
|
|
56
|
+
result.note("trained %d-byte dictionary" % len(d))
|
|
57
|
+
with conn_lib:
|
|
58
|
+
_ingest(conn_lib, result, codec, adapter_name, device, conn_src,
|
|
59
|
+
adapter.sessions(conn_src), adapter.messages,
|
|
60
|
+
limit=limit, level=level)
|
|
61
|
+
except Exception as exc:
|
|
62
|
+
conn_lib.rollback()
|
|
63
|
+
result.errors.append("%s: %s" % (type(exc).__name__, exc))
|
|
64
|
+
finally:
|
|
65
|
+
conn_src.close()
|
|
66
|
+
|
|
67
|
+
after = file_signature(path)
|
|
68
|
+
grew = _size(before["main"]) != _size(after["main"])
|
|
69
|
+
touched = before["main"] != after["main"] or before["wal"] != after["wal"]
|
|
70
|
+
if grew:
|
|
71
|
+
result.errors.append("SOURCE SIZE CHANGED DURING READ (%s -> %s bytes); "
|
|
72
|
+
"re-run to pick up the new rows"
|
|
73
|
+
% (_size(before["main"]), _size(after["main"])))
|
|
74
|
+
elif touched:
|
|
75
|
+
result.note("its app wrote to the file while we read; row counts still reconcile")
|
|
76
|
+
else:
|
|
77
|
+
result.note("source untouched (%s)" % mode)
|
|
78
|
+
return result
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _size(sig):
|
|
82
|
+
return int(str(sig).split(":")[0]) if sig else -1
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _train_from_source(adapter, conn_src):
|
|
86
|
+
samples, n = [], 0
|
|
87
|
+
for s in adapter.sessions(conn_src):
|
|
88
|
+
for m in adapter.messages(conn_src, s["source_sid"]):
|
|
89
|
+
for chunk in (m.get("text"),):
|
|
90
|
+
if chunk and len(chunk) > 32:
|
|
91
|
+
samples.append(chunk.encode()[:4096])
|
|
92
|
+
for p in m.get("parts") or []:
|
|
93
|
+
for chunk in (p.get("args"), p.get("text")):
|
|
94
|
+
if chunk and len(chunk) > 32:
|
|
95
|
+
samples.append(str(chunk).encode()[:4096])
|
|
96
|
+
n += 1
|
|
97
|
+
if n > 4000:
|
|
98
|
+
return train_dict(samples)
|
|
99
|
+
return train_dict(samples)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def run_archive(only=None, level=1, limit=None, db=None, dry_run=False,
|
|
103
|
+
with_identity=True):
|
|
104
|
+
conn = connect(db)
|
|
105
|
+
device = device_name()
|
|
106
|
+
from ..discover import sources as discover_sources
|
|
107
|
+
from .adapters import ADAPTERS as KNOWN
|
|
108
|
+
found = discover_sources()
|
|
109
|
+
wanted = [f for f in found if f.get("adapter") in KNOWN]
|
|
110
|
+
unsupported = sorted({f.get("adapter") for f in found
|
|
111
|
+
if f.get("adapter") and f.get("adapter") not in KNOWN})
|
|
112
|
+
if only:
|
|
113
|
+
names = set(only)
|
|
114
|
+
wanted = [f for f in wanted if f.get("adapter") in names]
|
|
115
|
+
out = {"device": device, "when": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
116
|
+
"sources": [], "totals": {}, "unsupported": unsupported}
|
|
117
|
+
for f in wanted:
|
|
118
|
+
r = archive_one(conn, f["adapter"], f["path"], device, level=level,
|
|
119
|
+
dry_run=dry_run, limit=limit)
|
|
120
|
+
out["sources"].append(r.as_dict())
|
|
121
|
+
for key in ("sessions", "messages", "parts", "raw_records", "new_rows", "skipped"):
|
|
122
|
+
out["totals"][key] = sum(s[key] for s in out["sources"])
|
|
123
|
+
# Identity is derived, so it runs after the append, not inside it: a source
|
|
124
|
+
# that failed to archive must not leave a half-labelled project behind.
|
|
125
|
+
if with_identity and not dry_run:
|
|
126
|
+
from ..identity import build
|
|
127
|
+
out["identity"] = build(conn)
|
|
128
|
+
return out
|