geneseed 4.31.0 → 5.0.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 (272) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/DESIGN.md +2 -2
  3. package/README.md +6 -5
  4. package/SHIPPED.md +4 -3
  5. package/adapters/bob/README.md +6 -5
  6. package/adapters/claude-code/README.md +4 -3
  7. package/adapters/claude-code/skills/geneseed/SKILL.md +1 -1
  8. package/adapters/openclaude/README.md +4 -3
  9. package/adapters/opencode/GLOBAL-HARNESS-SPEC.md +3 -1
  10. package/adapters/opencode/HOW-OPENCODE-LOADS.md +2 -1
  11. package/adapters/opencode/README.md +18 -18
  12. package/adapters/opencode/plugins/geneseed-activity.js +57 -1
  13. package/adapters/opencode/plugins/geneseed-context.js +220 -18
  14. package/adapters/opencode/plugins/geneseed-guard.js +578 -74
  15. package/adapters/opencode/plugins/geneseed-learn.js +97 -23
  16. package/bin/geneseed-cli.mjs +17 -25
  17. package/bin/geneseed-hook.mjs +23 -8
  18. package/docs/DESIGN.md +175 -0
  19. package/docs/PRD.md +111 -0
  20. package/docs/README.md +3 -2
  21. package/docs/architecture.md +145 -0
  22. package/docs/concepts/agents.md +1 -1
  23. package/docs/concepts/collaboration.md +1 -1
  24. package/docs/concepts/enforcement-table.md +1 -1
  25. package/docs/concepts/exclusions.md +6 -6
  26. package/docs/concepts/footprint.md +1 -1
  27. package/docs/concepts/foreman-mode.md +2 -2
  28. package/docs/concepts/hook-gates.md +1 -1
  29. package/docs/concepts/hooks.md +27 -11
  30. package/docs/concepts/host-matrix.md +3 -3
  31. package/docs/concepts/hosts.md +1 -1
  32. package/docs/concepts/kits.md +3 -1
  33. package/docs/concepts/loop-bricks.md +1 -1
  34. package/docs/concepts/loop-notes.md +4 -2
  35. package/docs/concepts/loop-templates.md +7 -4
  36. package/docs/concepts/loops.md +3 -0
  37. package/docs/concepts/ownership.md +2 -2
  38. package/docs/concepts/rules.md +15 -2
  39. package/docs/concepts/shared-tier.md +73 -0
  40. package/docs/concepts/skills.md +2 -2
  41. package/docs/concepts/themes.md +1 -1
  42. package/docs/extending.md +13 -12
  43. package/docs/guides/install-claude-code.md +1 -1
  44. package/docs/guides/install-opencode.md +1 -1
  45. package/docs/guides/migrate.md +4 -2
  46. package/docs/guides/project-context.md +2 -2
  47. package/docs/guides/run-a-loop.md +1 -1
  48. package/docs/guides/set-up-ownership.md +1 -1
  49. package/docs/guides/setup-footprint.md +1 -1
  50. package/docs/guides/uninstall.md +2 -1
  51. package/docs/guides/upgrade-to-5.md +116 -0
  52. package/docs/guides/upgrade.md +21 -9
  53. package/docs/guides/wiki.md +3 -3
  54. package/docs/reference/env-context.md +5 -3
  55. package/docs/reference/environment.md +1 -1
  56. package/docs/reference/glossary.md +2 -0
  57. package/docs/reference/loop-actions.md +1 -1
  58. package/docs/reference/opencode-plugins.md +3 -3
  59. package/docs/reference/plugin-activity.md +1 -1
  60. package/docs/reference/plugin-context.md +5 -0
  61. package/docs/reference/plugin-guard.md +14 -6
  62. package/docs/reference/plugin-learn.md +13 -6
  63. package/docs/reference/troubleshoot-hooks.md +3 -3
  64. package/docs/reference/troubleshoot-update.md +14 -0
  65. package/docs/token-footprint.md +4 -3
  66. package/docs/understand/a-day.md +2 -2
  67. package/docs/understand/design-choices-install.md +2 -1
  68. package/docs/understand/enforced-vs-asked.md +4 -3
  69. package/docs/understand/machine-bob.md +3 -1
  70. package/docs/understand/machine-claude.md +7 -5
  71. package/docs/understand/machine-opencode.md +7 -5
  72. package/docs/understand/on-your-machine.md +4 -0
  73. package/docs/understand/take-it-out.md +1 -1
  74. package/docs/web-ui.md +141 -73
  75. package/harness.config.json +1 -1
  76. package/js/README.md +10 -6
  77. package/js/build/args.mjs +10 -8
  78. package/js/build/bundle.mjs +11 -13
  79. package/js/build/driver.mjs +66 -65
  80. package/js/build/emit-claude.mjs +22 -16
  81. package/js/build/emit-common.mjs +4 -5
  82. package/js/build/emit-opencode.mjs +22 -22
  83. package/js/build/fold.mjs +515 -0
  84. package/js/build/generate.mjs +41 -52
  85. package/js/build/render.mjs +115 -29
  86. package/js/build/source.mjs +4 -1
  87. package/js/build/stubs.mjs +70 -9
  88. package/js/build/version.mjs +10 -10
  89. package/js/cli-table.json +23 -83
  90. package/js/hosts/activity.mjs +2 -2
  91. package/js/hosts/geneseed-dir.mjs +1 -1
  92. package/js/hosts/hooks-context.mjs +410 -99
  93. package/js/hosts/hooks-done.mjs +97 -31
  94. package/js/hosts/hooks-learn.mjs +38 -7
  95. package/js/hosts/hooks-prims.mjs +69 -2
  96. package/js/hosts/hooks.mjs +300 -64
  97. package/js/hosts/hosts.mjs +150 -51
  98. package/js/hosts/installs.mjs +55 -167
  99. package/js/hosts/link.mjs +3 -5
  100. package/js/hosts/mcp.mjs +1 -1
  101. package/js/hosts/memory-files.mjs +219 -17
  102. package/js/hosts/ownership-gate.mjs +1 -1
  103. package/js/hosts/settings.mjs +18 -13
  104. package/js/hosts/shim.mjs +4 -33
  105. package/js/hosts/store-watch.mjs +189 -0
  106. package/js/inspect/checks-authoring.mjs +3 -3
  107. package/js/inspect/checks-build.mjs +45 -18
  108. package/js/inspect/checks-counts.mjs +4 -4
  109. package/js/inspect/checks-repo.mjs +13 -14
  110. package/js/inspect/cost.mjs +24 -2
  111. package/js/inspect/diff.mjs +123 -123
  112. package/js/inspect/doctor.mjs +22 -27
  113. package/js/inspect/excludes.mjs +181 -62
  114. package/js/inspect/inventory.mjs +22 -27
  115. package/js/inspect/registry.mjs +106 -30
  116. package/js/inspect/scan.mjs +5 -5
  117. package/js/inspect/status.mjs +141 -119
  118. package/js/inspect/validate.mjs +22 -24
  119. package/js/lib/fs.mjs +47 -50
  120. package/js/lib/json.mjs +10 -17
  121. package/js/lib/machine-dir.mjs +73 -0
  122. package/js/lib/paths.mjs +22 -33
  123. package/js/lib/proc.mjs +1 -1
  124. package/js/lib/prompt.mjs +19 -27
  125. package/js/lib/text.mjs +8 -12
  126. package/js/lib/udiff.mjs +11 -15
  127. package/js/loop/catalog.mjs +2 -3
  128. package/js/loop/state.mjs +15 -5
  129. package/js/maintain/memory.mjs +17 -17
  130. package/js/maintain/migrate.mjs +79 -89
  131. package/js/maintain/setup.mjs +43 -32
  132. package/js/maintain/uninstall.mjs +43 -61
  133. package/js/maintain/update.mjs +200 -93
  134. package/js/ui/anim.mjs +21 -35
  135. package/js/ui/cli.mjs +36 -58
  136. package/js/ui/menu.mjs +22 -45
  137. package/js/ui/tui.mjs +27 -67
  138. package/js/web/actions.mjs +38 -38
  139. package/js/web/api.mjs +132 -76
  140. package/js/web/catalog.mjs +175 -46
  141. package/js/web/docs.mjs +33 -12
  142. package/js/web/doctor-worker.mjs +14 -0
  143. package/js/web/handler.mjs +14 -5
  144. package/js/web/routes.mjs +17 -19
  145. package/js/web/state.mjs +78 -19
  146. package/js/web/update-check.mjs +25 -10
  147. package/js/web/user-files.mjs +50 -105
  148. package/package.json +7 -4
  149. package/registry.json +48 -55
  150. package/src/AGENT.md.tmpl +13 -14
  151. package/src/agents/_self-improvement.md +1 -1
  152. package/src/agents/_template.md +4 -1
  153. package/src/agents/advocate.md +1 -1
  154. package/src/agents/architect.md +1 -1
  155. package/src/agents/developer.md +6 -3
  156. package/src/agents/devops-engineer.md +1 -1
  157. package/src/agents/docker-expert.md +1 -1
  158. package/src/agents/docs.md +1 -1
  159. package/src/agents/empiricist.md +1 -1
  160. package/src/agents/explorer.md +1 -1
  161. package/src/agents/framer.md +1 -1
  162. package/src/agents/historian.md +1 -1
  163. package/src/agents/kubernetes-specialist.md +1 -1
  164. package/src/agents/memory-curator.md +2 -2
  165. package/src/agents/operator.md +1 -1
  166. package/src/agents/performance.md +1 -1
  167. package/src/agents/pragmatist.md +1 -1
  168. package/src/agents/react-engineer.md +1 -1
  169. package/src/agents/react-reviewer.md +1 -1
  170. package/src/agents/researcher.md +1 -1
  171. package/src/agents/reviewer.md +1 -1
  172. package/src/agents/security.md +1 -1
  173. package/src/agents/skeptic.md +1 -1
  174. package/src/agents/spring-boot-engineer.md +1 -1
  175. package/src/agents/spring-reviewer.md +1 -1
  176. package/src/agents/spring-security.md +1 -1
  177. package/src/agents/steward.md +1 -1
  178. package/src/agents/tester.md +5 -2
  179. package/src/agents/user-advocate.md +1 -1
  180. package/src/agents/visionary.md +1 -1
  181. package/src/bricks/apply.md +3 -0
  182. package/src/bricks/test.md +6 -4
  183. package/src/loops/bugfix.json +11 -5
  184. package/src/loops/feature.json +7 -4
  185. package/src/memory/README.md +1 -1
  186. package/src/skills/_self-improvement.md +2 -2
  187. package/src/skills/daydream/SKILL.md +2 -2
  188. package/src/skills/daydream/instructions.md +1 -1
  189. package/src/skills/geneseed.md +1 -1
  190. package/src/skills/learn-mode.md +1 -2
  191. package/src/skills/loop.md +1 -0
  192. package/src/skills/profile.md +2 -2
  193. package/src/skills/rule/approve.md +69 -0
  194. package/src/skills/rule/consolidate.md +3 -3
  195. package/src/skills/rule.md +13 -5
  196. package/src/skills/ship.md +9 -1
  197. package/src/skills/skill-forge.md +1 -1
  198. package/src/skills/teach.md +29 -12
  199. package/src/skills/wiki.md +1 -1
  200. package/themes/_TEMPLATE.json +1 -2
  201. package/themes/biker.json +1 -2
  202. package/themes/commentator.json +1 -2
  203. package/themes/cyberpunk.json +1 -2
  204. package/themes/gamer.json +1 -2
  205. package/themes/imperial.json +1 -2
  206. package/themes/joker.json +1 -2
  207. package/themes/marvin.json +1 -2
  208. package/themes/mean.json +1 -2
  209. package/themes/military.json +1 -2
  210. package/themes/neutral.json +1 -2
  211. package/themes/pirate.json +1 -2
  212. package/themes/sports.json +1 -2
  213. package/themes/verstappen.json +1 -2
  214. package/themes/wizard.json +1 -2
  215. package/web/dist/assets/Activity-D8G4eClY.js +1 -0
  216. package/web/dist/assets/ActivityDetail-BtOBYk3M.js +1 -0
  217. package/web/dist/assets/AgentGlyph-k6o3gCM1.js +1 -0
  218. package/web/dist/assets/Bonsai-B_y20b3i.js +1 -0
  219. package/web/dist/assets/{CopyButton-IXnXzH4Y.js → CopyButton-CHQte7Ap.js} +1 -1
  220. package/web/dist/assets/Dashboard-B8uXeJZ_.js +2 -0
  221. package/web/dist/assets/{DataTable-BWbUx4bY.js → DataTable-b9zTShqJ.js} +1 -1
  222. package/web/dist/assets/Docs-Dgv_MWfT.js +5 -0
  223. package/web/dist/assets/{EmptyState-1sPNleqv.js → EmptyState-CY5Pm2xy.js} +1 -1
  224. package/web/dist/assets/FilterInput-qGKNSlxv.js +1 -0
  225. package/web/dist/assets/GreenhouseView-CSzTMSl_.js +1 -0
  226. package/web/dist/assets/Installs-BDk9lqBI.js +3 -0
  227. package/web/dist/assets/JournalView-CvRk1-m5.js +1 -0
  228. package/web/dist/assets/Kits-CoITzxWM.js +1 -0
  229. package/web/dist/assets/Laws-Ctf5r9rE.js +3 -0
  230. package/web/dist/assets/Library-DNwHYVXt.js +3 -0
  231. package/web/dist/assets/{Loops-C5u7fQOR.js → Loops-S85PMQ8m.js} +2 -2
  232. package/web/dist/assets/Markdown-0ORz7tAc.js +69 -0
  233. package/web/dist/assets/OperatorHudView-DuGz_sTk.js +1 -0
  234. package/web/dist/assets/Personal-afJNwvRS.js +2 -0
  235. package/web/dist/assets/RailCats-AW92uhsX.js +1 -0
  236. package/web/dist/assets/Settings-CGDFz-6j.js +1 -0
  237. package/web/dist/assets/Tabs-1qLrnqmn.js +1 -0
  238. package/web/dist/assets/api-C46vAuqp.js +1 -0
  239. package/web/dist/assets/controls-D4wmg_pl.js +1 -0
  240. package/web/dist/assets/index-COTd4TRZ.js +3 -0
  241. package/web/dist/assets/index-CtorA7uK.css +1 -0
  242. package/web/dist/assets/motion-RlUl1osO.js +1 -0
  243. package/web/dist/assets/react-C1iE8mnY.js +9 -0
  244. package/web/dist/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  245. package/web/dist/assets/{sections-ChwaobfW.js → sections-CtFz7HFH.js} +1 -1
  246. package/web/dist/assets/{usePoll-bDFN-Hr6.js → usePoll-o8ul-Sog.js} +1 -1
  247. package/web/dist/index.html +7 -7
  248. package/src/skills/quiz.md +0 -44
  249. package/web/dist/assets/Activity-B7cFtS00.js +0 -1
  250. package/web/dist/assets/ActivityDetail-C-GbMmuW.js +0 -1
  251. package/web/dist/assets/Bonsai-_YyexVC5.js +0 -1
  252. package/web/dist/assets/Dashboard-sCfEjowQ.js +0 -2
  253. package/web/dist/assets/Docs-w3Y7M5Ts.js +0 -5
  254. package/web/dist/assets/FilterInput-CZREvrjX.js +0 -1
  255. package/web/dist/assets/GreenhouseView-BWWbMKmg.js +0 -1
  256. package/web/dist/assets/Installs-CnkdJ-VA.js +0 -3
  257. package/web/dist/assets/JournalView-C7bPD3fZ.js +0 -1
  258. package/web/dist/assets/KitApply-CQQbnThf.js +0 -1
  259. package/web/dist/assets/Kits-aj07N7mT.js +0 -1
  260. package/web/dist/assets/Laws-DZ38nl_H.js +0 -3
  261. package/web/dist/assets/Library-QCGXPV5h.js +0 -2
  262. package/web/dist/assets/Markdown-DpmmtW2Y.js +0 -65
  263. package/web/dist/assets/OperatorHudView-Blu1lqiZ.js +0 -1
  264. package/web/dist/assets/Personal-ox_MktWO.js +0 -2
  265. package/web/dist/assets/RailCats-BuJD4Jou.js +0 -1
  266. package/web/dist/assets/Tabs-CIPyMAX-.js +0 -1
  267. package/web/dist/assets/api-BxjLd7Qd.js +0 -1
  268. package/web/dist/assets/index-0GCxkY7m.css +0 -1
  269. package/web/dist/assets/index-CzDi9JpF.js +0 -3
  270. package/web/dist/assets/motion-CXaUMNkg.js +0 -1
  271. package/web/dist/assets/react-DlYQp10C.js +0 -9
  272. package/web/dist/assets/rolldown-runtime-hePW80VL.js +0 -1
@@ -9,11 +9,18 @@
9
9
  * closure (the generator now imports this file too, and its spawn ban greps for that literal)
10
10
  * and made the hook module a row in `tests/unit/hook_cli.test.mjs`'s spawn allow-list for a
11
11
  * spawn the CLI never makes. Everything here is fs-only; `hooks-learn.mjs` is the one spawner.
12
+ *
13
+ * `user-rules.md`'s parser lives here too, and the draft's format and the fold's ledger reader: the
14
+ * web console edits or shows through them and the fold writes through them, and the build may not
15
+ * import `js/web` (spec C20).
12
16
  */
13
- import { existsSync, mkdirSync, renameSync, rmdirSync, unlinkSync } from 'node:fs';
17
+ import { isUtf8 } from 'node:buffer';
18
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmdirSync, unlinkSync } from 'node:fs';
14
19
  import path from 'node:path';
15
- import { readText, writeText } from '../lib/fs.mjs';
20
+ import { readText, writeText, writeTextAtomic } from '../lib/fs.mjs';
21
+ import { isDict } from '../lib/json.mjs';
16
22
  import { normcase } from '../lib/paths.mjs';
23
+ import { WHITESPACE, stripWhitespace } from '../lib/text.mjs';
17
24
  import { isFile, listDir, sortPaths, splitLines, splitWords } from './hooks-prims.mjs';
18
25
 
19
26
  const FRONTMATTER_RE = /^\s*---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/;
@@ -44,13 +51,24 @@ const MAP_HINT = 'Each topic file lists its facts; open the one the task needs.'
44
51
  const FACT_LINE_RE = /^- \[([^\]]*)\]\((?:\.\.\/)?([^/)]+)\.md\)(.*)$/;
45
52
  const MAP_LINE_RE = /^- \[[^\]]*\]\(topics\/[^)]+\.md\)/;
46
53
 
47
- /** `append_agent_lesson` — one dated bullet, capped at the newest MAX_AGENT_BULLETS. */
54
+ /**
55
+ * `append_agent_lesson` — one dated bullet, capped at the newest MAX_AGENT_BULLETS.
56
+ *
57
+ * A FILE THAT IS NOT UTF-8 IS LEFT WHOLE, the fold's rule (`foldRules` in js/build/fold.mjs): the
58
+ * read below replaces each bad byte, so rewriting the file would change a line nobody touched.
59
+ * The lesson is dropped and the answer is null; the caller says so. The tier's agent files are
60
+ * the ones that can be hand-edited in another encoding.
61
+ */
48
62
  export function appendAgentLesson(memDir, agent, lesson) {
49
63
  const d = path.join(memDir, 'agents');
50
64
  mkdirSync(d, { recursive: true });
51
65
  const f = path.join(d, `${agent}.md`);
52
66
  let bullets = [];
53
- if (existsSync(f)) bullets = splitLines(readText(f)).filter((l) => l.startsWith('- '));
67
+ if (existsSync(f)) {
68
+ const raw = readFileSync(f);
69
+ if (!isUtf8(raw)) return null;
70
+ bullets = splitLines(raw.toString('utf8')).filter((l) => l.startsWith('- '));
71
+ }
54
72
  const now = new Date();
55
73
  const day = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-`
56
74
  + `${String(now.getDate()).padStart(2, '0')}`;
@@ -95,7 +113,7 @@ function globMd(dir) {
95
113
  }
96
114
 
97
115
  /** Stems that name the store's own files, never a fact — `MEMORY` is the index itself. */
98
- const RESERVED_STEMS = new Set(['memory', 'readme']);
116
+ export const RESERVED_STEMS = new Set(['memory', 'readme']);
99
117
 
100
118
  /**
101
119
  * `_existing_slugs` — slugs already stored. learn never CREATES one of these; it may only
@@ -105,6 +123,16 @@ export function existingSlugs(memDir) {
105
123
  return new Set(globMd(memDir).map(stem).filter((s) => !RESERVED_STEMS.has(s.toLowerCase())));
106
124
  }
107
125
 
126
+ /**
127
+ * How many facts a store holds, by the same test the console's list uses. No folder is no facts
128
+ * (0); a folder that cannot be listed is null, so a row says "not read" rather than "no facts".
129
+ * The first listing is only for that answer: `existingSlugs` reads a failure as empty.
130
+ */
131
+ export function factCount(store) {
132
+ try { readdirSync(store); } catch (e) { return e?.code === 'ENOENT' ? 0 : null; }
133
+ return existingSlugs(store).size;
134
+ }
135
+
108
136
  /** Lines of a text file, or null when it cannot be read. */
109
137
  function readLines(p) {
110
138
  try { return splitLines(readText(p)); } catch { return null; }
@@ -117,7 +145,7 @@ function readLines(p) {
117
145
  function writeIfChanged(p, text) {
118
146
  const old = readLines(p);
119
147
  if (old && `${old.join('\n')}\n` === text) return;
120
- writeText(p, text);
148
+ writeTextAtomic(p, text);
121
149
  }
122
150
 
123
151
  /** A topic name as a file stem: `[a-z0-9-]`, any other run becomes `-`, empty becomes `misc`. */
@@ -167,6 +195,19 @@ function indexedFacts(memDir) {
167
195
  return found;
168
196
  }
169
197
 
198
+ /**
199
+ * What MEMORY.md holds that no index writer generated: the lines a person wrote.
200
+ * `generated(slug)` says whether a flat pointer to that slug counts as generated too.
201
+ */
202
+ export function indexNotes(memDir, generated) {
203
+ return (readLines(path.join(memDir, 'MEMORY.md')) ?? []).filter((l) => {
204
+ const t = l.trim();
205
+ const flat = FACT_LINE_RE.exec(t);
206
+ return t && t !== MEMORY_SEED.trim() && t !== MAP_HINT && !MAP_LINE_RE.test(t)
207
+ && !(flat && generated(flat[2]));
208
+ });
209
+ }
210
+
170
211
  /**
171
212
  * Rewrite MEMORY.md as the map: one line per topic file with its fact count.
172
213
  *
@@ -177,11 +218,7 @@ function indexedFacts(memDir) {
177
218
  */
178
219
  function writeMap(memDir, dropFlat) {
179
220
  const idx = path.join(memDir, 'MEMORY.md');
180
- const carried = (readLines(idx) ?? []).filter((l) => {
181
- const t = l.trim();
182
- return t && t !== MEMORY_SEED.trim() && t !== MAP_HINT && !MAP_LINE_RE.test(t)
183
- && !(dropFlat && FACT_LINE_RE.test(t));
184
- });
221
+ const carried = indexNotes(memDir, () => dropFlat);
185
222
  const tdir = path.join(memDir, TOPICS);
186
223
  const topics = globMd(tdir).map(stem).sort().map((t) => {
187
224
  const n = (readLines(path.join(tdir, `${t}.md`)) ?? [])
@@ -341,7 +378,7 @@ export function writeMemories(modelOutput, memDir, existing) {
341
378
  }
342
379
 
343
380
  /**
344
- * `_harness_tui_views._memory_drop_index` — remove the index line(s) naming `<name>.md`.
381
+ * Remove the index line(s) naming `<name>.md`.
345
382
  *
346
383
  * ITS PYTHON HOME IS THE TUI, and it is here because this is where its SIBLINGS' twins are:
347
384
  * `appendAgentLesson` writes the index lines this deletes and `consolidateMemory` rebuilds
@@ -352,7 +389,7 @@ export function writeMemories(modelOutput, memDir, existing) {
352
389
  * nothing in `js/` referenced it — which is the third time a plan's "already ported" column
353
390
  * was answered by reading rather than by trusting.
354
391
  *
355
- * SUBSTRING, NOT PARSE, exactly as the reference is: any line containing `(<name>.md)` goes,
392
+ * SUBSTRING, NOT PARSE: any line containing `(<name>.md)` goes,
356
393
  * so a hand-written index in a different shape still loses its entry. And the file is only
357
394
  * REWRITTEN when something actually changed, which keeps a delete of an unindexed fact from
358
395
  * touching the user's mtime.
@@ -377,21 +414,50 @@ export function memoryDropIndex(memDir, name) {
377
414
  }
378
415
  if (!touched) return;
379
416
  pruneTopicsDir(memDir);
380
- try { writeMap(memDir, false); } catch { /* the reference swallows OSError here too */ }
417
+ try { writeMap(memDir, false); } catch { /* best-effort */ }
381
418
  }
382
419
 
383
420
  /** Drop every line holding `needle`; the kept lines when something went, else null. */
384
421
  function dropLines(p, needle) {
385
422
  const lines = readLines(p);
386
- if (!lines) return null; // the reference's `except OSError: return`
423
+ if (!lines) return null; // unreadable: nothing to drop
387
424
  const keep = lines.filter((ln) => !ln.includes(needle));
388
425
  if (keep.length === lines.length) return null;
389
426
  try {
390
- writeText(p, `${keep.join('\n')}\n`);
391
- } catch { /* the reference swallows OSError here too */ }
427
+ writeTextAtomic(p, `${keep.join('\n')}\n`);
428
+ } catch { /* best-effort */ }
392
429
  return keep;
393
430
  }
394
431
 
432
+ /**
433
+ * Move a runtime store aside to a sibling
434
+ * `archived-<name>/<timestamp>/`.
435
+ *
436
+ * NEVER a delete. Memory is the one thing in this system a user cannot rebuild, so the
437
+ * destructive verb's most destructive option is still a move.
438
+ *
439
+ * `renameSync` rather than a copy-then-delete: the destination is a SIBLING of the source, so
440
+ * it is the same device by construction and a cross-device fallback has nothing to do.
441
+ * shortcut: rename only, and the day a store can live on another volume this needs a copy path.
442
+ *
443
+ * `move` is `copyFileSync` for a file that must stay readable until its replacement lands.
444
+ */
445
+ export function archiveStore(store, move = renameSync) {
446
+ // `toLocaleString('sv-SE')` — LOCAL time, matching the old hand-rolled stamp
447
+ // (`getHours()`/`getMinutes()`/`getSeconds()` are all local-time getters, unlike
448
+ // `toISOString()`'s UTC). sv-SE's default format is already zero-padded
449
+ // "YYYY-MM-DD HH:MM:SS"; stripping the punctuation and reinserting one dash reproduces
450
+ // the exact `YYYYMMDD-HHMMSS` shape the padStart version built by hand.
451
+ const stamp = new Date().toLocaleString('sv-SE').replace(/\D/g, '').replace(/^(\d{8})/, '$1-');
452
+ const parent = path.join(path.dirname(store), `archived-${path.basename(store)}`);
453
+ // A taken name gets `-2`, …: two moves in one second must not fail the second.
454
+ let dest = path.join(parent, stamp);
455
+ for (let n = 2; existsSync(dest); n += 1) dest = path.join(parent, `${stamp}-${n}`);
456
+ mkdirSync(parent, { recursive: true });
457
+ move(store, dest);
458
+ return dest;
459
+ }
460
+
395
461
  /**
396
462
  * `consolidate_memory` — rebuild both index levels from the fact files actually on disk:
397
463
  * index orphans, prune dead lines, refresh each line from its fact's description, report
@@ -411,3 +477,139 @@ export function consolidateMemory(memDir) {
411
477
  const pruned = [...old.keys()].filter((s) => !facts.has(s)).sort();
412
478
  return { added, pruned, duplicates: dups };
413
479
  }
480
+
481
+ /**
482
+ * `## R<n> — Title`, anchored at column 0 so a rule body's fenced code and the stub's
483
+ * indented format example never parse as rules.
484
+ *
485
+ * The whitespace classes are `WHITESPACE`, not `\s`: this pattern runs over a HAND-EDITED
486
+ * file, which is where a non-breaking space actually turns up. `\S` is its complement for
487
+ * the same reason.
488
+ *
489
+ * `\d` IS LEFT ASCII, and that is a declared divergence rather than an oversight, unlike
490
+ * `ruleFields` (`js/web/user-files.mjs`), which uses `\p{Nd}`. No theme seeds a non-ASCII rule id, no build
491
+ * writes one, and the web editor cannot produce one either — it writes `R<n>` itself from
492
+ * `max(ids) + 1`. Widening this to match would only move the gap one line down, to whatever
493
+ * parses the captured digits back into a number.
494
+ */
495
+ const RULE_HEAD_RE = new RegExp(
496
+ `^##[${WHITESPACE}]+R(\\d+)[${WHITESPACE}]*[—–-]+[${WHITESPACE}]*`
497
+ + `([^${WHITESPACE}].*?)[${WHITESPACE}]*$`,
498
+ );
499
+
500
+ /**
501
+ * A line `parseRules` reads as the edge of a rule: `## ` ends the current block, and a
502
+ * `RULE_HEAD_RE` line opens one (a non-breaking space after `##` does the second, not the first).
503
+ * ONE predicate for both the parser and `ruleFields`, so a body the writer accepts can never
504
+ * split or forge a rule when read back.
505
+ */
506
+ export const isRuleEdge = (line) => line.startsWith('## ') || RULE_HEAD_RE.test(line);
507
+
508
+ const META_RE = new RegExp(`^\\((.+)\\)[${WHITESPACE}]*$`);
509
+
510
+ /** `{}` when the line is body rather than metadata. */
511
+ function parseRuleMeta(line) {
512
+ const m = META_RE.exec(stripWhitespace(line));
513
+ if (!m) return {};
514
+ const meta = {};
515
+ for (const part of m[1].split('|')) {
516
+ const at = part.indexOf(':');
517
+ if (at < 0) continue; // `partition` with no separator — not a pair
518
+ const key = stripWhitespace(part.slice(0, at)).toLowerCase().replaceAll(' ', '_');
519
+ if (['scope', 'source', 'trial_until'].includes(key)) {
520
+ meta[key] = stripWhitespace(part.slice(at + 1));
521
+ }
522
+ }
523
+ return meta;
524
+ }
525
+
526
+ /**
527
+ * `user-rules.md` parsed to `[rules, warnings]`.
528
+ *
529
+ * Every rule carries its `start`/`end` LINE INDICES, which is what lets `apiRulesMutate`
530
+ * splice exactly one block and leave every other byte of the user's file — prose,
531
+ * formatting, hand-written sections — untouched.
532
+ * @returns {[Array<{id: number, start: number, end: number} & Record<string, any>>, string[]]}
533
+ */
534
+ export function parseRules(text) {
535
+ const lines = splitLines(text);
536
+ const rules = [];
537
+ const warnings = [];
538
+ const seen = new Set();
539
+ for (let idx = 0; idx < lines.length; idx += 1) {
540
+ const m = RULE_HEAD_RE.exec(lines[idx]);
541
+ if (!m) continue;
542
+ let end = lines.length;
543
+ for (let j = idx + 1; j < lines.length; j += 1) {
544
+ if (isRuleEdge(lines[j])) { end = j; break; }
545
+ }
546
+ const rid = Number(m[1]);
547
+ if (seen.has(rid)) warnings.push(`duplicate rule id R${rid}`);
548
+ seen.add(rid);
549
+ let k = idx + 1;
550
+ while (k < end && !stripWhitespace(lines[k])) k += 1;
551
+ const meta = k < end ? parseRuleMeta(lines[k]) : {};
552
+ if (Object.keys(meta).length) k += 1;
553
+ rules.push({
554
+ id: rid,
555
+ title: m[2],
556
+ scope: Object.hasOwn(meta, 'scope') ? meta.scope : 'project',
557
+ source: Object.hasOwn(meta, 'source') ? meta.source : '',
558
+ trial_until: Object.hasOwn(meta, 'trial_until') ? meta.trial_until : '',
559
+ body: stripWhitespace(lines.slice(k, end).join('\n')),
560
+ start: idx,
561
+ end,
562
+ });
563
+ }
564
+ return [rules, warnings];
565
+ }
566
+
567
+ // The draft's block headings: the fold writes them, `parseDraft` reads them, and the rule Rite's
568
+ // approval flow (src/skills/rule/approve.md) names them, so a change here changes that file too.
569
+ export const draftRuleHead = (host, title) => `## Rule from ${host}: ${title}`;
570
+ export const draftChoiceHead = (file) => `## Choose: ${file}`;
571
+ const DRAFT_RULE_RE = /^## Rule from ([^:]+): (.+)$/;
572
+ const DRAFT_CHOICE = draftChoiceHead('');
573
+
574
+ /**
575
+ * The blocks of `user-rules.draft.md`, as `{title, host, key, body}`, in file order. A
576
+ * `## Rule from <host>: <title>` block is a pointer line, then the rule. A `## Choose: <file>` block
577
+ * is a question about two files, so it keeps its title alone. Every other heading (`## Renumbered`,
578
+ * the file's record of past decisions) ends the block before it and adds none. `key` is the
579
+ * pointer line's `sha256`, the block's row in the ledger.
580
+ */
581
+ export function parseDraft(text) {
582
+ const out = [];
583
+ let open = null;
584
+ for (const line of splitLines(text)) {
585
+ if (line.startsWith('## ')) {
586
+ const rule = DRAFT_RULE_RE.exec(line);
587
+ open = rule ? { title: rule[2], host: rule[1], lines: [] }
588
+ : line.startsWith(DRAFT_CHOICE) ? { title: line.slice(3), host: null, lines: [] } : null;
589
+ if (open) out.push(open);
590
+ } else open?.lines.push(line);
591
+ }
592
+ return out.map(({ title, host, lines }) => ({
593
+ title, host, key: /sha256: (\w+)/.exec(lines[0] ?? '')?.[1],
594
+ body: host ? stripWhitespace(lines.slice(1).join('\n')) : '',
595
+ }));
596
+ }
597
+
598
+ /**
599
+ * The ledger, or an empty one. One that holds nothing counts as empty and is written whole by the
600
+ * next item, because a key set on `[]` never reaches the file and the item would be reported on
601
+ * every emit. Anything else that is no ledger throws: treating it as empty would draft every
602
+ * decided item again, and the failed step is what the user should see.
603
+ */
604
+ export function readFoldState(shared) {
605
+ const blank = (v) => v === null || v === undefined || (Array.isArray(v) && !v.length);
606
+ if (!existsSync(shared.foldState)) return { version: 1, items: {} };
607
+ const text = readFileSync(shared.foldState, 'utf8');
608
+ const state = text.trim() ? JSON.parse(text) : null;
609
+ if (blank(state)) return { version: 1, items: {} };
610
+ if (!isDict(state) || !(blank(state.items) || isDict(state.items))) {
611
+ throw new Error(`${shared.foldState} is not a ledger`);
612
+ }
613
+ if (blank(state.items)) state.items = {};
614
+ return state;
615
+ }
@@ -37,7 +37,7 @@ const MANAGED_BLOCK_RE = /<!-- BEGIN GENESEED -->[\s\S]*?<!-- END GENESEED -->/g
37
37
  const SECTION_RE = /^## Ownership[ \t]*\r?$/m;
38
38
 
39
39
  // Write-shaped tool names (Bob's `tool-gate` also routes reads here: `read_file` carries a path).
40
- export const WRITE_NAME_RE = /write|edit|diff|replace|insert/i;
40
+ export const WRITE_NAME_RE = /write|edit|diff|replace|insert|move|rename|delete|remove|trash|copy/i;
41
41
 
42
42
  // js/hosts/activity.mjs `safeStem`, copied (that module is not on the gate path): a hostile
43
43
  // session id can never steer the marker join out of its directory.
@@ -22,9 +22,8 @@
22
22
  *
23
23
  * HOOKS ARE APPEND-ONLY AND FAIL-CLOSED. Nothing here rewrites a hook group in place:
24
24
  * `mergeClaudeSettings` appends what is missing and removes only groups the manifest
25
- * recorded, and cleanup goes through `GENESEED_HOOK_SNIFF`, which has to keep recognising
26
- * BOTH the legacy interpreter+checkout form and the shim form. Dropping either spelling
27
- * strands live hooks in every config emitted before the change.
25
+ * recorded, and cleanup goes through `GENESEED_HOOK_SNIFF`, which recognises the shim form. A
26
+ * 1.x install, wired before the shim, must rebuild first.
28
27
  *
29
28
  * ONE KNOWN DIVERGENCE, recorded rather than reproduced. JS objects order integer-like
30
29
  * keys first, so a settings.json carrying a `"1"` or `"2"` at any level comes back from
@@ -405,9 +404,14 @@ function reconcileOpencodeSkillPermission(perm, names, staleNames = [], added =
405
404
  export function opencodeEditAsks(cfgDir, global, agentRel = null) {
406
405
  const cfg = path.basename(cfgDir);
407
406
  const tails = ['opencode.json', 'opencode.jsonc', ...['excludes.json', GLOBAL_MANIFEST, '.geneseed-emit',
408
- 'plugins/geneseed-*.js', ...(global ? ['AGENT.md', 'config.json'] : [])].map((f) => `${cfg}/${f}`),
407
+ 'plugins/*', 'plugin/*', 'agents/*.md', 'agent/*.md', 'mode/*.md', 'modes/*.md', 'tool/*', 'tools/*',
408
+ ...(global ? ['AGENT.md', 'config.json'] : [])].map((f) => `${cfg}/${f}`),
409
409
  ...['.claude', '.openclaude', '.bob'].flatMap((m) => [`${m}/settings.json`, `${m}/settings.local.json`]),
410
- '.bob/settings/settings.json'];
410
+ '.bob/settings/settings.json',
411
+ // Persist Insight: the rule and memory stores, which the guard no longer releases on a re-issue.
412
+ // The coined names match anywhere, as the guard and Claude's rule gate match them; the memory
413
+ // folders by their last segments, so a project's unrelated `memory/` is never asked about.
414
+ 'user-rules.md', 'user-rules.draft.md', 'MEMORY.md', `${cfg}/memory/*.md`, 'geneseed/memory/*.md'];
411
415
  const keys = [];
412
416
  if (agentRel) {
413
417
  const abs = path.resolve(path.dirname(cfgDir), agentRel);
@@ -415,6 +419,10 @@ export function opencodeEditAsks(cfgDir, global, agentRel = null) {
415
419
  const gitRel = git ? path.relative(git, abs).split(path.sep).join('/') : agentRel;
416
420
  keys.push(...new Set([agentRel, gitRel, `*../${agentRel}`,
417
421
  ...(agentRel.includes('/') ? [`*/${agentRel}`] : [])]));
422
+ // The store sits beside the carrier (`<out>/memory`, js/build/bundle.mjs), the same four shapes.
423
+ const beside = (rel) => path.posix.join(path.posix.dirname(rel), 'memory/*.md');
424
+ keys.push(...new Set([beside(agentRel), beside(gitRel), `*../${beside(agentRel)}`,
425
+ ...(agentRel.includes('/') ? [`*/${beside(agentRel)}`] : [])]));
418
426
  }
419
427
  try {
420
428
  const home = shimHome();
@@ -582,7 +590,7 @@ export function atomicWriteJson(p, config) {
582
590
 
583
591
  /** `_build_settings._merge_opencode_json`. Returns the resolved target path.
584
592
  *
585
- * Zero runtime callers — re-measured this phase and still true. `rituals/_harness_mcp.py`
593
+ * Zero runtime callers — re-measured this phase and still true. The MCP module
586
594
  * re-implements the inverse itself rather than inherit this one's permission/lsp side
587
595
  * effects, so the only crossings are the two emit-tree ones (`_build_emit.emit_opencode`,
588
596
  * `_build_global.emit_opencode_global`).
@@ -1138,13 +1146,10 @@ export function unwireClaudeExcludes(p, excludes) {
1138
1146
  }
1139
1147
 
1140
1148
  // ---- Settings integrity check -----------------------------------------------------
1141
- // Substrings that mark a hook command as Geneseed's. An ARRAY, not one string, because two
1142
- // shapes are in the wild and both must stay recognisable: the legacy direct form
1143
- // (interpreter + checkout harness.py) written by every install emitted before the shim, and
1144
- // the shim form. Dropping the legacy entry makes every not-yet-migrated install invisible
1145
- // to the orphan scan — the one place a stranded hook can still surface — so cleanup would
1146
- // silently leave live hooks behind in every config emitted before the shim landed.
1147
- export const GENESEED_HOOK_SNIFF = ['harness.py', SHIM_MARK];
1149
+ // Substrings that mark a hook command as Geneseed's. Every install since the shim names it; the
1150
+ // floor is stated, not guessed at: a 1.x install, wired to an interpreter and a checkout, must
1151
+ // rebuild first, or its hooks read as the user's own.
1152
+ export const GENESEED_HOOK_SNIFF = [SHIM_MARK];
1148
1153
 
1149
1154
  /** `_build_settings._settings_hook_groups` — flatten `hooks` to [event, group] pairs. */
1150
1155
  function settingsHookGroups(loaded) {
package/js/hosts/shim.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * The machine-wide HOOK SHIM — where it lives, what it says, whether it still resolves — and
3
- * the two shim-shaped readers `migrate` needs (`migrateShape`, the autostart scan).
3
+ * the shim-shaped reader `migrate` needs (the autostart scan).
4
4
  *
5
5
  * SPLIT OUT OF `js/hosts/settings.mjs` (2026-10) for its cheapest caller. Every CLI run asks
6
6
  * `shimDead()` (the dead-shim warning in `bin/geneseed-cli.mjs`), and that used to load the
@@ -361,37 +361,6 @@ export function hookRunnerEntry() {
361
361
  return { runner: process.execPath, entry: path.join(ROOT, 'bin', 'geneseed-hook.mjs') };
362
362
  }
363
363
 
364
- // P10d. `GENESEED_HOOK_SNIFF` answers "is this hook Geneseed's?". A MIGRATION needs the other
365
- // question — "is this Geneseed's OLD one?" — and the two are not the same sniff.
366
- //
367
- // THREE SHAPES ARE IN THE WILD, AND TWO OF THEM ARE IDENTICAL IN THE SETTINGS FILE:
368
- // 1. legacy-direct the command itself names `harness.py` (pre-shim, P0 and earlier)
369
- // 2. shim-python the command names the shim; the shim BODY runs python + harness.py
370
- // 3. shim-node the command names the shim; the shim BODY runs node + the .mjs entry
371
- //
372
- // 2 and 3 differ ONLY inside the shim body. A classifier reading the host config alone would
373
- // call a fully-unmigrated machine "already migrated" — silently — and `migrate` would no-op on
374
- // exactly the installs it exists for. The shim body is a REQUIRED input, not a refinement.
375
- const SHIM_ENTRY_MARK = 'geneseed-hook.mjs';
376
-
377
- /**
378
- * `_build_settings._migrate_shape` — 'legacy' | 'current' | 'none'.
379
- *
380
- * PURE — and currently reached only END TO END, by the `migrate/a-node-baked-shim-reads-as-current`
381
- * cell. No unit corpus drives it directly, which is worth knowing before trusting it.
382
- * 'none' is not a fault: a user's own settings.json may carry three hand-written hooks
383
- * and no Geneseed entry. That must read as
384
- * "nothing to migrate" rather than "unrecognised", or `migrate` refuses on the commonest
385
- * config on any machine.
386
- */
387
- export function migrateShape(commands, shimBody) {
388
- if (commands.some((c) => c.includes('harness.py'))) return 'legacy';
389
- if (commands.some((c) => c.includes(SHIM_MARK))) {
390
- return shimBody.includes(SHIM_ENTRY_MARK) ? 'current' : 'legacy';
391
- }
392
- return 'none';
393
- }
394
-
395
364
  /**
396
365
  * `_build_settings._autostart_paths` — where a hand-written web-daemon autostart entry lives.
397
366
  *
@@ -403,9 +372,11 @@ export function migrateShape(commands, shimBody) {
403
372
  * Both platforms' paths on both platforms, deliberately — the scan is a read that misses
404
373
  * harmlessly, and returning only the host platform's would make the macOS arm unreachable
405
374
  * from the Windows machine this port is developed on: an ungated branch dressed as a fork.
375
+ * With no home directory there is nowhere to look, and the same read misses: `[]`, not a throw.
406
376
  */
407
377
  export function autostartPaths() {
408
- const home = os.homedir();
378
+ let home;
379
+ try { home = os.homedir(); } catch { return []; }
409
380
  return [
410
381
  path.join(home, 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Start Menu',
411
382
  'Programs', 'Startup', 'geneseed-web.vbs'),
@@ -0,0 +1,189 @@
1
+ /**
2
+ * THE CHANGE REPORT: tells the user that a rule, profile, wiki manifest or memory file changed in
3
+ * a session with no approval. It detects; it prevents nothing. Shell is no boundary (the gates read
4
+ * only parsed forms), so this is what still catches a write they never saw, at the end of the turn.
5
+ *
6
+ * OFF THE PER-CALL PATH. Nothing here loads on a tool call. The hook entry takes the baseline after
7
+ * `context` has answered, once per session, and `learn` compares on Stop. Both are stats, no reads.
8
+ *
9
+ * WHAT COUNTS AS APPROVED, per host. Claude and OpenClaude: a Write, Edit or NotebookEdit the
10
+ * transcript shows ran, because a gated tool runs only past the host's prompt. The transcript is read
11
+ * only when a file changed, which keeps the common Stop to the stats. Bob has no transcript and no
12
+ * file-tool write passes its gate, so every change there is reported. OpenCode has this logic in
13
+ * the guard plugin, with the baseline in memory and approval from `tool.execute.after`.
14
+ *
15
+ * GENESEED'S OWN WRITES. `learn`, a memory removal and the fold run inside `recordOwnWrites`, which
16
+ * snapshots the store around the run and logs what moved to `memory/.own-writes.json`, as an exact
17
+ * size and mtime. A change matching the log is not reported. Limits: a write by anything else during
18
+ * that window is excused too, and the log is a plain file an agent could edit. The web console's
19
+ * edits are not logged, so one made during a session is reported.
20
+ *
21
+ * WHAT IT CANNOT TELL. Approval is per session, and the tier is shared: another session's approved
22
+ * write reads as a change here, so the line says so rather than call it unapproved. A Claude
23
+ * sub-agent's write sits in its own transcript and reads the same way. shortcut: a false alarm, the
24
+ * safe direction; read the sidechain files here if that proves noisy.
25
+ *
26
+ * WHAT IT CANNOT RESIST. The baseline, like the own-writes log, is a plain file in the install, and
27
+ * an agent that can write there can edit it, or set a file's size and time back. The report is
28
+ * evidence against a careless or a weak agent, not a control against a determined one.
29
+ *
30
+ * Every entry swallows its errors: a report that cannot be made must never change a hook's verdict.
31
+ * Nothing here prints. The caller decides where the line goes, because a Stop's stdout is one document.
32
+ */
33
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
34
+ import path from 'node:path';
35
+
36
+ import { machineDir } from '../lib/machine-dir.mjs';
37
+ import { normcase } from '../lib/paths.mjs';
38
+ import { sovereignBypass } from './hosts.mjs';
39
+
40
+ const STATE_DIR = path.join('notebook', 'store-baseline');
41
+ const OWN_LOG = '.own-writes.json';
42
+ const OWN_LOG_CAP = 2000;
43
+ const STALE_MS = 7 * 24 * 60 * 60 * 1000;
44
+ const NAMES_SHOWN = 5;
45
+
46
+ /** The store files under one home, as `path -> "size:mtime"`. The guard's `storeScan` is its twin. */
47
+ export function storeScan(home, found = {}) {
48
+ const stamp = (f) => {
49
+ try { const s = statSync(f); if (s.isFile()) found[f] = `${s.size}:${Math.trunc(s.mtimeMs)}`; } catch { /* absent */ }
50
+ };
51
+ for (const n of ['user-rules.md', 'PROFILE.md', 'geneseed-wiki.jsonc', 'wiki.jsonc', 'wiki.json']) stamp(path.join(home, n));
52
+ const walk = (dir) => {
53
+ let items = [];
54
+ try { items = readdirSync(dir, { withFileTypes: true }); } catch { return; }
55
+ for (const e of items) {
56
+ if (e.isDirectory()) { if (e.name !== 'archive' && !e.name.startsWith('archived-')) walk(path.join(dir, e.name)); }
57
+ else if (e.name.endsWith('.md')) stamp(path.join(dir, e.name));
58
+ }
59
+ };
60
+ walk(path.join(home, 'memory'));
61
+ return found;
62
+ }
63
+
64
+ const homesOf = (root) => [...new Set([root, machineDir()])];
65
+ const scanAll = (root) => homesOf(root).reduce((found, h) => storeScan(h, found), {});
66
+ const stateFile = (root, sid) => path.join(root, STATE_DIR, `${String(sid).replace(/[^\w.-]/g, '_').slice(0, 120)}.json`);
67
+ const readJson = (f) => { try { return JSON.parse(readFileSync(f, 'utf8')); } catch { return null; } };
68
+
69
+ function saveBaseline(root, sid, stamps) {
70
+ const f = stateFile(root, sid);
71
+ mkdirSync(path.dirname(f), { recursive: true });
72
+ writeFileSync(f, JSON.stringify(stamps));
73
+ }
74
+
75
+ /**
76
+ * The session's baseline, written once. SessionStart fires again on resume and compact: keeping the
77
+ * first one means those cannot launder a change made before them. Old sessions' files are dropped.
78
+ */
79
+ export function writeBaseline(root, sid) {
80
+ try {
81
+ if (typeof sid !== 'string' || !sid || sovereignBypass(root)) return;
82
+ const f = stateFile(root, sid);
83
+ if (existsSync(f)) return;
84
+ saveBaseline(root, sid, scanAll(root));
85
+ const dir = path.dirname(f);
86
+ for (const n of readdirSync(dir)) {
87
+ const old = path.join(dir, n);
88
+ if (Date.now() - statSync(old).mtimeMs > STALE_MS) unlinkSync(old);
89
+ }
90
+ } catch { /* no notebook, or a read-only install: no report */ }
91
+ }
92
+
93
+ /** What differs between two scans, sorted. */
94
+ export function changedFiles(before, now) {
95
+ return [...new Set([...Object.keys(before), ...Object.keys(now)])].filter((f) => before[f] !== now[f]).sort();
96
+ }
97
+
98
+ /**
99
+ * Run `fn`, Geneseed's own writer, and log what it moved under `home`. A throw from `fn` still logs
100
+ * and still propagates. `home` is the folder holding `memory/`.
101
+ */
102
+ export function recordOwnWrites(home, fn) {
103
+ let before = null;
104
+ try { before = storeScan(home); } catch { /* the write still runs */ }
105
+ try { return fn(); } finally {
106
+ try {
107
+ if (before) {
108
+ const now = storeScan(home);
109
+ const moved = changedFiles(before, now);
110
+ if (moved.length) {
111
+ const f = path.join(home, 'memory', OWN_LOG);
112
+ const log = { ...readJson(f) };
113
+ for (const p of moved) { delete log[p]; log[p] = now[p] ?? 'gone'; }
114
+ const kept = Object.entries(log).slice(-OWN_LOG_CAP);
115
+ mkdirSync(path.dirname(f), { recursive: true });
116
+ writeFileSync(f, JSON.stringify(Object.fromEntries(kept)));
117
+ }
118
+ }
119
+ } catch { /* the log never fails a write */ }
120
+ }
121
+ }
122
+
123
+ /** The files the transcript shows a file tool really wrote: a tool_use whose result was no error. */
124
+ export function approvedInTranscript(file, cwd) {
125
+ const asked = new Map();
126
+ const failed = new Set();
127
+ let text = '';
128
+ try { text = readFileSync(file, 'utf8'); } catch { return new Set(); }
129
+ for (const line of text.split('\n')) {
130
+ if (!line.includes('"tool_use"') && !line.includes('"tool_result"')) continue;
131
+ let row;
132
+ try { row = JSON.parse(line); } catch { continue; }
133
+ const blocks = row?.message?.content;
134
+ for (const b of Array.isArray(blocks) ? blocks : []) {
135
+ if (b?.type === 'tool_use' && /^(?:Write|Edit|MultiEdit|NotebookEdit)$/.test(b.name)) {
136
+ const p = b.input?.file_path ?? b.input?.notebook_path;
137
+ if (typeof p === 'string') asked.set(b.id, normcase(path.resolve(cwd || process.cwd(), p)));
138
+ } else if (b?.type === 'tool_result' && b.is_error) failed.add(b.tool_use_id);
139
+ }
140
+ }
141
+ return new Set([...asked].filter(([id]) => !failed.has(id)).map(([, p]) => p));
142
+ }
143
+
144
+ /** The line the user reads. The guard's `storeLine` is its twin, same words. */
145
+ export function storeLine(files) {
146
+ const shown = files.slice(0, NAMES_SHOWN).map((f) => f.split(/[\\/]/).slice(-2).join('/')).join(', ');
147
+ const more = files.length > NAMES_SHOWN ? ` (+${files.length - NAMES_SHOWN} more)` : '';
148
+ return `Geneseed change report: ${files.length} rule or memory file${files.length === 1 ? '' : 's'} `
149
+ + `changed outside this session's approved writes (another session may have made it): ${shown}${more}. `
150
+ + 'This detects a change; it prevented nothing.';
151
+ }
152
+
153
+ /** What `geneseed status` shows: the last report, machine-wide, written only where the tier exists. */
154
+ function noteForStatus(files, host) {
155
+ try {
156
+ const dir = machineDir();
157
+ if (existsSync(dir)) writeFileSync(path.join(dir, '.store-report.json'), JSON.stringify({ at: new Date().toISOString(), host, files }));
158
+ } catch { /* an unwritable status file must not swallow the report */ }
159
+ }
160
+
161
+ /** The last report within the stale window, or null. For `geneseed status`. */
162
+ export function lastStoreReport() {
163
+ try {
164
+ const r = readJson(path.join(machineDir(), '.store-report.json'));
165
+ return r && Array.isArray(r.files) && Date.now() - Date.parse(r.at) < STALE_MS ? r : null;
166
+ } catch { return null; } // no home directory: `status` must still answer
167
+ }
168
+
169
+ /**
170
+ * Compare at a turn's end: the line to show, or null. Rolls the baseline, so a change is said once,
171
+ * and a session with no baseline (installed mid-session) starts one here. `transcript` is null on Bob.
172
+ */
173
+ export function storeReport(root, sid, { transcript = null, cwd = null, host = 'claude' } = {}) {
174
+ try {
175
+ if (typeof sid !== 'string' || !sid) return null;
176
+ const before = readJson(stateFile(root, sid));
177
+ if (!before) { writeBaseline(root, sid); return null; }
178
+ const now = scanAll(root);
179
+ const changed = changedFiles(before, now);
180
+ if (!changed.length) return null;
181
+ saveBaseline(root, sid, now);
182
+ const own = homesOf(root).reduce((log, h) => ({ ...log, ...readJson(path.join(h, 'memory', OWN_LOG)) }), {});
183
+ const approved = typeof transcript === 'string' ? approvedInTranscript(transcript, cwd) : new Set();
184
+ const files = changed.filter((f) => own[f] !== (now[f] ?? 'gone') && !approved.has(normcase(f)));
185
+ if (!files.length) return null;
186
+ noteForStatus(files, host);
187
+ return storeLine(files);
188
+ } catch { return null; }
189
+ }