compactlab 0.2.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.
- compactlab/__init__.py +3 -0
- compactlab/adapters/__init__.py +2 -0
- compactlab/adapters/base.py +212 -0
- compactlab/adapters/cache.py +396 -0
- compactlab/adapters/claude_code.py +226 -0
- compactlab/adapters/codex.py +298 -0
- compactlab/adapters/dsh.py +287 -0
- compactlab/adapters/gemini_cli.py +259 -0
- compactlab/adapters/opencode.py +375 -0
- compactlab/apply/__init__.py +582 -0
- compactlab/cli/__init__.py +5 -0
- compactlab/cli/main.py +2436 -0
- compactlab/data/config_knobs.json +158 -0
- compactlab/data/harness_defaults.json +72 -0
- compactlab/data/harness_formats.json +300 -0
- compactlab/data/pricing.json +51 -0
- compactlab/engine/__init__.py +138 -0
- compactlab/engine/live.py +306 -0
- compactlab/engine/settings.py +175 -0
- compactlab/engine/watch.py +82 -0
- compactlab/eval/__init__.py +1 -0
- compactlab/eval/deep.py +390 -0
- compactlab/eval/executors.py +84 -0
- compactlab/eval/factcheck.py +75 -0
- compactlab/lens.py +80 -0
- compactlab/model/__init__.py +285 -0
- compactlab/pricing/__init__.py +211 -0
- compactlab/pricing/auto.py +118 -0
- compactlab/pricing/ids.py +148 -0
- compactlab/pricing/refresh.py +299 -0
- compactlab/publish.py +125 -0
- compactlab/py.typed +0 -0
- compactlab/recommend/__init__.py +201 -0
- compactlab/recommend/claude_code.py +172 -0
- compactlab/recommend/codex.py +104 -0
- compactlab/recommend/dsh.py +89 -0
- compactlab/recommend/gemini_cli.py +85 -0
- compactlab/recommend/opencode.py +117 -0
- compactlab/recommend/units.py +63 -0
- compactlab/report/__init__.py +3 -0
- compactlab/report/html.py +27 -0
- compactlab/report/template.html +1189 -0
- compactlab/service/__init__.py +1 -0
- compactlab/service/core.py +220 -0
- compactlab/service/http.py +133 -0
- compactlab/service/lock.py +92 -0
- compactlab/service/policy.py +258 -0
- compactlab/service/schedule.py +212 -0
- compactlab/share.py +553 -0
- compactlab/sim/__init__.py +1 -0
- compactlab/sim/baseline.py +214 -0
- compactlab/sim/calibrate.py +108 -0
- compactlab/sim/engine.py +1130 -0
- compactlab/sim/select.py +238 -0
- compactlab/sim/timing.py +134 -0
- compactlab/synth.py +416 -0
- compactlab/term/__init__.py +0 -0
- compactlab/term/style.py +134 -0
- compactlab/term/top.py +531 -0
- compactlab/term/views.py +598 -0
- compactlab/term/widgets.py +238 -0
- compactlab/verify.py +462 -0
- compactlab-0.2.0.dist-info/METADATA +243 -0
- compactlab-0.2.0.dist-info/RECORD +67 -0
- compactlab-0.2.0.dist-info/WHEEL +4 -0
- compactlab-0.2.0.dist-info/entry_points.txt +2 -0
- compactlab-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
"""OpenCode adapter (the v1 message store: OpenCode 1.x, checked against 1.19.5 history and the 1.19.6 source).
|
|
2
|
+
|
|
3
|
+
Data: `$XDG_DATA_HOME/opencode` (default `~/.local/share/opencode`, macOS included). Every session of every project
|
|
4
|
+
lives in one SQLite database, `opencode.db` (`opencode-<channel>.db` on non-release channels; the `OPENCODE_DB`
|
|
5
|
+
variable may point elsewhere). It is opened read-only with SQLite's normal locking: a reader in WAL mode never
|
|
6
|
+
blocks OpenCode's writer, and nothing is written. If a read-only connection cannot be opened (no `-shm` file and
|
|
7
|
+
no write access to create one) it falls back to `immutable=1`, which skips changes still in the WAL file.
|
|
8
|
+
|
|
9
|
+
Tables used: `session` (id, parent_id: a subagent run started by the task tool, time_updated in ms), `message`
|
|
10
|
+
(id, session_id, data JSON: role, time.created/completed, providerID/modelID, summary, finish, error) and `part`
|
|
11
|
+
(id, message_id, time_created in ms, data JSON with `type`). One billed request is one step: a `step-start` part,
|
|
12
|
+
then text/reasoning/tool parts, then a `step-finish` part whose `tokens` are DISJOINT: `input` (uncached),
|
|
13
|
+
`cache.read`, `cache.write`, `output` (reasoning excluded) and `reasoning`. A compaction is a user message with a
|
|
14
|
+
`compaction` part (`auto`, `overflow`) answered by an assistant message with `summary: true`; that message's own
|
|
15
|
+
step is the summary call, which is not a turn. A summary that ended with an error or without `finish` is dropped.
|
|
16
|
+
|
|
17
|
+
Not read: sessions stored by the OpenCode 2.x pre-releases (`session_v2`, `session_message`, `session_part`);
|
|
18
|
+
`doctor` counts them. The pre-SQLite JSON store (`storage/message`, `storage/part`) is migrated into the database by
|
|
19
|
+
OpenCode itself on start.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import json
|
|
25
|
+
import sqlite3
|
|
26
|
+
from collections.abc import Iterator
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Any
|
|
29
|
+
from urllib.parse import quote
|
|
30
|
+
|
|
31
|
+
from ..model import Compaction, Session, Turn
|
|
32
|
+
from .base import Adapter, BadRecord, Parser, _bump_error, count, register
|
|
33
|
+
|
|
34
|
+
KNOWN_PARTS = {
|
|
35
|
+
"text",
|
|
36
|
+
"reasoning",
|
|
37
|
+
"file",
|
|
38
|
+
"agent",
|
|
39
|
+
"compaction",
|
|
40
|
+
"subtask",
|
|
41
|
+
"retry",
|
|
42
|
+
"step-start",
|
|
43
|
+
"step-finish",
|
|
44
|
+
"tool",
|
|
45
|
+
"snapshot",
|
|
46
|
+
"patch",
|
|
47
|
+
}
|
|
48
|
+
_ARG_KEYS = ("filePath", "path", "pattern", "command", "url", "query", "file_path")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _obj(v: Any) -> dict[str, Any]:
|
|
52
|
+
return v if isinstance(v, dict) else {}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _ms(v: Any) -> float | None:
|
|
56
|
+
return float(v) / 1000 if isinstance(v, (int, float)) and not isinstance(v, bool) and v > 0 else None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _tool_key(d: dict[str, Any]) -> str:
|
|
60
|
+
inp = _obj(_obj(d.get("state")).get("input"))
|
|
61
|
+
arg = next((inp[k] for k in _ARG_KEYS if inp.get(k)), "")
|
|
62
|
+
return f"{d.get('tool', '?')}:{str(arg)[:200]}"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class OpenCodeParser(Parser):
|
|
66
|
+
"""Fed one session's rows in order: {"kind": "session" | "message" | "part" | "end", ...} (see `records`)."""
|
|
67
|
+
|
|
68
|
+
version = 2 # 2: the provider is the session's platform (prices: direct vendor, OpenRouter, Bedrock, ...)
|
|
69
|
+
|
|
70
|
+
def __init__(self, path: str):
|
|
71
|
+
self.session = Session(id=Path(path).stem, harness="opencode", role="main", path=path)
|
|
72
|
+
self.msg: dict[str, Any] = {} # data of the message being read
|
|
73
|
+
self.msg_turns = 0 # turns made from this message's steps
|
|
74
|
+
self.step_start: float | None = None
|
|
75
|
+
self.step_tools: list[tuple[str, str, int, float | None]] = [] # key, snippet, est. tokens, exec start
|
|
76
|
+
self.summary_text = ""
|
|
77
|
+
self.pending_user = ""
|
|
78
|
+
self.last_input_ts: float | None = None
|
|
79
|
+
|
|
80
|
+
def feed(self, d: dict[str, Any]) -> None:
|
|
81
|
+
kind = d.get("kind")
|
|
82
|
+
data = _obj(d.get("data"))
|
|
83
|
+
if kind == "session":
|
|
84
|
+
self.session.id = str(d.get("id") or self.session.id)
|
|
85
|
+
if d.get("parent_id"):
|
|
86
|
+
self.session.parent_id = str(d["parent_id"])
|
|
87
|
+
self.session.role = "subagent"
|
|
88
|
+
elif kind == "message":
|
|
89
|
+
self._end_message()
|
|
90
|
+
self.msg = data
|
|
91
|
+
role = data.get("role")
|
|
92
|
+
if role == "user":
|
|
93
|
+
self.last_input_ts = _ms(_obj(data.get("time")).get("created")) or self.last_input_ts
|
|
94
|
+
elif role != "assistant":
|
|
95
|
+
self.note_unknown(self.session, f"message:{role}")
|
|
96
|
+
elif kind == "part":
|
|
97
|
+
try:
|
|
98
|
+
self._part(data, _ms(d.get("time_created")))
|
|
99
|
+
except BadRecord:
|
|
100
|
+
self.session.parse_errors += 1
|
|
101
|
+
elif kind == "end":
|
|
102
|
+
self._end_message()
|
|
103
|
+
else:
|
|
104
|
+
self.note_unknown(self.session, f"record:{kind}")
|
|
105
|
+
|
|
106
|
+
def _part(self, d: dict[str, Any], ts: float | None) -> None:
|
|
107
|
+
typ = str(d.get("type"))
|
|
108
|
+
if typ not in KNOWN_PARTS:
|
|
109
|
+
self.note_unknown(self.session, f"part:{typ}")
|
|
110
|
+
return
|
|
111
|
+
role, summary = self.msg.get("role"), bool(self.msg.get("summary"))
|
|
112
|
+
if typ == "text" and isinstance(d.get("text"), str):
|
|
113
|
+
if role == "user" and not d.get("synthetic"):
|
|
114
|
+
self.pending_user = (self.pending_user + " " + d["text"]).strip()
|
|
115
|
+
elif summary:
|
|
116
|
+
self.summary_text += d["text"]
|
|
117
|
+
elif summary or role != "assistant":
|
|
118
|
+
return # the summary call's own steps and tools are not turns
|
|
119
|
+
elif typ == "step-start":
|
|
120
|
+
self.step_start, self.step_tools = ts, []
|
|
121
|
+
elif typ == "tool":
|
|
122
|
+
st = _obj(d.get("state"))
|
|
123
|
+
body = str(st.get("output") or st.get("error") or "")
|
|
124
|
+
start = _ms(_obj(st.get("time")).get("start"))
|
|
125
|
+
self.step_tools.append((_tool_key(d), body[:400], len(body) // 4, start))
|
|
126
|
+
elif typ == "step-finish":
|
|
127
|
+
self._turn(d.get("tokens"), ts)
|
|
128
|
+
|
|
129
|
+
def _turn(self, tokens: Any, ts: float | None) -> None:
|
|
130
|
+
s = self.session
|
|
131
|
+
tk = _obj(tokens)
|
|
132
|
+
cache = _obj(tk.get("cache"))
|
|
133
|
+
inp, cr, cw = count(tk.get("input")), count(cache.get("read")), count(cache.get("write"))
|
|
134
|
+
out = count(tk.get("output")) + count(tk.get("reasoning"))
|
|
135
|
+
tools, self.step_tools = self.step_tools, []
|
|
136
|
+
start, self.step_start = self.step_start, None
|
|
137
|
+
if inp + cr + cw == 0:
|
|
138
|
+
return # an aborted step, or a provider that reported no usage: nothing to replay
|
|
139
|
+
# the response ends where its last tool call starts running; the step itself also spans the tools
|
|
140
|
+
starts = [t for *_, t in tools if t]
|
|
141
|
+
end = min(max(starts), ts) if starts and ts else (max(starts) if starts else ts)
|
|
142
|
+
model = self.msg.get("modelID") or "unknown"
|
|
143
|
+
provider = self.msg.get("providerID")
|
|
144
|
+
if provider:
|
|
145
|
+
s.platform = str(provider) # OpenCode's provider ID: `anthropic` is the vendor's API, not OpenRouter
|
|
146
|
+
s.turns.append(
|
|
147
|
+
Turn(
|
|
148
|
+
ts=end,
|
|
149
|
+
ctx=inp + cr + cw,
|
|
150
|
+
cache_read=cr,
|
|
151
|
+
cache_write=cw,
|
|
152
|
+
output=out,
|
|
153
|
+
model=f"{provider}/{model}" if provider else str(model),
|
|
154
|
+
tool_keys=[k for k, *_ in tools],
|
|
155
|
+
tool_result_tokens=[n for _, _, n, _ in tools],
|
|
156
|
+
snippets=[b for _, b, _, _ in tools if b],
|
|
157
|
+
user_text=self.pending_user,
|
|
158
|
+
start_ts=start or self.last_input_ts,
|
|
159
|
+
)
|
|
160
|
+
)
|
|
161
|
+
self.msg_turns += 1
|
|
162
|
+
self.pending_user = ""
|
|
163
|
+
self.last_input_ts = ts or self.last_input_ts
|
|
164
|
+
|
|
165
|
+
def _end_message(self) -> None:
|
|
166
|
+
m, s = self.msg, self.session
|
|
167
|
+
times = _obj(m.get("time"))
|
|
168
|
+
created, done = _ms(times.get("created")), _ms(times.get("completed"))
|
|
169
|
+
if m.get("role") == "assistant" and m.get("summary"):
|
|
170
|
+
if m.get("finish") and not m.get("error"):
|
|
171
|
+
dur = done - created if done and created else None
|
|
172
|
+
s.compactions.append(
|
|
173
|
+
Compaction(
|
|
174
|
+
turn_index=len(s.turns),
|
|
175
|
+
pre_tokens=s.turns[-1].ctx if s.turns else None,
|
|
176
|
+
ts=done or created,
|
|
177
|
+
summary_text=self.summary_text[:2000],
|
|
178
|
+
duration_s=dur if dur is not None and 0 < dur <= 900 else None,
|
|
179
|
+
)
|
|
180
|
+
)
|
|
181
|
+
self.last_input_ts = done or self.last_input_ts
|
|
182
|
+
elif m.get("role") == "assistant" and self.msg_turns == 0 and isinstance(m.get("tokens"), dict):
|
|
183
|
+
try: # no step parts (an older build or an interrupted reply): the message's own totals
|
|
184
|
+
self.step_start = self.step_start or created
|
|
185
|
+
self._turn(m["tokens"], done or created)
|
|
186
|
+
except BadRecord:
|
|
187
|
+
s.parse_errors += 1
|
|
188
|
+
self.msg, self.msg_turns, self.summary_text = {}, 0, ""
|
|
189
|
+
self.step_start, self.step_tools = None, []
|
|
190
|
+
|
|
191
|
+
def finish(self) -> Session:
|
|
192
|
+
from ..model import snapshot
|
|
193
|
+
|
|
194
|
+
return snapshot(self.session)
|
|
195
|
+
|
|
196
|
+
def dump(self) -> dict[str, Any]:
|
|
197
|
+
from ..model import session_to_dict
|
|
198
|
+
|
|
199
|
+
st = {k: v for k, v in self.__dict__.items() if k != "session"}
|
|
200
|
+
return {"path": self.session.path, "session": session_to_dict(self.session), **st}
|
|
201
|
+
|
|
202
|
+
@classmethod
|
|
203
|
+
def load(cls, state: dict[str, Any]) -> OpenCodeParser:
|
|
204
|
+
from ..model import session_from_dict
|
|
205
|
+
|
|
206
|
+
p = cls(state["path"])
|
|
207
|
+
if "session" in state:
|
|
208
|
+
p.session = session_from_dict(state["session"])
|
|
209
|
+
for k, v in state.items():
|
|
210
|
+
if k not in ("path", "session") and hasattr(p, k):
|
|
211
|
+
setattr(p, k, [tuple(x) for x in v] if k == "step_tools" else v)
|
|
212
|
+
return p
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def connect(path: Path) -> tuple[sqlite3.Connection, str]:
|
|
216
|
+
"""A read-only connection and how it was opened ("ro", or "immutable" when read-only cannot open it)."""
|
|
217
|
+
uri = "file:" + quote(str(path.resolve()))
|
|
218
|
+
try:
|
|
219
|
+
con = sqlite3.connect(f"{uri}?mode=ro", uri=True, timeout=2)
|
|
220
|
+
con.execute("select 1 from sqlite_master limit 1").fetchall()
|
|
221
|
+
return con, "ro"
|
|
222
|
+
except sqlite3.OperationalError:
|
|
223
|
+
return sqlite3.connect(f"{uri}?mode=ro&immutable=1", uri=True), "immutable"
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _tables(con: sqlite3.Connection) -> set[str]:
|
|
227
|
+
return {r[0] for r in con.execute("select name from sqlite_master where type = 'table'")}
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _json(text: Any) -> dict[str, Any] | None:
|
|
231
|
+
try:
|
|
232
|
+
d = json.loads(text)
|
|
233
|
+
except (TypeError, ValueError):
|
|
234
|
+
return None
|
|
235
|
+
return d if isinstance(d, dict) else None
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def records(con: sqlite3.Connection, since_ms: int = 0) -> Iterator[tuple[str, dict[str, Any] | None]]:
|
|
239
|
+
"""(session id, record) for every v1 session updated since `since_ms`, rows in order; None = unreadable row."""
|
|
240
|
+
if not {"session", "message", "part"} <= _tables(con):
|
|
241
|
+
return
|
|
242
|
+
sessions = con.execute(
|
|
243
|
+
"select id, parent_id from session where time_updated >= ? order by time_created, id", (since_ms,)
|
|
244
|
+
).fetchall()
|
|
245
|
+
for sid, parent in sessions:
|
|
246
|
+
yield sid, {"kind": "session", "id": sid, "parent_id": parent}
|
|
247
|
+
parts: dict[str, list[tuple[Any, Any]]] = {}
|
|
248
|
+
for mid, created, data in con.execute(
|
|
249
|
+
"select message_id, time_created, data from part where session_id = ? order by id", (sid,)
|
|
250
|
+
):
|
|
251
|
+
parts.setdefault(mid, []).append((created, data))
|
|
252
|
+
for mid, data in con.execute("select id, data from message where session_id = ? order by id", (sid,)):
|
|
253
|
+
d = _json(data)
|
|
254
|
+
if d is None:
|
|
255
|
+
yield sid, None
|
|
256
|
+
continue
|
|
257
|
+
yield sid, {"kind": "message", "id": mid, "data": d}
|
|
258
|
+
for created, pdata in parts.get(mid, []):
|
|
259
|
+
pd = _json(pdata)
|
|
260
|
+
yield sid, ({"kind": "part", "time_created": created, "data": pd} if pd is not None else None)
|
|
261
|
+
yield sid, {"kind": "end"}
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
@register
|
|
265
|
+
class OpenCodeAdapter(Adapter):
|
|
266
|
+
name = "opencode"
|
|
267
|
+
parser_cls = OpenCodeParser
|
|
268
|
+
resumable = False
|
|
269
|
+
|
|
270
|
+
@classmethod
|
|
271
|
+
def default_roots(cls) -> list[Path]:
|
|
272
|
+
import os
|
|
273
|
+
|
|
274
|
+
base = os.environ.get("XDG_DATA_HOME") or "~/.local/share"
|
|
275
|
+
return [Path(os.path.expanduser(base)) / "opencode"]
|
|
276
|
+
|
|
277
|
+
@classmethod
|
|
278
|
+
def config_paths(cls) -> list[Path]:
|
|
279
|
+
import os
|
|
280
|
+
|
|
281
|
+
base = Path(os.path.expanduser(os.environ.get("XDG_CONFIG_HOME") or "~/.config")) / "opencode"
|
|
282
|
+
return [base / "opencode.json", base / "opencode.jsonc", base / "config.json"]
|
|
283
|
+
|
|
284
|
+
def find_files(self) -> Iterator[Path]:
|
|
285
|
+
for r in self.roots:
|
|
286
|
+
if r.is_file() and r.suffix == ".db":
|
|
287
|
+
yield r
|
|
288
|
+
elif r.exists():
|
|
289
|
+
yield from sorted(r.glob("opencode*.db"))
|
|
290
|
+
|
|
291
|
+
def read_records(self, path: Path, parser: Parser | None = None) -> Iterator[dict[str, Any]]:
|
|
292
|
+
"""Every session's rows in one stream (tests and `parse_file`); `load` splits them per session."""
|
|
293
|
+
con, _ = connect(path)
|
|
294
|
+
try:
|
|
295
|
+
for _, rec in records(con):
|
|
296
|
+
if rec is None:
|
|
297
|
+
_bump_error(parser)
|
|
298
|
+
continue
|
|
299
|
+
yield rec
|
|
300
|
+
finally:
|
|
301
|
+
con.close()
|
|
302
|
+
|
|
303
|
+
def load(self, path: Path, cache: Any = None, since: float | None = None) -> list[Session]:
|
|
304
|
+
"""Every session in the database updated since `since`. The scan cache is not used: one indexed
|
|
305
|
+
query per session is cheaper than hashing a database that changes on every reply."""
|
|
306
|
+
out: list[Session] = []
|
|
307
|
+
try:
|
|
308
|
+
con, _ = connect(path)
|
|
309
|
+
except sqlite3.DatabaseError as e:
|
|
310
|
+
raise OSError(f"{path}: {e}") from e
|
|
311
|
+
try:
|
|
312
|
+
parser: OpenCodeParser | None = None
|
|
313
|
+
for sid, rec in records(con, int(since * 1000) if since else 0):
|
|
314
|
+
if parser is None or parser.session.id != sid:
|
|
315
|
+
if parser is not None:
|
|
316
|
+
out.append(parser.finish())
|
|
317
|
+
parser = OpenCodeParser(f"{path}#{sid}")
|
|
318
|
+
if rec is None:
|
|
319
|
+
parser.session.parse_errors += 1
|
|
320
|
+
else:
|
|
321
|
+
parser.feed(rec)
|
|
322
|
+
if parser is not None:
|
|
323
|
+
out.append(parser.finish())
|
|
324
|
+
except sqlite3.DatabaseError as e:
|
|
325
|
+
raise OSError(f"{path}: {e}") from e
|
|
326
|
+
finally:
|
|
327
|
+
con.close()
|
|
328
|
+
return out
|
|
329
|
+
|
|
330
|
+
def fingerprint(self, path: Path, since: float | None = None) -> list[Any] | None:
|
|
331
|
+
"""The database and its write-ahead log as files (any write changes one of them), and which sessions are
|
|
332
|
+
recent enough to load: a session ages out of `since` without the file changing."""
|
|
333
|
+
files = [[q.name, q.stat().st_size, q.stat().st_mtime_ns] for q in (path, Path(f"{path}-wal")) if q.exists()]
|
|
334
|
+
try:
|
|
335
|
+
con, _ = connect(path)
|
|
336
|
+
except sqlite3.DatabaseError as e:
|
|
337
|
+
raise OSError(f"{path}: {e}") from e
|
|
338
|
+
try:
|
|
339
|
+
ids = (
|
|
340
|
+
con.execute(
|
|
341
|
+
"select id, time_updated from session where time_updated >= ? order by time_created, id",
|
|
342
|
+
(int(since * 1000) if since else 0,),
|
|
343
|
+
).fetchall()
|
|
344
|
+
if "session" in _tables(con)
|
|
345
|
+
else []
|
|
346
|
+
)
|
|
347
|
+
except sqlite3.DatabaseError as e:
|
|
348
|
+
raise OSError(f"{path}: {e}") from e
|
|
349
|
+
finally:
|
|
350
|
+
con.close()
|
|
351
|
+
return [str(path), self.parser_cls.version, files, ids]
|
|
352
|
+
|
|
353
|
+
def doctor_checks(self) -> list[dict[str, Any]]:
|
|
354
|
+
out = []
|
|
355
|
+
for path in self.find_files():
|
|
356
|
+
try:
|
|
357
|
+
con, how = connect(path)
|
|
358
|
+
try:
|
|
359
|
+
t = _tables(con)
|
|
360
|
+
v1 = con.execute("select count(*) from session").fetchone()[0] if "session" in t else 0
|
|
361
|
+
v2 = (
|
|
362
|
+
con.execute("select count(distinct session_id) from session_message").fetchone()[0]
|
|
363
|
+
if "session_message" in t
|
|
364
|
+
else 0
|
|
365
|
+
)
|
|
366
|
+
finally:
|
|
367
|
+
con.close()
|
|
368
|
+
except sqlite3.DatabaseError as e:
|
|
369
|
+
out.append({"ok": False, "label": "sqlite", "text": f"{path.name}: {e}"})
|
|
370
|
+
continue
|
|
371
|
+
text = f"{path.name}: {v1} sessions readable" + (" (opened immutable: WAL tail skipped)" * (how != "ro"))
|
|
372
|
+
if v2:
|
|
373
|
+
text += f"; {v2} stored by OpenCode 2.x are not read yet"
|
|
374
|
+
out.append({"ok": bool(v1) and how == "ro", "label": "sqlite", "text": text})
|
|
375
|
+
return out
|