opencode-agent-harness 0.0.0-stage → 0.2.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 (169) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE +21 -0
  3. package/README.md +590 -2
  4. package/bin/agent-harness.js +3059 -0
  5. package/contrib/global-plugins/README.md +49 -0
  6. package/contrib/global-plugins/harness-freshness.ts +355 -0
  7. package/package.json +48 -4
  8. package/templates/.agents/AGENTS.md +204 -0
  9. package/templates/.agents/features/INDEX.md +10 -0
  10. package/templates/.agents/handoffs/README.md +87 -0
  11. package/templates/.agents/memory/dev-loop.md +59 -0
  12. package/templates/.agents/memory/domain-map.md +29 -0
  13. package/templates/.agents/memory/environments.md +35 -0
  14. package/templates/.agents/memory/flow-map.md +23 -0
  15. package/templates/.agents/memory/history.md +7 -0
  16. package/templates/.agents/memory/locations.md +14 -0
  17. package/templates/.agents/memory/model-routing.md +261 -0
  18. package/templates/.agents/memory/orchestration.md +183 -0
  19. package/templates/.agents/memory/owned-files.md +19 -0
  20. package/templates/.agents/memory/product-principles.md +37 -0
  21. package/templates/.agents/memory/quality-parameters.md +37 -0
  22. package/templates/.agents/memory/stack-versions.md +35 -0
  23. package/templates/.agents/memory/test-design-parameters.md +36 -0
  24. package/templates/.agents/nightly.json +17 -0
  25. package/templates/.agents/qa-plans/README.md +70 -0
  26. package/templates/.agents/qa-runs/README.md +21 -0
  27. package/templates/.agents/reviews/README.md +47 -0
  28. package/templates/.agents/rules/00-operating.md +199 -0
  29. package/templates/.agents/skills/data-engineer/SKILL.md +31 -0
  30. package/templates/.agents/skills/devops-engineer/SKILL.md +50 -0
  31. package/templates/.agents/skills/diagnostics-expert/SKILL.md +44 -0
  32. package/templates/.agents/skills/docs/SKILL.md +140 -0
  33. package/templates/.agents/skills/features/SKILL.md +187 -0
  34. package/templates/.agents/skills/frontend-engineer/SKILL.md +81 -0
  35. package/templates/.agents/skills/handoff/SKILL.md +85 -0
  36. package/templates/.agents/skills/mobile-engineer/SKILL.md +101 -0
  37. package/templates/.agents/skills/planner/SKILL.md +112 -0
  38. package/templates/.agents/skills/product-manager/SKILL.md +115 -0
  39. package/templates/.agents/skills/qa-architect/SKILL.md +224 -0
  40. package/templates/.agents/skills/qa-runner/SKILL.md +64 -0
  41. package/templates/.agents/skills/security-engineer/SKILL.md +53 -0
  42. package/templates/.agents/skills/system-architect/SKILL.md +42 -0
  43. package/templates/.agents/skills/ui-designer/SKILL.md +71 -0
  44. package/templates/.github/workflows/ci.yml +148 -0
  45. package/templates/.github/workflows/deploy-uat.yml +95 -0
  46. package/templates/.github/workflows/nightly.yml +83 -0
  47. package/templates/.github/workflows/uat-health.yml +41 -0
  48. package/templates/.husky/pre-push +23 -0
  49. package/templates/.ignore +28 -0
  50. package/templates/.opencode/agents/data-engineer.md +37 -0
  51. package/templates/.opencode/agents/devops-engineer.md +37 -0
  52. package/templates/.opencode/agents/diagnostics-expert.md +37 -0
  53. package/templates/.opencode/agents/docs.md +37 -0
  54. package/templates/.opencode/agents/features.md +21 -0
  55. package/templates/.opencode/agents/frontend-engineer.md +37 -0
  56. package/templates/.opencode/agents/handoff.md +21 -0
  57. package/templates/.opencode/agents/mobile-engineer.md +37 -0
  58. package/templates/.opencode/agents/planner.md +34 -0
  59. package/templates/.opencode/agents/product-manager.md +29 -0
  60. package/templates/.opencode/agents/qa-architect.md +27 -0
  61. package/templates/.opencode/agents/qa-runner.md +17 -0
  62. package/templates/.opencode/agents/security-engineer.md +37 -0
  63. package/templates/.opencode/agents/system-architect.md +37 -0
  64. package/templates/.opencode/agents/ui-designer.md +37 -0
  65. package/templates/.opencode/commands/board.md +15 -0
  66. package/templates/.opencode/commands/checkpoint.md +25 -0
  67. package/templates/.opencode/commands/feature.md +56 -0
  68. package/templates/.opencode/commands/finish.md +36 -0
  69. package/templates/.opencode/commands/next.md +49 -0
  70. package/templates/.opencode/commands/report.md +55 -0
  71. package/templates/.opencode/commands/resume.md +39 -0
  72. package/templates/.opencode/commands/switch-model.md +34 -0
  73. package/templates/.opencode/commands/tidy.md +49 -0
  74. package/templates/.opencode/plugins/backlog-notify.ts +57 -0
  75. package/templates/.opencode/plugins/backlog.ts +272 -0
  76. package/templates/.opencode/plugins/checkpoint.ts +160 -0
  77. package/templates/.opencode/plugins/context-guard.ts +1164 -0
  78. package/templates/.opencode/plugins/diff.ts +85 -0
  79. package/templates/.opencode/plugins/gates.ts +71 -0
  80. package/templates/.opencode/plugins/job-notify.ts +241 -0
  81. package/templates/.opencode/plugins/orient.ts +67 -0
  82. package/templates/.opencode/plugins/session.ts +89 -0
  83. package/templates/.opencode/plugins/wait.ts +101 -0
  84. package/templates/.opencode/plugins/where.ts +70 -0
  85. package/templates/.opencode/skills/bounded-explore/SKILL.md +38 -0
  86. package/templates/.opencode/skills/dev-loop/SKILL.md +87 -0
  87. package/templates/.vercelignore +16 -0
  88. package/templates/AGENTS.md +27 -0
  89. package/templates/BACKLOG.md +95 -0
  90. package/templates/docs/ci-cd-pipeline.md +81 -0
  91. package/templates/docs/gates.md +128 -0
  92. package/templates/docs/mcp-integrations.md +97 -0
  93. package/templates/docs/mobile-testing.md +555 -0
  94. package/templates/docs/nightly-testing.md +106 -0
  95. package/templates/docs/wsl-optimizations.md +290 -0
  96. package/templates/opencode.json +188 -0
  97. package/templates/scripts/agent-report.js +541 -0
  98. package/templates/scripts/agent-search.sh +117 -0
  99. package/templates/scripts/backlog.js +1864 -0
  100. package/templates/scripts/board-service.sh +207 -0
  101. package/templates/scripts/checkpoint.js +290 -0
  102. package/templates/scripts/finalize.js +277 -0
  103. package/templates/scripts/nightly.js +913 -0
  104. package/templates/scripts/orient.js +514 -0
  105. package/templates/scripts/qa/board-client.js +260 -0
  106. package/templates/scripts/qa/board-lib.js +96 -0
  107. package/templates/scripts/qa/board-sync.js +469 -0
  108. package/templates/scripts/qa/capacity-lib.js +916 -0
  109. package/templates/scripts/qa/check-backlog.js +427 -0
  110. package/templates/scripts/qa/check-capacity.js +85 -0
  111. package/templates/scripts/qa/check-ci-policy.js +164 -0
  112. package/templates/scripts/qa/check-concurrency.js +344 -0
  113. package/templates/scripts/qa/check-dispatch-config.js +296 -0
  114. package/templates/scripts/qa/check-docs.js +284 -0
  115. package/templates/scripts/qa/check-integrate.js +98 -0
  116. package/templates/scripts/qa/check-linger.js +160 -0
  117. package/templates/scripts/qa/check-prefix-stability.js +183 -0
  118. package/templates/scripts/qa/check-product.js +177 -0
  119. package/templates/scripts/qa/check-qa-plan.js +378 -0
  120. package/templates/scripts/qa/check-qa-scripts.js +85 -0
  121. package/templates/scripts/qa/check-quality.js +249 -0
  122. package/templates/scripts/qa/check-test-wiring.js +253 -0
  123. package/templates/scripts/qa/ci-triage.js +346 -0
  124. package/templates/scripts/qa/ci-usage-lib.js +185 -0
  125. package/templates/scripts/qa/ci-wait-lib.js +294 -0
  126. package/templates/scripts/qa/command-classifier.js +552 -0
  127. package/templates/scripts/qa/context-guard-core.js +1618 -0
  128. package/templates/scripts/qa/diff.js +174 -0
  129. package/templates/scripts/qa/feature-scaffold.js +224 -0
  130. package/templates/scripts/qa/fixtures/backlog.md +104 -0
  131. package/templates/scripts/qa/governance.js +174 -0
  132. package/templates/scripts/qa/hash-file.js +32 -0
  133. package/templates/scripts/qa/lease-lib.js +263 -0
  134. package/templates/scripts/qa/merge-backlog.js +324 -0
  135. package/templates/scripts/qa/mobile-e2e/analyze-timings.js +300 -0
  136. package/templates/scripts/qa/mobile-e2e/apk-cache.js +420 -0
  137. package/templates/scripts/qa/mobile-e2e/backend-build-cache.js +203 -0
  138. package/templates/scripts/qa/mobile-e2e/boot-emulator.sh +432 -0
  139. package/templates/scripts/qa/mobile-e2e/build-apk.sh +210 -0
  140. package/templates/scripts/qa/mobile-e2e/check-flows.js +453 -0
  141. package/templates/scripts/qa/mobile-e2e/config.yaml +18 -0
  142. package/templates/scripts/qa/mobile-e2e/device-down.sh +88 -0
  143. package/templates/scripts/qa/mobile-e2e/device-up.sh +258 -0
  144. package/templates/scripts/qa/mobile-e2e/ios-simulator-down.sh +72 -0
  145. package/templates/scripts/qa/mobile-e2e/ios-simulator-up.sh +153 -0
  146. package/templates/scripts/qa/mobile-e2e/job-events.js +181 -0
  147. package/templates/scripts/qa/mobile-e2e/prewarm.sh +56 -0
  148. package/templates/scripts/qa/mobile-e2e/run-detached.sh +222 -0
  149. package/templates/scripts/qa/mobile-e2e/run-maestro.js +1543 -0
  150. package/templates/scripts/qa/mobile-e2e/ui-dump.js +327 -0
  151. package/templates/scripts/qa/models.allowlist.txt +32 -0
  152. package/templates/scripts/qa/provider-stats.js +878 -0
  153. package/templates/scripts/qa/run-clean.js +83 -0
  154. package/templates/scripts/qa/run-gates.js +212 -0
  155. package/templates/scripts/qa/run-loop.js +220 -0
  156. package/templates/scripts/qa/session-recon.js +512 -0
  157. package/templates/scripts/qa/store-lib.js +324 -0
  158. package/templates/scripts/qa/tool-lib.js +134 -0
  159. package/templates/scripts/qa/where.js +214 -0
  160. package/templates/scripts/qa/wslconfig-merge.js +157 -0
  161. package/templates/scripts/serve.js +1328 -0
  162. package/templates/scripts/setup-nightly.sh +185 -0
  163. package/templates/scripts/setup-tmpfs.sh +374 -0
  164. package/templates/scripts/ship.js +586 -0
  165. package/templates/scripts/switch-reasoning-model.ps1 +101 -0
  166. package/templates/scripts/switch-reasoning-model.sh +104 -0
  167. package/templates/scripts/wait-for.js +342 -0
  168. package/templates/scripts/wsl-gpu.sh +180 -0
  169. package/templates/scripts/wsl-tune.sh +261 -0
@@ -0,0 +1,512 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /*
4
+ * session-recon — tool-habit / context-hygiene recon over the local opencode
5
+ * store. Deterministic and dependency-free (reads via `opencode db --format
6
+ * json`, the same stable path as provider-stats.js). Complements
7
+ * `report:cost` (cost/tokens/turns/tiers) with the habits measured in the
8
+ * 2026-09-16 → 09-29 WSL recon: shell file-inspection where the dedicated tools
9
+ * exist, `cd`-chaining, whole-file / repeated reads, guessed paths, whole-tree
10
+ * dumps, hand-rolled polling, and dispatch prompt sizes.
11
+ *
12
+ * The same classification lives in the runtime guard (`context-guard-core.js`),
13
+ * so the report and the nudge can never drift.
14
+ *
15
+ * Nothing is inferred from character counts as a cost; every count is a real
16
+ * store row. When the store is unreachable the CLI fails loudly.
17
+ *
18
+ * Usage:
19
+ * node scripts/qa/session-recon.js [--since=14d] [--json]
20
+ * node scripts/qa/session-recon.js --export <file> # write a fixture
21
+ * node scripts/qa/session-recon.js --fixture <file> # read a fixture
22
+ * node scripts/qa/session-recon.js --root <dir> [--opencode <exe>]
23
+ *
24
+ * Fixture schema (stable): { schema, meta, sessions, parts, guardEvents }.
25
+ */
26
+
27
+ const fs = require("fs");
28
+ const path = require("path");
29
+ const PS = require("./provider-stats.js");
30
+ const CG = require("./context-guard-core.js");
31
+
32
+ const SCHEMA = "session-recon/1";
33
+ const LARGE_OUTPUT_BYTES = 30000;
34
+ const EDIT_TOOLS = new Set(["edit", "write", "patch", "multiedit", "apply_patch"]);
35
+
36
+ /* Tools that count as "real work started" for the orientation-depth metric: the
37
+ * first edit/write or dispatch marks the end of the orientation prologue. A
38
+ * resume/claim session otherwise re-derives git/serve/capacity state by hand.
39
+ * Both the V1 names and their V2 aliases (`task`->`subagent`) — the guard core
40
+ * does the same, and a drift-guard test enforces it. */
41
+ const WORK_TOOLS = new Set([
42
+ "edit",
43
+ "write",
44
+ "patch",
45
+ "multiedit",
46
+ "apply_patch",
47
+ "task",
48
+ "subagent",
49
+ ]);
50
+
51
+ // ---------------------------------------------------------------- pure core
52
+
53
+ /* Classify one bash command against the runtime guard's own predicates:
54
+ * `inspect` = read-only shell inspection the dedicated tools cover,
55
+ * `cdWrapped` = a leading shell `cd`, `dump` = a whole-tree output dump. */
56
+ function classifyBashCommand(command) {
57
+ const cmd = String(command || "");
58
+ const reroot = CG.rerootBash(cmd); // normalize a leading `cd <tree> &&` first
59
+ const effective = reroot ? reroot.command : cmd;
60
+ return {
61
+ inspect: CG.inspectCommand(effective),
62
+ cdWrapped: /^\s*cd\s/.test(cmd),
63
+ dump: CG.dumpCommand(cmd),
64
+ poll: CG.pollCommand(cmd),
65
+ gate: CG.gateKey(cmd),
66
+ };
67
+ }
68
+
69
+ function parseInput(input) {
70
+ if (input == null) return {};
71
+ if (typeof input === "object") return input;
72
+ try {
73
+ return JSON.parse(input);
74
+ } catch (_) {
75
+ return {};
76
+ }
77
+ }
78
+
79
+ function dayOf(ms) {
80
+ const n = Number(ms);
81
+ if (!Number.isFinite(n)) return "unknown";
82
+ return new Date(n).toISOString().slice(0, 10);
83
+ }
84
+
85
+ /* Roll up part-level tool habits. `parts` rows: { session_id, tool, input,
86
+ * outputLen, status, time_created }. Pure: no IO, so it is unit-testable. */
87
+ function analyzeTools(parts) {
88
+ const tools = new Map();
89
+ const inspect = new Map();
90
+ const perDay = new Map();
91
+ let bash = 0;
92
+ let cdWrapped = 0;
93
+ let inspectTotal = 0;
94
+ let dumps = 0;
95
+ let bashLarge = 0;
96
+ let readTotal = 0;
97
+ let readWhole = 0;
98
+ let readLarge = 0;
99
+ let readErrors = 0;
100
+ let readRereads = 0;
101
+ let taskCount = 0;
102
+ let taskPromptBytes = 0;
103
+ let taskPromptMax = 0;
104
+ let ghPolling = 0;
105
+ let sleeps = 0;
106
+ let polls = 0;
107
+ let editErrors = 0;
108
+ const pollKinds = new Map();
109
+ const gateRuns = new Map();
110
+ const readSeen = new Map(); // session_id -> Set(filePath)
111
+
112
+ for (const row of parts) {
113
+ const tool = String(row.tool || "?");
114
+ tools.set(tool, (tools.get(tool) || 0) + 1);
115
+ const day = dayOf(row.time_created);
116
+ if (!perDay.has(day)) perDay.set(day, { bash: 0, inspect: 0, cdWrapped: 0 });
117
+ const d = perDay.get(day);
118
+
119
+ if (tool === "bash" || tool === "shell") {
120
+ bash += 1;
121
+ d.bash += 1;
122
+ const input = parseInput(row.input);
123
+ const { inspect: ins, cdWrapped: cd, dump, poll, gate } = classifyBashCommand(input.command);
124
+ if (ins) {
125
+ inspectTotal += 1;
126
+ d.inspect += 1;
127
+ inspect.set(ins, (inspect.get(ins) || 0) + 1);
128
+ }
129
+ if (cd) {
130
+ cdWrapped += 1;
131
+ d.cdWrapped += 1;
132
+ }
133
+ if (dump) dumps += 1;
134
+ if (poll) {
135
+ polls += 1;
136
+ pollKinds.set(poll, (pollKinds.get(poll) || 0) + 1);
137
+ }
138
+ if (gate) gateRuns.set(gate, (gateRuns.get(gate) || 0) + 1);
139
+ if (Number(row.outputLen) >= LARGE_OUTPUT_BYTES) bashLarge += 1;
140
+ const command = String(input.command || "");
141
+ if (/gh\s+(run watch|run view|pr checks|pr view)\b/.test(command) || /for .*\bgh\b/.test(command)) {
142
+ ghPolling += 1;
143
+ }
144
+ if (/\bsleep\b/.test(command)) sleeps += 1;
145
+ } else if (tool === "read") {
146
+ readTotal += 1;
147
+ const input = parseInput(row.input);
148
+ const ranged = input.offset != null || input.limit != null;
149
+ if (!ranged) readWhole += 1;
150
+ if (Number(row.outputLen) >= LARGE_OUTPUT_BYTES) readLarge += 1;
151
+ if (String(row.status || "") === "error") readErrors += 1;
152
+ const fp = String(input.filePath || "");
153
+ if (fp) {
154
+ const seen = readSeen.get(row.session_id) || new Set();
155
+ if (seen.has(fp)) readRereads += 1;
156
+ seen.add(fp);
157
+ readSeen.set(row.session_id, seen);
158
+ }
159
+ } else if (tool === "task" || tool === "subagent") {
160
+ taskCount += 1;
161
+ const input = parseInput(row.input);
162
+ const bytes = typeof input.prompt === "string" ? input.prompt.length : 0;
163
+ taskPromptBytes += bytes;
164
+ if (bytes > taskPromptMax) taskPromptMax = bytes;
165
+ } else if (EDIT_TOOLS.has(tool)) {
166
+ if (String(row.status || "") === "error") editErrors += 1;
167
+ }
168
+ }
169
+
170
+ const toolList = [...tools.entries()]
171
+ .map(([tool, count]) => ({ tool, count }))
172
+ .sort((a, b) => b.count - a.count || a.tool.localeCompare(b.tool));
173
+ const inspectList = [...inspect.entries()]
174
+ .map(([tool, count]) => ({ tool, count }))
175
+ .sort((a, b) => b.count - a.count || a.tool.localeCompare(b.tool));
176
+ const perDayList = [...perDay.entries()]
177
+ .map(([date, v]) => ({ date, ...v }))
178
+ .sort((a, b) => a.date.localeCompare(b.date));
179
+ const orientation = analyzeOrientation(parts);
180
+
181
+ return {
182
+ tools: toolList,
183
+ bash,
184
+ inspect: inspectList,
185
+ inspectTotal,
186
+ inspectShare: bash ? inspectTotal / bash : null,
187
+ cdWrapped,
188
+ dumps,
189
+ bashLarge,
190
+ editErrors,
191
+ orientation,
192
+ read: {
193
+ total: readTotal,
194
+ whole: readWhole,
195
+ large: readLarge,
196
+ errors: readErrors,
197
+ rereads: readRereads,
198
+ wholeShare: readTotal ? readWhole / readTotal : null,
199
+ },
200
+ editErrors,
201
+ task: {
202
+ count: taskCount,
203
+ promptBytesTotal: taskPromptBytes,
204
+ promptBytesAvg: taskCount ? Math.round(taskPromptBytes / taskCount) : 0,
205
+ promptBytesMax: taskPromptMax,
206
+ },
207
+ polling: { gh: ghPolling, sleep: sleeps, poll: polls },
208
+ pollKinds: [...pollKinds.entries()]
209
+ .map(([mode, count]) => ({ mode, count }))
210
+ .sort((a, b) => b.count - a.count),
211
+ gateRuns: [...gateRuns.entries()]
212
+ .map(([gate, count]) => ({ gate, count }))
213
+ .sort((a, b) => b.count - a.count),
214
+ perDay: perDayList,
215
+ };
216
+ }
217
+
218
+ /* Orientation depth: how many tool calls a session spends BEFORE its first real
219
+ * work (an edit/write or a dispatch). A resume/claim session that hand-derives
220
+ * git/serve/capacity state shows a long prologue; `orient` exists to collapse it.
221
+ * Pure: returns { sessions, avg, max, long } where `long` counts sessions with a
222
+ * prologue of 10+ calls. */
223
+ function analyzeOrientation(parts) {
224
+ const bySession = new Map();
225
+ for (const row of parts) {
226
+ const sid = row.session_id;
227
+ if (!bySession.has(sid)) bySession.set(sid, []);
228
+ bySession.get(sid).push(row);
229
+ }
230
+ let total = 0;
231
+ let n = 0;
232
+ let max = 0;
233
+ let long = 0;
234
+ for (const [, rows] of bySession) {
235
+ const sorted = rows
236
+ .slice()
237
+ .sort((a, b) => (Number(a.time_created) || 0) - (Number(b.time_created) || 0));
238
+ let prologue = 0;
239
+ let started = false;
240
+ for (const row of sorted) {
241
+ if (WORK_TOOLS.has(String(row.tool || ""))) {
242
+ started = true;
243
+ break;
244
+ }
245
+ prologue += 1;
246
+ }
247
+ if (!started) continue; // never reached real work (a pure Q&A / no-op session)
248
+ total += prologue;
249
+ n += 1;
250
+ if (prologue > max) max = prologue;
251
+ if (prologue >= 10) long += 1;
252
+ }
253
+ return { sessions: n, avg: n ? Math.round(total / n) : 0, max, long };
254
+ }
255
+
256
+ /* Turn/cost concentration across primary sessions (a session with no parent).
257
+ * The 2026-09-16 → 09-29 window spent ~50% in >60-turn sessions; this makes that
258
+ * visible without cross-referencing provider-stats. */
259
+ function analyzeTurnBands(sessions) {
260
+ const bands = [
261
+ { band: "<=30", test: (t) => t <= 30 },
262
+ { band: "31-50", test: (t) => t > 30 && t <= 50 },
263
+ { band: "51-60", test: (t) => t > 50 && t <= 60 },
264
+ { band: "61-80", test: (t) => t > 60 && t <= 80 },
265
+ { band: "81-100", test: (t) => t > 80 && t <= 100 },
266
+ { band: ">100", test: (t) => t > 100 },
267
+ ].map((b) => ({ band: b.band, sessions: 0, cost: 0, test: b.test }));
268
+ const primaries = sessions.filter((s) => !s.parentId);
269
+ for (const s of primaries) {
270
+ const b = bands.find((x) => x.test(s.turns || 0));
271
+ if (!b) continue;
272
+ b.sessions += 1;
273
+ b.cost += s.cost || 0;
274
+ }
275
+ const totalCost = primaries.reduce((a, s) => a + (s.cost || 0), 0);
276
+ return bands.map(({ band, sessions: n, cost }) => ({
277
+ band,
278
+ sessions: n,
279
+ cost,
280
+ costShare: totalCost ? cost / totalCost : null,
281
+ }));
282
+ }
283
+
284
+ function summarizeGuardEvents(events) {
285
+ const kinds = new Map();
286
+ const perDay = new Map();
287
+ for (const e of events) {
288
+ const kind = String(e.kind || "?");
289
+ kinds.set(kind, (kinds.get(kind) || 0) + 1);
290
+ const day = String(e.ts || "").slice(0, 10) || "unknown";
291
+ if (!perDay.has(day)) perDay.set(day, new Map());
292
+ const d = perDay.get(day);
293
+ d.set(kind, (d.get(kind) || 0) + 1);
294
+ }
295
+ return {
296
+ total: events.length,
297
+ kinds: [...kinds.entries()].map(([kind, count]) => ({ kind, count })).sort((a, b) => b.count - a.count),
298
+ perDay: [...perDay.entries()].map(([date, m]) => ({ date, kinds: Object.fromEntries(m) })).sort((a, b) => a.date.localeCompare(b.date)),
299
+ };
300
+ }
301
+
302
+ function parseGuardEvents(text) {
303
+ const out = [];
304
+ for (const line of String(text || "").split(/\r?\n/)) {
305
+ const s = line.trim();
306
+ if (!s) continue;
307
+ try {
308
+ out.push(JSON.parse(s));
309
+ } catch (_) {
310
+ /* a torn final line is ignored, not fatal */
311
+ }
312
+ }
313
+ return out;
314
+ }
315
+
316
+ function analyze(stats) {
317
+ const habits = analyzeTools(stats.parts || []);
318
+ return {
319
+ habits,
320
+ turnBands: analyzeTurnBands(stats.sessions || []),
321
+ guard: summarizeGuardEvents(stats.guardEvents || []),
322
+ };
323
+ }
324
+
325
+ // ---------------------------------------------------------------- collect
326
+
327
+ /* Tool parts come from the SAME table generation the store resolved — on V2 they
328
+ * are embedded in `session_message.data.content[]`, never the frozen V1 `part`
329
+ * mirror (F-15). The flavour-aware query lives in provider-stats so the two
330
+ * consumers cannot drift. */
331
+ function readReconPartsSql(sessionIds, flavour) {
332
+ return PS.toolPartsSql(sessionIds, flavour);
333
+ }
334
+
335
+ function readGuardEvents(root) {
336
+ try {
337
+ return parseGuardEvents(fs.readFileSync(path.join(root, ".agents", "guard-events.jsonl"), "utf8"));
338
+ } catch (_) {
339
+ return [];
340
+ }
341
+ }
342
+
343
+ /* Collect observed sessions + tool parts for one project root. Injectable `runDb`
344
+ * keeps it unit-testable without a live opencode install. */
345
+ function collectRecon(opts = {}) {
346
+ const root = opts.root ? PS.normalizeRoot(opts.root) : PS.defaultRoot();
347
+ const opencode = opts.runDb ? opts.opencode || "opencode" : opts.opencode || PS.resolveOpencode();
348
+ if (!opts.runDb && !opencode) {
349
+ throw new Error("opencode CLI not found — install it, or set OPENCODE_BIN / pass --opencode <path>");
350
+ }
351
+ const runDb = opts.runDb || ((sql) => PS.runDbJson(opencode, sql));
352
+
353
+ const stats = PS.collectStats({ root, since: opts.since, opencode, runDb, now: opts.now, store: opts.store });
354
+ const ids = stats.sessions.map((s) => s.id);
355
+ const flavour = (stats.meta && stats.meta.store && stats.meta.store.flavour) || "v1";
356
+ const parts = ids.length ? PS.queryChunked(runDb, ids, (chunk) => readReconPartsSql(chunk, flavour)) : [];
357
+ const guardEvents = opts.guardEvents != null ? opts.guardEvents : readGuardEvents(root);
358
+ return { meta: { ...stats.meta, schema: SCHEMA, root }, sessions: stats.sessions, parts, guardEvents };
359
+ }
360
+
361
+ function readFixture(file) {
362
+ const doc = JSON.parse(fs.readFileSync(file, "utf8"));
363
+ if (!doc || doc.schema !== SCHEMA || !Array.isArray(doc.sessions) || !Array.isArray(doc.parts)) {
364
+ throw new Error(`${file} is not a ${SCHEMA} fixture`);
365
+ }
366
+ return {
367
+ meta: { ...(doc.meta || {}), schema: SCHEMA },
368
+ sessions: doc.sessions,
369
+ parts: doc.parts,
370
+ guardEvents: doc.guardEvents || [],
371
+ };
372
+ }
373
+
374
+ function writeFixture(file, stats) {
375
+ const doc = {
376
+ schema: SCHEMA,
377
+ meta: stats.meta,
378
+ sessions: stats.sessions,
379
+ parts: stats.parts,
380
+ guardEvents: stats.guardEvents,
381
+ };
382
+ fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true });
383
+ fs.writeFileSync(file, JSON.stringify(doc, null, 2) + "\n", "utf8");
384
+ return path.resolve(file);
385
+ }
386
+
387
+ // ---------------------------------------------------------------- CLI
388
+
389
+ function parseArgs(argv) {
390
+ const out = { json: false, since: null, exportFile: null, fixture: null, opencode: null, root: null, guardEvents: null, help: false };
391
+ for (let i = 0; i < argv.length; i++) {
392
+ const a = argv[i];
393
+ if (a === "--json") out.json = true;
394
+ else if (a === "--help" || a === "-h") out.help = true;
395
+ else if (a === "--since") out.since = argv[++i];
396
+ else if (a.startsWith("--since=")) out.since = a.slice("--since=".length);
397
+ else if (a === "--export") out.exportFile = argv[++i];
398
+ else if (a === "--fixture") out.fixture = argv[++i];
399
+ else if (a === "--opencode") out.opencode = argv[++i];
400
+ else if (a === "--root") out.root = argv[++i];
401
+ else if (a === "--guard-events") out.guardEvents = parseGuardEvents(fs.readFileSync(argv[++i], "utf8"));
402
+ }
403
+ return out;
404
+ }
405
+
406
+ function pct(x) {
407
+ return x == null ? "n/a" : (x * 100).toFixed(1) + "%";
408
+ }
409
+
410
+ function printHuman(stats, agg) {
411
+ const { meta } = stats;
412
+ const since = meta.since ? meta.since.arg : "all time";
413
+ console.log(`Session recon — ${meta.root} (${since})\n`);
414
+ const h = agg.habits;
415
+ if (!h.bash && !h.read.total) {
416
+ console.log(meta.note ? `No sessions: ${meta.note}` : "No tool activity in this window.");
417
+ return;
418
+ }
419
+ console.log(`Tool calls: bash ${h.bash} · read ${h.read.total} · task ${h.task.count}`);
420
+ console.log(
421
+ `Shell file-inspection (dedicated tools cover these): ${h.inspectTotal}` +
422
+ (h.inspectShare == null ? "" : ` (${pct(h.inspectShare)} of bash)`) +
423
+ ` — ${h.inspect.map((i) => i.tool + " " + i.count).join(", ") || "none"}`
424
+ );
425
+ console.log(`\`cd\`-wrapped bash: ${h.cdWrapped} · whole-tree dumps: ${h.dumps} · bash outputs > 30KB: ${h.bashLarge}`);
426
+ console.log(
427
+ `Reads: whole-file ${h.read.whole}` +
428
+ (h.read.wholeShare == null ? "" : ` (${pct(h.read.wholeShare)})`) +
429
+ ` · > 30KB ${h.read.large} · in-session re-reads ${h.read.rereads} · failed (guessed path) ${h.read.errors}` +
430
+ ` · failed edits ${h.editErrors}`
431
+ );
432
+ console.log(
433
+ `Dispatch prompts: ${h.task.count} (avg ${h.task.promptBytesAvg} B, max ${h.task.promptBytesMax} B) · ` +
434
+ `gh polling cmds ${h.polling.gh} · sleep cmds ${h.polling.sleep}`
435
+ );
436
+ console.log(
437
+ `Hand-rolled polls (use the bounded waiter): ${h.polling.poll}` +
438
+ (h.pollKinds.length ? ` — ${h.pollKinds.map((p) => p.mode + " " + p.count).join(", ")}` : "")
439
+ );
440
+ if (h.gateRuns.length) {
441
+ console.log(`Gate runs (re-run with no edit = batch instead): ${h.gateRuns.map((g) => g.gate + " " + g.count).join(", ")}`);
442
+ }
443
+ if (h.orientation && h.orientation.sessions) {
444
+ console.log(
445
+ `Orientation prologue (calls before first edit/dispatch): avg ${h.orientation.avg}, max ${h.orientation.max}, ` +
446
+ `${h.orientation.long} session(s) with 10+ — use \`orient\` to collapse it`
447
+ );
448
+ }
449
+
450
+ console.log("\nTurn bands (primary sessions):");
451
+ for (const b of agg.turnBands) {
452
+ if (!b.sessions) continue;
453
+ console.log(
454
+ ` ${b.band.padEnd(8)} ${String(b.sessions).padStart(4)} sessions ${PS.money(b.cost).padStart(10)} ${pct(b.costShare).padStart(6)} of cost`
455
+ );
456
+ }
457
+
458
+ if (agg.guard.total) {
459
+ console.log(`\nGuard events: ${agg.guard.total} — ${agg.guard.kinds.map((k) => k.kind + " " + k.count).join(", ")}`);
460
+ }
461
+ console.log("\nAll counts are observed opencode-store rows.");
462
+ }
463
+
464
+ function main() {
465
+ const args = parseArgs(process.argv.slice(2));
466
+ if (args.help) {
467
+ console.log(
468
+ "Usage: node scripts/qa/session-recon.js [--since=14d] [--json]\n" +
469
+ " [--export <file>] [--fixture <file>] [--root <dir>] [--opencode <path>] [--guard-events <file>]"
470
+ );
471
+ return;
472
+ }
473
+ const stats = args.fixture
474
+ ? readFixture(args.fixture)
475
+ : collectRecon({ root: args.root || PS.defaultRoot(), since: args.since, opencode: args.opencode, guardEvents: args.guardEvents });
476
+ const agg = analyze(stats);
477
+ if (args.exportFile) {
478
+ const file = writeFixture(args.exportFile, stats);
479
+ console.error(`session-recon: wrote ${file}`);
480
+ }
481
+ if (args.json) console.log(JSON.stringify({ schema: SCHEMA, ...stats, aggregates: agg }, null, 2));
482
+ else printHuman(stats, agg);
483
+ }
484
+
485
+ if (require.main === module) {
486
+ try {
487
+ main();
488
+ } catch (e) {
489
+ console.error("session-recon: " + (e && e.message ? e.message : e));
490
+ process.exit(1);
491
+ }
492
+ }
493
+
494
+ module.exports = {
495
+ SCHEMA,
496
+ LARGE_OUTPUT_BYTES,
497
+ classifyBashCommand,
498
+ parseInput,
499
+ dayOf,
500
+ analyzeTools,
501
+ analyzeTurnBands,
502
+ analyzeOrientation,
503
+ summarizeGuardEvents,
504
+ parseGuardEvents,
505
+ analyze,
506
+ readReconPartsSql,
507
+ readGuardEvents,
508
+ collectRecon,
509
+ readFixture,
510
+ writeFixture,
511
+ parseArgs,
512
+ };