geneseed 4.25.1 → 4.27.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 (97) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/DESIGN.md +6 -5
  3. package/README.md +10 -6
  4. package/SHIPPED.md +4 -3
  5. package/adapters/bob/README.md +26 -4
  6. package/adapters/claude-code/README.md +6 -2
  7. package/adapters/claude-code/skills/geneseed/SKILL.md +2 -2
  8. package/adapters/opencode/HOW-OPENCODE-LOADS.md +4 -2
  9. package/adapters/opencode/README.md +5 -2
  10. package/adapters/opencode/plugins/geneseed-activity.js +331 -31
  11. package/adapters/opencode/plugins/geneseed-guard.js +79 -4
  12. package/bin/geneseed-hook.mjs +13 -7
  13. package/docs/concepts/enforcement-table.md +12 -0
  14. package/docs/concepts/exclusions.md +15 -1
  15. package/docs/concepts/hook-gates.md +3 -2
  16. package/docs/concepts/hooks.md +12 -1
  17. package/docs/concepts/host-matrix.md +2 -2
  18. package/docs/concepts/ownership.md +79 -0
  19. package/docs/concepts/rules.md +1 -1
  20. package/docs/guides/set-up-ownership.md +77 -0
  21. package/docs/reference/glossary.md +1 -1
  22. package/docs/reference/opencode-plugins.md +1 -1
  23. package/docs/reference/plugin-activity.md +4 -2
  24. package/docs/reference/plugin-guard.md +1 -0
  25. package/docs/reference/troubleshoot-doctor.md +2 -2
  26. package/docs/understand/enforced-vs-asked.md +3 -2
  27. package/docs/understand/machine-bob.md +1 -1
  28. package/docs/understand/machine-claude.md +1 -1
  29. package/docs/understand/machine-opencode.md +2 -2
  30. package/docs/web-ui.md +21 -2
  31. package/harness.config.json +1 -1
  32. package/js/README.md +1 -0
  33. package/js/build/render.mjs +1 -1
  34. package/js/build/source.mjs +5 -1
  35. package/js/cli-table.json +46 -1
  36. package/js/hosts/activity.mjs +175 -30
  37. package/js/hosts/hooks-prims.mjs +2 -2
  38. package/js/hosts/hooks.mjs +45 -5
  39. package/js/hosts/ownership-gate.mjs +105 -0
  40. package/js/hosts/settings.mjs +14 -4
  41. package/js/inspect/cost.mjs +1 -1
  42. package/js/inspect/inventory.mjs +1 -1
  43. package/js/inspect/status.mjs +1 -1
  44. package/js/loop/registry.mjs +17 -0
  45. package/js/web/activity.mjs +116 -5
  46. package/package.json +1 -1
  47. package/registry.json +7 -0
  48. package/src/AGENT.md.tmpl +5 -0
  49. package/src/agents/developer.md +7 -1
  50. package/src/modes/foreman.md +4 -1
  51. package/src/ontology/universal.md +19 -0
  52. package/src/skills/_checkpoints.md +15 -0
  53. package/src/skills/develop.md +4 -0
  54. package/src/skills/document-project.md +2 -1
  55. package/src/skills/learn-mode.md +13 -17
  56. package/src/skills/ownership.md +139 -0
  57. package/src/skills/pipeline.md +1 -1
  58. package/themes/README.md +2 -2
  59. package/themes/_TEMPLATE.json +1 -0
  60. package/themes/biker.json +1 -0
  61. package/themes/commentator.json +1 -0
  62. package/themes/cyberpunk.json +1 -0
  63. package/themes/gamer.json +1 -0
  64. package/themes/imperial.json +1 -0
  65. package/themes/joker.json +1 -0
  66. package/themes/marvin.json +1 -0
  67. package/themes/mean.json +1 -0
  68. package/themes/military.json +1 -0
  69. package/themes/neutral.json +1 -0
  70. package/themes/pirate.json +1 -0
  71. package/themes/sports.json +1 -0
  72. package/themes/verstappen.json +1 -0
  73. package/themes/wizard.json +1 -0
  74. package/web/dist/assets/Activity-DfETiyWm.js +1 -0
  75. package/web/dist/assets/ActivityDetail-CnP3GPAN.js +1 -0
  76. package/web/dist/assets/Bonsai-CN4rRAHc.js +1 -0
  77. package/web/dist/assets/{CopyButton-B6myFV7a.js → CopyButton-CRAUXSG7.js} +1 -1
  78. package/web/dist/assets/{Dashboard-DEQCBcUW.js → Dashboard-CaqOqtkG.js} +2 -2
  79. package/web/dist/assets/Docs-BFxyAVdN.js +5 -0
  80. package/web/dist/assets/{GreenhouseView-CV1squu6.js → GreenhouseView-19roNb5W.js} +1 -1
  81. package/web/dist/assets/{Installs-C4TQVZ_-.js → Installs-BSoQN7w7.js} +3 -3
  82. package/web/dist/assets/{JournalView-CpXsT_JD.js → JournalView-BgU2ybaq.js} +1 -1
  83. package/web/dist/assets/{KitApply-fYh_YjQA.js → KitApply-Ckc0P5kt.js} +1 -1
  84. package/web/dist/assets/{Kits-BMuGOiTg.js → Kits-BZqWGWMu.js} +1 -1
  85. package/web/dist/assets/Laws-CnUWiNIx.js +3 -0
  86. package/web/dist/assets/{Library-DiZqRFL5.js → Library-rYO8owx_.js} +2 -2
  87. package/web/dist/assets/{Loops-DkwWkdPc.js → Loops-CljFhhQV.js} +2 -2
  88. package/web/dist/assets/{OperatorHudView-CLmq0lNh.js → OperatorHudView-xs7SCwCe.js} +1 -1
  89. package/web/dist/assets/{Personal-C70XacpA.js → Personal-CMPwtl36.js} +2 -2
  90. package/web/dist/assets/{Tabs-ChFhPGP6.js → Tabs-CEfSUVQp.js} +1 -1
  91. package/web/dist/assets/{index-DxCqnFPy.js → index-FLVXXvV3.js} +2 -2
  92. package/web/dist/assets/{index-Cqqs-PbJ.css → index-XTGBLKQr.css} +1 -1
  93. package/web/dist/index.html +2 -2
  94. package/web/dist/assets/Activity-BdMwEnFN.js +0 -1
  95. package/web/dist/assets/ActivityDetail-BgUjDuxO.js +0 -1
  96. package/web/dist/assets/Docs-ChBYcQbT.js +0 -5
  97. package/web/dist/assets/Laws-ndHW7Onu.js +0 -3
@@ -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) => {
@@ -13,10 +13,12 @@
13
13
  // memory file — that choice belongs to the user, via the rule skill.
14
14
  // - Wiki (AGENT.md §8): block mutations under a declared wiki's `protected`
15
15
  // folders — the user's knowledge base sets its own no-go zones in geneseed-wiki.jsonc.
16
+ // - Ownership: in an application repo whose root AGENTS.md has no `## Ownership` section,
17
+ // refuse the session's first write once, so the agent proposes the setup first.
16
18
  // High-confidence patterns only, so legitimate work is never caught. Borderline cases
17
19
  // (.env edits) are WARNED, not blocked. Every block is recorded in the gate
18
20
  // ledger (`<cfg>/notebook/gates.jsonl`) under the hook's rule key (`law-1`, `rigor-5`,
19
- // `law-4`, `ops-2`, `process-1`, `wiki`); every skill or subagent call, blocked or not, is
21
+ // `law-4`, `ops-2`, `process-1`, `wiki`, `ownership`); every skill or subagent call, blocked or not, is
20
22
  // counted in `<cfg>/notebook/usage.jsonl` when that `notebook/` exists and `.usage-off` does not.
21
23
  //
22
24
  // GENESEED_GUARD=off disable entirely.
@@ -152,6 +154,8 @@ const CARRIER_TEXT = carrierText()
152
154
  const gateOff = (marker) => new RegExp(`^${marker}:[ \\t]*off[ \\t]*\\r?$`, "m").test(CARRIER_TEXT)
153
155
  const DELETION_GATE_OFF = gateOff("Deletion gate")
154
156
  const SECRETS_GATE_OFF = gateOff("Secrets gate")
157
+ // `--no-ownership-gate` (ruling D25): the ownership first-write gate below stands down.
158
+ const OWNERSHIP_GATE_OFF = gateOff("Ownership gate")
155
159
 
156
160
  // OpenCode 1.x paints a plugin's stderr over its TUI input box (in red); its own log API
157
161
  // writes to the log file instead. The V1 entry sets LOG_CLIENT; V2 and tests have no
@@ -1347,6 +1351,54 @@ function protectedIn(target) {
1347
1351
  }
1348
1352
  }
1349
1353
 
1354
+ // ---- the ownership first-write gate --------------------------------------------
1355
+ // Twin of js/hosts/ownership-gate.mjs's `ownershipBlock` — keep in step (same manifests, same
1356
+ // managed-block strip, same section match, same reason). In an application repo (a git root
1357
+ // holding a build manifest) whose root AGENTS.md has no `## Ownership` section outside the
1358
+ // Geneseed block, the first write of a session is refused once, so the agent proposes the setup
1359
+ // to the developer; the session and root are recorded BEFORE the refusal, so the next write
1360
+ // passes. The marker is this module Set: the plugin lives as long as the OpenCode process.
1361
+ const OWNERSHIP_SEEN = new Set()
1362
+ const OWNERSHIP_MANIFESTS = new Set(["package.json", "pom.xml", "pyproject.toml", "go.mod", "Cargo.toml",
1363
+ "composer.json", "Gemfile"])
1364
+ const isManifest = (n) => OWNERSHIP_MANIFESTS.has(n) || n.startsWith("build.gradle") || n.endsWith(".csproj")
1365
+ const MANAGED_BLOCK_RE = /<!-- BEGIN GENESEED -->[\s\S]*?<!-- END GENESEED -->/g
1366
+ const OWNERSHIP_SECTION_RE = /^## Ownership[ \t]*\r?$/m
1367
+ const OWNERSHIP_TAIL = "Opt out per repo: `## Ownership` with `mode: off` in the root `AGENTS.md`; per " +
1368
+ "install: rebuild with `--no-ownership-gate`. Offer the full documentation " +
1369
+ "(`/document-project`) as yes / later. Stop and ask the developer now; re-issue the write only " +
1370
+ "after they answer. This gate fires once per session and repo."
1371
+ const OWNERSHIP_REASON_NONE = "Geneseed (Ownership) — this application has no `AGENTS.md` with " +
1372
+ "`## Ownership`. Before writing, propose to the developer: set it up (ownership skill), or " +
1373
+ `proceed without for this session. ${OWNERSHIP_TAIL}`
1374
+ const OWNERSHIP_REASON_NO_SECTION = "Geneseed (Ownership) — this application's `AGENTS.md` has no " +
1375
+ "`## Ownership` section. Before writing, ask the developer: add the Ownership section " +
1376
+ `(ownership skill), or proceed without for this session? ${OWNERSHIP_TAIL}`
1377
+ // The reason to refuse this write, or null. `p` is absolute. Never throws.
1378
+ function ownershipBlock(p, sessionID) {
1379
+ try {
1380
+ if (typeof sessionID !== "string" || !sessionID) return null
1381
+ const root = gitRootOf(path.dirname(p))
1382
+ if (!root || !readdirSync(root).some(isManifest)) return null
1383
+ const rel = nocase(path.relative(root, p).replace(/\\/g, "/"))
1384
+ if (rel === nocase("AGENTS.md") || rel.startsWith(nocase(".geneseed/"))) return null
1385
+ // The install's own bookkeeping (memory/, notebook/ beside plugins/, or $GENESEED_HARNESS)
1386
+ // never spends the block — the hook twin's `installRoot`.
1387
+ for (const home of [path.dirname(PLUGIN_DIR), process.env.GENESEED_HARNESS].filter(Boolean)) {
1388
+ const inside = path.relative(path.resolve(home), p)
1389
+ if (!inside.startsWith("..") && !path.isAbsolute(inside)) return null
1390
+ }
1391
+ let text = null
1392
+ try { text = readFileSync(path.join(root, "AGENTS.md"), "utf8") } catch { /* none: gate */ }
1393
+ const own = text === null ? "" : text.replace(MANAGED_BLOCK_RE, "")
1394
+ if (OWNERSHIP_SECTION_RE.test(own)) return null
1395
+ const key = `${sessionID}|${nocase(root)}`
1396
+ if (OWNERSHIP_SEEN.has(key)) return null
1397
+ OWNERSHIP_SEEN.add(key)
1398
+ return own.trim() ? OWNERSHIP_REASON_NO_SECTION : OWNERSHIP_REASON_NONE
1399
+ } catch { return null }
1400
+ }
1401
+
1350
1402
  // Mutation-class tools for the wiki check — wider than WRITE_TOOLS because moving,
1351
1403
  // renaming, or deleting a protected note is as destructive as overwriting it. Same
1352
1404
  // substring stance: over-matching the class is harmless (see WRITE_TOOLS note).
@@ -1386,6 +1438,17 @@ export const GeneseedGuard = async (ctx) => {
1386
1438
  if (ctx?.client) LOG_CLIENT = ctx.client
1387
1439
  // The session's working directory, the same resolution the context plugin uses.
1388
1440
  const root = () => ctx?.worktree || ctx?.directory || process.cwd()
1441
+ // Whether a session has a parent (a subagent's child session). V2 hands in `sessionMeta`
1442
+ // (`ctx.session.get`); V1 asks its client. Read only on the rare would-block path; a failed
1443
+ // lookup reads as a top-level session.
1444
+ const isChildSession = async (sid) => {
1445
+ try {
1446
+ const info = ctx?.sessionMeta ? await ctx.sessionMeta(sid)
1447
+ : await ctx?.client?.session?.get?.({ path: { id: sid } })
1448
+ const meta = info?.data ?? info
1449
+ return Boolean(meta?.parentID ?? meta?.parentId)
1450
+ } catch { return false }
1451
+ }
1389
1452
  return {
1390
1453
  "tool.execute.before": async (input, output) => {
1391
1454
  // Bypass before counting, the order Claude's toolGate keeps: an excluded repo is
@@ -1398,11 +1461,13 @@ export const GeneseedGuard = async (ctx) => {
1398
1461
  const args = output?.args || input?.args || {}
1399
1462
  // `rule` is the ledger key, spelled as js/hosts/hooks.mjs spells it (`law-1`,
1400
1463
  // `law-4`, `process-1`) plus `wiki`, so status counts one vocabulary across hosts.
1401
- const deny = async (why, rule) => {
1464
+ // `tail: false` for the ownership gate: its reason names its own ways out, and the next
1465
+ // write passes anyway, so pointing at GENESEED_GUARD=off would only invite disabling it.
1466
+ const deny = async (why, rule, tail = true) => {
1402
1467
  if (WARN_ONLY) { log(`WARN (would block): ${why}`); return false }
1403
1468
  log(`BLOCKED: ${why}`)
1404
1469
  await ledger(rule)
1405
- throw new Error(`[geneseed-guard] blocked: ${why} — set GENESEED_GUARD=off to allow`)
1470
+ throw new Error(`[geneseed-guard] blocked: ${why}${tail ? " — set GENESEED_GUARD=off to allow" : ""}`)
1406
1471
  }
1407
1472
  try {
1408
1473
  // `apply_patch`'s own tool resolves every marker path against `instance.directory`
@@ -1443,6 +1508,14 @@ export const GeneseedGuard = async (ctx) => {
1443
1508
  return
1444
1509
  }
1445
1510
  }
1511
+ // The ownership first-write gate, last, as in js/hosts/hooks.mjs's ruleDecide. A child
1512
+ // session is a subagent (ruling D29): it cannot ask the user, so it never spends a block.
1513
+ if (!OWNERSHIP_GATE_OFF) {
1514
+ for (const p of paths) {
1515
+ const why = ownershipBlock(path.resolve(cwd, p), input?.sessionID)
1516
+ if (why && !(await isChildSession(input.sessionID))) { await deny(why, "ownership", false); return }
1517
+ }
1518
+ }
1446
1519
  }
1447
1520
  if (hasAny(tool, WIKI_MUTATE_TOOLS)) {
1448
1521
  for (const p of pickPath(args, cwd)) {
@@ -1499,10 +1572,12 @@ export const GeneseedGuard = async (ctx) => {
1499
1572
  async function setupV2(ctx) {
1500
1573
  const hooks = await GeneseedGuard({
1501
1574
  worktree: ctx?.location?.project?.directory, directory: ctx?.location?.directory,
1575
+ sessionMeta: (sessionID) => ctx.session.get({ sessionID }),
1502
1576
  })
1503
1577
  await ctx.tool.hook("execute.before", async (event) => {
1504
1578
  try {
1505
- await hooks["tool.execute.before"]({ tool: event.tool }, { args: event.input })
1579
+ // `sessionID` rides on every V2 execute.before event (@opencode/plugin 2.1.4 `ToolHooks`).
1580
+ await hooks["tool.execute.before"]({ tool: event.tool, sessionID: event.sessionID }, { args: event.input })
1506
1581
  } catch (err) {
1507
1582
  const why = String(err?.message || "")
1508
1583
  if (!why.startsWith("[geneseed-guard]")) return