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
@@ -20,10 +20,11 @@ import { assertSourceComplete, build, phaseLog, ensureMemoryStore } from './bund
20
20
  import {
21
21
  claimAndWrite, globalMemory, globalNotebook, shipLeanLaws, stripCapabilityLinks,
22
22
  } from './emit-common.mjs';
23
+ import { foldOnEmit } from './fold.mjs';
23
24
  import { renderAll } from './render.mjs';
24
25
  import {
25
26
  ensureExcludesStub, ensureNotebookIndex, ensureProfileStub, ensureRulesStub,
26
- ensureWikiStub,
27
+ ensureWikiStub, sharedRootFor,
27
28
  } from './stubs.mjs';
28
29
  import { writeVersion } from './version.mjs';
29
30
  import { mkdirSync } from 'node:fs';
@@ -42,8 +43,7 @@ import { mkdirSync } from 'node:fs';
42
43
  * earlier than RENDER, which still holds since nothing after this logs a phase at all.
43
44
  *
44
45
  * `manifestExisted` only ever arrives from the per-repo caller; the global emit does not pass
45
- * it, matching the Python side, so the pre-manifest header line stays unreachable from there on
46
- * both sides.
46
+ * it, so the pre-manifest header line stays unreachable from there.
47
47
  *
48
48
  * `overridesDir` is a THIRD directory, and it is not `dir` for the per-repo emit: the
49
49
  * per-repo `agent-overrides.json` lives beside the portable bundle in `out`, while every other
@@ -172,19 +172,14 @@ export function emitOpencodeRender(cfg, job) {
172
172
  * per-repo" OpenCode deployment. PRUNE and MANIFEST are the driver's; there is no VERIFY,
173
173
  * because this emit writes no settings file.
174
174
  *
175
- * ASSEMBLY, NOT TRANSLATION. Every unit it needs was already here — 58 of the 65 functions
176
- * in its Python closure, counted with `ast` rather than by name-mapping, which is how the
177
- * scout that produced this list first reported `_posture_body` and `_mode_body` as missing
178
- * when both are `registerBody` in `js/build/render.mjs`. What is new is the assembly and the
179
- * three values that had to be decided on the Python side.
175
+ * ASSEMBLY, NOT TRANSLATION. Every unit it needs already exists elsewhere (`_posture_body`
176
+ * and `_mode_body`, for one, are `registerBody` in `js/build/render.mjs`); what is here is the
177
+ * assembly and the values the caller must decide.
180
178
  *
181
- * `cfgDir` IS THE FIRST OF THEM AND THE REASON THE OTHERS WERE ASKED ABOUT.
182
- * `_build_core._opencode_config_dir` is an `_OWNED` name — the suite and `harness diff`
183
- * both redirect it at a sandbox — so resolving it here would render 135 files into the
184
- * developer's real `~/.config/opencode`. Python's entry point resolves it once, before
185
- * anything else, and sends the answer. Fourth phase running (`STRUCTURE` at P2d,
186
- * `capabilityLinkRe` at P2e, `_PREAMBLE_CONFIG_DIR` at P3b): send the decision, never the
187
- * resolver.
179
+ * `cfgDir` IS THE FIRST OF THEM. The suite and `harness diff` both redirect the OpenCode
180
+ * config dir at a sandbox, so resolving it here would render 135 files into the
181
+ * developer's real `~/.config/opencode`. The entry point resolves it once, before
182
+ * anything else, and sends the answer: send the decision, never the resolver.
188
183
  *
189
184
  * `out` IS NOT THE TARGET, and with the default nobody can tell. `emit_opencode_global`
190
185
  * writes into `<cfg>` and takes `out` ONLY as the legacy bundle to migrate a memory or
@@ -193,7 +188,7 @@ export function emitOpencodeRender(cfg, job) {
193
188
  * leaves them coincident — the `claude/bundle-in-subfolder` finding at a third call site.
194
189
  *
195
190
  * `agentPath` travels for the same reason `emitOpencodeRender`'s does: it is WIRE's one
196
- * input, and `Path.as_posix()` is the Python side's spelling of it.
191
+ * input, and it is a POSIX-style path.
197
192
  */
198
193
  export function emitOpencodeGlobalRender(cfg, job) {
199
194
  phaseLog('RENDER');
@@ -204,7 +199,9 @@ export function emitOpencodeGlobalRender(cfg, job) {
204
199
 
205
200
  // No `lawsPrefix`: the standalone laws dir sits beside AGENT.md in <cfg>, so the lean
206
201
  // pointer's relative `laws/universal.md` resolves with no prefix.
207
- const { theme, items } = renderAll(cfg, themeName, { footprint, nativeCatalog });
202
+ // A re-render of a deployed install sends that install's root, null included.
203
+ const { sharedRoot = sharedRootFor(cfgDir, 'opencode') } = job;
204
+ const { theme, items } = renderAll(cfg, themeName, { footprint, nativeCatalog, sharedRoot });
208
205
  assertSourceComplete(cfg, 'opencode-global');
209
206
  mkdirSync(cfgDir, { recursive: true });
210
207
 
@@ -212,17 +209,18 @@ export function emitOpencodeGlobalRender(cfg, job) {
212
209
  const agentText = items.find((i) => i.rel === 'AGENT.md' && i.text !== null)?.text ?? null;
213
210
  if (agentText !== null) {
214
211
  // OpenCode loads agents/skills natively, so drop AGENT.md's per-row spec links to
215
- // plain names. Memory links stay RELATIVE: in the global layout AGENT.md and the
216
- // store are siblings, so `memory/` resolves from AGENT.md's own location and stays
217
- // hermetic — no absolute path a doctor check would flag as an escape.
212
+ // plain names. Memory LINKS stay relative: in the global layout AGENT.md and the host
213
+ // store are siblings, so `memory/README.md` resolves from AGENT.md's own location and stays
214
+ // hermetic. The shared store is named in code spans only (`pathTokens`), never as a link
215
+ // target, which a doctor check would flag as an escape.
218
216
  const agentDest = path.join(cfgDir, 'AGENT.md');
219
217
  claimAndWrite(cfgDir, agentDest, 'AGENT.md', stripCapabilityLinks(agentText), owned);
220
218
  }
221
219
  // Co-owned, so never in `owned` — see `opencodeSentinelWrite`.
222
220
  opencodeSentinelWrite(cfgDir);
223
221
 
224
- // `manifestExisted` is deliberately not passed — the Python does not pass it either, so
225
- // the pre-manifest header line is unreachable from this emit on both sides.
222
+ // `manifestExisted` is deliberately not passed, so
223
+ // the pre-manifest header line is unreachable from this emit.
226
224
  const {
227
225
  nAgents, nSkills, nPlugins, nWorkflows, primary, nCommands, cfgName, skillDenies, editRecord, editRefused,
228
226
  } = opencodeLayer(cfg, items, themeName, theme, cfgDir, owned, {
@@ -237,6 +235,8 @@ export function emitOpencodeGlobalRender(cfg, job) {
237
235
  ensureRulesStub(cfgDir);
238
236
  ensureProfileStub(cfgDir);
239
237
  ensureExcludesStub(cfgDir);
238
+ // As in `emitClaudeRender`: after the seeds.
239
+ if (sharedRoot !== null) foldOnEmit('opencode', cfgDir);
240
240
 
241
241
  if (writeVersion(cfg, cfgDir) !== null) owned.push(VERSION_MARKER);
242
242
 
@@ -0,0 +1,515 @@
1
+ /**
2
+ * The fold: a global install's own stores move into the shared tier, once, in the emit (D2).
3
+ *
4
+ * Nothing here deletes. A file reaches the tier through a temp name, is read back,
5
+ * and only then does the host copy move aside (`archiveStore`, D10). A failed copy keeps the old
6
+ * store readable, because the host layer still serves it, and the next emit retries from the
7
+ * files on disk: there is no progress record to go stale.
8
+ *
9
+ * THE TEMP NAME IS WHAT MAKES A RETRY SAFE. A torn `x.md` in the tier would differ from its source
10
+ * on the next run and become a permanent `x-<host>.md` collision.
11
+ *
12
+ * A SECOND RUN WRITES NOTHING, and no test of bytes alone can see that. A folded host holds seeds,
13
+ * which every step passes over; `.fold-state.json` (C7) holds what stays behind on purpose.
14
+ *
15
+ * A RULE LEAVES A HOST FILE ONLY WHEN THE SHARED FILE ALREADY HOLDS IT (`foldRules`): everything
16
+ * else stays there, in force, until the user decides. A host `user-rules.draft.md` is not the
17
+ * fold's at all (C18). Spawn-free, and it reaches neither `js/maintain` nor `js/web` (C20).
18
+ */
19
+ import { isUtf8 } from 'node:buffer';
20
+ import { createHash } from 'node:crypto';
21
+ import {
22
+ constants, copyFileSync, existsSync, linkSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync,
23
+ rmSync, writeFileSync,
24
+ } from 'node:fs';
25
+ import path from 'node:path';
26
+
27
+ import { EXCLUDES_FILE, isCanonical } from '../hosts/hosts.mjs';
28
+ import { LINE_BREAK, listDir, splitLines } from '../hosts/hooks-prims.mjs';
29
+ import {
30
+ archiveStore, consolidateMemory, draftChoiceHead, draftRuleHead, existingSlugs, indexNotes, MEMORY_SEED, parseRules,
31
+ readFoldState,
32
+ } from '../hosts/memory-files.mjs';
33
+ import { foldExcludes } from '../inspect/excludes.mjs';
34
+ import { recordOwnWrites } from '../hosts/store-watch.mjs';
35
+ import { isDir, isFile, printErr, printOut, readText, writeTextAtomic } from '../lib/fs.mjs';
36
+ import { jsonDumpsIndent } from '../lib/json.mjs';
37
+ import { LEGACY_WIKI_SEED, NOTES_DIRS, WIKI_NAMES, sharedPaths } from '../lib/machine-dir.mjs';
38
+ import { normcase } from '../lib/paths.mjs';
39
+ import {
40
+ SESSION_SEEDS, WIKI_FILE, ensureMemoryIndex, ensureProfileStub, ensureWikiStub,
41
+ } from './stubs.mjs';
42
+
43
+ const sha256 = (data) => createHash('sha256').update(data).digest('hex');
44
+ /** A seed as the context hook hashes it: CRLF folded, because `writeText` expands it on Windows. */
45
+ const seedHash = (bytes) => sha256(bytes.toString('utf8').replaceAll('\r\n', '\n'));
46
+ const WHOLE_FILE_SEEDS = new Set([sha256(SESSION_SEEDS['PROFILE.md']), sha256(SESSION_SEEDS[WIKI_FILE]),
47
+ LEGACY_WIKI_SEED]);
48
+ const isWholeFileSeed = (bytes) => WHOLE_FILE_SEEDS.has(seedHash(bytes));
49
+
50
+ /** A folded store keeps these: the re-seed restores them, and their text never says "not folded". */
51
+ const STORE_KEEPS = ['README.md', '.gitignore', '.own-writes.json'];
52
+ const DRAFT_HEAD = '# User rules — draft\n\nNot active. The rule Rite applies decisions.\n';
53
+
54
+ /**
55
+ * Claim `dest` with the finished bytes, or throw EEXIST: a rename would replace a file another
56
+ * process landed since the `existsSync`. A hard link is atomic and exclusive.
57
+ * shortcut: a volume with no hard links takes the exclusive copy, which a crash can leave torn.
58
+ */
59
+ function claimFile(tmp, dest) {
60
+ try {
61
+ linkSync(tmp, dest);
62
+ } catch (e) {
63
+ if (e.code === 'EEXIST') throw e;
64
+ copyFileSync(tmp, dest, constants.COPYFILE_EXCL);
65
+ }
66
+ rmSync(tmp, { force: true });
67
+ }
68
+
69
+ /**
70
+ * `bytes` at `dest`, or nothing there: a short write fails on its temp name, never on `dest`.
71
+ * `exclusive` is for a name the caller found free; without it the file is meant to be replaced.
72
+ */
73
+ function landFile(dest, bytes, { exclusive = false } = {}) {
74
+ mkdirSync(path.dirname(dest), { recursive: true });
75
+ const tmp = `${dest}.${process.pid}.fold-tmp`;
76
+ try {
77
+ writeFileSync(tmp, bytes);
78
+ if (!readFileSync(tmp).equals(bytes)) throw new Error(`a short write to ${dest}`);
79
+ if (exclusive) claimFile(tmp, dest);
80
+ else renameSync(tmp, dest);
81
+ } catch (e) {
82
+ try { rmSync(tmp, { force: true }); } catch { /* a stray temp name is no fact; the error below matters */ }
83
+ throw e;
84
+ }
85
+ }
86
+
87
+ /** A path with its links resolved, for comparing. A path that does not exist yet stands for itself. */
88
+ function realOf(p) {
89
+ try { return normcase(realpathSync.native(p)); } catch { return normcase(path.resolve(p)); }
90
+ }
91
+
92
+ /**
93
+ * Is `src` the tier under another name, or inside it, or around it? Then moving it aside would move
94
+ * what the tier reads, through a link either way round, and there is nothing to fold. Every
95
+ * `archiveStore` here is behind this check, or behind `verifyCopies` for a single linked file.
96
+ */
97
+ function sharesTier(src, shared) {
98
+ const a = realOf(src);
99
+ return [shared.root, shared.memory, shared.notes, ...NOTES_DIRS.map((sub) => path.join(shared.notes, sub)),
100
+ shared.profile, shared.wiki, shared.rules].map(realOf)
101
+ .some((b) => a === b || a.startsWith(b + path.sep) || b.startsWith(a + path.sep));
102
+ }
103
+
104
+ /**
105
+ * Where `bytes` called `name` belong in `dir`: the first of `name`, `<stem>-<host>`,
106
+ * `<stem>-<host>-2`, … that is free or already holds them. Walking the same chain makes a repeat
107
+ * land on its own earlier copy, so a collision is written once.
108
+ */
109
+ function landing(bytes, name, dir, host) {
110
+ const { name: stem, ext } = path.parse(name);
111
+ for (let n = 1; ; n += 1) {
112
+ const dest = path.join(dir, n === 1 ? name : `${stem}-${host}${n === 2 ? '' : `-${n - 1}`}${ext}`);
113
+ // `lstat`: a dangling link reads as absent to `existsSync` and as taken to the claim.
114
+ if (!lstatSync(dest, { throwIfNoEntry: false })) return { dest, write: true, collision: n > 1 };
115
+ if (readFileSync(dest).equals(bytes)) return { dest, write: false, collision: false };
116
+ }
117
+ }
118
+
119
+ /** Fold step 1's copy rule over `names` in `srcDir`. Returns the [source, landed] pairs to verify. */
120
+ function copyFiles(names, srcDir, destDir, ctx, tally) {
121
+ const { host, dryRun, report } = ctx;
122
+ const pairs = [];
123
+ for (const name of names) {
124
+ const src = path.join(srcDir, name);
125
+ const bytes = readFileSync(src);
126
+ for (;;) {
127
+ const { dest, write, collision } = landing(bytes, name, destDir, host);
128
+ try {
129
+ if (write && !dryRun) landFile(dest, bytes, { exclusive: true });
130
+ } catch (e) {
131
+ if (e.code === 'EEXIST') continue; // lost the name: walk the chain again
132
+ throw e;
133
+ }
134
+ pairs.push([src, dest]);
135
+ if (write) report[tally] += 1;
136
+ if (collision) report.collisions += 1;
137
+ break;
138
+ }
139
+ }
140
+ return pairs;
141
+ }
142
+
143
+ /**
144
+ * Would replacing `hostFile` replace what the tier reads? Real paths, because a link anywhere on
145
+ * the way counts: the tier file, or a folder above it. The one safe case is a host link to a tier
146
+ * file that is no link: the rename takes the link, and the tier file stays.
147
+ */
148
+ function isTierFile(hostFile, tierFile) {
149
+ if (realOf(hostFile) !== realOf(tierFile)) return false;
150
+ const isLink = (p) => lstatSync(p).isSymbolicLink();
151
+ return !isLink(hostFile) || isLink(tierFile);
152
+ }
153
+
154
+ /** A link the fold is about to move out from under would dangle, so it stops the move. */
155
+ function refuseLink(src, dest) {
156
+ if (realOf(src) === realOf(dest)) throw new Error(`${dest} is a link to ${src}`);
157
+ }
158
+
159
+ function verifyCopies(pairs) {
160
+ for (const [src, dest] of pairs) {
161
+ refuseLink(src, dest);
162
+ if (!readFileSync(src).equals(readFileSync(dest))) throw new Error(`${dest} does not match ${src}`);
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Lessons are compared and rewritten as BYTES: latin1 maps each byte to one character and back, so
168
+ * a line that is not UTF-8 survives, where a UTF-8 decode would write U+FFFD over it and then
169
+ * verify its own damage. A newline byte never sits inside a UTF-8 sequence, so lines still split.
170
+ */
171
+ const AS_BYTES = 'latin1';
172
+
173
+ /** A lesson file's lines: every one that is not blank, CRLF folded. */
174
+ const lessonsOf = (text) => text.split(/\r?\n/).filter((l) => l.trim());
175
+
176
+ /**
177
+ * `agents/<name>.md`: one tier file per agent, so hosts merge by line rather than collide. No cap
178
+ * here (`appendAgentLesson`'s is the writer's): verification needs every source line present.
179
+ * Returns the [source, landed] pairs for `verifyLessons`.
180
+ */
181
+ function foldLessons(store, tierMemory, { dryRun, report }) {
182
+ const srcDir = path.join(store, 'agents');
183
+ const pairs = [];
184
+ for (const name of listDir(srcDir).filter((n) => n.endsWith('.md')).sort()) {
185
+ const src = path.join(srcDir, name);
186
+ const dest = path.join(tierMemory, 'agents', name);
187
+ const raw = readFileSync(src);
188
+ const lessons = lessonsOf(raw.toString(AS_BYTES));
189
+ pairs.push([src, dest]);
190
+ if (!existsSync(dest)) {
191
+ report.lessons += lessons.filter((l) => !l.startsWith('# ')).length;
192
+ if (!dryRun) landFile(dest, raw, { exclusive: true });
193
+ continue;
194
+ }
195
+ const text = readFileSync(dest, AS_BYTES);
196
+ const have = new Set(lessonsOf(text));
197
+ const missing = [...new Set(lessons)].filter((l) => !have.has(l));
198
+ if (!missing.length) continue;
199
+ report.lessons += missing.length;
200
+ if (dryRun) continue;
201
+ const eol = text.includes('\r\n') ? '\r\n' : '\n';
202
+ const sep = text.endsWith('\n') || !text ? '' : eol;
203
+ landFile(dest, Buffer.from(`${text}${sep}${missing.join(eol)}${eol}`, AS_BYTES));
204
+ }
205
+ return pairs;
206
+ }
207
+
208
+ function verifyLessons(pairs) {
209
+ for (const [src, dest] of pairs) {
210
+ refuseLink(src, dest);
211
+ const have = new Set(lessonsOf(readFileSync(dest, AS_BYTES)));
212
+ const lost = lessonsOf(readFileSync(src, AS_BYTES)).find((l) => !have.has(l));
213
+ if (lost !== undefined) throw new Error(`${dest} lacks a lesson of ${src}`);
214
+ }
215
+ }
216
+
217
+ /** Does the store hold anything a seeded one does not? The whole trigger: a seed folds to nothing. */
218
+ function storeHolds(store) {
219
+ return listDir(store).some((name) => {
220
+ if (STORE_KEEPS.includes(name)) return false;
221
+ const p = path.join(store, name);
222
+ if (isDir(p)) return listDir(p).length > 0;
223
+ return name !== 'MEMORY.md' || seedHash(readFileSync(p)) !== sha256(MEMORY_SEED);
224
+ });
225
+ }
226
+
227
+ /**
228
+ * Every file under `dir` that `carried` does not claim, as `<label>/<path>`. The archive keeps them,
229
+ * and only the report tells the user so. A link is listed, not walked: only the link moves.
230
+ */
231
+ function leftBehind(dir, label, carried, rel = '') {
232
+ return readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1)).flatMap((e) => {
233
+ const r = rel ? `${rel}/${e.name}` : e.name;
234
+ if (carried(r)) return [];
235
+ return e.isDirectory() ? leftBehind(path.join(dir, e.name), label, carried, r) : [`${label}/${r}`];
236
+ });
237
+ }
238
+
239
+ const factNames = (store) => [...existingSlugs(store)].map((s) => `${s}.md`).sort();
240
+
241
+ /**
242
+ * Fold steps 1 and 6. `topics/`, `MEMORY.md`, `archive/` are not copied: the archive keeps them.
243
+ * The tier rebuilds its index from facts, so an index with a line of the user's counts as left
244
+ * behind. A pointer is the user's too when no fact stands behind it.
245
+ */
246
+ function foldMemory(cfgDir, ctx) {
247
+ const { shared, dryRun, report } = ctx;
248
+ const store = path.join(cfgDir, 'memory');
249
+ if (sharesTier(store, shared) || !storeHolds(store)) return;
250
+ const names = factNames(store);
251
+ const facts = copyFiles(names, store, shared.memory, ctx, 'facts');
252
+ const lessons = foldLessons(store, shared.memory, ctx);
253
+ const noted = indexNotes(store, (slug) => names.includes(`${slug}.md`)).length > 0;
254
+ const carried = new Set([...STORE_KEEPS, ...(noted ? [] : ['MEMORY.md']), 'topics', ...names,
255
+ ...lessons.map(([src]) => `agents/${path.basename(src)}`)].map(normcase));
256
+ const stayed = leftBehind(store, 'memory', (r) => carried.has(normcase(r)));
257
+ if (dryRun) {
258
+ report.stayed.push(...stayed);
259
+ report.archived = path.join(cfgDir, 'archived-memory');
260
+ return;
261
+ }
262
+ verifyCopies(facts);
263
+ verifyLessons(lessons);
264
+ // A fact the `learn` hook wrote during the copy would reach only the archive: wait for the next emit.
265
+ if (factNames(store).join('\n') !== names.join('\n')) throw new Error(`${store} changed during the fold`);
266
+ consolidateMemory(shared.memory);
267
+ report.archived = archiveStore(store);
268
+ report.stayedIn.memory = report.archived;
269
+ report.stayed.push(...stayed);
270
+ mkdirSync(store, { recursive: true });
271
+ for (const keep of STORE_KEEPS) {
272
+ const kept = path.join(report.archived, keep);
273
+ if (isFile(kept)) copyFileSync(kept, path.join(store, keep));
274
+ }
275
+ ensureMemoryIndex(store);
276
+ }
277
+
278
+ /**
279
+ * Fold step 2. The host notes then move aside, as a store does: they would otherwise differ from
280
+ * a tier note the moment an agent edits it, and the next fold would write the stale text back as
281
+ * a collision. `collectNotes` would also list each one twice while both exist.
282
+ */
283
+ function foldNotes(cfgDir, ctx) {
284
+ const { shared, dryRun, report } = ctx;
285
+ for (const sub of NOTES_DIRS) {
286
+ const src = path.join(cfgDir, 'notebook', sub);
287
+ const names = listDir(src).filter((n) => n.endsWith('.md') && isFile(path.join(src, n))).sort();
288
+ if (!names.length || sharesTier(src, shared)) continue;
289
+ const pairs = copyFiles(names, src, path.join(shared.notes, sub), ctx, 'notes');
290
+ const label = `notebook/${sub}`;
291
+ const stayed = leftBehind(src, label, (r) => names.includes(r));
292
+ if (!dryRun) {
293
+ verifyCopies(pairs);
294
+ report.stayedIn[label] = archiveStore(src);
295
+ }
296
+ report.stayed.push(...stayed);
297
+ }
298
+ }
299
+
300
+ const itemKey = (kind, host, bytes) => createHash('sha256').update(`${kind}\0${host}\0`).update(bytes).digest('hex');
301
+
302
+ /**
303
+ * A block in the draft and a C7 record. The key names the host too, so two hosts holding the same
304
+ * text are two decisions. Draft first: a stop between the writes leaves a block the next run
305
+ * recognises, not a lost one.
306
+ */
307
+ function draftItem(kind, key, block, tally, { host, shared, dryRun, report }) {
308
+ const state = readFoldState(shared);
309
+ if (state.items[key]) return;
310
+ report[tally] += 1;
311
+ if (dryRun) return;
312
+ const text = existsSync(shared.draft) ? readText(shared.draft) : DRAFT_HEAD;
313
+ if (!text.includes(`sha256: ${key}`)) writeTextAtomic(shared.draft, `${text}\n${block}`);
314
+ state.items[key] = { kind, host, state: 'pending' };
315
+ writeTextAtomic(shared.foldState, `${jsonDumpsIndent(state)}\n`);
316
+ }
317
+
318
+ /** A pointer in the draft, never a copy (C9): each host's differing file gets its own decision. */
319
+ function draftChoice(kind, hostFile, sharedFile, bytes, ctx) {
320
+ const key = itemKey(kind, ctx.host, bytes);
321
+ draftItem(kind, key, `${draftChoiceHead(path.basename(sharedFile))}\n`
322
+ + `(hosts: shared, ${ctx.host} | paths: ${sharedFile}, ${hostFile} | sha256: ${key})\n`
323
+ + 'Which one becomes the shared file?\n', 'pending', ctx);
324
+ }
325
+
326
+ /**
327
+ * Fold step 4 for one whole file, over each name it has gone by. The re-seed waits for the end of
328
+ * the walk: `ensureWikiStub` renames a legacy file it finds, and this walk has not reached it yet.
329
+ */
330
+ function foldWholeFile(kind, hostFiles, sharedFile, reseed, ctx) {
331
+ const { dryRun, report } = ctx;
332
+ let setAside = false;
333
+ for (const file of hostFiles) {
334
+ if (!isFile(file) || sharesTier(file, ctx.shared)) continue;
335
+ const bytes = readFileSync(file);
336
+ if (isWholeFileSeed(bytes)) continue;
337
+ const held = isFile(sharedFile) ? readFileSync(sharedFile) : null;
338
+ const same = held !== null && held.equals(bytes);
339
+ if (held !== null && !same && !isWholeFileSeed(held)) {
340
+ draftChoice(kind, file, sharedFile, bytes, ctx);
341
+ continue;
342
+ }
343
+ if (!same) report.moved.push(kind);
344
+ if (dryRun) continue;
345
+ if (!same) landFile(sharedFile, bytes, { exclusive: held === null });
346
+ verifyCopies([[file, sharedFile]]);
347
+ archiveStore(file);
348
+ setAside = true;
349
+ }
350
+ if (setAside) reseed();
351
+ }
352
+
353
+ /** What makes two rules one (fold step 5): metadata and number do not. Line endings are already gone. */
354
+ const ruleText = (r) => `${r.title}\n${r.body}`;
355
+
356
+ /**
357
+ * A pending rule this host no longer holds waits for nothing: it merged, because another host's
358
+ * copy was approved, or the user took it out. Left alone, it would count as pending for ever, and
359
+ * approving it would raise a rule the user removed. A rule body holds no `## ` line, so a block is
360
+ * one piece of this split. Block first: a stop between the writes is finished by the next run.
361
+ */
362
+ function settleRules(live, { host, shared, dryRun }) {
363
+ if (dryRun) return;
364
+ const state = readFoldState(shared);
365
+ const gone = Object.keys(state.items).filter((key) => {
366
+ const item = state.items[key];
367
+ return item.kind === 'rule' && item.host === host && item.state === 'pending' && !live.has(key);
368
+ });
369
+ if (!gone.length) return;
370
+ if (existsSync(shared.draft)) {
371
+ const pieces = readText(shared.draft).split(/^(?=## )/m);
372
+ writeTextAtomic(shared.draft, pieces.filter((p) => !gone.some((key) => p.includes(`sha256: ${key}`))).join(''));
373
+ }
374
+ for (const key of gone) delete state.items[key];
375
+ writeTextAtomic(shared.foldState, `${jsonDumpsIndent(state)}\n`);
376
+ }
377
+
378
+ /**
379
+ * `text` without the merged rules, every other byte kept, or the seed when nothing of the user's
380
+ * is left. Anything else stays: `parseRules` reads only `## R<n> — Title`, so a hand-written
381
+ * section may be a rule in all but its form, and a seed would take it out of force.
382
+ */
383
+ function withoutRules(text, merged) {
384
+ const drop = new Set(merged.flatMap((r) => Array.from({ length: r.end - r.start }, (_, i) => r.start + i)));
385
+ // The split keeps each break, so the line at index `i` is the piece at `2i`, its break at `2i + 1`.
386
+ const rest = text.split(new RegExp(`(${LINE_BREAK.source})`)).filter((_, n) => !drop.has(Math.floor(n / 2))).join('');
387
+ const seed = SESSION_SEEDS['user-rules.md'];
388
+ const seedLines = new Set(splitLines(seed));
389
+ return splitLines(rest).every((l) => !l.trim() || seedLines.has(l)) ? seed : rest;
390
+ }
391
+
392
+ /**
393
+ * Fold step 5. A rule the shared file holds word for word leaves the host file: it binds from
394
+ * there. Any other goes to the draft and stays, so nothing stops binding before the user decides
395
+ * (C8), and an approval needs no code here: the rule Rite puts it in the shared file, and the next
396
+ * fold finds a duplicate. A rejected rule is the exception to the merge, because "keep it on this
397
+ * host" holds even if the shared file later says the same.
398
+ *
399
+ * The old file is copied aside, not moved: the host file must exist at every moment, because the
400
+ * rules it keeps bind through it. When the shared file IS the host file (`isTierFile`), rewriting
401
+ * it would take the merged rules out of force.
402
+ *
403
+ * A FILE THAT IS NOT UTF-8 IS LEFT WHOLE, and no rule in it is read: the text below has each bad
404
+ * byte replaced, so a rewrite or a draft would change a rule the user never touched.
405
+ */
406
+ function foldRules(cfgDir, ctx) {
407
+ const { host, shared, dryRun, report } = ctx;
408
+ const file = path.join(cfgDir, path.basename(shared.rules));
409
+ if (!isFile(file) || isTierFile(file, shared.rules)) return;
410
+ const { items } = readFoldState(shared);
411
+ const raw = readFileSync(file);
412
+ const text = raw.toString('utf8');
413
+ if (!isUtf8(raw)) {
414
+ report.notices.push(`${file} is not UTF-8, so its rules stay there and bind; save it as UTF-8 to fold them`);
415
+ return;
416
+ }
417
+ const [rules] = parseRules(text);
418
+ const held = new Set(parseRules(isFile(shared.rules) ? readFileSync(shared.rules, 'utf8') : '')[0].map(ruleText));
419
+ const lines = splitLines(text);
420
+ const live = new Set();
421
+ const merged = [];
422
+ for (const r of rules) {
423
+ const key = itemKey('rule', host, ruleText(r));
424
+ if (held.has(ruleText(r)) && items[key]?.state !== 'rejected') { merged.push(r); continue; }
425
+ if (live.has(key)) continue;
426
+ live.add(key);
427
+ const own = lines.slice(r.start + 1, r.end).join('\n').trim();
428
+ draftItem('rule', key, `${draftRuleHead(host, r.title)}\n(source: ${file} | old: R${r.id} | sha256: ${key})\n${own}\n`,
429
+ 'rules', ctx);
430
+ }
431
+ settleRules(live, ctx);
432
+ if (!merged.length || dryRun) return;
433
+ archiveStore(file, copyFileSync);
434
+ landFile(file, Buffer.from(withoutRules(text, merged)));
435
+ }
436
+
437
+ /**
438
+ * Fold one host. Never throws: a step that fails lands in `report.failed`, the steps after it
439
+ * still run, and what it did not finish stays in place for the next emit. `dryRun` walks the same
440
+ * code and writes nothing, so each host's preview is read against the tier as it stands.
441
+ */
442
+ export function foldHost({ host, cfgDir, shared, dryRun = false }) {
443
+ const report = {
444
+ host, facts: 0, lessons: 0, notes: 0, excludes: 0, wired: 0, collisions: 0, pending: 0, rules: 0,
445
+ moved: [], archived: null, stayed: [], stayedIn: {}, wiredPaths: [], notices: [], failed: [],
446
+ };
447
+ const step = (name, fn) => {
448
+ try { fn(); } catch (e) { report.failed.push(`${name}: ${e.message}`); }
449
+ };
450
+ const ctx = { host, shared, dryRun, report };
451
+ step('memory', () => foldMemory(cfgDir, ctx));
452
+ step('notes', () => foldNotes(cfgDir, ctx));
453
+ step(EXCLUDES_FILE, () => {
454
+ const { added, wired, paths, notices, errors } = foldExcludes(host, cfgDir, dryRun);
455
+ Object.assign(report, { excludes: added, wired, wiredPaths: paths, notices });
456
+ report.failed.push(...errors.map((e) => `${EXCLUDES_FILE}: ${e}`));
457
+ });
458
+ step('profile', () => foldWholeFile('profile', [path.join(cfgDir, 'PROFILE.md')], shared.profile,
459
+ () => ensureProfileStub(cfgDir), ctx));
460
+ step('wiki', () => foldWholeFile('wiki', WIKI_NAMES.map((n) => path.join(cfgDir, n)), shared.wiki,
461
+ () => ensureWikiStub(cfgDir), ctx));
462
+ step('rules', () => foldRules(cfgDir, ctx));
463
+ return report;
464
+ }
465
+
466
+ const counted = (n, one) => `${n} ${one}${n === 1 ? '' : 's'}`;
467
+ const STAYED_SHOWN = 5;
468
+
469
+ /**
470
+ * The files only the archive holds now, each run of them followed by its own archive (`stayedIn`,
471
+ * by label). A dry run has moved nothing, so it has no archive to name. The line stays one line,
472
+ * and `report.stayed` keeps them all.
473
+ */
474
+ function stayedWords(stayed, stayedIn) {
475
+ const more = stayed.length - STAYED_SHOWN;
476
+ const groups = new Map();
477
+ for (const s of stayed.slice(0, STAYED_SHOWN)) {
478
+ const label = Object.keys(stayedIn).find((l) => s.startsWith(`${l}/`));
479
+ groups.set(label, [...(groups.get(label) ?? []), s]);
480
+ }
481
+ const named = [...groups].map(([label, files]) => `${files.join(', ')}${label ? ` (${stayedIn[label]})` : ''}`);
482
+ return `${counted(stayed.length, 'file')} left in the archive: ${named.join(', ')}${more > 0 ? ` and ${more} more` : ''}`;
483
+ }
484
+
485
+ /** A report as the words after `<host>: `, or '' when it did nothing (C7: nothing is reported twice). */
486
+ export function foldSummary(r) {
487
+ return [
488
+ r.facts && `${counted(r.facts, 'fact')} folded`,
489
+ r.lessons && counted(r.lessons, 'lesson'),
490
+ r.notes && counted(r.notes, 'note'),
491
+ r.excludes && counted(r.excludes, 'exclude path'),
492
+ r.wired && `${counted(r.wired, 'excluded folder')} wired${r.wiredPaths.length ? ` (${r.wiredPaths.join(', ')})` : ''}`,
493
+ ...r.moved.map((kind) => `${kind} moved`),
494
+ r.collisions && counted(r.collisions, 'collision'),
495
+ r.rules && `${counted(r.rules, 'rule')} to approve`,
496
+ r.pending && `${r.pending} to approve`,
497
+ r.archived && 'old store moved aside',
498
+ r.stayed.length && stayedWords(r.stayed, r.stayedIn),
499
+ ].filter(Boolean).join(', ');
500
+ }
501
+
502
+ /** The emit's call, on a canonical install only: `diff`, Restore and a stray `--config-dir` fold nothing. */
503
+ export function foldOnEmit(host, cfgDir) {
504
+ if (!isCanonical(cfgDir, host)) return;
505
+ const shared = sharedPaths();
506
+ // Both ends: the fold writes the tier, and moves the host's own files aside.
507
+ const report = recordOwnWrites(cfgDir, () => recordOwnWrites(shared.root, () => foldHost({ host, cfgDir, shared })));
508
+ const summary = foldSummary(report);
509
+ if (summary) printOut(`[shared] ${host}: ${summary}\n`);
510
+ for (const n of report.notices) printErr(`[shared] ${n}\n`);
511
+ for (const f of report.failed) {
512
+ printErr(`[shared] ${host}: fold stopped at ${f}; what was not folded stays in place, `
513
+ + 'and the next emit retries\n');
514
+ }
515
+ }