@osovv/vv-opencode 2.9.0 → 2.10.0
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.
- package/CHANGELOG.md +14 -0
- package/README.md +3 -2
- package/dist/lib/managed-skills.d.ts +3 -1
- package/dist/lib/managed-skills.js +23 -3
- package/dist/lib/managed-skills.js.map +1 -1
- package/dist/lib/opencode/agent-registrations.js +28 -5
- package/dist/lib/opencode/agent-registrations.js.map +1 -1
- package/dist/lib/opencode/inspection.js +13 -3
- package/dist/lib/opencode/inspection.js.map +1 -1
- package/dist/plugins/workflow/checkpoints.js +27 -5
- package/dist/plugins/workflow/checkpoints.js.map +1 -1
- package/package.json +1 -1
- package/schemas/vvoc/v3.json +1 -1
- package/templates/skills/vv-execute/references/tool-contracts.md +1 -1
- package/templates/skills/vv-reflect/references/session-graph.py +105 -23
- package/templates/skills/vvoc-project-session-history/SKILL.md +72 -0
- package/templates/skills/vvoc-project-session-history/scripts/project_history.py +581 -0
|
@@ -0,0 +1,581 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Extract a bounded, readable recap source from OpenCode's local SQLite history."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import sqlite3
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
from datetime import datetime
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Iterable
|
|
15
|
+
from urllib.parse import quote
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
DEFAULT_DB = Path("~/.local/share/opencode/opencode.db").expanduser()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def parse_args() -> argparse.Namespace:
|
|
22
|
+
parser = argparse.ArgumentParser(
|
|
23
|
+
description="Extract recent OpenCode sessions for the current project as Markdown."
|
|
24
|
+
)
|
|
25
|
+
parser.add_argument("--db", type=Path, default=DEFAULT_DB)
|
|
26
|
+
parser.add_argument("--project", type=Path, default=Path.cwd())
|
|
27
|
+
parser.add_argument("--sessions", type=int, default=6)
|
|
28
|
+
parser.add_argument("--include-children", action="store_true")
|
|
29
|
+
parser.add_argument("--skip-newest", action="store_true")
|
|
30
|
+
parser.add_argument("--head-user-messages", type=int, default=2)
|
|
31
|
+
parser.add_argument("--tail-messages", type=int, default=7)
|
|
32
|
+
parser.add_argument("--message-chars", type=int, default=1800)
|
|
33
|
+
return parser.parse_args()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def fail(message: str) -> None:
|
|
37
|
+
print(f"error: {message}", file=sys.stderr)
|
|
38
|
+
raise SystemExit(1)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def normalized_path(value: str | os.PathLike[str] | None) -> str | None:
|
|
42
|
+
if not value:
|
|
43
|
+
return None
|
|
44
|
+
return os.path.realpath(os.path.abspath(os.path.expanduser(os.fspath(value))))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def project_root(project: Path) -> str:
|
|
48
|
+
start = normalized_path(project)
|
|
49
|
+
if start is None or not os.path.isdir(start):
|
|
50
|
+
fail(f"project directory does not exist: {project}")
|
|
51
|
+
try:
|
|
52
|
+
result = subprocess.run(
|
|
53
|
+
["git", "-C", start, "rev-parse", "--show-toplevel"],
|
|
54
|
+
check=True,
|
|
55
|
+
capture_output=True,
|
|
56
|
+
text=True,
|
|
57
|
+
timeout=10,
|
|
58
|
+
)
|
|
59
|
+
root = normalized_path(result.stdout.strip())
|
|
60
|
+
return root or start
|
|
61
|
+
except (FileNotFoundError, subprocess.CalledProcessError, subprocess.TimeoutExpired):
|
|
62
|
+
return start
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def connect_readonly(db_path: Path) -> sqlite3.Connection:
|
|
66
|
+
path = db_path.expanduser().resolve()
|
|
67
|
+
if not path.is_file():
|
|
68
|
+
fail(f"OpenCode database not found: {path}")
|
|
69
|
+
# Percent-encode the path: SQLite URI parsing treats '?' and '#' as
|
|
70
|
+
# query/fragment delimiters, so raw interpolation breaks odd --db values.
|
|
71
|
+
connection = sqlite3.connect(f"file:{quote(str(path))}?mode=ro", uri=True, timeout=10)
|
|
72
|
+
connection.row_factory = sqlite3.Row
|
|
73
|
+
connection.execute("PRAGMA query_only = ON")
|
|
74
|
+
return connection
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def table_names(connection: sqlite3.Connection) -> set[str]:
|
|
78
|
+
return {
|
|
79
|
+
row["name"]
|
|
80
|
+
for row in connection.execute(
|
|
81
|
+
"SELECT name FROM sqlite_master WHERE type = 'table'"
|
|
82
|
+
)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def load_json(raw: Any) -> Any:
|
|
87
|
+
if not isinstance(raw, str) or not raw:
|
|
88
|
+
return {}
|
|
89
|
+
try:
|
|
90
|
+
return json.loads(raw)
|
|
91
|
+
except json.JSONDecodeError:
|
|
92
|
+
return {}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def timestamp(value: Any) -> str:
|
|
96
|
+
try:
|
|
97
|
+
number = float(value)
|
|
98
|
+
except (TypeError, ValueError):
|
|
99
|
+
return "unknown"
|
|
100
|
+
if number > 100_000_000_000:
|
|
101
|
+
number /= 1000
|
|
102
|
+
try:
|
|
103
|
+
return datetime.fromtimestamp(number).astimezone().isoformat(timespec="minutes")
|
|
104
|
+
except (OverflowError, OSError, ValueError):
|
|
105
|
+
return "unknown"
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def is_within(path: str | None, root: str) -> bool:
|
|
109
|
+
if path is None:
|
|
110
|
+
return False
|
|
111
|
+
try:
|
|
112
|
+
return os.path.commonpath([path, root]) == root
|
|
113
|
+
except ValueError:
|
|
114
|
+
return False
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def matching_project_ids(
|
|
118
|
+
connection: sqlite3.Connection, tables: set[str], root: str
|
|
119
|
+
) -> set[str]:
|
|
120
|
+
project_ids: set[str] = set()
|
|
121
|
+
if "project" in tables:
|
|
122
|
+
for row in connection.execute("SELECT id, worktree FROM project"):
|
|
123
|
+
worktree = normalized_path(row["worktree"])
|
|
124
|
+
if worktree == root:
|
|
125
|
+
project_ids.add(row["id"])
|
|
126
|
+
if "project_directory" in tables:
|
|
127
|
+
for row in connection.execute(
|
|
128
|
+
"SELECT project_id, directory FROM project_directory"
|
|
129
|
+
):
|
|
130
|
+
directory = normalized_path(row["directory"])
|
|
131
|
+
if directory == root:
|
|
132
|
+
project_ids.add(row["project_id"])
|
|
133
|
+
return project_ids
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def select_sessions(
|
|
137
|
+
connection: sqlite3.Connection,
|
|
138
|
+
tables: set[str],
|
|
139
|
+
root: str,
|
|
140
|
+
count: int,
|
|
141
|
+
include_children: bool,
|
|
142
|
+
skip_newest: bool,
|
|
143
|
+
) -> list[sqlite3.Row]:
|
|
144
|
+
# OpenCode V2 writes sessions into session_v2; the legacy V1 session table
|
|
145
|
+
# stopped receiving rows around 2026-10-02 and is absent entirely on hosts
|
|
146
|
+
# that started with V2. List columns explicitly: the two tables share the
|
|
147
|
+
# columns below but order them differently, so SELECT * would misalign.
|
|
148
|
+
session_columns = (
|
|
149
|
+
"id, project_id, parent_id, slug, directory, title, time_updated, "
|
|
150
|
+
"summary_files, summary_additions, summary_deletions, summary_diffs"
|
|
151
|
+
)
|
|
152
|
+
sources: list[str] = []
|
|
153
|
+
if "session_v2" in tables:
|
|
154
|
+
sources.append(f"SELECT {session_columns} FROM session_v2")
|
|
155
|
+
if "session" in tables:
|
|
156
|
+
if sources:
|
|
157
|
+
sources.append(
|
|
158
|
+
f"SELECT {session_columns} FROM session "
|
|
159
|
+
"WHERE id NOT IN (SELECT id FROM session_v2)"
|
|
160
|
+
)
|
|
161
|
+
else:
|
|
162
|
+
sources.append(f"SELECT {session_columns} FROM session")
|
|
163
|
+
if not sources:
|
|
164
|
+
fail("database has neither session nor session_v2 table")
|
|
165
|
+
|
|
166
|
+
project_ids = matching_project_ids(connection, tables, root)
|
|
167
|
+
rows = list(connection.execute(" UNION ALL ".join(sources)))
|
|
168
|
+
matched = []
|
|
169
|
+
for row in rows:
|
|
170
|
+
directory = normalized_path(row["directory"])
|
|
171
|
+
same_project = row["project_id"] in project_ids
|
|
172
|
+
if not same_project and not is_within(directory, root):
|
|
173
|
+
continue
|
|
174
|
+
if not include_children and row["parent_id"] is not None:
|
|
175
|
+
continue
|
|
176
|
+
matched.append(row)
|
|
177
|
+
|
|
178
|
+
matched.sort(key=lambda row: row["time_updated"] or 0, reverse=True)
|
|
179
|
+
if skip_newest and matched:
|
|
180
|
+
matched = matched[1:]
|
|
181
|
+
return matched[:count]
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def content_text(value: Any) -> str:
|
|
185
|
+
if isinstance(value, str):
|
|
186
|
+
return value.strip()
|
|
187
|
+
if isinstance(value, list):
|
|
188
|
+
texts = [content_text(item) for item in value]
|
|
189
|
+
return "\n".join(text for text in texts if text)
|
|
190
|
+
if not isinstance(value, dict):
|
|
191
|
+
return ""
|
|
192
|
+
|
|
193
|
+
item_type = str(value.get("type", "")).lower()
|
|
194
|
+
if item_type in {"text", "input_text", "output_text"} and isinstance(
|
|
195
|
+
value.get("text"), str
|
|
196
|
+
):
|
|
197
|
+
return value["text"].strip()
|
|
198
|
+
if item_type:
|
|
199
|
+
# Typed non-text parts (reasoning, tool, step-start, ...) must not leak
|
|
200
|
+
# their inner "text"/"content" fields into the recap: only type:text
|
|
201
|
+
# parts carry conversation text.
|
|
202
|
+
return ""
|
|
203
|
+
for key in ("text", "content", "message", "prompt", "output"):
|
|
204
|
+
if key in value:
|
|
205
|
+
text = content_text(value[key])
|
|
206
|
+
if text:
|
|
207
|
+
return text
|
|
208
|
+
return ""
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def legacy_messages(
|
|
212
|
+
connection: sqlite3.Connection, tables: set[str], session_id: str
|
|
213
|
+
) -> list[dict[str, Any]]:
|
|
214
|
+
if not {"message", "part"}.issubset(tables):
|
|
215
|
+
return []
|
|
216
|
+
rows = connection.execute(
|
|
217
|
+
"""
|
|
218
|
+
SELECT
|
|
219
|
+
m.id AS message_id,
|
|
220
|
+
m.time_created AS message_time,
|
|
221
|
+
m.data AS message_data,
|
|
222
|
+
p.time_created AS part_time,
|
|
223
|
+
p.data AS part_data
|
|
224
|
+
FROM message AS m
|
|
225
|
+
LEFT JOIN part AS p ON p.message_id = m.id
|
|
226
|
+
WHERE m.session_id = ?
|
|
227
|
+
ORDER BY m.time_created, m.id, p.time_created, p.id
|
|
228
|
+
""",
|
|
229
|
+
(session_id,),
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
grouped: dict[str, dict[str, Any]] = {}
|
|
233
|
+
for row in rows:
|
|
234
|
+
message_data = load_json(row["message_data"])
|
|
235
|
+
role = message_data.get("role")
|
|
236
|
+
if role not in {"user", "assistant"}:
|
|
237
|
+
continue
|
|
238
|
+
entry = grouped.setdefault(
|
|
239
|
+
row["message_id"],
|
|
240
|
+
{"role": role, "time": row["message_time"], "texts": []},
|
|
241
|
+
)
|
|
242
|
+
part_data = load_json(row["part_data"])
|
|
243
|
+
if part_data.get("type") == "text" and isinstance(part_data.get("text"), str):
|
|
244
|
+
text = part_data["text"].strip()
|
|
245
|
+
if text:
|
|
246
|
+
entry["texts"].append(text)
|
|
247
|
+
|
|
248
|
+
messages = []
|
|
249
|
+
for entry in grouped.values():
|
|
250
|
+
text = "\n".join(entry.pop("texts"))
|
|
251
|
+
if text:
|
|
252
|
+
entry["text"] = text
|
|
253
|
+
messages.append(entry)
|
|
254
|
+
return messages
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def modern_messages(
|
|
258
|
+
connection: sqlite3.Connection, tables: set[str], session_id: str
|
|
259
|
+
) -> list[dict[str, Any]]:
|
|
260
|
+
# OpenCode's 2026-11-25 storage migration moved message parts into
|
|
261
|
+
# session_part (keyed by session_message.id, ordered by ordinal) while
|
|
262
|
+
# assistant session_message rows keep content=[]. Preload the text parts
|
|
263
|
+
# for this session once; a message row uses them only when its inline
|
|
264
|
+
# extraction is empty, so transition-era rows cannot duplicate.
|
|
265
|
+
part_texts: dict[str, list[str]] = {}
|
|
266
|
+
if "session_part" in tables:
|
|
267
|
+
for row in connection.execute(
|
|
268
|
+
"""
|
|
269
|
+
SELECT message_id, ordinal, data
|
|
270
|
+
FROM session_part
|
|
271
|
+
WHERE session_id = ? AND type = 'text'
|
|
272
|
+
ORDER BY message_id, ordinal
|
|
273
|
+
""",
|
|
274
|
+
(session_id,),
|
|
275
|
+
):
|
|
276
|
+
text = content_text(load_json(row["data"]))
|
|
277
|
+
if text:
|
|
278
|
+
part_texts.setdefault(row["message_id"], []).append(text)
|
|
279
|
+
|
|
280
|
+
messages: list[dict[str, Any]] = []
|
|
281
|
+
if "session_message" in tables:
|
|
282
|
+
for row in connection.execute(
|
|
283
|
+
"""
|
|
284
|
+
SELECT id, type, time_created, data
|
|
285
|
+
FROM session_message
|
|
286
|
+
WHERE session_id = ?
|
|
287
|
+
ORDER BY time_created, seq, id
|
|
288
|
+
""",
|
|
289
|
+
(session_id,),
|
|
290
|
+
):
|
|
291
|
+
data = load_json(row["data"])
|
|
292
|
+
row_type = str(row["type"] or "").lower()
|
|
293
|
+
role = data.get("role")
|
|
294
|
+
if role not in {"user", "assistant"}:
|
|
295
|
+
if row_type in {"user", "assistant"}:
|
|
296
|
+
role = row_type
|
|
297
|
+
elif row_type.startswith("user-"):
|
|
298
|
+
role = "user"
|
|
299
|
+
elif row_type.startswith("assistant-"):
|
|
300
|
+
role = "assistant"
|
|
301
|
+
if role not in {"user", "assistant"}:
|
|
302
|
+
continue
|
|
303
|
+
text = content_text(data)
|
|
304
|
+
if not text:
|
|
305
|
+
text = "\n".join(part_texts.get(row["id"], []))
|
|
306
|
+
if text:
|
|
307
|
+
messages.append(
|
|
308
|
+
{"role": role, "time": row["time_created"], "text": text}
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
if "session_input" in tables:
|
|
312
|
+
for row in connection.execute(
|
|
313
|
+
"""
|
|
314
|
+
SELECT time_created, prompt
|
|
315
|
+
FROM session_input
|
|
316
|
+
WHERE session_id = ?
|
|
317
|
+
ORDER BY admitted_seq, id
|
|
318
|
+
""",
|
|
319
|
+
(session_id,),
|
|
320
|
+
):
|
|
321
|
+
text = content_text(load_json(row["prompt"])) or str(row["prompt"]).strip()
|
|
322
|
+
if text:
|
|
323
|
+
messages.append(
|
|
324
|
+
{"role": "user", "time": row["time_created"], "text": text}
|
|
325
|
+
)
|
|
326
|
+
return messages
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def deduplicate_messages(messages: Iterable[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
330
|
+
result = []
|
|
331
|
+
seen: set[tuple[str, str]] = set()
|
|
332
|
+
for message in sorted(messages, key=lambda item: item.get("time") or 0):
|
|
333
|
+
key = (message["role"], " ".join(message["text"].split()))
|
|
334
|
+
if not key[1] or key in seen:
|
|
335
|
+
continue
|
|
336
|
+
seen.add(key)
|
|
337
|
+
result.append(message)
|
|
338
|
+
return result
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def choose_messages(
|
|
342
|
+
messages: list[dict[str, Any]], head_users: int, tail_messages: int
|
|
343
|
+
) -> tuple[list[dict[str, Any]], int]:
|
|
344
|
+
selected_indexes: set[int] = set()
|
|
345
|
+
user_count = 0
|
|
346
|
+
for index, message in enumerate(messages):
|
|
347
|
+
if message["role"] == "user" and user_count < head_users:
|
|
348
|
+
selected_indexes.add(index)
|
|
349
|
+
user_count += 1
|
|
350
|
+
start = max(0, len(messages) - tail_messages)
|
|
351
|
+
selected_indexes.update(range(start, len(messages)))
|
|
352
|
+
selected = [message for index, message in enumerate(messages) if index in selected_indexes]
|
|
353
|
+
return selected, len(messages) - len(selected)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def todos(
|
|
357
|
+
connection: sqlite3.Connection, tables: set[str], session_id: str
|
|
358
|
+
) -> list[sqlite3.Row]:
|
|
359
|
+
if "todo" not in tables:
|
|
360
|
+
return []
|
|
361
|
+
return list(
|
|
362
|
+
connection.execute(
|
|
363
|
+
"""
|
|
364
|
+
SELECT content, status, priority, position
|
|
365
|
+
FROM todo
|
|
366
|
+
WHERE session_id = ?
|
|
367
|
+
ORDER BY position
|
|
368
|
+
""",
|
|
369
|
+
(session_id,),
|
|
370
|
+
)
|
|
371
|
+
)
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def relative_project_file(value: Any, root: str) -> str | None:
|
|
375
|
+
if not isinstance(value, str) or not value:
|
|
376
|
+
return None
|
|
377
|
+
path = normalized_path(value if os.path.isabs(value) else os.path.join(root, value))
|
|
378
|
+
if path is None or not is_within(path, root):
|
|
379
|
+
return None
|
|
380
|
+
return os.path.relpath(path, root)
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def collect_files_from_json(value: Any, root: str, result: list[str]) -> None:
|
|
384
|
+
if isinstance(value, list):
|
|
385
|
+
for item in value:
|
|
386
|
+
collect_files_from_json(item, root, result)
|
|
387
|
+
return
|
|
388
|
+
if not isinstance(value, dict):
|
|
389
|
+
return
|
|
390
|
+
for key in ("file", "filePath", "path"):
|
|
391
|
+
file_name = relative_project_file(value.get(key), root)
|
|
392
|
+
if file_name:
|
|
393
|
+
result.append(file_name)
|
|
394
|
+
if isinstance(value.get("files"), list):
|
|
395
|
+
for item in value["files"]:
|
|
396
|
+
if isinstance(item, str):
|
|
397
|
+
file_name = relative_project_file(item, root)
|
|
398
|
+
if file_name:
|
|
399
|
+
result.append(file_name)
|
|
400
|
+
else:
|
|
401
|
+
collect_files_from_json(item, root, result)
|
|
402
|
+
if "diffs" in value:
|
|
403
|
+
collect_files_from_json(value["diffs"], root, result)
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def changed_files(
|
|
407
|
+
connection: sqlite3.Connection,
|
|
408
|
+
tables: set[str],
|
|
409
|
+
session: sqlite3.Row,
|
|
410
|
+
root: str,
|
|
411
|
+
) -> list[str]:
|
|
412
|
+
found: list[str] = []
|
|
413
|
+
collect_files_from_json(load_json(session["summary_diffs"]), root, found)
|
|
414
|
+
|
|
415
|
+
if "message" in tables:
|
|
416
|
+
for row in connection.execute(
|
|
417
|
+
"SELECT data FROM message WHERE session_id = ?", (session["id"],)
|
|
418
|
+
):
|
|
419
|
+
data = load_json(row["data"])
|
|
420
|
+
collect_files_from_json(data.get("summary", {}), root, found)
|
|
421
|
+
|
|
422
|
+
if "part" in tables:
|
|
423
|
+
for row in connection.execute(
|
|
424
|
+
"SELECT data FROM part WHERE session_id = ?", (session["id"],)
|
|
425
|
+
):
|
|
426
|
+
data = load_json(row["data"])
|
|
427
|
+
if data.get("type") == "patch":
|
|
428
|
+
collect_files_from_json(data, root, found)
|
|
429
|
+
|
|
430
|
+
# Post-migration patch parts live in session_part tool rows: edit and
|
|
431
|
+
# write carry the touched file in state.input.path. Other tools are not
|
|
432
|
+
# recorded patches and contribute nothing.
|
|
433
|
+
if "session_part" in tables:
|
|
434
|
+
for row in connection.execute(
|
|
435
|
+
"SELECT data FROM session_part WHERE session_id = ? AND type = 'tool'",
|
|
436
|
+
(session["id"],),
|
|
437
|
+
):
|
|
438
|
+
data = load_json(row["data"])
|
|
439
|
+
if str(data.get("name", "")).lower() in {"edit", "write"}:
|
|
440
|
+
state = data.get("state")
|
|
441
|
+
if isinstance(state, dict) and isinstance(state.get("input"), dict):
|
|
442
|
+
collect_files_from_json(state["input"], root, found)
|
|
443
|
+
|
|
444
|
+
unique = []
|
|
445
|
+
seen = set()
|
|
446
|
+
for file_name in found:
|
|
447
|
+
if file_name not in seen:
|
|
448
|
+
seen.add(file_name)
|
|
449
|
+
unique.append(file_name)
|
|
450
|
+
return unique
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def truncate(text: str, maximum: int) -> str:
|
|
454
|
+
compact = text.strip()
|
|
455
|
+
if len(compact) <= maximum:
|
|
456
|
+
return compact
|
|
457
|
+
return compact[: maximum - 1].rstrip() + "…"
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def render_session(
|
|
461
|
+
connection: sqlite3.Connection,
|
|
462
|
+
tables: set[str],
|
|
463
|
+
session: sqlite3.Row,
|
|
464
|
+
root: str,
|
|
465
|
+
head_users: int,
|
|
466
|
+
tail_messages: int,
|
|
467
|
+
message_chars: int,
|
|
468
|
+
) -> None:
|
|
469
|
+
kind = "child" if session["parent_id"] else "top-level"
|
|
470
|
+
print(f"## {session['title'] or session['slug'] or 'untitled session'}")
|
|
471
|
+
print()
|
|
472
|
+
print(f"- Session: `{session['id']}` ({kind})")
|
|
473
|
+
print(f"- Updated: {timestamp(session['time_updated'])}")
|
|
474
|
+
if session["parent_id"]:
|
|
475
|
+
print(f"- Parent: `{session['parent_id']}`")
|
|
476
|
+
summary = (
|
|
477
|
+
session["summary_files"],
|
|
478
|
+
session["summary_additions"],
|
|
479
|
+
session["summary_deletions"],
|
|
480
|
+
)
|
|
481
|
+
if any(isinstance(value, (int, float)) and value for value in summary):
|
|
482
|
+
print(
|
|
483
|
+
"- Recorded diff: "
|
|
484
|
+
f"{summary[0] or 0} files, +{summary[1] or 0}/-{summary[2] or 0}"
|
|
485
|
+
)
|
|
486
|
+
|
|
487
|
+
files = changed_files(connection, tables, session, root)
|
|
488
|
+
if files:
|
|
489
|
+
preview = files[:24]
|
|
490
|
+
suffix = f" (+{len(files) - len(preview)} more)" if len(files) > len(preview) else ""
|
|
491
|
+
print(f"- Files mentioned by recorded patches: {', '.join(f'`{item}`' for item in preview)}{suffix}")
|
|
492
|
+
|
|
493
|
+
session_todos = todos(connection, tables, session["id"])
|
|
494
|
+
if session_todos:
|
|
495
|
+
print("- Todos recorded at session end (may be stale):")
|
|
496
|
+
for item in session_todos[:15]:
|
|
497
|
+
print(
|
|
498
|
+
f" - [{item['status']}] ({item['priority']}) "
|
|
499
|
+
f"{truncate(item['content'], 500)}"
|
|
500
|
+
)
|
|
501
|
+
if len(session_todos) > 15:
|
|
502
|
+
print(f" - … {len(session_todos) - 15} more")
|
|
503
|
+
|
|
504
|
+
legacy = legacy_messages(connection, tables, session["id"])
|
|
505
|
+
modern = modern_messages(connection, tables, session["id"])
|
|
506
|
+
messages = deduplicate_messages([*legacy, *modern])
|
|
507
|
+
selected, omitted = choose_messages(messages, head_users, tail_messages)
|
|
508
|
+
if selected:
|
|
509
|
+
print("- Selected conversation evidence:")
|
|
510
|
+
for message in selected:
|
|
511
|
+
label = "USER" if message["role"] == "user" else "ASSISTANT"
|
|
512
|
+
text = truncate(message["text"], message_chars).replace("\n", "\n ")
|
|
513
|
+
print(f" - {label} ({timestamp(message['time'])}):\n {text}")
|
|
514
|
+
if omitted:
|
|
515
|
+
print(f" - … {omitted} intermediate text messages omitted")
|
|
516
|
+
elif messages:
|
|
517
|
+
print("- Conversation evidence omitted by the requested message limits.")
|
|
518
|
+
else:
|
|
519
|
+
print("- No user/assistant text messages were found in supported schemas.")
|
|
520
|
+
print()
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def validate_limits(args: argparse.Namespace) -> None:
|
|
524
|
+
for name in (
|
|
525
|
+
"sessions",
|
|
526
|
+
"head_user_messages",
|
|
527
|
+
"tail_messages",
|
|
528
|
+
"message_chars",
|
|
529
|
+
):
|
|
530
|
+
if getattr(args, name) < 0:
|
|
531
|
+
fail(f"--{name.replace('_', '-')} must be non-negative")
|
|
532
|
+
if args.sessions == 0:
|
|
533
|
+
fail("--sessions must be greater than zero")
|
|
534
|
+
if args.message_chars < 200:
|
|
535
|
+
fail("--message-chars must be at least 200")
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def main() -> None:
|
|
539
|
+
args = parse_args()
|
|
540
|
+
validate_limits(args)
|
|
541
|
+
root = project_root(args.project)
|
|
542
|
+
connection = connect_readonly(args.db)
|
|
543
|
+
try:
|
|
544
|
+
tables = table_names(connection)
|
|
545
|
+
sessions = select_sessions(
|
|
546
|
+
connection,
|
|
547
|
+
tables,
|
|
548
|
+
root,
|
|
549
|
+
args.sessions,
|
|
550
|
+
args.include_children,
|
|
551
|
+
args.skip_newest,
|
|
552
|
+
)
|
|
553
|
+
print("# OpenCode project session history")
|
|
554
|
+
print()
|
|
555
|
+
print(f"- Project root: `{root}`")
|
|
556
|
+
print(f"- Database: `{args.db.expanduser().resolve()}` (read-only)")
|
|
557
|
+
print(
|
|
558
|
+
"- Scope: "
|
|
559
|
+
+ ("top-level and child sessions" if args.include_children else "top-level sessions")
|
|
560
|
+
)
|
|
561
|
+
print(f"- Sessions returned: {len(sessions)}")
|
|
562
|
+
print()
|
|
563
|
+
if not sessions:
|
|
564
|
+
print("No matching sessions found.")
|
|
565
|
+
return
|
|
566
|
+
for session in sessions:
|
|
567
|
+
render_session(
|
|
568
|
+
connection,
|
|
569
|
+
tables,
|
|
570
|
+
session,
|
|
571
|
+
root,
|
|
572
|
+
args.head_user_messages,
|
|
573
|
+
args.tail_messages,
|
|
574
|
+
args.message_chars,
|
|
575
|
+
)
|
|
576
|
+
finally:
|
|
577
|
+
connection.close()
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
if __name__ == "__main__":
|
|
581
|
+
main()
|