@osovv/vv-opencode 2.3.3 → 2.5.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.
Files changed (108) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +18 -13
  3. package/dist/cli.js +5 -3
  4. package/dist/cli.js.map +1 -1
  5. package/dist/commands/doctor.d.ts +4 -0
  6. package/dist/commands/doctor.js +60 -51
  7. package/dist/commands/doctor.js.map +1 -1
  8. package/dist/commands/plugin-toggle.d.ts +0 -16
  9. package/dist/commands/plugin-toggle.js +2 -34
  10. package/dist/commands/plugin-toggle.js.map +1 -1
  11. package/dist/commands/preset.d.ts +0 -8
  12. package/dist/commands/preset.js +3 -24
  13. package/dist/commands/preset.js.map +1 -1
  14. package/dist/commands/role.js +2 -30
  15. package/dist/commands/role.js.map +1 -1
  16. package/dist/commands/session.d.ts +50 -0
  17. package/dist/commands/session.js +354 -0
  18. package/dist/commands/session.js.map +1 -0
  19. package/dist/lib/managed-agents.js +2 -2
  20. package/dist/lib/managed-agents.js.map +1 -1
  21. package/dist/lib/managed-skills.js +3 -3
  22. package/dist/lib/managed-skills.js.map +1 -1
  23. package/dist/lib/opencode/agent-registrations.js +103 -13
  24. package/dist/lib/opencode/agent-registrations.js.map +1 -1
  25. package/dist/lib/opencode/inspection.js +131 -5
  26. package/dist/lib/opencode/inspection.js.map +1 -1
  27. package/dist/plugins/analytics/index.js +8 -19
  28. package/dist/plugins/analytics/index.js.map +1 -1
  29. package/dist/plugins/guardian/index.js +7 -21
  30. package/dist/plugins/guardian/index.js.map +1 -1
  31. package/dist/plugins/hashline-edit/index.js +6 -20
  32. package/dist/plugins/hashline-edit/index.js.map +1 -1
  33. package/dist/plugins/model-roles/index.d.ts +3 -3
  34. package/dist/plugins/model-roles/index.js +8 -8
  35. package/dist/plugins/model-roles/index.js.map +1 -1
  36. package/dist/plugins/peak-hours/index.js +9 -20
  37. package/dist/plugins/peak-hours/index.js.map +1 -1
  38. package/dist/plugins/secrets-redaction/index.js +11 -24
  39. package/dist/plugins/secrets-redaction/index.js.map +1 -1
  40. package/dist/plugins/spec-guard/index.js +10 -22
  41. package/dist/plugins/spec-guard/index.js.map +1 -1
  42. package/dist/plugins/system-context-injection/guidance.d.ts +6 -0
  43. package/dist/plugins/system-context-injection/guidance.js +79 -0
  44. package/dist/plugins/system-context-injection/guidance.js.map +1 -0
  45. package/dist/plugins/system-context-injection/index.js +20 -121
  46. package/dist/plugins/system-context-injection/index.js.map +1 -1
  47. package/dist/plugins/tool-history-compaction/index.js +14 -25
  48. package/dist/plugins/tool-history-compaction/index.js.map +1 -1
  49. package/dist/plugins/web-tools/index.js +14 -25
  50. package/dist/plugins/web-tools/index.js.map +1 -1
  51. package/dist/plugins/workflow/index.d.ts +3 -2
  52. package/dist/plugins/workflow/index.js +6 -22
  53. package/dist/plugins/workflow/index.js.map +1 -1
  54. package/dist/plugins/workflow/input-validation.d.ts +1 -1
  55. package/dist/plugins/workflow/input-validation.js +2 -2
  56. package/dist/plugins/workflow/input-validation.js.map +1 -1
  57. package/dist/plugins/workflow/results.d.ts +40 -40
  58. package/dist/plugins/workflow/system-instruction.md +20 -0
  59. package/dist/runtime/auxiliary.d.ts +11 -6
  60. package/dist/runtime/auxiliary.js +43 -35
  61. package/dist/runtime/auxiliary.js.map +1 -1
  62. package/dist/runtime/context-inspection.d.ts +7 -6
  63. package/dist/runtime/context-inspection.js +37 -43
  64. package/dist/runtime/context-inspection.js.map +1 -1
  65. package/dist/runtime/context.d.ts +22 -45
  66. package/dist/runtime/context.js +348 -634
  67. package/dist/runtime/context.js.map +1 -1
  68. package/dist/runtime/model-registry.d.ts +3 -34
  69. package/dist/runtime/model-registry.js +10 -190
  70. package/dist/runtime/model-registry.js.map +1 -1
  71. package/dist/runtime/session-settings.d.ts +204 -0
  72. package/dist/runtime/session-settings.js +445 -0
  73. package/dist/runtime/session-settings.js.map +1 -0
  74. package/dist/runtime/snapshot-config.d.ts +7 -70
  75. package/dist/runtime/snapshot-config.js +16 -198
  76. package/dist/runtime/snapshot-config.js.map +1 -1
  77. package/dist/runtime/types.d.ts +15 -256
  78. package/dist/runtime/types.js +9 -63
  79. package/dist/runtime/types.js.map +1 -1
  80. package/dist/tui/settings/plugin.d.ts +29 -0
  81. package/dist/tui/settings/plugin.js +134 -0
  82. package/dist/tui/settings/plugin.js.map +1 -0
  83. package/dist/tui.js +12 -12
  84. package/dist/tui.js.map +1 -1
  85. package/package.json +1 -1
  86. package/schemas/vvoc/v3.json +1 -1
  87. package/templates/agents/vv-code-reviewer.md +2 -2
  88. package/templates/agents/vv-controller.md +176 -151
  89. package/templates/agents/vv-implementer.md +2 -2
  90. package/templates/agents/vv-reflector.md +7 -0
  91. package/templates/agents/vv-spec-reviewer.md +2 -2
  92. package/templates/skills/vv-execute/SKILL.md +25 -4
  93. package/templates/skills/vv-execute/references/tool-contracts.md +3 -3
  94. package/templates/skills/vv-reflect/SKILL.md +1 -0
  95. package/templates/skills/vv-reflect/references/session-graph.py +581 -7
  96. package/templates/skills/vv-review/SKILL.md +2 -2
  97. package/dist/lib/rebind-request.d.ts +0 -41
  98. package/dist/lib/rebind-request.js +0 -134
  99. package/dist/lib/rebind-request.js.map +0 -1
  100. package/dist/runtime/snapshot-store.d.ts +0 -63
  101. package/dist/runtime/snapshot-store.js +0 -668
  102. package/dist/runtime/snapshot-store.js.map +0 -1
  103. package/dist/runtime/snapshots.d.ts +0 -36
  104. package/dist/runtime/snapshots.js +0 -508
  105. package/dist/runtime/snapshots.js.map +0 -1
  106. package/dist/tui/rebind/plugin.d.ts +0 -22
  107. package/dist/tui/rebind/plugin.js +0 -101
  108. package/dist/tui/rebind/plugin.js.map +0 -1
@@ -4,13 +4,21 @@
4
4
  The reflector agent uses this as its mechanical pre-pass: it resolves the target
5
5
  session, walks the session_v2 parent/child tree, and reports tool-call friction
6
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.
7
+ tail per node. `--archive` switches to a streaming machine-wide aggregate over
8
+ many sessions, with filters and JSON/Markdown output.
9
9
 
10
- Invocation example:
10
+ The current schema stores tool entries in `session_message`; the legacy `part`
11
+ table is a subset of those calls (the same callID appears in both). Read both
12
+ only by unioning on the call id, with `session_message` winning; never sum the
13
+ two tables. The extractor never writes to the database or the repository.
14
+
15
+ Invocation examples:
11
16
 
12
17
  python3 "$HOME/.config/opencode/skills/vvoc/vv-reflect/references/session-graph.py" \
13
18
  --project "$PWD" --format json
19
+
20
+ python3 "$HOME/.config/opencode/skills/vvoc/vv-reflect/references/session-graph.py" \
21
+ --archive --since 2026-02-01 --out /tmp/opencode/archive
14
22
  """
15
23
 
16
24
  from __future__ import annotations
@@ -23,7 +31,8 @@ import re
23
31
  import sqlite3
24
32
  import subprocess
25
33
  import sys
26
- from datetime import datetime, timezone
34
+ from collections import Counter, defaultdict
35
+ from datetime import date, datetime, time, timezone
27
36
  from pathlib import Path
28
37
  from typing import Any
29
38
 
@@ -61,10 +70,10 @@ TEST_COMMAND_RE = re.compile(
61
70
 
62
71
  def parse_args() -> argparse.Namespace:
63
72
  parser = argparse.ArgumentParser(
64
- description="Read-only OpenCode 2.x session + subagent tree with friction signals."
73
+ description="Read-only OpenCode 2.x session + subagent tree with friction signals, or a machine-wide archive aggregate."
65
74
  )
66
75
  parser.add_argument("--db", type=Path, default=DEFAULT_DB)
67
- parser.add_argument("--project", type=Path, default=Path.cwd())
76
+ parser.add_argument("--project", type=Path, default=None)
68
77
  parser.add_argument("--session", type=str, default=None)
69
78
  parser.add_argument("--child", type=str, default=None)
70
79
  parser.add_argument("--depth", type=int, default=MAX_DEPTH_DEFAULT)
@@ -73,6 +82,17 @@ def parse_args() -> argparse.Namespace:
73
82
  parser.add_argument("--message-chars", type=int, default=1200)
74
83
  parser.add_argument("--top-tools", type=int, default=6)
75
84
  parser.add_argument("--format", choices=("json", "md"), default="json")
85
+ parser.add_argument(
86
+ "--archive",
87
+ action="store_true",
88
+ help="Aggregate tool calls across sessions instead of walking one session tree.",
89
+ )
90
+ parser.add_argument("--since", type=str, default=None, help="Archive lower bound (YYYY-MM-DD).")
91
+ parser.add_argument("--until", type=str, default=None, help="Archive upper bound (YYYY-MM-DD).")
92
+ parser.add_argument("--agent", type=str, default=None, help="Archive filter by session agent.")
93
+ parser.add_argument("--skill", type=str, default=None, help="Archive filter by loaded skill id.")
94
+ parser.add_argument("--top", type=int, default=10, help="Archive top-N rows per section.")
95
+ parser.add_argument("--out", type=Path, default=None, help="Archive output directory.")
76
96
  return parser.parse_args()
77
97
 
78
98
 
@@ -519,13 +539,543 @@ def render_md(payload: dict[str, Any]) -> str:
519
539
  return "\n".join(lines) + "\n"
520
540
 
521
541
 
542
+ def parse_date_bound(value: str | None, label: str, end_of_day: bool) -> int | None:
543
+ if value is None:
544
+ return None
545
+ try:
546
+ day = date.fromisoformat(value)
547
+ except ValueError:
548
+ fail(f"{label} must be YYYY-MM-DD, got {value!r}")
549
+ moment = datetime.combine(day, time.max if end_of_day else time.min, tzinfo=timezone.utc)
550
+ return int(moment.timestamp() * 1000)
551
+
552
+
553
+ def tool_name(entry: dict[str, Any]) -> str:
554
+ name = entry.get("name") or entry.get("tool")
555
+ return str(name) if name else "unknown"
556
+
557
+
558
+ def tool_input(entry: dict[str, Any]) -> Any:
559
+ state = entry.get("state")
560
+ if isinstance(state, dict) and state.get("input") is not None:
561
+ return state.get("input")
562
+ return entry.get("input")
563
+
564
+
565
+ def tool_status(entry: dict[str, Any]) -> str:
566
+ state = entry.get("state")
567
+ if isinstance(state, dict) and state.get("status") is not None:
568
+ return str(state.get("status"))
569
+ return str(entry.get("status") or "unknown")
570
+
571
+
572
+ def tool_time(entry: dict[str, Any], fallback: Any) -> int | None:
573
+ state = entry.get("state")
574
+ if isinstance(state, dict):
575
+ timing = state.get("time")
576
+ if isinstance(timing, dict):
577
+ for key in ("completed", "start", "created"):
578
+ value = timing.get(key)
579
+ if isinstance(value, (int, float)):
580
+ return int(value)
581
+ timing = entry.get("time")
582
+ if isinstance(timing, dict):
583
+ for key in ("completed", "start", "created"):
584
+ value = timing.get(key)
585
+ if isinstance(value, (int, float)):
586
+ return int(value)
587
+ if isinstance(timing, (int, float)):
588
+ return int(timing)
589
+ if isinstance(fallback, (int, float)):
590
+ return int(fallback)
591
+ return None
592
+
593
+
594
+ def tool_error_text(entry: dict[str, Any]) -> str | None:
595
+ if tool_status(entry) != "error":
596
+ return None
597
+ state = entry.get("state")
598
+ candidates: list[Any] = []
599
+ if isinstance(state, dict):
600
+ for key in ("error", "message", "output"):
601
+ candidates.append(state.get(key))
602
+ candidates.append(entry.get("error"))
603
+ for candidate in candidates:
604
+ if isinstance(candidate, str) and candidate.strip():
605
+ return candidate
606
+ if isinstance(candidate, dict):
607
+ for key in ("message", "name", "type", "value"):
608
+ value = candidate.get(key)
609
+ if isinstance(value, str) and value.strip():
610
+ return value
611
+ return "unknown error"
612
+
613
+
614
+ def normalize_error(text: str) -> str:
615
+ normalized = re.sub(r"\b[0-9a-f]{8,}\b", "<hex>", text, flags=re.IGNORECASE)
616
+ normalized = re.sub(r"\b\d+(?:\.\d+)?\b", "<n>", normalized)
617
+ normalized = re.sub(r"\s+", " ", normalized).strip()
618
+ return normalized[:300]
619
+
620
+
621
+ def first_argument_signature(name: str, value: Any) -> str:
622
+ if isinstance(value, dict):
623
+ for key in (
624
+ "command",
625
+ "filePath",
626
+ "file",
627
+ "path",
628
+ "pattern",
629
+ "query",
630
+ "url",
631
+ "id",
632
+ "name",
633
+ "agent",
634
+ "prompt",
635
+ ):
636
+ candidate = value.get(key)
637
+ if isinstance(candidate, str) and candidate.strip():
638
+ return f"{key}={candidate.strip()[:160]}"
639
+ if value:
640
+ key = sorted(value)[0]
641
+ candidate = value[key]
642
+ return f"{key}={str(candidate)[:160]}"
643
+ if isinstance(value, str):
644
+ return value[:160]
645
+ return ""
646
+
647
+
648
+ def skill_id_for_call(name: str, value: Any) -> str | None:
649
+ if name != "skill" or not isinstance(value, dict):
650
+ return None
651
+ for key in ("id", "name"):
652
+ candidate = value.get(key)
653
+ if isinstance(candidate, str) and candidate.strip():
654
+ return candidate.strip()
655
+ return None
656
+
657
+
658
+ def archive_session_rows(
659
+ connection: sqlite3.Connection,
660
+ tables: set[str],
661
+ args: argparse.Namespace,
662
+ since_ms: int | None,
663
+ until_ms: int | None,
664
+ ) -> dict[str, dict[str, Any]]:
665
+ project_roots: dict[str, str] = {}
666
+ if "project" in tables:
667
+ for row in connection.execute("SELECT id, worktree FROM project"):
668
+ project_roots[str(row["id"])] = normalized_path(row["worktree"]) or ""
669
+ root_filter = normalized_path(args.project) if args.project is not None else None
670
+ if args.project is not None and root_filter is None:
671
+ fail(f"project directory does not exist: {args.project}")
672
+
673
+ sessions: dict[str, dict[str, Any]] = {}
674
+ for row in connection.execute(
675
+ """
676
+ SELECT id, project_id, parent_id, directory, title, agent, cost,
677
+ time_created, time_updated
678
+ FROM session_v2
679
+ """
680
+ ):
681
+ created = row["time_created"]
682
+ if since_ms is not None and (not isinstance(created, (int, float)) or created < since_ms):
683
+ continue
684
+ if until_ms is not None and (not isinstance(created, (int, float)) or created > until_ms):
685
+ continue
686
+ if args.agent is not None and str(row["agent"] or "") != args.agent:
687
+ continue
688
+ directory = normalized_path(row["directory"])
689
+ project_root = project_roots.get(str(row["project_id"] or ""), "")
690
+ if root_filter is not None and not (
691
+ is_within(directory, root_filter) or is_within(project_root, root_filter)
692
+ ):
693
+ continue
694
+ sessions[str(row["id"])] = {
695
+ "id": str(row["id"]),
696
+ "project_id": str(row["project_id"] or ""),
697
+ "project": project_root or directory or "unknown",
698
+ "parent_id": row["parent_id"],
699
+ "directory": directory or "",
700
+ "title": str(row["title"] or ""),
701
+ "agent": str(row["agent"] or "unknown"),
702
+ "cost": float(row["cost"] or 0),
703
+ "time_created": int(created) if isinstance(created, (int, float)) else 0,
704
+ }
705
+ return sessions
706
+
707
+
708
+ def archive_calls(
709
+ connection: sqlite3.Connection,
710
+ tables: set[str],
711
+ sessions: dict[str, dict[str, Any]],
712
+ ) -> dict[str, dict[str, Any]]:
713
+ calls: dict[str, dict[str, Any]] = {}
714
+
715
+ if "part" in tables:
716
+ columns = {
717
+ str(row["name"])
718
+ for row in connection.execute("PRAGMA table_info(part)")
719
+ }
720
+ for row in connection.execute("SELECT * FROM part"):
721
+ data = load_json(row["data"])
722
+ if not isinstance(data, dict) or data.get("type") != "tool":
723
+ continue
724
+ call_id = data.get("callID") or data.get("id")
725
+ session_id = row["session_id"] if "session_id" in columns else data.get("sessionID")
726
+ if not call_id or not session_id or str(session_id) not in sessions:
727
+ continue
728
+ calls[str(call_id)] = {
729
+ "id": str(call_id),
730
+ "session_id": str(session_id),
731
+ "name": tool_name(data),
732
+ "status": tool_status(data),
733
+ "input": tool_input(data),
734
+ "time": tool_time(data, row["time_created"] if "time_created" in columns else None),
735
+ "error": tool_error_text(data),
736
+ }
737
+
738
+ for row in connection.execute(
739
+ """
740
+ SELECT session_id, seq, time_created, data
741
+ FROM session_message
742
+ WHERE type = 'assistant'
743
+ ORDER BY seq
744
+ """
745
+ ):
746
+ session_id = str(row["session_id"])
747
+ if session_id not in sessions:
748
+ continue
749
+ data = load_json(row["data"])
750
+ if not isinstance(data, dict):
751
+ continue
752
+ content = data.get("content")
753
+ if not isinstance(content, list):
754
+ continue
755
+ for entry in content:
756
+ if not isinstance(entry, dict) or entry.get("type") != "tool":
757
+ continue
758
+ call_id = entry.get("id")
759
+ if not call_id:
760
+ continue
761
+ calls[str(call_id)] = {
762
+ "id": str(call_id),
763
+ "session_id": session_id,
764
+ "name": tool_name(entry),
765
+ "status": tool_status(entry),
766
+ "input": tool_input(entry),
767
+ "time": tool_time(entry, row["time_created"]),
768
+ "error": tool_error_text(entry),
769
+ }
770
+ return calls
771
+
772
+
773
+ def archive_aggregate(
774
+ connection: sqlite3.Connection,
775
+ tables: set[str],
776
+ args: argparse.Namespace,
777
+ ) -> dict[str, Any]:
778
+ since_ms = parse_date_bound(args.since, "--since", False)
779
+ until_ms = parse_date_bound(args.until, "--until", True)
780
+ if since_ms is not None and until_ms is not None and since_ms > until_ms:
781
+ fail("--since must not be after --until")
782
+
783
+ sessions = archive_session_rows(connection, tables, args, since_ms, until_ms)
784
+ calls = archive_calls(connection, tables, sessions)
785
+
786
+ if args.skill is not None:
787
+ matching_sessions = {
788
+ call["session_id"]
789
+ for call in calls.values()
790
+ if skill_id_for_call(call["name"], call["input"]) == args.skill
791
+ }
792
+ sessions = {
793
+ session_id: session
794
+ for session_id, session in sessions.items()
795
+ if session_id in matching_sessions
796
+ }
797
+ calls = {
798
+ call_id: call
799
+ for call_id, call in calls.items()
800
+ if call["session_id"] in sessions
801
+ }
802
+
803
+ tool_stats: dict[str, dict[str, Any]] = defaultdict(
804
+ lambda: {"calls": 0, "errors": 0, "sessions": set(), "months": Counter()}
805
+ )
806
+ skills: dict[str, dict[str, Any]] = defaultdict(
807
+ lambda: {"loads": 0, "sessions": set(), "projects": set()}
808
+ )
809
+ agents: dict[str, dict[str, Any]] = defaultdict(
810
+ lambda: {"sessions": set(), "calls": 0, "errors": 0}
811
+ )
812
+ projects: dict[str, dict[str, Any]] = defaultdict(
813
+ lambda: {"calls": 0, "errors": 0, "sessions": set(), "tools": Counter()}
814
+ )
815
+ repeated: dict[tuple[str, str], dict[str, Any]] = defaultdict(
816
+ lambda: {"calls": 0, "errors": 0, "sessions": set()}
817
+ )
818
+ error_counter: Counter[str] = Counter()
819
+ session_stats: dict[str, dict[str, int]] = defaultdict(
820
+ lambda: {"calls": 0, "errors": 0}
821
+ )
822
+ skill_loads = 0
823
+ subagent_calls = 0
824
+
825
+ for call in calls.values():
826
+ session = sessions[call["session_id"]]
827
+ name = call["name"]
828
+ status = call["status"]
829
+ is_error = status == "error"
830
+ session_id = call["session_id"]
831
+ when = call["time"] or session["time_created"]
832
+ month = (
833
+ datetime.fromtimestamp(when / 1000, tz=timezone.utc).strftime("%Y-%m")
834
+ if isinstance(when, (int, float)) and when > 0
835
+ else "unknown"
836
+ )
837
+ stats = tool_stats[name]
838
+ stats["calls"] += 1
839
+ stats["errors"] += 1 if is_error else 0
840
+ stats["sessions"].add(session_id)
841
+ stats["months"][month] += 1
842
+
843
+ agent = agents[session["agent"]]
844
+ agent["sessions"].add(session_id)
845
+ agent["calls"] += 1
846
+ agent["errors"] += 1 if is_error else 0
847
+
848
+ project = projects[session["project"]]
849
+ project["calls"] += 1
850
+ project["errors"] += 1 if is_error else 0
851
+ project["sessions"].add(session_id)
852
+ project["tools"][name] += 1
853
+
854
+ session_stat = session_stats[session_id]
855
+ session_stat["calls"] += 1
856
+ session_stat["errors"] += 1 if is_error else 0
857
+
858
+ signature = (name, first_argument_signature(name, call["input"]))
859
+ repeat = repeated[signature]
860
+ repeat["calls"] += 1
861
+ repeat["errors"] += 1 if is_error else 0
862
+ repeat["sessions"].add(session_id)
863
+
864
+ skill_id = skill_id_for_call(name, call["input"])
865
+ if skill_id is not None:
866
+ skill_loads += 1
867
+ skill = skills[skill_id]
868
+ skill["loads"] += 1
869
+ skill["sessions"].add(session_id)
870
+ skill["projects"].add(session["project"])
871
+ if name in {"subagent", "task"}:
872
+ subagent_calls += 1
873
+
874
+ if is_error:
875
+ message = normalize_error(call.get("error") or tool_error_text(call) or "unknown error")
876
+ error_counter[message] += 1
877
+
878
+ top = args.top
879
+ if top <= 0:
880
+ fail("--top must be positive")
881
+
882
+ serialized_tools = []
883
+ for name, stats in sorted(tool_stats.items(), key=lambda item: (-item[1]["calls"], item[0])):
884
+ serialized_tools.append(
885
+ {
886
+ "name": name,
887
+ "calls": stats["calls"],
888
+ "errors": stats["errors"],
889
+ "rate": round(stats["errors"] / stats["calls"], 4) if stats["calls"] else 0,
890
+ "sessions": len(stats["sessions"]),
891
+ "months": dict(sorted(stats["months"].items())),
892
+ }
893
+ )
894
+
895
+ serialized_skills = [
896
+ {
897
+ "id": skill_id,
898
+ "loads": stats["loads"],
899
+ "sessions": len(stats["sessions"]),
900
+ "projects": len(stats["projects"]),
901
+ }
902
+ for skill_id, stats in sorted(skills.items(), key=lambda item: (-item[1]["loads"], item[0]))
903
+ ]
904
+
905
+ serialized_agents = [
906
+ {
907
+ "agent": name,
908
+ "sessions": len(stats["sessions"]),
909
+ "calls": stats["calls"],
910
+ "errors": stats["errors"],
911
+ }
912
+ for name, stats in sorted(agents.items(), key=lambda item: (-item[1]["calls"], item[0]))
913
+ ]
914
+
915
+ serialized_projects = [
916
+ {
917
+ "project": name,
918
+ "calls": stats["calls"],
919
+ "errors": stats["errors"],
920
+ "sessions": len(stats["sessions"]),
921
+ "top_tools": [
922
+ {"name": tool, "calls": count}
923
+ for tool, count in stats["tools"].most_common(top)
924
+ ],
925
+ }
926
+ for name, stats in sorted(projects.items(), key=lambda item: (-item[1]["calls"], item[0]))
927
+ ]
928
+
929
+ serialized_repeated = [
930
+ {
931
+ "tool": name,
932
+ "shape": shape,
933
+ "calls": stats["calls"],
934
+ "errors": stats["errors"],
935
+ "sessions": len(stats["sessions"]),
936
+ }
937
+ for (name, shape), stats in sorted(
938
+ repeated.items(), key=lambda item: (-item[1]["calls"], item[0])
939
+ )
940
+ if stats["calls"] >= 2
941
+ ][:top]
942
+
943
+ session_rows = []
944
+ for session_id, stats in session_stats.items():
945
+ session = sessions[session_id]
946
+ session_rows.append(
947
+ {
948
+ "id": session_id,
949
+ "title": session["title"],
950
+ "agent": session["agent"],
951
+ "project": session["project"],
952
+ "calls": stats["calls"],
953
+ "errors": stats["errors"],
954
+ "time_created": timestamp(session["time_created"]),
955
+ }
956
+ )
957
+ by_errors = sorted(session_rows, key=lambda row: (-row["errors"], -row["calls"]))[:top]
958
+ by_calls = sorted(session_rows, key=lambda row: (-row["calls"], -row["errors"]))[:top]
959
+
960
+ return {
961
+ "kind": "archive",
962
+ "database": str(args.db.expanduser().resolve()),
963
+ "schema": "session_v2",
964
+ "filters": {
965
+ "since": args.since,
966
+ "until": args.until,
967
+ "project": str(args.project) if args.project is not None else None,
968
+ "agent": args.agent,
969
+ "skill": args.skill,
970
+ },
971
+ "totals": {
972
+ "sessions": len(sessions),
973
+ "calls": len(calls),
974
+ "errors": sum(stats["errors"] for stats in tool_stats.values()),
975
+ "tools": len(tool_stats),
976
+ "skill_loads": skill_loads,
977
+ "subagent_calls": subagent_calls,
978
+ },
979
+ "tools": serialized_tools,
980
+ "skills": serialized_skills,
981
+ "agents": serialized_agents,
982
+ "projects": serialized_projects,
983
+ "repeated_calls": serialized_repeated,
984
+ "top_errors": [
985
+ {"message": message, "count": count}
986
+ for message, count in error_counter.most_common(top)
987
+ ],
988
+ "sessions": {"by_errors": by_errors, "by_calls": by_calls},
989
+ }
990
+
991
+
992
+ def render_archive_md(payload: dict[str, Any]) -> str:
993
+ totals = payload["totals"]
994
+ filters = payload["filters"]
995
+ lines = [
996
+ "# OpenCode archive aggregate",
997
+ "",
998
+ f"- Database: `{payload['database']}` (read-only)",
999
+ f"- Sessions: {totals['sessions']}",
1000
+ f"- Tool calls: {totals['calls']}",
1001
+ f"- Errors: {totals['errors']}",
1002
+ f"- Tools: {totals['tools']}",
1003
+ f"- Skill loads: {totals['skill_loads']}",
1004
+ f"- Subagent calls: {totals['subagent_calls']}",
1005
+ f"- Filters: since={filters['since'] or 'none'}, until={filters['until'] or 'none'}, project={filters['project'] or 'none'}, agent={filters['agent'] or 'none'}, skill={filters['skill'] or 'none'}",
1006
+ "",
1007
+ "## Tools",
1008
+ "",
1009
+ "| Tool | Calls | Errors | Rate | Sessions |",
1010
+ "|---|---:|---:|---:|---:|",
1011
+ ]
1012
+ for tool in payload["tools"]:
1013
+ lines.append(
1014
+ f"| {tool['name']} | {tool['calls']} | {tool['errors']} | {tool['rate']:.2%} | {tool['sessions']} |"
1015
+ )
1016
+
1017
+ lines.extend(["", "## Skills", "", "| Skill | Loads | Sessions | Projects |", "|---|---:|---:|---:|"])
1018
+ if payload["skills"]:
1019
+ for skill in payload["skills"]:
1020
+ lines.append(
1021
+ f"| {skill['id']} | {skill['loads']} | {skill['sessions']} | {skill['projects']} |"
1022
+ )
1023
+ else:
1024
+ lines.append("| none | 0 | 0 | 0 |")
1025
+
1026
+ lines.extend(["", "## Agents", "", "| Agent | Sessions | Calls | Errors |", "|---|---:|---:|---:|"])
1027
+ for agent in payload["agents"]:
1028
+ lines.append(
1029
+ f"| {agent['agent']} | {agent['sessions']} | {agent['calls']} | {agent['errors']} |"
1030
+ )
1031
+
1032
+ lines.extend(["", "## Projects", "", "| Project | Calls | Errors | Sessions |", "|---|---:|---:|---:|"])
1033
+ for project in payload["projects"]:
1034
+ lines.append(
1035
+ f"| {project['project']} | {project['calls']} | {project['errors']} | {project['sessions']} |"
1036
+ )
1037
+
1038
+ lines.extend(["", "## Repeated call shapes", "", "| Tool | Shape | Calls | Errors | Sessions |", "|---|---|---:|---:|---:|"])
1039
+ if payload["repeated_calls"]:
1040
+ for item in payload["repeated_calls"]:
1041
+ lines.append(
1042
+ f"| {item['tool']} | `{item['shape']}` | {item['calls']} | {item['errors']} | {item['sessions']} |"
1043
+ )
1044
+ else:
1045
+ lines.append("| none | - | 0 | 0 | 0 |")
1046
+
1047
+ lines.extend(["", "## Top errors", ""])
1048
+ if payload["top_errors"]:
1049
+ for item in payload["top_errors"]:
1050
+ lines.append(f"- {item['count']}× {item['message']}")
1051
+ else:
1052
+ lines.append("- none")
1053
+
1054
+ lines.extend(["", "## Sessions by errors", "", "| Session | Agent | Calls | Errors |", "|---|---|---:|---:|"])
1055
+ for session in payload["sessions"]["by_errors"]:
1056
+ lines.append(
1057
+ f"| {session['id']} {session['title']} | {session['agent']} | {session['calls']} | {session['errors']} |"
1058
+ )
1059
+
1060
+ return "\n".join(lines) + "\n"
1061
+
1062
+
1063
+ def write_archive_outputs(payload: dict[str, Any], out_dir: Path) -> None:
1064
+ out_dir.mkdir(parents=True, exist_ok=True)
1065
+ (out_dir / "aggregate.json").write_text(
1066
+ json.dumps(payload, indent=2, ensure_ascii=False, sort_keys=True) + "\n",
1067
+ encoding="utf-8",
1068
+ )
1069
+ (out_dir / "digest.md").write_text(render_archive_md(payload), encoding="utf-8")
1070
+
1071
+
522
1072
  def main() -> None:
523
1073
  if hasattr(sys.stdout, "reconfigure"):
524
1074
  sys.stdout.reconfigure(encoding="utf-8", errors="replace")
525
1075
  args = parse_args()
526
1076
  if args.depth < 0 or args.max_nodes <= 0:
527
1077
  fail("--depth must be non-negative and --max-nodes must be positive")
528
- root = project_root(args.project)
1078
+ root = project_root(args.project if args.project is not None else Path.cwd())
529
1079
  connection = connect_readonly(args.db)
530
1080
  try:
531
1081
  tables = table_names(connection)
@@ -534,6 +1084,30 @@ def main() -> None:
534
1084
  "unsupported OpenCode schema: expected session_v2 and session_message "
535
1085
  f"(found: {', '.join(sorted(tables)) or 'none'})"
536
1086
  )
1087
+ if args.archive:
1088
+ payload = archive_aggregate(connection, tables, args)
1089
+ if args.out is not None:
1090
+ write_archive_outputs(payload, args.out)
1091
+ print(
1092
+ json.dumps(
1093
+ {
1094
+ "sessions": payload["totals"]["sessions"],
1095
+ "calls": payload["totals"]["calls"],
1096
+ "errors": payload["totals"]["errors"],
1097
+ "tools": payload["totals"]["tools"],
1098
+ "skill_loads": payload["totals"]["skill_loads"],
1099
+ "subagent_calls": payload["totals"]["subagent_calls"],
1100
+ "written_to": str(args.out.expanduser().resolve()),
1101
+ },
1102
+ ensure_ascii=False,
1103
+ )
1104
+ )
1105
+ elif args.format == "md":
1106
+ print(render_archive_md(payload), end="")
1107
+ else:
1108
+ print(json.dumps(payload, indent=2, ensure_ascii=False, sort_keys=True))
1109
+ return
1110
+
537
1111
  project_ids = matching_project_ids(connection, tables, root)
538
1112
  target, source = resolve_target(
539
1113
  connection, project_ids, root, args.session, args.child
@@ -14,8 +14,8 @@ You are the vv-review skill. Your job is to route review requests to the appropr
14
14
  - Spec review (vv-spec-reviewer): when checking against a spec or acceptance criteria
15
15
  - Code review (vv-code-reviewer): when checking for bugs, regressions, maintainability, or security
16
16
  - Both: when the request calls for comprehensive review</rule>
17
- <step>Open one review-only work item with work_item_open before dispatching tracked reviewer sub-agents. Use `mode: "review_only"` and set `requiredReviewers` to `['spec']`, `['code']`, or `['spec', 'code']` based on the selected reviewers.</step>
18
- <step>Put the exact `VVOC_WORK_ITEM_ID` returned by `work_item_open` as the first line of each reviewer sub-agent prompt; reviewer results report `PASS`, `FAIL`, or `NEEDS_CONTEXT` and carry no route.</step>
17
+ <step>Open one review-only work item with work_item_open before dispatching tracked reviewer sub-agents. Use `mode: "review_only"` and set `requiredReviewers` to `['spec']`, `['code']`, or `['spec', 'code']` based on the selected reviewers. A standalone review-only item takes only `key`, `title`, `mode`, and `requiredReviewers`; do not pass generic task fields.</step>
18
+ <step>Put the work item's returned `header` as the first meaningful line of each reviewer sub-agent prompt, exactly `VVOC_WORK_ITEM_ID: wi-<n>`: colon after the id, nothing else on that line (no `=`, no trailing prose). Reviewer results report `PASS`, `FAIL`, or `NEEDS_CONTEXT` and carry no route. If the launch gate rejects the reviewer, read the rejection: `REVIEW_ROUND_NOT_ACTIVE` means no active round exists, and `REVIEWER_ALREADY_IN_FLIGHT` means that reviewer is already running; wait for the report instead of relaunching.</step>
19
19
  <step>Collect findings from each required reviewer. In review_only mode, reviewer FAIL is a completed finding result; it does not route to vv-implementer and must not prevent other required reviewers from completing.</step>
20
20
  <step>Findings are the FINAL output. Do NOT proceed to fixes without explicit user confirmation.</step>
21
21
  <step>When the request is a re-review after a fix, scope the reviewer packets to a scoped re-review: verify the prior findings against the fix and the fix's material effects — including directly affected consumers where necessary — rather than re-reviewing an entire unchanged change from scratch. Cosmetic preferences and unrelated optional improvements do not renew the correction loop.</step>