geneseed 4.25.0 → 4.26.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 (46) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/SHIPPED.md +1 -1
  3. package/adapters/bob/README.md +25 -3
  4. package/adapters/claude-code/README.md +1 -1
  5. package/adapters/opencode/HOW-OPENCODE-LOADS.md +3 -1
  6. package/adapters/opencode/plugins/geneseed-activity.js +331 -31
  7. package/bin/geneseed-hook.mjs +4 -4
  8. package/docs/concepts/hook-gates.md +2 -1
  9. package/docs/concepts/hooks.md +10 -0
  10. package/docs/concepts/host-matrix.md +2 -2
  11. package/docs/reference/opencode-plugins.md +1 -1
  12. package/docs/reference/plugin-activity.md +4 -2
  13. package/docs/understand/machine-opencode.md +1 -1
  14. package/docs/web-ui.md +17 -0
  15. package/harness.config.json +1 -1
  16. package/js/hosts/activity.mjs +175 -30
  17. package/js/hosts/hooks-prims.mjs +2 -2
  18. package/js/hosts/settings.mjs +6 -1
  19. package/js/loop/registry.mjs +17 -0
  20. package/js/web/activity.mjs +116 -5
  21. package/package.json +1 -1
  22. package/web/dist/assets/Activity-Dq8_Xhxu.js +1 -0
  23. package/web/dist/assets/ActivityDetail-BIxt9mAe.js +1 -0
  24. package/web/dist/assets/Bonsai-CN4rRAHc.js +1 -0
  25. package/web/dist/assets/{CopyButton-OAosTklC.js → CopyButton-DmXwAzBl.js} +1 -1
  26. package/web/dist/assets/{Dashboard-DaHEnWqC.js → Dashboard-BsevsUea.js} +2 -2
  27. package/web/dist/assets/Docs-BkipFlm8.js +5 -0
  28. package/web/dist/assets/{GreenhouseView-CFlG_Hc5.js → GreenhouseView-BJmyqf49.js} +1 -1
  29. package/web/dist/assets/{Installs-CiXf3lrO.js → Installs-CICECChj.js} +3 -3
  30. package/web/dist/assets/{JournalView-DyU4FF-8.js → JournalView-BOyq2Abk.js} +1 -1
  31. package/web/dist/assets/{KitApply-BvFIdwPN.js → KitApply-BRSZjM_N.js} +1 -1
  32. package/web/dist/assets/{Kits-BVL_ltSl.js → Kits-DPGxX2Vv.js} +1 -1
  33. package/web/dist/assets/Laws-CY0hBpkK.js +3 -0
  34. package/web/dist/assets/{Library-CC9ZrdJX.js → Library-PzXbaBWz.js} +2 -2
  35. package/web/dist/assets/{Loops-DPzHBX45.js → Loops-DflSj8Pz.js} +2 -2
  36. package/web/dist/assets/{OperatorHudView-9pCFPQzN.js → OperatorHudView-CjJlJqGm.js} +1 -1
  37. package/web/dist/assets/{Personal-DXbWBfgp.js → Personal-CC7cLkTe.js} +2 -2
  38. package/web/dist/assets/{Tabs-BroMBj5m.js → Tabs-DCzA2Eop.js} +1 -1
  39. package/web/dist/assets/index-XTGBLKQr.css +1 -0
  40. package/web/dist/assets/{index-GG_nvc-S.js → index-xjpstIKL.js} +2 -2
  41. package/web/dist/index.html +2 -2
  42. package/web/dist/assets/Activity-DuFFKHgv.js +0 -1
  43. package/web/dist/assets/ActivityDetail-DfyAAmqe.js +0 -1
  44. package/web/dist/assets/Docs-D_yGLbPG.js +0 -5
  45. package/web/dist/assets/Laws-j55SbGkb.js +0 -3
  46. package/web/dist/assets/index-BpCoORVg.css +0 -1
package/CHANGELOG.md CHANGED
@@ -8,6 +8,28 @@ label. For the capability ↔ spec map, see [SHIPPED.md](SHIPPED.md).
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [4.26.0] — 2026-10-26
12
+
13
+ Minor: Activity's Garden — every live session as a pixel bonsai, fed by richer activity snapshots on every host (where files are, who changed them, sub-agents, turns, context, compactions), plus OpenCode files and the host filter fixed.
14
+
15
+ ### Added
16
+ - **A session's detail page shows its bonsai.** The same pixel tree as the Garden, with hoverable pads listing each author's files and a legend of turns, context, compactions and sub-agents — for a live session and for an ended one, which is drawn as it was, without motion or bubbles.
17
+ - **Activity has a Garden view.** A `List | Garden` switch shows every live session as a pixel bonsai (Canopy style, with a Sakura palette toggle): one shelf per repo, one tree per session. The pot is coloured by host. The tree grows with the prompt count and its crown with the context fill (yellow tips past 80 %), and is pruned flat at each compaction before it grows back. A running sub-agent is a branch with its own pad, tinted by agent type; a finished one leaves a pruned stub and a fallen leaf. Each changed file is a blossom on its author's pad; hover lists the paths. `!` means the session waits for you, `x` an error. A red thread joins two sessions on the same file in one worktree, an amber one across two worktrees. Past ten trees, quiet shelves fold into chips.
18
+ - **Activity records more of each session (Claude Code, OpenClaude, IBM Bob).** Each changed file now keeps its path relative to the session's git root (never absolute; a file outside the repo keeps only its name) and who changed it: the session or one of its sub-agents. Snapshots also carry the sub-agents (a new `SubagentStart` hook on Claude Code and OpenClaude shows one the moment it starts), the git root and main repo, the prompt count, the context size, and the compactions. Bob's sub-agents show, but Bob's hooks do not say which one changed a file.
19
+ - **Activity records OpenCode sub-agents and more of each session.** A child session (a `task` sub-agent) is no longer skipped: it shows as a sub-agent of its parent, and the files it changes are credited to it. Each file keeps its path relative to the repo (never absolute), and the snapshot carries the git root and main repo, the prompt count, the context size and the compactions. On OpenCode 2, changed files now show too, without line counts.
20
+ - **Activity's API serves the garden's data.** Each live session now also carries its git root and main repo (with a case-folded `repo_key` to group them), sub-agents, prompt count, context size, compactions, its uncapped changed files (`files_all`) and the loops running in its worktree. A new top-level `collisions` lists every file two writers changed among the live sessions: same worktree, or two worktrees of one repo. The loop join reads the registry without writing it, so a page view still never writes a file.
21
+
22
+ ### Fixed
23
+ - **OpenCode sessions show their changed files on Activity.** OpenCode 1.x never fills the session summary's diffs; the per-turn diffs sit on the user message (`message.updated`), and a zeroed summary on every step wiped the list. Files now fold from each turn (a repeat of the same turn replaces it, a new turn adds), `session.diff` stays the fallback for 1.3, and an `/undo` (`message.removed`) drops the undone turn.
24
+ - **Activity's host filter lists the hosts again.** The reader dropped each session's `host`, so the filter had no options; an OpenCode plugin snapshot, which carries no host, now reads as `opencode`.
25
+
26
+ ## [4.25.1] — 2026-10-25
27
+
28
+ Patch: Activity, session detail and Doctor use the full width.
29
+
30
+ ### Fixed
31
+ - **Activity, a session's detail and Doctor use the full width** like the other pages, instead of stopping at 820px.
32
+
11
33
  ## [4.25.0] — 2026-10-25
12
34
 
13
35
  Minor: the console's styles use the size tokens, page by page; pages use the full window width; dead CSS removed.
package/SHIPPED.md CHANGED
@@ -20,7 +20,7 @@ historical references, not files distributed with the repo.
20
20
  > **On version numbers.** [`harness.config.json`](harness.config.json)'s `version` is a
21
21
  > human-readable label only. The canonical identity of an installed harness is the
22
22
  > **source fingerprint** stamped in `.geneseed-version` (see `geneseed version`), not the
23
- > string. Current label: **4.25.0**.
23
+ > string. Current label: **4.26.0**.
24
24
 
25
25
  ## Capabilities
26
26
 
@@ -95,7 +95,9 @@ names but **not Claude's protocol**, and the global file at the **nested**
95
95
  and the one way to refuse a call is **exit code 2**. Claude's `permissionDecision:
96
96
  "ask"` on stdout is therefore invisible to Bob — the groups earlier versions wrote were
97
97
  permissive on every call.
98
- - **`SubagentStop` and `PreCompact` are not Bob events**, so they are not written.
98
+ - **`SubagentStop` is not a Bob event**, so it is not written. Bob 2.2.3 does have
99
+ `PreCompact` and `PostCompact` (its bundle's event list and schema); Geneseed does not wire
100
+ them yet, so `learn` still runs on `Stop` only.
99
101
 
100
102
  What the global emit writes into `~/.bob/settings/settings.json`:
101
103
 
@@ -110,6 +112,25 @@ Every hook also feeds the Activity view after it decides (off with `GENESEED_ACT
110
112
  Bob sends no transcript, so a Bob session shows only the calls `tool-gate` sees; see
111
113
  `docs/reference/plugin-activity.md`.
112
114
 
115
+ **The payload Bob actually sends.** Bob 2.2.3's hook runner (read in its shipped bundle,
116
+ `resources/app/extensions/bob-code/dist/extension.js`) writes the payload to stdin and closes
117
+ it, for every event. The keys are Claude's: `hook_event_name`, `session_id` (the root task's
118
+ id), `cwd` (the root workspace, with a lower-case drive letter on Windows), and on tool events
119
+ `tool_name`, `tool_input` (the model's raw arguments) and `tool_use_id`. Older notes describe
120
+ `{event, session_id, tool, input, output}`; the activity writer reads both shapes.
121
+ - The edit tools are `write_file`, `apply_diff`, `insert_content` and `search_and_replace`,
122
+ each with a `path` that Bob resolves against the workspace and expands a leading `~` in. The
123
+ writer does the same, then stores the path relative to the git root.
124
+ - `spawn_subagent` and `start_subtask` run their own task, but its tool calls fire the
125
+ parent's hooks with the parent's `session_id` and no sub-agent id. Activity therefore shows
126
+ such a sub-agent as a branch with no id, which the next `Stop` closes, and marks the session
127
+ `attribution: false`: its files cannot be told from the parent's.
128
+ - After a compaction, Bob fires `SessionStart` with `source: "compact"`. The writer counts a
129
+ compaction there; any other Bob `SessionStart` is not recorded, because the first prompt's
130
+ `UserPromptSubmit` records the session right after it.
131
+ - Bob has no `SessionEnd`, `SubagentStart` or `SubagentStop`. Its settings schema is strict:
132
+ one unknown event key drops the whole hooks block, so none of those is ever written.
133
+
113
134
  No matcher on `PreToolUse`, deliberately: Bob's tools page already drifts from its own
114
135
  changelog (`web_fetch`, the 2.1.0 Office/IBM-docs tools are undocumented there), so an
115
136
  allow-list built from it would fail open on the next tool Bob adds, and a deny-list needs a
@@ -128,8 +149,9 @@ carries.
128
149
  `~/.bob/settings.json` (your own keys there are kept) and writes the new set to the
129
150
  nested file.
130
151
 
131
- **Unverified live.** There is no Bob install on the authoring machine; this is Bob's
132
- documented contract, with the payload field names assumed to be Claude's. If a field
152
+ **Partly verified.** The payload field names are Claude's: Bob 2.2.3's bundle shows them,
153
+ and a live Activity check on 2026-10-25 recorded a Bob session from them. The gates' own
154
+ verdicts are still Bob's documented contract. If a field
133
155
  name differs the gate defers rather than misfires, and the harness still holds through
134
156
  the `rules/geneseed.md` preamble — the same behaviour-contract parity every
135
157
  non-OpenCode host gets. `/hooks` in Bob Shell 2.0.2+ lists the hooks it loaded and
@@ -70,7 +70,7 @@ absolute-path hooks instead — `geneseed setup` does that for you.) It:
70
70
  and auto-compaction is the moment that window is about to be summarised away.
71
71
  This captures memory *before* the summary; the SessionStart `context` hook (which
72
72
  also fires on the `compact` source) re-seeds context *after* it.
73
- - on **UserPromptSubmit** and **SessionEnd**, runs `geneseed-hook activity`, which decides
73
+ - on **UserPromptSubmit**, **SessionEnd** and **SubagentStart**, runs `geneseed-hook activity`, which decides
74
74
  nothing and prints nothing: it records the session for the web console's Activity view.
75
75
  Every other hook above feeds that view too, after it has decided. `GENESEED_ACTIVITY=off`
76
76
  (or the console's toggle) turns it off; see `docs/reference/plugin-activity.md`.
@@ -92,7 +92,9 @@ changed for each plugin:
92
92
  | throwaway session + `prompt` to distil | `ctx.generate.text({ prompt, model })`: one stateless call |
93
93
  | a hook throws to block a tool | a throw is a **defect that fails the whole step**. The guard renames the call instead (see `geneseed-guard.js`) |
94
94
  | `@opencode-ai/plugin` `tool()` helper | `@opencode/plugin`; a plain JSON-schema `input` needs no helper |
95
- | `todo.updated`, session `summary` diffs | no V2 event. The activity cards show no todos or files on V2 |
95
+ | `todo.updated` | no V2 event. The activity cards show no todos on V2 |
96
+ | user-message `summary.diffs` (files touched) | `session.step.ended` / `step.failed` `files`: paths only, so the activity cards show files with no line counts, and a revert never removes one |
97
+ | `session.compacted` | `session.compaction.ended` |
96
98
  | tool part carries its name | `session.tool.called` has no name; it rides on `session.tool.input.started` |
97
99
  | tools `bash`, `apply_patch`, `task` | renamed `shell`, `patch`, `subagent` (the old ids are aliases). The guard's substring classes cover both spellings; its usage counter takes `subagent` (type under `agent`) beside `task`, since the hook sees the name before alias resolution |
98
100
 
@@ -14,9 +14,16 @@
14
14
  // the reader from ever seeing a torn file. The reader lists an entry whose `pid` is
15
15
  // dead or whose `updated_at` is stale as ended, and never deletes it.
16
16
  //
17
- // FLAT: one entry per top-level session. Sub-agent fan-out (subtask parts,
18
- // parent→children tree) is deferred — child sessions (those with a parentID) and the
19
- // learn plugin's throwaway `geneseed-*` distil sessions are skipped entirely.
17
+ // ONE CARD PER ROOT SESSION. A child session (one with a parentID: a `task` / `subagent`
18
+ // sub-agent) gets no card of its own; it becomes a row of its root session's `agents`
19
+ // (running while the child is busy, done when it goes idle), and the files it changes fold
20
+ // into the root's `files` with `by` = the child id. The learn plugin's throwaway `geneseed-*`
21
+ // distil sessions are skipped entirely, and so is a child whose parent this process does not
22
+ // track.
23
+ //
24
+ // Snapshot v2 (the Activity garden) adds `files[].path` and `files[].by`, `root` (OpenCode's
25
+ // own worktree), `repo` (its main checkout), `agents`, `turns`, `context` and the compaction
26
+ // trio — see docs/reference/opencode-plugins.md.
20
27
  //
21
28
  // v1.1 enriches each entry from events/fields it already receives or one `case` away:
22
29
  // the current phase (tool/thinking), model, session token+cost totals, turn-elapsed,
@@ -26,7 +33,7 @@
26
33
  // swallowed — it never blocks a session. See docs/specs/2026-06-15-live-activity-surface.md
27
34
  // and docs/specs/2026-06-18-activity-v1.1-enriched-cards.md.
28
35
 
29
- import fs from "node:fs"
36
+ import fs, { existsSync, statSync, readFileSync } from "node:fs"
30
37
  import os from "node:os"
31
38
  import path from "node:path"
32
39
 
@@ -127,6 +134,130 @@ function acctTotals(map, msgId, cost, tokens) {
127
134
  return { cost: c, tokens: t }
128
135
  }
129
136
 
137
+ // Where a FileDiff's file is, for the garden: OpenCode's own path (relative to the worktree,
138
+ // `/`-separated) when there is a root, else null — as for anything that would leave the root
139
+ // or is absolute (`../`, `/`, a drive, a UNC path). Never an absolute path on disk, and never
140
+ // a basename in `path`, where it would collide with a same-named file at the top of the repo.
141
+ function relPath(file, root) {
142
+ const p = String(file).replace(/\\/g, "/")
143
+ if (!root || p.startsWith("/") || /^[A-Za-z]:/.test(p) || p === ".." || p.startsWith("../")) return null
144
+ return p
145
+ }
146
+
147
+ // FileDiff lists -> the entry's files block. Lists sum per (OpenCode's raw path, by), so one
148
+ // session-wide list passes through unchanged and several per-turn lists become the session's
149
+ // churn; two files of one name stay two rows even when `path` is null. Only {file, path,
150
+ // additions, deletions, by} goes to disk: a FileDiff also carries `patch`, the full diff
151
+ // text, which never does. An entry without `file` (optional upstream) is dropped. A count
152
+ // upstream does not give (V2's step files) stays null rather than reading as 0.
153
+ // Pure; exported for tests. slimDiff trims a list as it is stored, so no patch text is
154
+ // held in memory for the life of the session either (`raw` is the merge key, memory only).
155
+ const slimDiff = (d, by = null, root = null) => {
156
+ const raw = d?.file ? String(d.file).replace(/\\/g, "/") : null
157
+ return { raw, file: raw && path.posix.basename(raw), path: raw && relPath(raw, root),
158
+ additions: d?.additions ?? null, deletions: d?.deletions ?? null, by }
159
+ }
160
+ const addCount = (a, b) => (b == null ? a : (a ?? 0) + b)
161
+ function foldDiffs(lists) {
162
+ const byKey = new Map()
163
+ for (const list of lists) for (const d of list) {
164
+ if (!d?.raw) continue
165
+ const key = `${d.raw}\0${d.by ?? ""}`
166
+ const f = byKey.get(key) ?? { file: d.file, path: d.path, additions: null, deletions: null, by: d.by ?? null }
167
+ f.additions = addCount(f.additions, d.additions); f.deletions = addCount(f.deletions, d.deletions)
168
+ byKey.set(key, f)
169
+ }
170
+ const items = [...byKey.values()]
171
+ return {
172
+ count: items.length,
173
+ additions: items.reduce((n, f) => n + (f.additions || 0), 0),
174
+ deletions: items.reduce((n, f) => n + (f.deletions || 0), 0),
175
+ items,
176
+ }
177
+ }
178
+
179
+ // The session's own turn diff is a snapshot of the whole worktree, so the turn a sub-agent
180
+ // was launched in (and every later one: a background child outlives its turn) also holds the
181
+ // files that sub-agent changed. Each of the session's own (`by: null`) rows is dropped from a
182
+ // turn list keyed at or after the launch turn of a sub-agent that reported the same file, or
183
+ // each sub-agent edit would be drawn twice; a parent edit from an earlier turn stays the
184
+ // parent's. `turns` is Map(key -> slim rows), `launchedIn` Map(child sid -> the parent's
185
+ // user-message id at launch, null when none was seen). Turn order is id order: OpenCode ids
186
+ // ascend, and V2's per-step keys are `files:<assistantMessageID>`, which sort after the
187
+ // prompt that started their turn. Pure; returns the lists to fold.
188
+ function ownRowsDeduped(turns, launchedIn) {
189
+ const since = new Map() // raw path -> the earliest launch turn of a child that reported it
190
+ for (const list of turns.values()) for (const d of list) {
191
+ if (d.by == null || !launchedIn.has(d.by)) continue
192
+ const at = launchedIn.get(d.by) ?? ""
193
+ if (!since.has(d.raw) || at < since.get(d.raw)) since.set(d.raw, at)
194
+ }
195
+ const order = (key) => String(key).replace(/^files:/, "")
196
+ return [...turns].map(([key, list]) => list.filter((d) =>
197
+ d.by != null || !since.has(d.raw) || order(key) < since.get(d.raw)))
198
+ }
199
+
200
+ // The fs-only readers below are twins of js/hosts/gitref.mjs (gitRootOf, gitDirOf,
201
+ // mainWorktreeOf): a plugin is copied whole into an install and cannot import js/.
202
+ // tests/plugins/activity.test.mjs compares each with its original, quotes, semicolons and
203
+ // layout aside; change one, change both.
204
+ function gitRootOf(cwd) {
205
+ try {
206
+ let dir = path.resolve(cwd)
207
+ for (;;) {
208
+ if (existsSync(path.join(dir, ".git"))) return dir
209
+ const up = path.dirname(dir)
210
+ if (up === dir) return null
211
+ dir = up
212
+ }
213
+ } catch {
214
+ return null
215
+ }
216
+ }
217
+ function gitDirOf(root) {
218
+ const dotgit = path.join(root, ".git")
219
+ if (statSync(dotgit).isFile()) {
220
+ const m = /^gitdir:\s*(.+?)\s*$/m.exec(readFileSync(dotgit, "utf8"))
221
+ if (!m) throw new Error(`${dotgit} does not name a gitdir`)
222
+ return path.resolve(root, m[1])
223
+ }
224
+ return dotgit
225
+ }
226
+ function mainWorktreeOf(cwd) {
227
+ try {
228
+ const root = gitRootOf(cwd)
229
+ if (!root || !statSync(path.join(root, ".git")).isFile()) return null
230
+ const gitdir = gitDirOf(root)
231
+ const common = path.resolve(gitdir, readFileSync(path.join(gitdir, "commondir"), "utf8").trim())
232
+ return path.basename(common) === ".git" ? path.dirname(common) : null
233
+ } catch {
234
+ return null
235
+ }
236
+ }
237
+
238
+ // `root` from OpenCode's own worktree: V1 passes the checkout's top level (a linked worktree
239
+ // is its own root), or "/" for a project outside a repository — as is the drive root a
240
+ // global project resolves to, so a filesystem root is no root. `repo` is the main checkout,
241
+ // the root itself on a main checkout.
242
+ function rootsOf(worktree) {
243
+ if (typeof worktree !== "string" || !worktree) return { root: null, repo: null }
244
+ const root = path.resolve(worktree)
245
+ if (root === path.parse(root).root) return { root: null, repo: null }
246
+ return { root, repo: mainWorktreeOf(root) ?? root }
247
+ }
248
+
249
+ // The context-window figure from an assistant message's tokens: input + cache, as OpenCode
250
+ // counts its own context (`input` already excludes the cache). The event carries no window,
251
+ // so it is the estimate every writer shares: 200 000, or 1 000 000 past that. null for an
252
+ // update with no tokens yet (a new message's first update), which must not reset the figure.
253
+ function contextOf(tokens) {
254
+ const used = (tokens?.input || 0) + (tokens?.cache?.read || 0) + (tokens?.cache?.write || 0)
255
+ return used > 0 ? { used, window: used > 200000 ? 1000000 : 200000 } : null
256
+ }
257
+
258
+ // The snapshot v2 keys: set as given (null included) whenever an event carries them.
259
+ const V2_KEYS = ["root", "repo", "agents", "turns", "context", "compactions", "compacted_at", "context_at_compaction"]
260
+
130
261
  // Pure reducer: prev entry (or null) + an extracted event → next entry, or null to
131
262
  // delete the file. The hook does the IO + derivation; this just merges. Truthy-set
132
263
  // fields (title/cwd/agent/model) only overwrite when provided; clearable fields
@@ -149,6 +280,7 @@ function applyEvent(prev, ev) {
149
280
  if ("turn_started_at" in ev) next.turn_started_at = ev.turn_started_at
150
281
  if ("error" in ev) next.error = ev.error
151
282
  if ("blocked_on" in ev) next.blocked_on = ev.blocked_on
283
+ for (const k of V2_KEYS) if (k in ev) next[k] = ev[k]
152
284
  const st = ev.status || nextStatus(ev.type, ev.statusType)
153
285
  if (st) next.status = st
154
286
  return next
@@ -184,9 +316,13 @@ function removeDetail(sid) { try { fs.unlinkSync(detailPath(sid)) } catch {} }
184
316
 
185
317
  // --- plugin ------------------------------------------------------------------
186
318
 
187
- export const GeneseedActivity = async () => {
319
+ export const GeneseedActivity = async (input) => {
320
+ const { root, repo } = rootsOf(input?.worktree) // once: one OpenCode instance, one worktree
188
321
  const owned = new Map() // sid -> entry (top-level sessions this process tracks)
189
- const skipped = new Set() // sid -> child / geneseed throwaway, ignored from here on
322
+ const skipped = new Set() // sid -> geneseed throwaway / orphan child, ignored from here on
323
+ const childOf = new Map() // child sid -> the owned root session it is a sub-agent of
324
+ const agentRows = new Map() // owned sid -> Map(child sid -> {id, type, status, started})
325
+ const launchedIn = new Map() // child sid -> its root session's user-message id at launch (see ownRowsDeduped)
190
326
  const accts = new Map() // sid -> Map(messageId -> {cost,tokens}) — token/cost accumulation
191
327
  const pending = new Map() // sid -> Set(permissionId) — open permission prompts (→ blocked)
192
328
  const timelines = new Map() // sid -> Map(key -> step record) — the v1.2 detail ring (insertion-ordered)
@@ -199,11 +335,59 @@ export const GeneseedActivity = async () => {
199
335
  // keyed by message id so a streaming assistant turn updates in place (not per delta).
200
336
  const detFor = (sid) => {
201
337
  let d = details.get(sid)
202
- if (!d) { d = { files: null, todos: null, lastMs: 0, convo: new Map() }; details.set(sid, d) }
338
+ if (!d) { d = { files: null, todos: null, lastMs: 0, convo: new Map(), turnDiffs: new Map(), wideDiff: null, turnIds: new Set(), lastUser: null }; details.set(sid, d) }
203
339
  return d
204
340
  }
341
+ // The session's latest user-message id (ids ascend; an older message can re-fire later).
342
+ const sawUser = (sid, id) => {
343
+ const d = detFor(sid)
344
+ if (id && (!d.lastUser || id > d.lastUser)) d.lastUser = id
345
+ }
346
+ // Files touched + churn. Where each OpenCode version puts them (session/summary.ts):
347
+ // - 1.19.x: only on the USER message, `summary.diffs`, recomputed after every step of
348
+ // that turn from its first step-start to its latest step-finish snapshot. The session
349
+ // summary is zeroed and session.diff sent empty on every step.
350
+ // - 1.3.x: the same per-turn diffs, plus a session-wide list on session.diff.
351
+ // So the per-turn diffs are the one source, keyed by user message id like acctTotals:
352
+ // the same id replaces (the turn grew), a new id adds per file (a new turn, a new
353
+ // baseline). A session-wide list (session.diff, or a session summary carrying diffs) is
354
+ // only the fallback while no turn has reported: two sources would make the card flicker,
355
+ // and 1.19's revert sends a session.diff that holds the range about to be undone.
356
+ // A sub-agent's turns land in its root session's map with `by` = the child id (message ids
357
+ // are unique across sessions). V2 has no turn diff: each step's files ride a synthetic
358
+ // per-step list (toV1Events), keyed the same way.
359
+ // shortcut: summarize is forked upstream, so an older recompute can land after a newer
360
+ // one and replace it; fine for a live card, upgrade if a turn's numbers must be exact.
361
+ const setFiles = (sid, ev) => {
362
+ const d = detFor(sid)
363
+ const files = foldDiffs(d.turnDiffs.size ? ownRowsDeduped(d.turnDiffs, launchedIn) : [d.wideDiff ?? []])
364
+ ev.files = { ...files, items: files.items.slice(0, FILE_CAP) } // card: capped
365
+ d.files = files // detail: uncapped
366
+ }
367
+ const wideDiff = (sid, list) => {
368
+ if (!Array.isArray(list) || !owned.has(sid)) return false
369
+ detFor(sid).wideDiff = list.map((d) => slimDiff(d, null, root))
370
+ return !detFor(sid).turnDiffs.size // write only when it is the source in force
371
+ }
372
+ // A turn's diff list (user message `id` of session `owner`; `by` the child that ran it).
373
+ const turnDiff = (owner, id, list, by) => {
374
+ detFor(owner).turnDiffs.set(id, list.map((d) => slimDiff(d, by, root)))
375
+ }
376
+ const agentsOf = (sid) => { let m = agentRows.get(sid); if (!m) { m = new Map(); agentRows.set(sid, m) } return m }
377
+ // Create or update a sub-agent row of `owner`; writes only on a change.
378
+ const setAgent = (owner, id, patch) => {
379
+ const m = agentsOf(owner)
380
+ const prev = m.get(id)
381
+ const row = { ...(prev ?? { id, type: null, status: "running", started: Math.floor(Date.now() / 1000) }), ...patch }
382
+ if (prev && prev.status === row.status && prev.type === row.type) return
383
+ m.set(id, row)
384
+ persist(owner, { type: "agent", agents: [...m.values()] })
385
+ flushDetail(owner, true)
386
+ }
205
387
  const forget = (sid) => {
206
388
  owned.delete(sid); accts.delete(sid); pending.delete(sid); timelines.delete(sid); details.delete(sid)
389
+ agentRows.delete(sid)
390
+ for (const [child, owner] of childOf) if (owner === sid) { childOf.delete(child); launchedIn.delete(child) }
207
391
  removeEntry(sid); removeDetail(sid)
208
392
  }
209
393
 
@@ -231,7 +415,7 @@ export const GeneseedActivity = async () => {
231
415
  const now = Date.now()
232
416
  if (!force && now - d.lastMs < DETAIL_THROTTLE_MS) return
233
417
  d.lastMs = now
234
- writeJson(detailPath(sid), { files: d.files, todos: d.todos, conversation: [...d.convo.values()], timeline: [...tlFor(sid).values()] })
418
+ writeJson(detailPath(sid), { files: d.files, todos: d.todos, agents: [...agentsOf(sid).values()], conversation: [...d.convo.values()], timeline: [...tlFor(sid).values()] })
235
419
  } catch (err) { log(`detail ${sid} failed: ${err?.message ?? err}`) }
236
420
  }
237
421
  // Record a message part into the timeline. Returns true when it should force a flush.
@@ -261,8 +445,44 @@ export const GeneseedActivity = async () => {
261
445
  }
262
446
  }
263
447
 
264
- const isThrowaway = (title, parentID) =>
265
- !!parentID || (typeof title === "string" && title.startsWith("geneseed-"))
448
+ const isThrowaway = (title) => typeof title === "string" && title.startsWith("geneseed-")
449
+
450
+ // A sub-agent's events, routed to its root session `owner`. Only what the parent's card
451
+ // shows is read: the child's busy/idle (its branch's status — not the parent's `task` part,
452
+ // which with background=true completes while the child still runs) and its turn diffs.
453
+ const onChild = (event, props, sid, owner) => {
454
+ if (!owned.has(owner)) return
455
+ switch (event.type) {
456
+ case "session.status":
457
+ setAgent(owner, sid, { status: props.status?.type === "idle" ? "done" : "running" })
458
+ return
459
+ case "session.idle":
460
+ case "session.deleted":
461
+ setAgent(owner, sid, { status: "done" })
462
+ if (event.type === "session.deleted") childOf.delete(sid)
463
+ return
464
+ case "message.updated": {
465
+ const info = props.info ?? {}
466
+ if (info.role !== "user" || !info.id || !Array.isArray(info.summary?.diffs)) return
467
+ turnDiff(owner, info.id, info.summary.diffs, sid)
468
+ const ev = { type: "child.diff" }
469
+ setFiles(owner, ev)
470
+ persist(owner, ev)
471
+ flushDetail(owner, true)
472
+ return
473
+ }
474
+ case "message.removed": {
475
+ if (!detFor(owner).turnDiffs.delete(props.messageID)) return
476
+ const ev = { type: "child.diff" }
477
+ setFiles(owner, ev)
478
+ persist(owner, ev)
479
+ flushDetail(owner, true)
480
+ return
481
+ }
482
+ default:
483
+ return
484
+ }
485
+ }
266
486
 
267
487
  const persist = (sid, ev) => {
268
488
  try {
@@ -289,33 +509,52 @@ export const GeneseedActivity = async () => {
289
509
  const props = event.properties ?? event.payload ?? {}
290
510
  const sid = sidOf(props)
291
511
  if (!sid || skipped.has(sid)) return
512
+ const owner = childOf.get(sid)
513
+ if (owner) { onChild(event, props, sid, owner); return }
292
514
 
293
515
  switch (event.type) {
294
516
  case "session.created":
295
517
  case "session.updated": {
296
518
  const info = props.info ?? {}
297
- // A child/subagent session or a geneseed-* distil session is background
298
- // machinery — drop it (and any file we already wrote when its title was
299
- // still blank). Sub-agent fan-out is the deferred tree.
300
- if (isThrowaway(info.title, info.parentID ?? info.parentId)) {
519
+ // A geneseed-* distil session is background machinery — drop it (and any file we
520
+ // already wrote when its title was still blank).
521
+ if (isThrowaway(info.title)) {
301
522
  skipped.add(sid)
302
523
  if (owned.has(sid)) forget(sid)
303
524
  return
304
525
  }
526
+ // A child session is a sub-agent of the root session its parent belongs to; one
527
+ // whose parent this process does not track has nowhere to go.
528
+ const parentID = info.parentID ?? info.parentId
529
+ if (parentID) {
530
+ const top = childOf.get(parentID) ?? (owned.has(parentID) ? parentID : null)
531
+ if (!top) { skipped.add(sid); return }
532
+ childOf.set(sid, top)
533
+ launchedIn.set(sid, detFor(top).lastUser)
534
+ setAgent(top, sid, { type: info.agent || null, status: "running",
535
+ started: Math.floor((info.time?.created || Date.now()) / 1000) })
536
+ return
537
+ }
305
538
  if (event.type !== "session.created" && !owned.has(sid)) return
306
539
  const ev = { type: event.type, title: info.title ?? null, cwd: info.directory }
307
- // Files touched + churn ride the session summary (cumulative).
308
- const s = info.summary
309
- if (s) {
310
- const all = (s.diffs || []).map((d) => ({ file: d.file, additions: d.additions, deletions: d.deletions }))
311
- const files = { count: s.files || 0, additions: s.additions || 0, deletions: s.deletions || 0 }
312
- ev.files = { ...files, items: all.slice(0, FILE_CAP) } // card: capped
313
- detFor(sid).files = { ...files, items: all } // detail: uncapped
314
- }
540
+ if (!owned.has(sid)) Object.assign(ev, { root, repo, agents: [], turns: 0, context: null,
541
+ compactions: 0, compacted_at: null, context_at_compaction: null })
542
+ // A session summary is a files source only when it carries diffs (see setFiles):
543
+ // 1.19 sends it zeroed on every step, which must not wipe the card.
544
+ const wide = wideDiff(sid, info.summary?.diffs)
545
+ if (wide) setFiles(sid, ev)
315
546
  persist(sid, ev)
316
- if (s) flushDetail(sid, true)
547
+ if (wide) flushDetail(sid, true)
317
548
  return
318
549
  }
550
+ case "session.diff":
551
+ if (wideDiff(sid, props.diff)) {
552
+ const ev = { type: event.type }
553
+ setFiles(sid, ev)
554
+ persist(sid, ev)
555
+ flushDetail(sid, true)
556
+ }
557
+ return
319
558
  case "session.deleted":
320
559
  forget(sid)
321
560
  return
@@ -335,7 +574,20 @@ export const GeneseedActivity = async () => {
335
574
  case "message.updated": {
336
575
  if (!owned.has(sid)) return
337
576
  const info = props.info ?? {}
338
- if (info.role !== "assistant") { persist(sid, { type: event.type }); return } // user msg → bump busy
577
+ if (info.role !== "assistant") { // user msg → bump busy, and fold its turn's diffs
578
+ const ev = { type: event.type }
579
+ if (info.role === "user") sawUser(sid, info.id)
580
+ const diffs = info.summary?.diffs
581
+ // No diffs array (the message as first created) leaves the turn as it was;
582
+ // an empty one is real: that turn has changed nothing so far.
583
+ if (info.role === "user" && info.id && Array.isArray(diffs)) {
584
+ turnDiff(sid, info.id, diffs, null)
585
+ setFiles(sid, ev)
586
+ }
587
+ persist(sid, ev)
588
+ if (ev.files) flushDetail(sid, true)
589
+ return
590
+ }
339
591
  const m = acctFor(sid)
340
592
  const isNewTurn = !m.has(info.id)
341
593
  const totals = acctTotals(m, info.id,
@@ -350,9 +602,32 @@ export const GeneseedActivity = async () => {
350
602
  }
351
603
  if (info.error) ev.error = errStr(info.error)
352
604
  else if (isNewTurn) ev.error = null // a fresh turn clears a stale error
605
+ // The compaction summary's input is the conversation it replaces, not the context now.
606
+ const context = info.summary ? null : contextOf(info.tokens)
607
+ if (context) ev.context = context
353
608
  persist(sid, ev)
354
609
  return
355
610
  }
611
+ case "session.compacted": {
612
+ // Counted, stamped, and the context it cut from kept; the context now is unknown until
613
+ // the next assistant message. No status: a compaction runs inside a busy turn and must
614
+ // not show the session idle.
615
+ const prev = owned.get(sid)
616
+ if (!prev) return
617
+ persist(sid, { type: event.type, context: null, compactions: (prev.compactions || 0) + 1,
618
+ compacted_at: Math.floor(Date.now() / 1000), context_at_compaction: prev.context?.used ?? null })
619
+ return
620
+ }
621
+ case "message.removed": {
622
+ // /undo: SessionRevert.cleanup removes each reverted message, so its turn's
623
+ // diffs must leave the totals with it.
624
+ if (!owned.has(sid) || !detFor(sid).turnDiffs.delete(props.messageID)) return
625
+ const ev = { type: event.type }
626
+ setFiles(sid, ev)
627
+ persist(sid, ev)
628
+ flushDetail(sid, true)
629
+ return
630
+ }
356
631
  case "message.part.updated": {
357
632
  if (!owned.has(sid)) return
358
633
  const part = props.part ?? {}
@@ -412,6 +687,18 @@ export const GeneseedActivity = async () => {
412
687
  const sid = input?.sessionID
413
688
  if (!sid || skipped.has(sid) || !owned.has(sid)) return
414
689
  const parts = output?.parts || []
690
+ const id = output?.message?.id ?? input.messageID
691
+ sawUser(sid, id)
692
+ // `turns`: one per user prompt. chat.message fires once per prompt; the same id seen
693
+ // twice is one turn, and a prompt without an id still counts. A prompt made only of
694
+ // synthetic parts is not the user's: a background task hands its result back that way
695
+ // (v1.19.4 TaskTool.injectBackgroundResult).
696
+ if (!(parts.length && parts.every((p) => p?.synthetic))) {
697
+ const ids = detFor(sid).turnIds
698
+ const n = ids.size
699
+ ids.add(id ?? Symbol("prompt"))
700
+ if (ids.size !== n) persist(sid, { type: "chat.message", turns: ids.size })
701
+ }
415
702
  const text = parts.filter((p) => p?.type === "text" && p.text).map((p) => p.text).join(" ").trim()
416
703
  if (!text) return
417
704
  pushTurn(sid, input.messageID, "user", text)
@@ -425,7 +712,7 @@ export const GeneseedActivity = async () => {
425
712
 
426
713
  // ponytail: OpenCode treats every export as a plugin and rejects non-functions; hang
427
714
  // the test helpers off the factory instead — reachable via import, invisible to the loader.
428
- Object.assign(GeneseedActivity, { sidOf, nextStatus, applyEvent, acctTotals, errStr, snip, safeName, activityDir, enabledFromFlag, toV1Events })
715
+ Object.assign(GeneseedActivity, { sidOf, nextStatus, applyEvent, acctTotals, foldDiffs, errStr, snip, safeName, activityDir, enabledFromFlag, toV1Events })
429
716
 
430
717
  // --- OpenCode 2 --------------------------------------------------------------
431
718
  // `export default { id, server, setup }` serves V1 (>= 1.3.4) and V2 from one file — why, and
@@ -435,8 +722,10 @@ Object.assign(GeneseedActivity, { sidOf, nextStatus, applyEvent, acctTotals, err
435
722
  // execution, a message as steps, tool calls as called/success/failed), but every fact the
436
723
  // cards show is still in it. Rather than a second reducer, `toV1Events` translates each
437
724
  // V2 event into the V1 event(s) the handler above already reduces, so both majors write
438
- // the same files. Not carried: todos (V2 publishes no todo event) and files-touched (the
439
- // V1 session summary has no V2 event).
725
+ // the same files. Files touched come from each step's `files` (RelativePath[], no line
726
+ // counts), carried as a synthetic per-step user-message diff list so they fold like V1's turn
727
+ // diffs, a sub-agent's included. Not carried: todos (V2 publishes no todo event), line counts
728
+ // (null), and a revert (the session.revert.* events are not read, so the list never shrinks).
440
729
 
441
730
  // A V2 SessionError ({ type, message }) in the V1 error union errStr reads.
442
731
  const v1Error = (e) => (e ? { name: e.type, data: { message: e.message || e.type } } : undefined)
@@ -451,10 +740,15 @@ function toV1Events(ev, tools) {
451
740
  const t = typeof ev.created === "number" ? ev.created : Date.now()
452
741
  const msg = (info) => ({ type: "message.updated", properties: { info: { role: "assistant", sessionID, ...info } } })
453
742
  const part = (p) => ({ type: "message.part.updated", properties: { part: { sessionID, ...p } } })
743
+ const stepFiles = () => (Array.isArray(d.files) ? [{ type: "message.updated", properties: { info: {
744
+ role: "user", sessionID, id: `files:${d.assistantMessageID}`,
745
+ summary: { diffs: d.files.map((file) => ({ file, additions: null, deletions: null })) } } } }] : [])
454
746
  switch (ev.type) {
455
747
  case "session.created":
456
748
  return [{ type: "session.created", properties: { info: {
457
- id: sessionID, title: d.title, parentID: d.parentID, directory: d.location?.directory } } }]
749
+ id: sessionID, title: d.title, parentID: d.parentID, agent: d.agent, directory: d.location?.directory } } }]
750
+ case "session.compaction.ended":
751
+ return [{ type: "session.compacted", properties: { sessionID } }]
458
752
  case "session.renamed":
459
753
  return [{ type: "session.updated", properties: { info: { id: sessionID, title: d.title } } }]
460
754
  case "session.deleted":
@@ -473,9 +767,9 @@ function toV1Events(ev, tools) {
473
767
  case "session.step.started":
474
768
  return [msg({ id: d.assistantMessageID, mode: d.agent, modelID: d.model?.id, time: { created: t } })]
475
769
  case "session.step.ended":
476
- return [msg({ id: d.assistantMessageID, cost: d.cost, tokens: d.tokens, time: { completed: t } })]
770
+ return [msg({ id: d.assistantMessageID, cost: d.cost, tokens: d.tokens, time: { completed: t } }), ...stepFiles()]
477
771
  case "session.step.failed":
478
- return [msg({ id: d.assistantMessageID, cost: d.cost, tokens: d.tokens, error: v1Error(d.error), time: { completed: t } })]
772
+ return [msg({ id: d.assistantMessageID, cost: d.cost, tokens: d.tokens, error: v1Error(d.error), time: { completed: t } }), ...stepFiles()]
479
773
  // The name rides only on `input.started`; `called` carries the input but no name.
480
774
  case "session.tool.input.started":
481
775
  tools.set(d.id, { name: d.name, start: undefined })
@@ -510,7 +804,13 @@ function toV1Events(ev, tools) {
510
804
  }
511
805
 
512
806
  async function setupV2(ctx) {
513
- const hooks = await GeneseedActivity()
807
+ // V2 passes no worktree path (ctx.worktree is the worktree API), so the root is the
808
+ // checkout's top level above the instance directory, read off disk like V1's input. Step
809
+ // files are relative to the same tree (core snapshot.ts: git.repo.discover on
810
+ // location.project.directory, which project.ts resolves from the nearest `.git` above the
811
+ // directory), but OpenCode takes its realPath: through a symlinked path the two spellings
812
+ // of the root differ, while the relative file paths do not.
813
+ const hooks = await GeneseedActivity({ worktree: gitRootOf(ctx?.location?.directory) })
514
814
  const tools = new Map()
515
815
  // The user's prompt, as V1's chat.message hook received it.
516
816
  await ctx.session.hook("prompt", async (event) => {
@@ -118,10 +118,10 @@ async function trackActivity(verb, args) {
118
118
  const root = verb === 'learn' ? (args.memory && !args.file ? path.dirname(args.memory) : null)
119
119
  : args.root;
120
120
  if (!root || process.env.GENESEED_LEARN_CHILD || isatty(0) || !activityOn(root)) return;
121
- // `context` never read stdin before this writer, and whether Bob's SessionStart pipes one
122
- // and closes it is unverified: a read there could hold the session's start. A Bob session
123
- // is first recorded by its first prompt or tool call instead.
124
- if (verb === 'context' && args.host === 'bob') return;
121
+ // `context` never read stdin before this writer. On Bob that read is safe: Bob 2.2.3's hook
122
+ // runner writes the payload and closes stdin for every event (`stdin.end(JSON.stringify(...))`
123
+ // in its bundle), so the read returns at once. The writer keeps only a Bob SessionStart that
124
+ // reports a compaction (`applyHookEvent`).
125
125
  const raw = readStdin();
126
126
  if (!raw.includes('session_id')) return;
127
127
  const { recordActivity } = await import('../js/hosts/activity.mjs');