@osovv/vv-opencode 2.3.0-rc.6 → 2.3.0-rc.7

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.
@@ -0,0 +1,571 @@
1
+ #!/usr/bin/env python3
2
+ """Build a bounded, read-only view of one OpenCode 2.x session and its subagent tree.
3
+
4
+ The reflector agent uses this as its mechanical pre-pass: it resolves the target
5
+ session, walks the session_v2 parent/child tree, and reports tool-call friction
6
+ signals (errors, retries, heavy tool use, test invocations) plus a short message
7
+ tail per node. It reads only the current OpenCode 2.x schema (`session_v2` +
8
+ `session_message`) and never writes to the database or the repository.
9
+
10
+ Invocation example:
11
+
12
+ python3 "$HOME/.config/opencode/skills/vvoc/vv-reflect/references/session-graph.py" \
13
+ --project "$PWD" --format json
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import hashlib
20
+ import json
21
+ import os
22
+ import re
23
+ import sqlite3
24
+ import subprocess
25
+ import sys
26
+ from datetime import datetime, timezone
27
+ from pathlib import Path
28
+ from typing import Any
29
+
30
+
31
+ def default_db_path() -> Path:
32
+ override = os.environ.get("OPENCODE_DATA_HOME")
33
+ if override:
34
+ return Path(override).expanduser() / "opencode.db"
35
+ data_home = os.environ.get("XDG_DATA_HOME")
36
+ base = Path(data_home).expanduser() if data_home else Path.home() / ".local" / "share"
37
+ return base / "opencode" / "opencode.db"
38
+
39
+
40
+ DEFAULT_DB = default_db_path()
41
+ MUTATING_TOOLS = {
42
+ "edit",
43
+ "write",
44
+ "patch",
45
+ "apply_patch",
46
+ "hashline_edit",
47
+ "str_replace_editor",
48
+ "str_replace",
49
+ "create",
50
+ }
51
+ MAX_NODES_DEFAULT = 60
52
+ MAX_DEPTH_DEFAULT = 4
53
+ HEAVY_TOOL_CALLS = 40
54
+ REPEAT_THRESHOLD = 3
55
+ TEST_COMMAND_RE = re.compile(
56
+ r"\b(vitest|jest|pytest|bun test|go test|cargo test|npm test|pnpm test|"
57
+ r"yarn test|tsc|typecheck|lint|oxlint|eslint|ruff|biome)\b",
58
+ re.IGNORECASE,
59
+ )
60
+
61
+
62
+ def parse_args() -> argparse.Namespace:
63
+ parser = argparse.ArgumentParser(
64
+ description="Read-only OpenCode 2.x session + subagent tree with friction signals."
65
+ )
66
+ parser.add_argument("--db", type=Path, default=DEFAULT_DB)
67
+ parser.add_argument("--project", type=Path, default=Path.cwd())
68
+ parser.add_argument("--session", type=str, default=None)
69
+ parser.add_argument("--child", type=str, default=None)
70
+ parser.add_argument("--depth", type=int, default=MAX_DEPTH_DEFAULT)
71
+ parser.add_argument("--max-nodes", type=int, default=MAX_NODES_DEFAULT)
72
+ parser.add_argument("--tail-messages", type=int, default=4)
73
+ parser.add_argument("--message-chars", type=int, default=1200)
74
+ parser.add_argument("--top-tools", type=int, default=6)
75
+ parser.add_argument("--format", choices=("json", "md"), default="json")
76
+ return parser.parse_args()
77
+
78
+
79
+ def fail(message: str) -> None:
80
+ print(f"error: {message}", file=sys.stderr)
81
+ raise SystemExit(1)
82
+
83
+
84
+ def normalized_path(value: Any) -> str | None:
85
+ if not value:
86
+ return None
87
+ try:
88
+ return os.path.realpath(os.path.abspath(os.path.expanduser(os.fspath(value))))
89
+ except (TypeError, ValueError):
90
+ return None
91
+
92
+
93
+ def project_root(project: Path) -> str:
94
+ start = normalized_path(project)
95
+ if start is None or not os.path.isdir(start):
96
+ fail(f"project directory does not exist: {project}")
97
+ try:
98
+ result = subprocess.run(
99
+ ["git", "-C", start, "rev-parse", "--show-toplevel"],
100
+ check=True,
101
+ capture_output=True,
102
+ text=True,
103
+ timeout=10,
104
+ )
105
+ return normalized_path(result.stdout.strip()) or start
106
+ except (FileNotFoundError, subprocess.CalledProcessError, subprocess.TimeoutExpired):
107
+ return start
108
+
109
+
110
+ def connect_readonly(db_path: Path) -> sqlite3.Connection:
111
+ path = db_path.expanduser().resolve()
112
+ if not path.is_file():
113
+ fail(f"OpenCode database not found: {path}")
114
+ try:
115
+ connection = sqlite3.connect(f"{path.as_uri()}?mode=ro", uri=True, timeout=10)
116
+ except sqlite3.Error as error:
117
+ fail(f"cannot open OpenCode database read-only: {error}")
118
+ connection.row_factory = sqlite3.Row
119
+ connection.execute("PRAGMA query_only = ON")
120
+ return connection
121
+
122
+
123
+ def table_names(connection: sqlite3.Connection) -> set[str]:
124
+ return {
125
+ row["name"]
126
+ for row in connection.execute(
127
+ "SELECT name FROM sqlite_master WHERE type = 'table'"
128
+ )
129
+ }
130
+
131
+
132
+ def load_json(raw: Any) -> Any:
133
+ if not isinstance(raw, str) or not raw:
134
+ return {}
135
+ try:
136
+ return json.loads(raw)
137
+ except json.JSONDecodeError:
138
+ return {}
139
+
140
+
141
+ def timestamp(value: Any) -> str:
142
+ try:
143
+ number = float(value)
144
+ except (TypeError, ValueError):
145
+ return "unknown"
146
+ if number > 100_000_000_000:
147
+ number /= 1000
148
+ try:
149
+ return datetime.fromtimestamp(number).astimezone().isoformat(timespec="minutes")
150
+ except (OverflowError, OSError, ValueError):
151
+ return "unknown"
152
+
153
+
154
+ def is_within(path: str | None, root: str) -> bool:
155
+ if path is None:
156
+ return False
157
+ try:
158
+ return os.path.commonpath([path, root]) == root
159
+ except ValueError:
160
+ return False
161
+
162
+
163
+ def matching_project_ids(
164
+ connection: sqlite3.Connection, tables: set[str], root: str
165
+ ) -> set[str]:
166
+ project_ids: set[str] = set()
167
+ if "project" in tables:
168
+ for row in connection.execute("SELECT id, worktree FROM project"):
169
+ if normalized_path(row["worktree"]) == root:
170
+ project_ids.add(row["id"])
171
+ if "project_directory" in tables:
172
+ for row in connection.execute(
173
+ "SELECT project_id, directory FROM project_directory"
174
+ ):
175
+ if normalized_path(row["directory"]) == root:
176
+ project_ids.add(row["project_id"])
177
+ return project_ids
178
+
179
+
180
+ def fetch_session(
181
+ connection: sqlite3.Connection, session_id: str
182
+ ) -> sqlite3.Row | None:
183
+ return connection.execute(
184
+ "SELECT * FROM session_v2 WHERE id = ?", (session_id,)
185
+ ).fetchone()
186
+
187
+
188
+ def resolve_target(
189
+ connection: sqlite3.Connection,
190
+ project_ids: set[str],
191
+ root: str,
192
+ session_arg: str | None,
193
+ child_arg: str | None,
194
+ ) -> tuple[sqlite3.Row, str]:
195
+ if session_arg:
196
+ row = fetch_session(connection, session_arg)
197
+ if row is None:
198
+ fail(f"session not found: {session_arg}")
199
+ return row, "explicit-session"
200
+
201
+ if child_arg:
202
+ child = fetch_session(connection, child_arg)
203
+ if child is None:
204
+ fail(f"session not found: {child_arg}")
205
+ parent_id = child["parent_id"]
206
+ if not parent_id:
207
+ return child, "child-is-top-level"
208
+ parent = fetch_session(connection, parent_id)
209
+ if parent is None:
210
+ fail(f"parent session not found for child: {child_arg}")
211
+ return parent, "parent-of-child"
212
+
213
+ rows = list(connection.execute("SELECT * FROM session_v2"))
214
+ matched = [
215
+ row
216
+ for row in rows
217
+ if row["project_id"] in project_ids
218
+ or is_within(normalized_path(row["directory"]), root)
219
+ ]
220
+ if not matched:
221
+ fail("no sessions found for this project")
222
+ top_level = [row for row in matched if not row["parent_id"]]
223
+ pool = top_level if top_level else matched
224
+ pool.sort(key=lambda row: row["time_updated"] or 0, reverse=True)
225
+ source = "newest-top-level" if top_level else "newest-matched"
226
+ return pool[0], source
227
+
228
+
229
+ def children_of(connection: sqlite3.Connection, parent_id: str) -> list[sqlite3.Row]:
230
+ rows = list(
231
+ connection.execute(
232
+ "SELECT * FROM session_v2 WHERE parent_id = ?", (parent_id,)
233
+ )
234
+ )
235
+ rows.sort(key=lambda row: row["time_created"] or 0)
236
+ return rows
237
+
238
+
239
+ def session_messages(
240
+ connection: sqlite3.Connection, session_id: str
241
+ ) -> list[sqlite3.Row]:
242
+ return list(
243
+ connection.execute(
244
+ """
245
+ SELECT seq, type, time_created, data
246
+ FROM session_message
247
+ WHERE session_id = ?
248
+ ORDER BY seq
249
+ """,
250
+ (session_id,),
251
+ )
252
+ )
253
+
254
+
255
+ def tool_entries(messages: list[sqlite3.Row]) -> list[dict[str, Any]]:
256
+ tools: list[dict[str, Any]] = []
257
+ for row in messages:
258
+ if row["type"] != "assistant":
259
+ continue
260
+ data = load_json(row["data"])
261
+ if not isinstance(data, dict):
262
+ continue
263
+ content = data.get("content")
264
+ if not isinstance(content, list):
265
+ continue
266
+ for entry in content:
267
+ if isinstance(entry, dict) and entry.get("type") == "tool":
268
+ tools.append(entry)
269
+ return tools
270
+
271
+
272
+ def tool_stats(messages: list[sqlite3.Row], top: int) -> dict[str, Any]:
273
+ per_tool: dict[str, int] = {}
274
+ repeats: dict[tuple[str, str], int] = {}
275
+ errors = 0
276
+ tool_calls = 0
277
+ test_runs = 0
278
+ for entry in tool_entries(messages):
279
+ tool_calls += 1
280
+ name = str(entry.get("name") or "unknown")
281
+ per_tool[name] = per_tool.get(name, 0) + 1
282
+ state = entry.get("state")
283
+ if not isinstance(state, dict):
284
+ state = {}
285
+ if str(state.get("status")) == "error":
286
+ errors += 1
287
+ inp = state.get("input")
288
+ if isinstance(inp, dict):
289
+ command = inp.get("command")
290
+ if name in {"shell", "bash"} and isinstance(command, str):
291
+ if TEST_COMMAND_RE.search(command):
292
+ test_runs += 1
293
+ signature = hashlib.sha1(
294
+ json.dumps(inp, sort_keys=True, default=str).encode("utf-8")
295
+ ).hexdigest()
296
+ else:
297
+ signature = hashlib.sha1(str(inp).encode("utf-8")).hexdigest()
298
+ repeats[(name, signature)] = repeats.get((name, signature), 0) + 1
299
+ repeated = [
300
+ {"tool": name, "count": count}
301
+ for (name, _), count in sorted(repeats.items(), key=lambda kv: -kv[1])
302
+ if count >= REPEAT_THRESHOLD
303
+ ][:top]
304
+ top_tools = dict(sorted(per_tool.items(), key=lambda kv: -kv[1])[:top])
305
+ return {
306
+ "tool_calls": tool_calls,
307
+ "errors": errors,
308
+ "per_tool": top_tools,
309
+ "repeated": repeated,
310
+ "test_runs": test_runs,
311
+ }
312
+
313
+
314
+ def collect_files(value: Any, found: list[str]) -> None:
315
+ if isinstance(value, list):
316
+ for item in value:
317
+ collect_files(item, found)
318
+ return
319
+ if not isinstance(value, dict):
320
+ return
321
+ for key in ("file", "filePath", "path"):
322
+ item = value.get(key)
323
+ if isinstance(item, str) and item:
324
+ found.append(item)
325
+ for key in ("files", "diffs"):
326
+ if key in value:
327
+ collect_files(value[key], found)
328
+
329
+
330
+ def changed_files(messages: list[sqlite3.Row], row: sqlite3.Row) -> list[str]:
331
+ found: list[str] = []
332
+ for entry in tool_entries(messages):
333
+ name = str(entry.get("name") or "")
334
+ if name not in MUTATING_TOOLS:
335
+ continue
336
+ state = entry.get("state")
337
+ if not isinstance(state, dict):
338
+ continue
339
+ collect_files(state.get("input"), found)
340
+ collect_files(load_json(row["summary_diffs"]), found)
341
+ seen: set[str] = set()
342
+ unique: list[str] = []
343
+ for item in found:
344
+ if item not in seen:
345
+ seen.add(item)
346
+ unique.append(item)
347
+ return unique
348
+
349
+
350
+ def message_tail(
351
+ connection: sqlite3.Connection,
352
+ session_id: str,
353
+ limit: int,
354
+ chars: int,
355
+ ) -> list[dict[str, Any]]:
356
+ if limit <= 0:
357
+ return []
358
+ rows = list(
359
+ connection.execute(
360
+ """
361
+ SELECT seq, type, time_created, data
362
+ FROM session_message
363
+ WHERE session_id = ? AND type IN ('user', 'assistant')
364
+ ORDER BY seq DESC
365
+ LIMIT ?
366
+ """,
367
+ (session_id, limit),
368
+ )
369
+ )
370
+ rows.reverse()
371
+ tail: list[dict[str, Any]] = []
372
+ for row in rows:
373
+ data = load_json(row["data"])
374
+ if not isinstance(data, dict):
375
+ continue
376
+ if row["type"] == "user":
377
+ text = data.get("text") if isinstance(data.get("text"), str) else ""
378
+ role = "user"
379
+ else:
380
+ content = data.get("content")
381
+ parts = [
382
+ entry.get("text", "")
383
+ for entry in content
384
+ if isinstance(entry, dict) and entry.get("type") == "text"
385
+ ] if isinstance(content, list) else []
386
+ text = "\n".join(part for part in parts if part)
387
+ role = "assistant"
388
+ text = text.strip()
389
+ if not text:
390
+ continue
391
+ tail.append(
392
+ {
393
+ "role": role,
394
+ "time": timestamp(row["time_created"]),
395
+ "text": text[:chars],
396
+ "truncated": len(text) > chars,
397
+ }
398
+ )
399
+ return tail
400
+
401
+
402
+ def build_node(
403
+ connection: sqlite3.Connection,
404
+ row: sqlite3.Row,
405
+ depth: int,
406
+ args: argparse.Namespace,
407
+ counter: list[int],
408
+ ) -> dict[str, Any] | None:
409
+ if counter[0] >= args.max_nodes:
410
+ return None
411
+ counter[0] += 1
412
+ messages = session_messages(connection, row["id"])
413
+ stats = tool_stats(messages, args.top_tools)
414
+ signals = {
415
+ "has_errors": stats["errors"] > 0,
416
+ "heavy_tool_use": stats["tool_calls"] >= HEAVY_TOOL_CALLS,
417
+ "ran_tests": stats["test_runs"] > 0,
418
+ "repeated_calls": len(stats["repeated"]) > 0,
419
+ }
420
+ children = children_of(connection, row["id"])
421
+ node: dict[str, Any] = {
422
+ "id": row["id"],
423
+ "parent_id": row["parent_id"],
424
+ "depth": depth,
425
+ "agent": row["agent"],
426
+ "title": row["title"],
427
+ "directory": row["directory"],
428
+ "time_created": timestamp(row["time_created"]),
429
+ "time_updated": timestamp(row["time_updated"]),
430
+ "duration_minutes": round(
431
+ ((row["time_updated"] or 0) - (row["time_created"] or 0)) / 60000, 1
432
+ ),
433
+ "cost": round(row["cost"] or 0, 4),
434
+ "tokens_input": row["tokens_input"] or 0,
435
+ "tokens_output": row["tokens_output"] or 0,
436
+ "signals": signals,
437
+ "stats": stats,
438
+ "files": changed_files(messages, row)[:20],
439
+ "tail": message_tail(connection, row["id"], args.tail_messages, args.message_chars),
440
+ "children": [],
441
+ "children_truncated": 0,
442
+ "truncated": False,
443
+ }
444
+ if depth >= args.depth:
445
+ node["children_truncated"] = len(children)
446
+ else:
447
+ dropped = 0
448
+ for child in children:
449
+ child_node = build_node(connection, child, depth + 1, args, counter)
450
+ if child_node is None:
451
+ dropped += 1
452
+ continue
453
+ node["children"].append(child_node)
454
+ node["children_truncated"] = dropped
455
+ node["truncated"] = node["children_truncated"] > 0
456
+ return node
457
+
458
+
459
+ def collect(node: dict[str, Any], acc: list[dict[str, Any]]) -> None:
460
+ acc.append(node)
461
+ for child in node["children"]:
462
+ collect(child, acc)
463
+
464
+
465
+ def summarize(nodes: list[dict[str, Any]]) -> dict[str, Any]:
466
+ return {
467
+ "sessions": len(nodes),
468
+ "subagents": sum(1 for node in nodes if node["parent_id"]),
469
+ "max_depth": max((node["depth"] for node in nodes), default=0),
470
+ "tool_calls": sum(node["stats"]["tool_calls"] for node in nodes),
471
+ "errors": sum(node["stats"]["errors"] for node in nodes),
472
+ "test_runs": sum(node["stats"]["test_runs"] for node in nodes),
473
+ "truncated_nodes": [node["id"] for node in nodes if node["truncated"]],
474
+ "dropped_children": sum(node["children_truncated"] for node in nodes),
475
+ "nodes_with_errors": [node["id"] for node in nodes if node["signals"]["has_errors"]],
476
+ "nodes_with_heavy_tool_use": [
477
+ node["id"] for node in nodes if node["signals"]["heavy_tool_use"]
478
+ ],
479
+ "nodes_with_repeated_calls": [
480
+ node["id"] for node in nodes if node["signals"]["repeated_calls"]
481
+ ],
482
+ "nodes_that_ran_tests": [
483
+ node["id"] for node in nodes if node["signals"]["ran_tests"]
484
+ ],
485
+ }
486
+
487
+
488
+ def render_md(payload: dict[str, Any]) -> str:
489
+ lines: list[str] = []
490
+ lines.append("# Session graph")
491
+ lines.append("")
492
+ lines.append(f"- Target: `{payload['target']['id']}` ({payload['target']['source']})")
493
+ lines.append(f"- Database: `{payload['database']}` (read-only)")
494
+ summary = payload["summary"]
495
+ lines.append(
496
+ f"- Sessions: {summary['sessions']} (subagents: {summary['subagents']}), "
497
+ f"tool calls: {summary['tool_calls']}, errors: {summary['errors']}, tests: {summary['test_runs']}"
498
+ )
499
+ if summary["dropped_children"]:
500
+ lines.append(
501
+ f"- Truncated: {summary['dropped_children']} child session(s) not traversed "
502
+ f"(depth/max-nodes bound)"
503
+ )
504
+ lines.append("")
505
+
506
+ def walk(node: dict[str, Any], depth: int) -> None:
507
+ pad = " " * depth
508
+ kind = "subagent" if node["parent_id"] else "session"
509
+ marker = f", truncated +{node['children_truncated']}" if node["children_truncated"] else ""
510
+ lines.append(
511
+ f"{pad}- [{kind}] `{node['id']}` {node['title']} "
512
+ f"(tools={node['stats']['tool_calls']}, errors={node['stats']['errors']}, "
513
+ f"tests={node['stats']['test_runs']}, {node['duration_minutes']}m{marker})"
514
+ )
515
+ for child in node["children"]:
516
+ walk(child, depth + 1)
517
+
518
+ walk(payload["tree"], 0)
519
+ return "\n".join(lines) + "\n"
520
+
521
+
522
+ def main() -> None:
523
+ if hasattr(sys.stdout, "reconfigure"):
524
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
525
+ args = parse_args()
526
+ if args.depth < 0 or args.max_nodes <= 0:
527
+ fail("--depth must be non-negative and --max-nodes must be positive")
528
+ root = project_root(args.project)
529
+ connection = connect_readonly(args.db)
530
+ try:
531
+ tables = table_names(connection)
532
+ if "session_v2" not in tables or "session_message" not in tables:
533
+ fail(
534
+ "unsupported OpenCode schema: expected session_v2 and session_message "
535
+ f"(found: {', '.join(sorted(tables)) or 'none'})"
536
+ )
537
+ project_ids = matching_project_ids(connection, tables, root)
538
+ target, source = resolve_target(
539
+ connection, project_ids, root, args.session, args.child
540
+ )
541
+ counter = [0]
542
+ tree = build_node(connection, target, 0, args, counter)
543
+ if tree is None:
544
+ fail("no nodes collected")
545
+ nodes: list[dict[str, Any]] = []
546
+ collect(tree, nodes)
547
+ payload = {
548
+ "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
549
+ "database": str(args.db.expanduser().resolve()),
550
+ "project_root": root,
551
+ "schema": "session_v2",
552
+ "target": {"id": target["id"], "title": target["title"], "source": source},
553
+ "tree": tree,
554
+ "summary": summarize(nodes),
555
+ }
556
+ output = render_md(payload) if args.format == "md" else json.dumps(
557
+ payload, indent=2, ensure_ascii=False
558
+ )
559
+ try:
560
+ print(output)
561
+ except BrokenPipeError:
562
+ try:
563
+ sys.stdout.close()
564
+ finally:
565
+ os._exit(0)
566
+ finally:
567
+ connection.close()
568
+
569
+
570
+ if __name__ == "__main__":
571
+ main()