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
@@ -524,7 +524,8 @@ export function resolveSkillNames(names, {
524
524
  }
525
525
 
526
526
  /**
527
- * The laws whose hook gate an install can switch off, in law order: the cfg/profile key, the
527
+ * The hook gates an install can switch off (the laws', in law order, then the ownership gate,
528
+ * which has no law: `law: null`): the cfg/profile key, the
528
529
  * build flag, the carrier marker (`<marker>: off`, written only when off) and the law. ONE
529
530
  * table, so the flag, the marker, the rebuild argv, the read-back and `status` cannot drift
530
531
  * apart. Every gate is ARMED by default and the law's text binds either way. The deletion row
@@ -534,6 +535,9 @@ export const GATE_SWITCHES = [
534
535
  { key: 'secretsGate', flag: '--no-secrets-gate', arg: 'noSecretsGate', marker: 'Secrets gate', law: 'I' },
535
536
  { key: 'doneGate', flag: '--no-done-gate', arg: 'noDoneGate', marker: 'Done gate', law: 'III' },
536
537
  { key: 'deletionGate', flag: '--no-deletion-gate', arg: 'noDeletionGate', marker: 'Deletion gate', law: 'IV' },
538
+ // Not a law's gate (`law: null`): the ownership first-write gate (js/hosts/ownership-gate.mjs,
539
+ // ruling D25). Its off switch is this flag, never `harness.config.json` (args.mjs says why).
540
+ { key: 'ownershipGate', flag: '--no-ownership-gate', arg: 'noOwnershipGate', marker: 'Ownership gate', law: null },
537
541
  ];
538
542
 
539
543
  /**
package/js/cli-table.json CHANGED
@@ -336,6 +336,21 @@
336
336
  "is_flag": true,
337
337
  "type": null,
338
338
  "hidden": false
339
+ },
340
+ {
341
+ "names": [
342
+ "--no-ownership-gate"
343
+ ],
344
+ "dest": "no_ownership_gate",
345
+ "metavar": null,
346
+ "help": "switch the ownership first-write gate off for this install: an application repo with no '## Ownership' section in its root AGENTS.md is no longer stopped once per session before its first write (not a law's gate); written to the carrier as 'Ownership gate: off' and replayed by rebuilds",
347
+ "choices": null,
348
+ "default": false,
349
+ "required": false,
350
+ "nargs": "0",
351
+ "is_flag": true,
352
+ "type": null,
353
+ "hidden": false
339
354
  }
340
355
  ],
341
356
  "mutex": []
@@ -1216,7 +1231,7 @@
1216
1231
  },
1217
1232
  {
1218
1233
  "name": "rule-gate",
1219
- "help": "PreToolUse hook: force an ASK before any write to user-rules.md or memory (Persist Insight backstop)",
1234
+ "help": "PreToolUse hook: force an ASK before any write to user-rules.md or memory (Persist Insight backstop), and stop the first write of a session once in an application repo with no ## Ownership section in its root AGENTS.md (the ownership gate)",
1220
1235
  "description": "",
1221
1236
  "positionals": [],
1222
1237
  "options": [
@@ -1264,6 +1279,21 @@
1264
1279
  "is_flag": true,
1265
1280
  "type": null,
1266
1281
  "hidden": false
1282
+ },
1283
+ {
1284
+ "names": [
1285
+ "--no-ownership-gate"
1286
+ ],
1287
+ "dest": "no_ownership_gate",
1288
+ "metavar": null,
1289
+ "help": "skip the ownership first-write gate (set by the emit when the install was built --no-ownership-gate); every other check still runs",
1290
+ "choices": null,
1291
+ "default": false,
1292
+ "required": false,
1293
+ "nargs": "0",
1294
+ "is_flag": true,
1295
+ "type": null,
1296
+ "hidden": false
1267
1297
  }
1268
1298
  ],
1269
1299
  "mutex": []
@@ -1556,6 +1586,21 @@
1556
1586
  "is_flag": true,
1557
1587
  "type": null,
1558
1588
  "hidden": false
1589
+ },
1590
+ {
1591
+ "names": [
1592
+ "--no-ownership-gate"
1593
+ ],
1594
+ "dest": "no_ownership_gate",
1595
+ "metavar": null,
1596
+ "help": "skip the ownership first-write gate (set by the emit when the install was built --no-ownership-gate); every other check still runs",
1597
+ "choices": null,
1598
+ "default": false,
1599
+ "required": false,
1600
+ "nargs": "0",
1601
+ "is_flag": true,
1602
+ "type": null,
1603
+ "hidden": false
1559
1604
  }
1560
1605
  ],
1561
1606
  "mutex": []
@@ -5,24 +5,41 @@
5
5
  * session into `<cfg>/activity/`; this module writes the same files for the hosts whose hooks are
6
6
  * processes rather than a resident plugin — Claude Code, OpenClaude and Bob. The web reader
7
7
  * (`js/web/activity.mjs`) cannot tell the two writers apart, and must not need to: the schema is
8
- * the plugin's, plus `writer: "hook"`, `host`, and the two private cursors below (`normalizeEntry`
9
- * never returns them).
8
+ * the plugin's, plus `writer: "hook"`, `host`, and the private fields below — the transcript
9
+ * cursors `transcript_offset`/`last_message_id`, and Bob's pending `subtask_prompts`
10
+ * (`normalizeEntry` never returns them).
10
11
  *
11
12
  * NOT A NEW HOOK ON EVERY TOOL CALL. `bin/geneseed-hook.mjs` calls `recordActivity` after the verb
12
13
  * the host ran anyway has decided (the gates, `context`, `learn`), plus the `activity` verb for
13
- * the two events no other verb is wired to (UserPromptSubmit, SessionEnd). So a Claude session's
14
- * live phase moves only on the gated tools (`Bash|PowerShell`, `Write|Edit|NotebookEdit`,
14
+ * the events no other verb is wired to (UserPromptSubmit, SessionEnd, SubagentStart). So a Claude
15
+ * session's live phase moves only on the gated tools (`Bash|PowerShell`, `Write|Edit|NotebookEdit`,
15
16
  * `Skill|Agent|Task`); the rest of the turn's tool calls arrive at Stop, read out of the
16
17
  * transcript from a stored byte offset (`readTranscriptDelta`). Bob sends no `transcript_path`,
17
18
  * so a Bob session shows only what its matcher-less `tool-gate` sees, call by call.
18
19
  *
20
+ * SNAPSHOT V2 (the Activity garden: docs/concepts/hooks.md). Each file row is keyed by
21
+ * `(path, by)`: `by` is the Claude/OpenClaude sub-agent's `agent_id`, or null for the session.
22
+ * `agents[]` grows a branch on the first event that carries an `agent_id` (SubagentStart, at
23
+ * launch) and closes it on SubagentStop. Bob's payloads carry no sub-agent id (its
24
+ * `spawn_subagent`/`start_subtask` calls fire the PARENT's hooks), so a Bob spawn is an id-less
25
+ * branch that the next root Stop closes, and the session says `attribution: false`. `turns`
26
+ * counts prompts; `context` is the last assistant message's input-side tokens; `compactions`,
27
+ * `compacted_at` and `context_at_compaction` come from PreCompact (Bob: SessionStart `compact`).
28
+ * `root`/`repo` come from the SESSION's cwd only — a worktree sub-agent's own cwd never moves them.
29
+ *
19
30
  * THIS MODULE IS NEVER LOADED WHEN TRACKING IS OFF — the entry checks the flag first, then imports
20
31
  * this file dynamically. It must never print: a hook's stdout is its verdict, and every write
21
32
  * here is best-effort (a hook that fails is a tool call that fails).
22
33
  *
23
- * WHAT IS RECORDED, AND WHAT NEVER IS. A tool's name, a file path's BASENAME, line counts, todo
24
- * text, a prompt snippet and the last assistant message snippet (240 characters each). Never a
25
- * shell command, a file's content or an edit's text: those are where secrets live.
34
+ * WHAT IS RECORDED, AND WHAT NEVER IS. A tool's name, a changed file's path RELATIVE TO THE
35
+ * SESSION'S GIT ROOT (`/`-separated; a file outside the root, or a session outside any repo, gets
36
+ * `path: null` and keeps its basename only, in `file` — a path is never stored absolute), the
37
+ * root and main-repo directories
38
+ * themselves, line counts, todo text, a prompt snippet and the last assistant message snippet
39
+ * (240 characters each). Timeline and phase labels stay basename-only. Never a shell command, a
40
+ * file's content or an edit's text: those are where secrets live. The relative path is the one
41
+ * thing the garden needs to place a file and to see two sessions touch the same one; it says
42
+ * no more than the repo's own tree does, and the directory is git-ignored and 0700.
26
43
  *
27
44
  * Liveness is owned here because two writers need it now. The hooks have no resident process,
28
45
  * so they record `pid: null` and are live by staleness alone; a plugin snapshot keeps its pid
@@ -34,8 +51,11 @@ import {
34
51
  closeSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readSync,
35
52
  renameSync, statSync, unlinkSync, writeFileSync,
36
53
  } from 'node:fs';
54
+ import os from 'node:os';
37
55
  import path from 'node:path';
38
56
  import { parseIntStrict, stripWhitespace } from '../lib/text.mjs';
57
+ // Neither is a new module on the hook path: `hosts.mjs` already imports both.
58
+ import { gitRootOf, mainWorktreeOf } from './gitref.mjs';
39
59
  import { SECRET_RE } from './hooks-prims.mjs';
40
60
  import { sovereignBypass } from './hosts.mjs';
41
61
 
@@ -66,6 +86,13 @@ const SNIPPET_LEN = 160;
66
86
  const SID_CAP = 128;
67
87
  // Edit tools count as touching a file only when they carry an edit, so a Read never counts.
68
88
  const EDIT_FIELDS = ['content', 'new_string', 'new_source', 'diff'];
89
+ // Bob 2.2.3's edit tools, by name: `search_and_replace` carries none of the fields above.
90
+ const BOB_EDITS = new Set(['write_file', 'apply_diff', 'insert_content', 'search_and_replace']);
91
+ // Bob's sub-agent tools. Their calls fire the parent's hooks with no sub-agent id (F17).
92
+ const BOB_SPAWNS = new Set(['spawn_subagent', 'start_subtask']);
93
+ // The context window is not in the transcript: past the 200k one, it can only be the 1M one.
94
+ const WINDOW = 200_000;
95
+ const WINDOW_1M = 1_000_000;
69
96
 
70
97
  /**
71
98
  * The plugin's safe-name scheme, capped: every separator, `..`-forming slash and drive colon
@@ -148,6 +175,26 @@ function isLink(p) {
148
175
  const lineCount = (s) => (typeof s === 'string' && s ? s.split('\n').length : 0);
149
176
  const baseOf = (p) => (typeof p === 'string' && p ? path.basename(p.replace(/\\/g, '/')) : null);
150
177
 
178
+ /**
179
+ * A tool's file path as stored: relative to `root`, `/`-separated, or `null` when there is no
180
+ * root or the file falls outside it (`..`, or another drive, where `path.relative` answers
181
+ * absolute) — the row then keeps only its basename in `file`, so a stray `README.md` outside the
182
+ * repo never reads as the repo's own. A relative path resolves against the session's cwd; Bob's
183
+ * own resolver also expands a leading `~` (F22), so this does too. `path.relative` compares
184
+ * case-insensitively on Windows, which is what Bob's lower-case drive letter (`c:\...`) needs.
185
+ */
186
+ function relPath(p, { cwd, root, host }) {
187
+ if (!baseOf(p) || !root || !cwd) return null;
188
+ try {
189
+ const abs = path.resolve(cwd, host === 'bob' ? p.replace(/^~/, os.homedir()) : p);
190
+ const rel = path.relative(root, abs);
191
+ if (!rel || rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) return null;
192
+ return rel.split(path.sep).join('/');
193
+ } catch {
194
+ return null;
195
+ }
196
+ }
197
+
151
198
  /**
152
199
  * The bytes of `file` written since `offset`, as parsed JSONL objects, and the offset to resume
153
200
  * from. Only COMPLETE lines are consumed, so a line the host is still writing is read next time.
@@ -195,8 +242,13 @@ function toolLabel(name, input) {
195
242
  return typeof named === 'string' && named ? `${name} ${snip(named, 60)}` : name;
196
243
  }
197
244
 
198
- /** Folds one tool call into the session's state: a timeline row, and its file or todo list. */
199
- function applyTool(st, name, input, t, id, status) {
245
+ /**
246
+ * Folds one tool call into the session's state: a timeline row, and its file or todo list.
247
+ * `where` is `{cwd, root, host, by}`: where a path resolves, and who made the edit (`by`: a
248
+ * sub-agent id, or null for the session). A file row is keyed by `(path, by)`; a row with no
249
+ * path (outside the root, or a v1 row) keys as `(file, by)`.
250
+ */
251
+ function applyTool(st, name, input, t, id, status, where) {
200
252
  if (typeof name !== 'string' || !name) return;
201
253
  const label = toolLabel(name, input);
202
254
  const kind = ['Agent', 'Task'].includes(name) ? 'subtask' : 'tool';
@@ -205,12 +257,17 @@ function applyTool(st, name, input, t, id, status) {
205
257
  row.status = status;
206
258
  } else {
207
259
  st.timeline.push({ t, kind, label, tool: name, status, ...(id ? { id } : {}) });
208
- const file = baseOf(input.file_path ?? input.path ?? input.notebook_path);
209
- if (file && EDIT_FIELDS.some((k) => typeof input[k] === 'string')) {
210
- let f = st.files.find((x) => x.file === file);
211
- if (!f) { f = { file, additions: 0, deletions: 0 }; st.files.push(f); }
212
- f.additions += lineCount(input.content ?? input.new_string ?? input.new_source);
213
- f.deletions += lineCount(input.old_string);
260
+ const raw = input.file_path ?? input.path ?? input.notebook_path;
261
+ const file = baseOf(raw);
262
+ if (file && (EDIT_FIELDS.some((k) => typeof input[k] === 'string') || BOB_EDITS.has(name))) {
263
+ const rel = relPath(raw, where);
264
+ const by = where.by;
265
+ let f = st.files.find((x) => (x.path ?? null) === rel && (rel !== null || x.file === file)
266
+ && (x.by ?? null) === by);
267
+ if (!f) { f = { file, path: rel, by, additions: 0, deletions: 0 }; st.files.push(f); }
268
+ // `replace`/`search`: Bob's search_and_replace. apply_diff's SEARCH/REPLACE body is not parsed.
269
+ f.additions += lineCount(input.content ?? input.new_string ?? input.new_source ?? input.replace);
270
+ f.deletions += lineCount(input.old_string ?? input.search);
214
271
  }
215
272
  }
216
273
  if (Array.isArray(input.todos)) {
@@ -220,10 +277,17 @@ function applyTool(st, name, input, t, id, status) {
220
277
  return label;
221
278
  }
222
279
 
223
- /** Folds a transcript delta (Claude's JSONL) in: model, token totals, tool calls, last reply. */
224
- function applyTranscript(st, entries, nowMs) {
280
+ /**
281
+ * Folds a transcript delta (Claude's JSONL) in: model, token totals, tool calls, last reply, and
282
+ * `context` — the input-side tokens (input + cache read + cache creation) of the LAST assistant
283
+ * message carrying usage, which is what the model saw on that call. `null` when the delta has
284
+ * none, so the caller keeps the previous reading. A sidechain line (an older Claude wrote
285
+ * sub-agent turns into the parent transcript) is a different context and never counts.
286
+ */
287
+ function applyTranscript(st, entries, nowMs, where) {
225
288
  const counted = new Set(st.last_message_id ? [st.last_message_id] : []);
226
289
  let reply = null;
290
+ let context = null;
227
291
  for (const e of entries) {
228
292
  const m = e.type === 'assistant' && e.message && typeof e.message === 'object' ? e.message : null;
229
293
  if (!m) continue;
@@ -233,16 +297,22 @@ function applyTranscript(st, entries, nowMs) {
233
297
  st.last_message_id = m.id;
234
298
  st.tokens += (Number(m.usage.input_tokens) || 0) + (Number(m.usage.output_tokens) || 0);
235
299
  }
300
+ // Claude Code's `<synthetic>` messages carry all-zero usage: no reading, never an overwrite.
301
+ if (m.usage && typeof m.usage === 'object' && e.isSidechain !== true && m.model !== '<synthetic>') {
302
+ const used = ['input_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens']
303
+ .reduce((a, k) => a + (Number(m.usage[k]) || 0), 0);
304
+ if (used > 0) context = { used, window: used > WINDOW ? WINDOW_1M : WINDOW };
305
+ }
236
306
  const t = Date.parse(e.timestamp) || nowMs;
237
307
  for (const b of Array.isArray(m.content) ? m.content : []) {
238
308
  if (b && b.type === 'tool_use') {
239
- applyTool(st, b.name, b.input && typeof b.input === 'object' ? b.input : {}, t, b.id, 'completed');
309
+ applyTool(st, b.name, b.input && typeof b.input === 'object' ? b.input : {}, t, b.id, 'completed', where);
240
310
  } else if (b && b.type === 'text' && typeof b.text === 'string' && b.text.trim()) {
241
311
  reply = { text: b.text, t };
242
312
  }
243
313
  }
244
314
  }
245
- return reply;
315
+ return { reply, context };
246
316
  }
247
317
 
248
318
  /** `{count, additions, deletions, items}` over a file list, `items` capped at `cap`. */
@@ -261,15 +331,19 @@ function todosSummary(items, cap) {
261
331
 
262
332
  const ROLL = { SessionStart: 'idle', UserPromptSubmit: 'busy', PreToolUse: 'busy',
263
333
  Stop: 'waiting-input', SessionEnd: 'ended' };
264
- const KNOWN = new Set([...Object.keys(ROLL), 'SubagentStop', 'PreCompact']);
334
+ const KNOWN = new Set([...Object.keys(ROLL), 'SubagentStart', 'SubagentStop', 'PreCompact']);
335
+ const str = (v) => (typeof v === 'string' && v ? v : null);
265
336
 
266
337
  /**
267
338
  * The previous snapshot and detail (or null), a hook payload, and the clock → the next
268
339
  * `{snap, detail}`, or `null` when the event is not one this writer records. NOT pure: the new
269
340
  * detail reuses, and updates in place, `prevDetail`'s lists — the caller writes the result and
270
341
  * discards the input, so a copy would only cost time on the hook path. `delta` is what
271
- * `readTranscriptDelta` returned for a Stop, or null. Claude-shaped and Bob-shaped payloads
272
- * (`{event, tool, input}`) are both read; a tool payload with no event name is a PreToolUse.
342
+ * `readTranscriptDelta` returned for a Stop or a PreCompact, or null. Claude-shaped payloads
343
+ * (Bob 2.2.3 sends them too) and the older Bob shape (`{event, tool, input}`) are both read; a
344
+ * tool payload with no event name is a PreToolUse. A Bob SessionStart is recorded only for a
345
+ * compaction (`source: "compact"`): its startup and resume fire just before the UserPromptSubmit
346
+ * that records the session anyway.
273
347
  */
274
348
  export function applyHookEvent(prev, prevDetail, payload, now, { host = 'claude', delta = null } = {}) {
275
349
  const p = payload;
@@ -278,12 +352,43 @@ export function applyHookEvent(prev, prevDetail, payload, now, { host = 'claude'
278
352
  : (typeof p.event === 'string' ? p.event : null);
279
353
  if (!ev && tool) ev = 'PreToolUse';
280
354
  if (!KNOWN.has(ev)) return null;
355
+ const compact = ev === 'SessionStart' && p.source === 'compact';
356
+ if (host === 'bob' && ev === 'SessionStart' && !compact) return null;
281
357
  const nowMs = Math.round(now * 1000);
282
358
  const det = prevDetail || {};
283
359
  const snap = prev ? { ...prev } : {
284
360
  session_id: p.session_id, agent: null, title: null, cwd: null, status: 'idle', pid: null,
285
361
  writer: 'hook', host,
286
362
  };
363
+ // v2 fields, defaulted so a v1 snapshot resumed across the upgrade grows them in place.
364
+ snap.agents = Array.isArray(snap.agents) ? snap.agents : [];
365
+ snap.turns = Number(snap.turns) || 0;
366
+ snap.context ??= null;
367
+ snap.compactions = Number(snap.compactions) || 0;
368
+ snap.compacted_at ??= null;
369
+ snap.context_at_compaction ??= null;
370
+ const agentId = str(p.agent_id)?.slice(0, SID_CAP) ?? null;
371
+ // Only the session's own events place it: a worktree sub-agent sends its own cwd.
372
+ if (!agentId && str(p.cwd) && p.cwd !== snap.cwd) {
373
+ snap.cwd = p.cwd;
374
+ snap.root = undefined;
375
+ }
376
+ if (snap.root === undefined) {
377
+ snap.root = snap.cwd ? gitRootOf(snap.cwd) : null;
378
+ snap.repo = snap.cwd ? (mainWorktreeOf(snap.cwd) ?? snap.root) : null;
379
+ }
380
+ const where = { cwd: snap.cwd, root: snap.root, host, by: agentId };
381
+ if (agentId) {
382
+ const type = str(p.agent_type) ? snip(p.agent_type, 60) : null;
383
+ let a = snap.agents.find((x) => x.id === agentId);
384
+ if (!a) {
385
+ a = { id: agentId, type, status: 'running', started: now };
386
+ snap.agents.push(a);
387
+ } else if (type) {
388
+ a.type = type;
389
+ }
390
+ if (ev === 'SubagentStop') a.status = 'done';
391
+ }
287
392
  const st = {
288
393
  timeline: Array.isArray(det.timeline) ? det.timeline : [],
289
394
  conversation: Array.isArray(det.conversation) ? det.conversation : [],
@@ -294,14 +399,39 @@ export function applyHookEvent(prev, prevDetail, payload, now, { host = 'claude'
294
399
  last_message_id: snap.last_message_id ?? null,
295
400
  };
296
401
  snap.updated_at = now;
297
- if (typeof p.cwd === 'string' && p.cwd) snap.cwd = p.cwd;
298
402
  if (typeof p.model === 'string' && p.model) st.model = p.model;
299
- if (ROLL[ev]) snap.status = ROLL[ev];
403
+ // A compaction's SessionStart fires mid-turn: it must not idle a busy session.
404
+ if (ROLL[ev] && !compact) snap.status = ROLL[ev];
405
+ // The transcript delta (Stop, PreCompact): its last usage is the context now.
406
+ const transcript = () => {
407
+ if (!delta) return null;
408
+ const r = applyTranscript(st, delta.entries, nowMs, { ...where, by: null });
409
+ snap.transcript_offset = delta.offset;
410
+ if (r.context) snap.context = r.context;
411
+ return r.reply;
412
+ };
413
+ const compacted = () => {
414
+ snap.compactions += 1;
415
+ snap.compacted_at = now;
416
+ snap.context_at_compaction = snap.context?.used ?? null;
417
+ // Unknown until the next Stop reads the regrown size: a /compact with no Stop after it must
418
+ // not read as still full.
419
+ snap.context = null;
420
+ };
300
421
  if (ev === 'SessionStart') {
301
422
  st.timeline.push({ t: nowMs, kind: 'step', label: `Session ${snip(p.source || 'start', 20)}`, status: 'completed' });
423
+ // Claude and OpenClaude count a compaction on PreCompact, which comes first; Bob has only this.
424
+ if (compact && host === 'bob') compacted();
302
425
  } else if (ev === 'UserPromptSubmit') {
303
426
  snap.turn_started_at = now;
304
427
  snap.phase = null;
428
+ // Bob's start_subtask re-enters Bob's input path with its message as the prompt (2.2.3
429
+ // bundle: `handleInputMessage` → `runTurn` → UserPromptSubmit on the root): not a user turn.
430
+ const pending = Array.isArray(snap.subtask_prompts) ? snap.subtask_prompts : [];
431
+ const mine = typeof p.prompt === 'string' ? pending.indexOf(snip(p.prompt.trim(), CONV_LEN)) : -1;
432
+ if (mine >= 0) pending.splice(mine, 1);
433
+ else snap.turns += 1;
434
+ if (pending.length) snap.subtask_prompts = pending; else delete snap.subtask_prompts;
305
435
  if (typeof p.prompt === 'string' && p.prompt.trim()) {
306
436
  if (!snap.title) snap.title = snip(p.prompt);
307
437
  st.conversation.push({ role: 'user', text: snip(p.prompt, CONV_LEN), t: nowMs });
@@ -309,20 +439,34 @@ export function applyHookEvent(prev, prevDetail, payload, now, { host = 'claude'
309
439
  } else if (ev === 'PreToolUse') {
310
440
  const input = (p.tool_input && typeof p.tool_input === 'object') ? p.tool_input
311
441
  : ((p.input && typeof p.input === 'object') ? p.input : {});
312
- const label = applyTool(st, tool, input, nowMs, typeof p.tool_use_id === 'string' ? p.tool_use_id : null, 'running');
442
+ const label = applyTool(st, tool, input, nowMs, typeof p.tool_use_id === 'string' ? p.tool_use_id : null, 'running', where);
313
443
  if (label) snap.phase = label;
444
+ if (host === 'bob' && BOB_SPAWNS.has(tool)) {
445
+ const named = str(input.name) ?? str(input.title);
446
+ snap.agents.push({ id: null, type: named ? snip(named, 60) : null, status: 'running', started: now });
447
+ snap.attribution = false;
448
+ // The prompt its turn will fire, redacted and cut like any prompt snippet; the next
449
+ // matching UserPromptSubmit consumes it. Capped, so a refused subtask cannot pile up.
450
+ if (tool === 'start_subtask' && str(input.message)) {
451
+ snap.subtask_prompts = [...(snap.subtask_prompts ?? []), snip(input.message.trim(), CONV_LEN)].slice(-TODO_CAP);
452
+ }
453
+ }
314
454
  } else if (ev === 'Stop') {
315
- const reply = delta ? applyTranscript(st, delta.entries, nowMs) : null;
316
- if (delta) snap.transcript_offset = delta.offset;
455
+ const reply = transcript();
317
456
  const last = typeof p.last_assistant_message === 'string' ? p.last_assistant_message : reply?.text;
318
457
  if (last && last.trim()) st.conversation.push({ role: 'assistant', text: snip(last, CONV_LEN), t: nowMs });
319
458
  for (const r of st.timeline) if (r.status === 'running') r.status = 'completed';
459
+ // Bob's id-less branches have no stop of their own: the root turn's end closes them.
460
+ for (const a of snap.agents) if (a.id === null && a.status === 'running') a.status = 'done';
320
461
  snap.phase = null;
321
462
  snap.turn_started_at = null;
322
- } else if (ev === 'SubagentStop') {
463
+ } else if (ev === 'SubagentStart' || ev === 'SubagentStop') {
323
464
  const who = typeof p.agent_type === 'string' && p.agent_type ? ` ${snip(p.agent_type, 60)}` : '';
324
- st.timeline.push({ t: nowMs, kind: 'subtask', label: `Subagent${who} done`, status: 'completed' });
465
+ st.timeline.push({ t: nowMs, kind: 'subtask', label: `Subagent${who} ${ev === 'SubagentStart' ? 'started' : 'done'}`,
466
+ status: 'completed' });
325
467
  } else if (ev === 'PreCompact') {
468
+ transcript();
469
+ compacted();
326
470
  st.timeline.push({ t: nowMs, kind: 'step', label: 'Compacting', status: 'completed' });
327
471
  } else if (ev === 'SessionEnd') {
328
472
  snap.phase = null;
@@ -335,6 +479,7 @@ export function applyHookEvent(prev, prevDetail, payload, now, { host = 'claude'
335
479
  snap.todos = todosSummary(st.todos, TODO_CAP);
336
480
  const detail = {
337
481
  files: filesSummary(st.files, Infinity),
482
+ agents: snap.agents,
338
483
  todos: todosSummary(st.todos, Infinity),
339
484
  conversation: st.conversation.slice(-CONV_CAP),
340
485
  timeline: st.timeline.slice(-LOG_CAP),
@@ -367,7 +512,7 @@ export function recordActivity(root, raw, { host = 'claude', now = Date.now() /
367
512
  if (prev) prevDet = readJson(path.join(dir, 'archive', `${stem}.detail.json`));
368
513
  }
369
514
  const ev = p.hook_event_name ?? p.event;
370
- const delta = ev === 'Stop' && typeof p.transcript_path === 'string'
515
+ const delta = (ev === 'Stop' || ev === 'PreCompact') && typeof p.transcript_path === 'string'
371
516
  ? readTranscriptDelta(p.transcript_path, prev ? Number(prev.transcript_offset) || 0 : 0) : null;
372
517
  const next = applyHookEvent(prev, prevDet, p, now, { host, delta });
373
518
  if (!next) return false;
@@ -151,8 +151,8 @@ export function activityOn(root) {
151
151
  }
152
152
 
153
153
  /**
154
- * The `activity` verb, wired to the two events no other verb runs on (UserPromptSubmit;
155
- * SessionEnd on Claude and OpenClaude). It decides nothing and prints nothing: the entry's
154
+ * The `activity` verb, wired to the events no other verb runs on (UserPromptSubmit; SessionEnd
155
+ * and SubagentStart on Claude and OpenClaude). It decides nothing and prints nothing: the entry's
156
156
  * `trackActivity` records the payload after every verb alike, this one included.
157
157
  */
158
158
  export const cmdActivity = () => 0;
@@ -10,8 +10,10 @@
10
10
  *
11
11
  * THREE HOSTS, TWO DIALECTS. `--host` names the host that will read the verdict. Claude Code
12
12
  * (the default) reads `hookSpecificOutput.permissionDecision: "ask"` and shows the user a
13
- * prompt. `--host bob` is Bob's own protocol: PreToolUse ignores stdout and refuses only on
14
- * EXIT CODE 2, so `BLOCK_RULES` (Laws I and IV, plus rigor-5 and ops-2) exit 2 with the reason on stderr
13
+ * prompt; the one `"deny"` (the ownership first-write gate, `./ownership-gate.mjs`) carries
14
+ * its reason to the MODEL instead. `--host bob` is Bob's own protocol: PreToolUse ignores stdout and refuses only on
15
+ * EXIT CODE 2, so `BLOCK_RULES` (Laws I and IV, plus rigor-5 and ops-2) exit 2 with the reason on stderr,
16
+ * as does the ownership gate (through `deny`, with a one-time tail in place of `BOB_FINAL`),
15
17
  * and the rest is a stderr line with exit 0; SessionStart context is plain stdout, as on
16
18
  * Claude. `--host openclaude` speaks Claude's dialect verbatim (OpenClaude is a Claude Code
17
19
  * fork); the flag only picks which root file counts as native for `context`'s discovery.
@@ -63,6 +65,7 @@ import { currentBranch, gitRootOf, loopLaunched } from './gitref.mjs';
63
65
  import { LOSS_CANDIDATE_RE, catastrophic, lossReason, stripStructure } from './loss.mjs';
64
66
  import { selfAndParents, readStdin, SECRET_RE } from './hooks-prims.mjs';
65
67
  import { recordUse } from './usage.mjs';
68
+ import { ownershipBlock } from './ownership-gate.mjs';
66
69
 
67
70
  // ======================================================================================
68
71
  // git-gate — Doctrine process 5's tool-boundary backstop
@@ -175,10 +178,20 @@ export function loopExempt(command, cwd) {
175
178
  * 378-line module parse, being the only thing on the gate path that needed it.
176
179
  * `tests/unit/hook_gates.test.mjs` holds the two byte-identical over non-ASCII reasons.
177
180
  */
178
- export function askDecision(reason) {
181
+ export function askDecision(reason) { return decisionDoc('ask', reason); }
182
+
183
+ /**
184
+ * The `permissionDecision: "deny"` twin of `askDecision`, same spelling. Claude Code shows an
185
+ * ask's reason to the USER and a deny's reason to the MODEL (hooks reference, the
186
+ * `permissionDecisionReason` row), so a gate whose reason is an instruction to the agent (the
187
+ * ownership gate: "propose the setup") must deny, not ask.
188
+ */
189
+ export function denyDecision(reason) { return decisionDoc('deny', reason); }
190
+
191
+ function decisionDoc(decision, reason) {
179
192
  const value = JSON.stringify(reason)
180
193
  .replace(/[\u007f-￿]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
181
- return '{"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "ask", '
194
+ return `{"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "${decision}", `
182
195
  + `"permissionDecisionReason": ${value}}}\n`;
183
196
  }
184
197
 
@@ -284,6 +297,28 @@ function ask(args, verb, rule, reason) {
284
297
  return 0;
285
298
  }
286
299
 
300
+ /**
301
+ * Said after Bob's ownership block, in place of `BOB_FINAL`: this block is NOT final. The
302
+ * marker was written before the refusal, so the same write passes once the developer answered.
303
+ */
304
+ const BOB_ONCE = ' On Bob this block is one-time, not final: the same write passes once the '
305
+ + 'developer has answered.';
306
+
307
+ /**
308
+ * Refuse, and record it, for a gate whose reason the AGENT must read (`denyDecision`), not a
309
+ * prompt for the user. Not `ask`: the ownership rule is not in `BLOCK_RULES`, so on Bob `ask`
310
+ * would warn and let the call through. Bob: exit 2 with `BOB_ONCE`, never `BOB_FINAL`.
311
+ */
312
+ function deny(args, verb, rule, reason) {
313
+ ledger(args && args.root, verb, rule);
314
+ if (HOST === 'bob') {
315
+ err(`[geneseed] BLOCKED: ${reason}${BOB_ONCE}\n`);
316
+ return BOB_DENY_EXIT;
317
+ }
318
+ out(denyDecision(reason));
319
+ return 0;
320
+ }
321
+
287
322
  /**
288
323
  * FAIL CLOSED. Wraps a gate verb so that any throw — a payload that is not JSON, a path
289
324
  * primitive refusing a form, a bug — becomes an `ask` carrying the error, never a silent
@@ -615,7 +650,12 @@ function ruleDecide(args, payload) {
615
650
  + 'check: fix the code, not the check, unless the user asks for this edit.');
616
651
  }
617
652
  const target = ruleGateTarget(p, args.root);
618
- if (!target) return 0;
653
+ if (!target) {
654
+ // The ownership first-write gate (./ownership-gate.mjs), last: every rule above outranks it.
655
+ // `--no-ownership-gate`: the install switched it off (D25).
656
+ const why = args.noOwnershipGate ? null : ownershipBlock(p, payload, body, args.root);
657
+ return why ? deny(args, 'rule-gate', 'ownership', why) : 0;
658
+ }
619
659
  return ask(args, 'rule-gate', 'process-1', `Geneseed (Persist Insight) \u2014 writing to `
620
660
  + `${target}: a standing rule, or a fact to remember? That choice is the user's. Run the `
621
661
  + 'rule skill first.');
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The ownership first-write gate — the hook half of the ownership skill (`src/skills/ownership.md`).
3
+ *
4
+ * In an APPLICATION repo (a git root holding a build manifest) whose root `AGENTS.md` has no
5
+ * `## Ownership` section outside Geneseed's managed block, the first write of a session is
6
+ * refused once, with a reason telling the agent to propose the setup to the developer. The hook
7
+ * never sees the developer's answer, so "once" is a marker: the root is recorded per session
8
+ * BEFORE the refusal, and every later write in that (session, repo) passes. The `AGENT.md`
9
+ * pointer line carries the rest, shell writes included (this gate sees Write|Edit|NotebookEdit,
10
+ * and Bob's write tools, only).
11
+ *
12
+ * ON THE HOOK PATH, so builtins plus `gitRootOf` and `normcase` only — both already loaded by
13
+ * `./hooks.mjs`. `managedBlockWrite`'s delimiters are inlined, not imported: `settings.mjs` is a
14
+ * 1 200-line module the gate path must not parse. NEVER THROWS: a throw would reach `guardGate`
15
+ * and become a gate-error ask on every write in every repo; any surprise is a defer.
16
+ *
17
+ * The OpenCode guard (`adapters/opencode/plugins/geneseed-guard.js`, `ownershipBlock`) is this
18
+ * file's twin and cannot import it — keep the two in step.
19
+ */
20
+ import { appendFileSync, mkdirSync, readFileSync, readdirSync } from 'node:fs';
21
+ import os from 'node:os';
22
+ import path from 'node:path';
23
+ import { normcase } from '../lib/paths.mjs';
24
+ import { gitRootOf } from './gitref.mjs';
25
+
26
+ // D5: the build manifests that make a git root an "application". Exact names, plus two families.
27
+ const MANIFESTS = new Set(['package.json', 'pom.xml', 'pyproject.toml', 'go.mod', 'Cargo.toml',
28
+ 'composer.json', 'Gemfile']);
29
+ const isManifest = (n) => MANIFESTS.has(n) || n.startsWith('build.gradle') || n.endsWith('.csproj');
30
+
31
+ // `managedBlockWrite`'s delimiters (js/hosts/settings.mjs `delimiters('GENESEED')`). On a Bob
32
+ // project install the block holds the whole carrier, `#### Ownership` included — hence the strip
33
+ // and the exact `##` heading match. `\r?`: a CRLF file's `$` sits after the `\r`.
34
+ const MANAGED_BLOCK_RE = /<!-- BEGIN GENESEED -->[\s\S]*?<!-- END GENESEED -->/g;
35
+ const SECTION_RE = /^## Ownership[ \t]*\r?$/m;
36
+
37
+ // Write-shaped tool names (Bob's `tool-gate` also routes reads here: `read_file` carries a path).
38
+ const WRITE_NAME_RE = /write|edit|diff|replace|insert/i;
39
+
40
+ // js/hosts/activity.mjs `safeStem`, copied (that module is not on the gate path): a hostile
41
+ // session id can never steer the marker join out of its directory.
42
+ const safeStem = (sid) => String(sid).replace(/[^A-Za-z0-9_.-]/gu, '_').slice(0, 128);
43
+
44
+ // The marker folder is PER USER: on a shared POSIX /tmp, one folder for everyone would let a
45
+ // second user's marker (or a file planted at the folder's name) silently disarm the gate for
46
+ // the first. The uid where there is one; else the user name; Windows' tmpdir is per user anyway.
47
+ function userTag() {
48
+ if (typeof process.getuid === 'function') return String(process.getuid());
49
+ try { return safeStem(os.userInfo().username); } catch { return 'user'; }
50
+ }
51
+
52
+ const TAIL = 'Opt out per repo: `## Ownership` with `mode: off` in the root `AGENTS.md`; per '
53
+ + 'install: rebuild with `--no-ownership-gate`. Offer the full documentation '
54
+ + '(`/document-project`) as yes / later. Stop and ask the developer now; re-issue the write only '
55
+ + 'after they answer. This gate fires once per session and repo.';
56
+ const REASON_NONE = 'Geneseed (Ownership) — this application has no `AGENTS.md` with '
57
+ + '`## Ownership`. Before writing, propose to the developer: set it up (ownership skill), or '
58
+ + `proceed without for this session. ${TAIL}`;
59
+ const REASON_NO_SECTION = 'Geneseed (Ownership) — this application\'s `AGENTS.md` has no '
60
+ + '`## Ownership` section. Before writing, ask the developer: add the Ownership section '
61
+ + `(ownership skill), or proceed without for this session? ${TAIL}`;
62
+
63
+ /**
64
+ * The refusal reason for this write, or null to defer. `p` is the write target as the payload
65
+ * names it; `body` is the text the write carries (`ruleDecide` already joined it); `installRoot`
66
+ * is the install's own dir (`--root`), whose bookkeeping (memory, notebook) never spends the block.
67
+ */
68
+ export function ownershipBlock(p, payload, body, installRoot = null) {
69
+ try {
70
+ const sid = payload && payload.session_id;
71
+ if (typeof sid !== 'string' || !sid) return null;
72
+ // D29: a sub-agent cannot ask the user, and must not spend the session's one block.
73
+ if (payload.agent_id) return null;
74
+ if (!body && !WRITE_NAME_RE.test(String(payload.tool_name || ''))) return null;
75
+ const target = path.resolve(typeof payload.cwd === 'string' ? payload.cwd : '.', p);
76
+ const root = gitRootOf(path.dirname(target));
77
+ if (!root || !readdirSync(root).some(isManifest)) return null;
78
+ // Writing the setup itself is never what the gate stops.
79
+ const rel = normcase(path.relative(root, target));
80
+ if (rel === normcase('AGENTS.md') || rel.startsWith(normcase('.geneseed/'))) return null;
81
+ if (installRoot) {
82
+ const inInstall = path.relative(path.resolve(installRoot), target);
83
+ if (!inInstall.startsWith('..') && !path.isAbsolute(inInstall)) return null;
84
+ }
85
+ let text = null;
86
+ try { text = readFileSync(path.join(root, 'AGENTS.md'), 'utf8'); } catch { /* none: gate */ }
87
+ const own = text === null ? '' : text.replace(MANAGED_BLOCK_RE, '');
88
+ if (SECTION_RE.test(own)) return null; // on or off, the team has decided
89
+ // shortcut: one small marker file per session, never pruned (the OS temp cleaner owns it);
90
+ // prune here if the folder is ever seen to grow past a few thousand files.
91
+ const dir = path.join(os.tmpdir(), `geneseed-ownership-${userTag()}`);
92
+ const marker = path.join(dir, safeStem(sid));
93
+ const key = normcase(root);
94
+ let seen = '';
95
+ try { seen = readFileSync(marker, 'utf8'); } catch { /* first gated write of the session */ }
96
+ if (seen.split('\n').includes(key)) return null;
97
+ // Recorded BEFORE refusing: a marker that cannot be written must defer, or every write of
98
+ // the session would be refused.
99
+ mkdirSync(dir, { recursive: true });
100
+ appendFileSync(marker, `${key}\n`);
101
+ return own.trim() ? REASON_NO_SECTION : REASON_NONE;
102
+ } catch {
103
+ return null;
104
+ }
105
+ }