somora 2026.930.1

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 (404) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +364 -0
  3. package/bin/node-version.d.mts +3 -0
  4. package/bin/node-version.mjs +45 -0
  5. package/bin/somora.mjs +77 -0
  6. package/config.example.yaml +896 -0
  7. package/docs/agents.md +677 -0
  8. package/docs/api.md +3194 -0
  9. package/docs/browser.md +317 -0
  10. package/docs/builder.md +331 -0
  11. package/docs/cache-strategy.md +373 -0
  12. package/docs/compaction.md +253 -0
  13. package/docs/display.md +154 -0
  14. package/docs/dream-phases.md +891 -0
  15. package/docs/files.md +387 -0
  16. package/docs/imagegen.md +366 -0
  17. package/docs/images/somora-hero.png +0 -0
  18. package/docs/images/somora-mobile-2026-05-23.png +0 -0
  19. package/docs/images/somora-tui-2026-05-23.png +0 -0
  20. package/docs/images/somora-web-2026-05-23.png +0 -0
  21. package/docs/index.md +178 -0
  22. package/docs/lsp.md +93 -0
  23. package/docs/mcp.md +332 -0
  24. package/docs/memory.md +407 -0
  25. package/docs/mobile.md +310 -0
  26. package/docs/models.md +379 -0
  27. package/docs/projects.md +425 -0
  28. package/docs/realtime-voice.md +293 -0
  29. package/docs/resources.md +230 -0
  30. package/docs/sampling.md +128 -0
  31. package/docs/security.md +189 -0
  32. package/docs/sentinel.md +295 -0
  33. package/docs/setup.md +1217 -0
  34. package/docs/skills.md +501 -0
  35. package/docs/team.md +189 -0
  36. package/docs/thinking.md +463 -0
  37. package/docs/tmux.md +399 -0
  38. package/docs/tools.md +117 -0
  39. package/docs/videogen.md +191 -0
  40. package/docs/voice.md +288 -0
  41. package/docs/web.md +893 -0
  42. package/docs/wiki.md +583 -0
  43. package/npm-shrinkwrap.json +5670 -0
  44. package/package.json +116 -0
  45. package/src/attachments/store.ts +196 -0
  46. package/src/browser/change-stream.ts +31 -0
  47. package/src/browser/display.ts +108 -0
  48. package/src/browser/policy.ts +121 -0
  49. package/src/browser/screencast.ts +374 -0
  50. package/src/browser/service.ts +1337 -0
  51. package/src/browser/session.ts +15 -0
  52. package/src/browser/snapshot.ts +40 -0
  53. package/src/cli/auth.ts +117 -0
  54. package/src/cli/codex.ts +41 -0
  55. package/src/cli/lsp.ts +71 -0
  56. package/src/cli/resolvers/clawhub.ts +400 -0
  57. package/src/cli/setup.ts +835 -0
  58. package/src/cli/skill.ts +619 -0
  59. package/src/cli/somora.ts +548 -0
  60. package/src/cli/systemd-unit.ts +72 -0
  61. package/src/cli/team.ts +148 -0
  62. package/src/cli/tui/activity-stream.ts +121 -0
  63. package/src/cli/tui/api.ts +479 -0
  64. package/src/cli/tui/app.tsx +1169 -0
  65. package/src/cli/tui/autocomplete.tsx +55 -0
  66. package/src/cli/tui/commands.ts +913 -0
  67. package/src/cli/tui/dream-glyphs.ts +22 -0
  68. package/src/cli/tui/footer.tsx +15 -0
  69. package/src/cli/tui/format.ts +28 -0
  70. package/src/cli/tui/header.tsx +279 -0
  71. package/src/cli/tui/index.tsx +120 -0
  72. package/src/cli/tui/markdown.tsx +63 -0
  73. package/src/cli/tui/sampling.ts +162 -0
  74. package/src/cli/tui/separator.tsx +13 -0
  75. package/src/cli/tui/state.ts +42 -0
  76. package/src/cli/tui/stream.ts +330 -0
  77. package/src/cli/tui/thinking-text.ts +54 -0
  78. package/src/cli/tui/turn-views.tsx +499 -0
  79. package/src/cli/tui/types.ts +410 -0
  80. package/src/cli/tui/work-queue.ts +161 -0
  81. package/src/cli/update-args.ts +55 -0
  82. package/src/cli/wiki.ts +406 -0
  83. package/src/compaction/index.ts +28 -0
  84. package/src/compaction/midturn.ts +210 -0
  85. package/src/compaction/policy.ts +154 -0
  86. package/src/compaction/summarize.ts +691 -0
  87. package/src/compaction/template.ts +90 -0
  88. package/src/compaction/types.ts +148 -0
  89. package/src/config/loader.ts +276 -0
  90. package/src/config/reload.ts +43 -0
  91. package/src/config/types.ts +2292 -0
  92. package/src/dream/deep-actions.ts +324 -0
  93. package/src/dream/deep-dispatcher.ts +237 -0
  94. package/src/dream/deep-llm.ts +388 -0
  95. package/src/dream/deep-prompts.ts +106 -0
  96. package/src/dream/deep-runner.ts +757 -0
  97. package/src/dream/deep-skip-cache.ts +199 -0
  98. package/src/dream/deep-worker.ts +229 -0
  99. package/src/dream/json-salvage.ts +34 -0
  100. package/src/dream/judge.ts +188 -0
  101. package/src/dream/loop-state.ts +286 -0
  102. package/src/dream/lucid-actions.ts +303 -0
  103. package/src/dream/lucid-batches.ts +94 -0
  104. package/src/dream/lucid-prompt.ts +82 -0
  105. package/src/dream/lucid-runner.ts +744 -0
  106. package/src/dream/lucid-storage.ts +277 -0
  107. package/src/dream/lucid-structure.ts +102 -0
  108. package/src/dream/lucid-types.ts +137 -0
  109. package/src/dream/lucid-worker.ts +224 -0
  110. package/src/dream/rem-dedup.ts +502 -0
  111. package/src/dream/rem-extract.ts +782 -0
  112. package/src/dream/rem-reset-run.ts +67 -0
  113. package/src/dream/rem-runner.ts +696 -0
  114. package/src/dream/rem-worker.ts +527 -0
  115. package/src/dream/review-window.ts +71 -0
  116. package/src/dream/scheduler-state.ts +129 -0
  117. package/src/dream/storage.ts +497 -0
  118. package/src/dream/types.ts +133 -0
  119. package/src/dream/wiki-context.ts +133 -0
  120. package/src/engine/a2a.ts +33 -0
  121. package/src/engine/availability.ts +63 -0
  122. package/src/engine/claude-cli.ts +969 -0
  123. package/src/engine/codex-app-server-client.ts +294 -0
  124. package/src/engine/codex-bin.ts +49 -0
  125. package/src/engine/codex-cli.ts +1014 -0
  126. package/src/engine/codex-dynamic-tools.ts +239 -0
  127. package/src/engine/codex-home.ts +63 -0
  128. package/src/engine/codex-thread-config.ts +74 -0
  129. package/src/engine/context-budget.ts +257 -0
  130. package/src/engine/engine-meta-labels.ts +211 -0
  131. package/src/engine/grok-cli.ts +941 -0
  132. package/src/engine/inline-think.ts +59 -0
  133. package/src/engine/model-availability.ts +105 -0
  134. package/src/engine/openai-compatible.ts +2464 -0
  135. package/src/engine/reasoning-retry.ts +83 -0
  136. package/src/engine/registry.ts +13 -0
  137. package/src/engine/replay.ts +195 -0
  138. package/src/engine/sampling.ts +90 -0
  139. package/src/engine/thinking-params.ts +264 -0
  140. package/src/engine/types.ts +269 -0
  141. package/src/engine/user-tag.ts +24 -0
  142. package/src/imagegen/aspect.ts +128 -0
  143. package/src/imagegen/generate.ts +642 -0
  144. package/src/imagegen/references.ts +75 -0
  145. package/src/imagegen/types.ts +154 -0
  146. package/src/lsp/client.ts +183 -0
  147. package/src/lsp/fake-server.helper.mjs +42 -0
  148. package/src/lsp/format.ts +29 -0
  149. package/src/lsp/index.ts +21 -0
  150. package/src/lsp/manager.ts +238 -0
  151. package/src/lsp/registry.ts +151 -0
  152. package/src/mcp/config.ts +117 -0
  153. package/src/mcp/hub/audit.ts +55 -0
  154. package/src/mcp/hub/bridge.ts +115 -0
  155. package/src/mcp/hub/catalog.ts +69 -0
  156. package/src/mcp/hub/credentials.ts +406 -0
  157. package/src/mcp/hub/env-expand.ts +14 -0
  158. package/src/mcp/hub/manager.ts +770 -0
  159. package/src/mcp/hub/normalize.ts +213 -0
  160. package/src/mcp/server.ts +368 -0
  161. package/src/mcp/tool-schema.ts +20 -0
  162. package/src/media/capabilities.ts +392 -0
  163. package/src/media/records.ts +175 -0
  164. package/src/media/store.ts +217 -0
  165. package/src/media/types.ts +69 -0
  166. package/src/memory/chunking.ts +168 -0
  167. package/src/memory/embeddings.ts +262 -0
  168. package/src/memory/index.ts +15 -0
  169. package/src/memory/inject.ts +197 -0
  170. package/src/memory/manager.ts +996 -0
  171. package/src/memory/registry.ts +176 -0
  172. package/src/memory/rescan.ts +101 -0
  173. package/src/memory/retrieval.ts +586 -0
  174. package/src/memory/shared-index.ts +372 -0
  175. package/src/memory/slug.ts +39 -0
  176. package/src/memory/storage.ts +385 -0
  177. package/src/memory/watcher.ts +134 -0
  178. package/src/multimodal/blocks.ts +101 -0
  179. package/src/multimodal/dimensions.ts +214 -0
  180. package/src/multimodal/load.ts +86 -0
  181. package/src/multimodal/mime.ts +135 -0
  182. package/src/multimodal/pdf-render.ts +80 -0
  183. package/src/multimodal/user-content.ts +266 -0
  184. package/src/persona/files.ts +144 -0
  185. package/src/persona/loader.ts +598 -0
  186. package/src/persona/skill-gating-store.ts +59 -0
  187. package/src/persona/tool-gating-store.ts +113 -0
  188. package/src/projects/focus.ts +186 -0
  189. package/src/projects/prompt-block.ts +106 -0
  190. package/src/projects/scheme.ts +107 -0
  191. package/src/projects/store.ts +144 -0
  192. package/src/projects/types.ts +73 -0
  193. package/src/sentinel/dispatcher.ts +97 -0
  194. package/src/sentinel/schedule.ts +271 -0
  195. package/src/sentinel/scheduler.ts +840 -0
  196. package/src/sentinel/store.ts +259 -0
  197. package/src/sentinel/types.ts +221 -0
  198. package/src/server/activity-stream.ts +160 -0
  199. package/src/server/ask-calls.ts +137 -0
  200. package/src/server/ask-wait-graph.ts +171 -0
  201. package/src/server/async-tasks.ts +199 -0
  202. package/src/server/builder-busy.ts +86 -0
  203. package/src/server/builder-prompt.ts +204 -0
  204. package/src/server/builder-questions.ts +117 -0
  205. package/src/server/builder-session.ts +249 -0
  206. package/src/server/chat-aborts.ts +83 -0
  207. package/src/server/claude-config-dir.ts +71 -0
  208. package/src/server/claude-credential-sync.ts +454 -0
  209. package/src/server/env-file.ts +100 -0
  210. package/src/server/env.ts +115 -0
  211. package/src/server/heal-session.ts +151 -0
  212. package/src/server/history-page.ts +46 -0
  213. package/src/server/index.ts +7244 -0
  214. package/src/server/lockfile.ts +89 -0
  215. package/src/server/logger.ts +67 -0
  216. package/src/server/logs.ts +187 -0
  217. package/src/server/loopback-fetch.ts +130 -0
  218. package/src/server/openai-client.ts +89 -0
  219. package/src/server/prompt-assembly.ts +334 -0
  220. package/src/server/restart-reconcile.ts +139 -0
  221. package/src/server/run-turn-fallback.ts +275 -0
  222. package/src/server/run-turn-types.ts +91 -0
  223. package/src/server/run-turn.ts +1474 -0
  224. package/src/server/sanitize-assistant-text.ts +112 -0
  225. package/src/server/session-export.ts +220 -0
  226. package/src/server/session-queue.ts +376 -0
  227. package/src/server/session-workdir.ts +49 -0
  228. package/src/server/sse-h2-safe.ts +61 -0
  229. package/src/server/sse-liveness.ts +162 -0
  230. package/src/server/sse-serializer.ts +161 -0
  231. package/src/server/start-turn.ts +249 -0
  232. package/src/server/steer-inbox.ts +107 -0
  233. package/src/server/tls-keeper.ts +153 -0
  234. package/src/server/tool-format.ts +167 -0
  235. package/src/server/turn-framing.ts +52 -0
  236. package/src/server/turn-origin-kind.ts +74 -0
  237. package/src/server/turn-origin.ts +40 -0
  238. package/src/server/work-ledger.ts +975 -0
  239. package/src/server/workspace.ts +114 -0
  240. package/src/setup/config-edit.ts +201 -0
  241. package/src/setup/presets.ts +71 -0
  242. package/src/setup/prompt.ts +163 -0
  243. package/src/setup/tailscale.ts +44 -0
  244. package/src/skills/bin-checks.ts +227 -0
  245. package/src/skills/bootstrap.ts +347 -0
  246. package/src/skills/env-scope.ts +175 -0
  247. package/src/skills/gating.ts +71 -0
  248. package/src/skills/lint.ts +202 -0
  249. package/src/skills/load.ts +368 -0
  250. package/src/skills/path-helpers.ts +102 -0
  251. package/src/skills/registry.ts +178 -0
  252. package/src/ssh/exec.ts +142 -0
  253. package/src/ssh/index.ts +12 -0
  254. package/src/ssh/known-hosts.ts +109 -0
  255. package/src/ssh/pool.ts +307 -0
  256. package/src/storage/sessions.ts +602 -0
  257. package/src/team/render.ts +149 -0
  258. package/src/team/resolve.ts +122 -0
  259. package/src/team/store.ts +124 -0
  260. package/src/team/types.ts +111 -0
  261. package/src/team/write.ts +95 -0
  262. package/src/testing/isolated-home.mts +46 -0
  263. package/src/tmux/attention-watcher.ts +272 -0
  264. package/src/tmux/attention.ts +336 -0
  265. package/src/tmux/list.ts +91 -0
  266. package/src/tmux/origin-store.ts +102 -0
  267. package/src/tmux/tui-markers.ts +267 -0
  268. package/src/tools/agents/ask-cancel.ts +94 -0
  269. package/src/tools/agents/ask-result.ts +235 -0
  270. package/src/tools/agents/ask.ts +704 -0
  271. package/src/tools/agents/builder-dispatch.ts +217 -0
  272. package/src/tools/agents/images.ts +104 -0
  273. package/src/tools/agents/index.ts +42 -0
  274. package/src/tools/agents/long-task-timeouts.ts +39 -0
  275. package/src/tools/agents/session-list.ts +136 -0
  276. package/src/tools/agents/session-model.ts +106 -0
  277. package/src/tools/agents/spawn.ts +845 -0
  278. package/src/tools/agents/status.ts +589 -0
  279. package/src/tools/browser/index.ts +6 -0
  280. package/src/tools/browser/ops.ts +145 -0
  281. package/src/tools/browser/tools.ts +184 -0
  282. package/src/tools/builder/short-descriptions.ts +80 -0
  283. package/src/tools/builder/tools.ts +222 -0
  284. package/src/tools/docs/index.ts +1 -0
  285. package/src/tools/docs/tools.ts +228 -0
  286. package/src/tools/dream/index.ts +11 -0
  287. package/src/tools/dream/tools.ts +1002 -0
  288. package/src/tools/exec/allowlist.ts +233 -0
  289. package/src/tools/exec/background-detach.helper.mts +27 -0
  290. package/src/tools/exec/blacklist.ts +336 -0
  291. package/src/tools/exec/concurrency.ts +150 -0
  292. package/src/tools/exec/fit-output.ts +82 -0
  293. package/src/tools/exec/index.ts +7 -0
  294. package/src/tools/exec/internal-env.ts +89 -0
  295. package/src/tools/exec/job-store.ts +403 -0
  296. package/src/tools/exec/local.ts +649 -0
  297. package/src/tools/exec/remote.ts +399 -0
  298. package/src/tools/exec/tools.ts +934 -0
  299. package/src/tools/file/analyze.ts +378 -0
  300. package/src/tools/file/index.ts +2 -0
  301. package/src/tools/file/local.ts +707 -0
  302. package/src/tools/file/lsp-hook.ts +72 -0
  303. package/src/tools/file/persona-guard.ts +61 -0
  304. package/src/tools/file/policy.ts +292 -0
  305. package/src/tools/file/read-format.ts +129 -0
  306. package/src/tools/file/remote.ts +680 -0
  307. package/src/tools/file/replace.ts +507 -0
  308. package/src/tools/file/search-window.ts +224 -0
  309. package/src/tools/file/tools.ts +658 -0
  310. package/src/tools/file/write-scope.ts +182 -0
  311. package/src/tools/gating.ts +106 -0
  312. package/src/tools/image/budget.ts +82 -0
  313. package/src/tools/image/index.ts +7 -0
  314. package/src/tools/image/tools.ts +601 -0
  315. package/src/tools/index.ts +99 -0
  316. package/src/tools/memory/index.ts +12 -0
  317. package/src/tools/memory/tools.ts +399 -0
  318. package/src/tools/projects/index.ts +1 -0
  319. package/src/tools/projects/tools.ts +643 -0
  320. package/src/tools/registry.ts +427 -0
  321. package/src/tools/resources/index.ts +8 -0
  322. package/src/tools/resources/tools.ts +176 -0
  323. package/src/tools/resources/visibility.ts +60 -0
  324. package/src/tools/sentinel/index.ts +1 -0
  325. package/src/tools/sentinel/tools.ts +592 -0
  326. package/src/tools/skill/index.ts +4 -0
  327. package/src/tools/skill/tools.ts +285 -0
  328. package/src/tools/time/index.ts +5 -0
  329. package/src/tools/time/tools.ts +123 -0
  330. package/src/tools/tmux/index.ts +1 -0
  331. package/src/tools/tmux/local.ts +277 -0
  332. package/src/tools/tmux/remote.ts +168 -0
  333. package/src/tools/tmux/tools.ts +1064 -0
  334. package/src/tools/tool-output.ts +97 -0
  335. package/src/tools/types.ts +227 -0
  336. package/src/tools/video/index.ts +1 -0
  337. package/src/tools/video/tools.ts +425 -0
  338. package/src/tools/web/fetch.ts +337 -0
  339. package/src/tools/web/index.ts +4 -0
  340. package/src/tools/web/tools.ts +186 -0
  341. package/src/tools/wiki/index.ts +1 -0
  342. package/src/tools/wiki/tools.ts +445 -0
  343. package/src/tts/cache-gc.ts +128 -0
  344. package/src/tts/prepare-for-tts.ts +114 -0
  345. package/src/tts/service.ts +332 -0
  346. package/src/types/events.ts +695 -0
  347. package/src/types/turn-origin.ts +53 -0
  348. package/src/version.ts +21 -0
  349. package/src/videogen/dialects.ts +222 -0
  350. package/src/videogen/generate.ts +484 -0
  351. package/src/videogen/jobs.ts +178 -0
  352. package/src/videogen/runner.ts +125 -0
  353. package/src/videogen/wake.ts +119 -0
  354. package/src/voice/realtime/call.ts +948 -0
  355. package/src/voice/realtime/consult.ts +293 -0
  356. package/src/voice/realtime/fake-provider.ts +134 -0
  357. package/src/voice/realtime/manager.ts +384 -0
  358. package/src/voice/realtime/openai-provider.ts +471 -0
  359. package/src/voice/realtime/persona.ts +227 -0
  360. package/src/voice/realtime/session-match.ts +116 -0
  361. package/src/voice/realtime/types.ts +182 -0
  362. package/src/wiki/conflict.ts +113 -0
  363. package/src/wiki/explorer.ts +578 -0
  364. package/src/wiki/index-builder.ts +172 -0
  365. package/src/wiki/language.ts +134 -0
  366. package/src/wiki/log-builder.ts +150 -0
  367. package/src/wiki/map.ts +258 -0
  368. package/src/wiki/migration/analyze.ts +304 -0
  369. package/src/wiki/migration/execute.ts +689 -0
  370. package/src/wiki/migration/refine.ts +402 -0
  371. package/src/wiki/migration/store.ts +100 -0
  372. package/src/wiki/move-page.ts +57 -0
  373. package/src/wiki/structure-file.ts +192 -0
  374. package/src/wiki/taxonomy.ts +140 -0
  375. package/src/wiki/templates.ts +163 -0
  376. package/src/wiki/types.ts +133 -0
  377. package/templates/skills/README.md +24 -0
  378. package/templates/skills/_templates/api-wrapper/SKILL.md +26 -0
  379. package/templates/skills/_templates/cli-wrapper/BOOTSTRAP.md +32 -0
  380. package/templates/skills/_templates/cli-wrapper/SKILL.md +24 -0
  381. package/templates/skills/_templates/default/SKILL.md +25 -0
  382. package/templates/skills/builder-handover/SKILL.md +96 -0
  383. package/templates/skills/builder-handover/assets/ORDER.md +12 -0
  384. package/templates/skills/skill-author/SKILL.md +110 -0
  385. package/tsconfig.json +22 -0
  386. package/web/dist/assets/index-BaVv6pB2.js +631 -0
  387. package/web/dist/assets/index-BaVv6pB2.js.map +1 -0
  388. package/web/dist/assets/index-V3FV3Z25.css +32 -0
  389. package/web/dist/favicon.svg +8 -0
  390. package/web/dist/index.html +20 -0
  391. package/web/package.json +36 -0
  392. package/web/tsconfig.json +25 -0
  393. package/web-mobile/dist/apple-touch-icon.png +0 -0
  394. package/web-mobile/dist/assets/index-BqKt7IMx.css +1 -0
  395. package/web-mobile/dist/assets/index-X_vRr6cd.js +88 -0
  396. package/web-mobile/dist/assets/index-X_vRr6cd.js.map +1 -0
  397. package/web-mobile/dist/favicon.svg +8 -0
  398. package/web-mobile/dist/icon-192.png +0 -0
  399. package/web-mobile/dist/icon-512.png +0 -0
  400. package/web-mobile/dist/index.html +27 -0
  401. package/web-mobile/dist/manifest.webmanifest +32 -0
  402. package/web-mobile/dist/service-worker.js +90 -0
  403. package/web-mobile/package.json +28 -0
  404. package/web-mobile/tsconfig.json +25 -0
@@ -0,0 +1,192 @@
1
+ // The structure file — `_struktur.md` / `_structure.md` in the wiki root.
2
+ //
3
+ // One table row per folder: path, purpose, who described it (template,
4
+ // Deep, a person), when. It is the wiki's own memory of what its
5
+ // folders mean: Deep reads it into the map (src/wiki/map.ts) on every
6
+ // run, writes the purpose of a folder it creates, and people edit it
7
+ // in Obsidian like any page. Folders that exist on disk but were never
8
+ // described have an empty purpose until the migration or a person
9
+ // fills it in. The table IS the data (parsed back on load); the
10
+ // frontmatter holds only the language and the template version.
11
+
12
+ import { readFile, writeFile, rename } from 'node:fs/promises';
13
+ import { join } from 'node:path';
14
+ import matter from 'gray-matter';
15
+ import type { WikiLanguage } from './language.ts';
16
+ import { taxonomyFor } from './taxonomy.ts';
17
+
18
+ export type FolderOrigin = 'template' | 'deep' | 'user' | 'unknown';
19
+
20
+ export interface StructureFolder {
21
+ path: string;
22
+ purpose: string;
23
+ origin: FolderOrigin;
24
+ /** ISO date the entry was written. */
25
+ since: string;
26
+ }
27
+
28
+ export interface StructureDuplicate {
29
+ /** Page basename that exists in several folders. */
30
+ name: string;
31
+ paths: string[];
32
+ noted: string;
33
+ }
34
+
35
+ export interface StructureFile {
36
+ language: WikiLanguage;
37
+ /** The taxonomy version this wiki was last migrated to; 0 = never. */
38
+ template_version: number;
39
+ folders: StructureFolder[];
40
+ /** Same-name pages Deep found in several folders — for the migration. */
41
+ duplicates: StructureDuplicate[];
42
+ }
43
+
44
+ export function structureFileName(language: WikiLanguage): string {
45
+ return language === 'en' ? '_structure.md' : '_struktur.md';
46
+ }
47
+
48
+ /** `_struktur.md` / `_structure.md` in any language — skipped by the
49
+ * index builder and the memory indexer: it describes pages, it is none. */
50
+ export function isStructureFileName(name: string): boolean {
51
+ return name === '_struktur.md' || name === '_structure.md';
52
+ }
53
+
54
+ export function emptyStructure(language: WikiLanguage): StructureFile {
55
+ return { language, template_version: 0, folders: [], duplicates: [] };
56
+ }
57
+
58
+ const ORIGINS: readonly FolderOrigin[] = ['template', 'deep', 'user', 'unknown'];
59
+ const asOrigin = (v: unknown): FolderOrigin => (ORIGINS.includes(String(v) as FolderOrigin) ? (String(v) as FolderOrigin) : 'user');
60
+
61
+ /**
62
+ * The table in the body is the source of truth — Obsidian shows a
63
+ * frontmatter list of objects as raw JSON in yellow (2026-09-29), and a
64
+ * person edits a sentence in a table, not in YAML. The first version
65
+ * kept the data in the frontmatter; a file written that way is still
66
+ * read when its body has no table rows.
67
+ */
68
+ export async function loadStructureFile(wikiAbs: string, language: WikiLanguage): Promise<StructureFile> {
69
+ let raw: string;
70
+ try {
71
+ raw = await readFile(join(wikiAbs, structureFileName(language)), 'utf8');
72
+ } catch (err) {
73
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return emptyStructure(language);
74
+ throw err;
75
+ }
76
+ return parseStructureFile(raw, language);
77
+ }
78
+
79
+ /** Exported for tests. */
80
+ export function parseStructureFile(raw: string, language: WikiLanguage): StructureFile {
81
+ const parsed = matter(raw);
82
+ const data = parsed.data as Partial<StructureFile>;
83
+ const out: StructureFile = { language, template_version: Number(data.template_version ?? 0) || 0, folders: [], duplicates: [] };
84
+ const seen = new Set<string>();
85
+ for (const line of parsed.content.split('\n')) {
86
+ const t = line.trim();
87
+ if (!t.startsWith('|')) continue;
88
+ const cells = t.replace(/^\|/, '').replace(/\|$/, '').split('|').map((c) => c.trim());
89
+ if (cells.length < 4) continue;
90
+ const path = normalizeFolder(cells[0]!.replace(/`/g, ''));
91
+ if (!path || /^-+$/.test(path) || seen.has(path)) continue;
92
+ // The header row: its first cell is a word, not a path — but a
93
+ // top folder is a word too, so the header is told by its origin
94
+ // column, which is never a real origin.
95
+ const origin = String(cells[2]);
96
+ if (!ORIGINS.includes(origin as FolderOrigin) && origin !== '') continue;
97
+ seen.add(path);
98
+ out.folders.push({ path, purpose: cells[1]!, origin: origin ? asOrigin(origin) : 'user', since: cells[3]! });
99
+ }
100
+ const dupRe = /^- (\S+): (.+?)(?: \((\d{4}-\d{2}-\d{2})\))?$/;
101
+ let inDup = false;
102
+ for (const line of parsed.content.split('\n')) {
103
+ if (line.startsWith('## ')) inDup = /gleichnamige|same-name/i.test(line);
104
+ if (!inDup) continue;
105
+ const m = dupRe.exec(line.trim());
106
+ if (m) out.duplicates.push({ name: m[1]!, paths: m[2]!.split(',').map((x) => normalizeFolder(x.trim())).filter(Boolean), noted: m[3] ?? '' });
107
+ }
108
+ // Fallback: the first format kept the rows in the frontmatter.
109
+ if (out.folders.length === 0 && Array.isArray(data.folders)) {
110
+ for (const f of data.folders as unknown[]) {
111
+ if (!f || typeof f !== 'object' || typeof (f as StructureFolder).path !== 'string') continue;
112
+ const e = f as StructureFolder;
113
+ out.folders.push({ path: normalizeFolder(e.path), purpose: String(e.purpose ?? ''), origin: asOrigin(e.origin), since: String(e.since ?? '') });
114
+ }
115
+ }
116
+ if (out.duplicates.length === 0 && Array.isArray(data.duplicates)) {
117
+ for (const d of data.duplicates as unknown[]) {
118
+ if (!d || typeof d !== 'object' || typeof (d as StructureDuplicate).name !== 'string') continue;
119
+ const e = d as StructureDuplicate;
120
+ out.duplicates.push({ name: e.name, paths: Array.isArray(e.paths) ? e.paths.map(String) : [], noted: String(e.noted ?? '') });
121
+ }
122
+ }
123
+ out.folders.sort((a, b) => a.path.localeCompare(b.path));
124
+ return out;
125
+ }
126
+
127
+ export async function saveStructureFile(wikiAbs: string, data: StructureFile): Promise<void> {
128
+ const file = join(wikiAbs, structureFileName(data.language));
129
+ const content = matter.stringify(renderBody(data), {
130
+ language: data.language,
131
+ template_version: data.template_version,
132
+ });
133
+ const tmp = `${file}.tmp-${process.pid}`;
134
+ await writeFile(tmp, content, 'utf8');
135
+ await rename(tmp, file);
136
+ }
137
+
138
+ export function normalizeFolder(p: string): string {
139
+ return p.replace(/^\/+|\/+$/g, '').replace(/\.md$/i, '');
140
+ }
141
+
142
+ /** Describe a folder; an existing entry is updated only when it had no
143
+ * purpose or was `unknown` — a person's or the template's wording is
144
+ * never overwritten by Deep. Returns true when something changed. */
145
+ export function describeFolder(data: StructureFile, entry: { path: string; purpose: string; origin: FolderOrigin }, now = new Date()): boolean {
146
+ const path = normalizeFolder(entry.path);
147
+ const existing = data.folders.find((f) => f.path === path);
148
+ if (existing) {
149
+ if (existing.purpose.trim() && existing.origin !== 'unknown') return false;
150
+ existing.purpose = entry.purpose;
151
+ existing.origin = entry.origin;
152
+ existing.since = now.toISOString().slice(0, 10);
153
+ return true;
154
+ }
155
+ data.folders.push({ path, purpose: entry.purpose, origin: entry.origin, since: now.toISOString().slice(0, 10) });
156
+ data.folders.sort((a, b) => a.path.localeCompare(b.path));
157
+ return true;
158
+ }
159
+
160
+ export function noteDuplicate(data: StructureFile, name: string, paths: string[], now = new Date()): boolean {
161
+ const sorted = [...new Set(paths.map(normalizeFolder))].sort();
162
+ const existing = data.duplicates.find((d) => d.name === name);
163
+ if (existing) {
164
+ if (existing.paths.join('|') === sorted.join('|')) return false;
165
+ existing.paths = sorted;
166
+ existing.noted = now.toISOString().slice(0, 10);
167
+ return true;
168
+ }
169
+ data.duplicates.push({ name, paths: sorted, noted: now.toISOString().slice(0, 10) });
170
+ return true;
171
+ }
172
+
173
+ function renderBody(data: StructureFile): string {
174
+ const t = taxonomyFor(data.language);
175
+ const de = data.language === 'de';
176
+ const lines: string[] = [];
177
+ lines.push(de ? '# Struktur dieses Wikis' : '# Structure of this wiki');
178
+ lines.push('');
179
+ lines.push(de
180
+ ? 'Ein Ordner sagt, welche Art von Seite darin liegt. Diese Tabelle ist die Landkarte, die Deep beim Einordnen neuer Seiten liest. Die Sätze in der Spalte „Zweck" dürfen von Hand geändert werden; die Spalten Ordner, Herkunft und seit lässt man stehen.'
181
+ : 'A folder says what kind of page lives in it. This table is the map Deep reads when it files new pages. Edit the sentences in the "Purpose" column by hand as you like; leave the Folder, Origin and since columns as they are.');
182
+ lines.push('');
183
+ lines.push(de ? '| Ordner | Zweck | Herkunft | seit |' : '| Folder | Purpose | Origin | since |');
184
+ lines.push('|---|---|---|---|');
185
+ for (const f of data.folders) lines.push(`| ${f.path} | ${f.purpose.replace(/\|/g, '/').replace(/\s*\n\s*/g, ' ')} | ${f.origin} | ${f.since} |`);
186
+ if (data.duplicates.length > 0) {
187
+ lines.push('', de ? '## Gleichnamige Seiten in mehreren Ordnern' : '## Same-name pages in several folders', '');
188
+ for (const d of data.duplicates) lines.push(`- ${d.name}: ${d.paths.join(', ')} (${d.noted})`);
189
+ }
190
+ lines.push('', de ? `Vorlage: Version ${data.template_version || '—'} (aktuell ${t.version}).` : `Template: version ${data.template_version || '—'} (current ${t.version}).`);
191
+ return lines.join('\n') + '\n';
192
+ }
@@ -0,0 +1,140 @@
1
+ // The shipped wiki folder template — one per wiki language.
2
+ //
3
+ // Why (Rene, 2026-09-29): Deep used to be told "pick personen / projekte
4
+ // / wissen … or invent a new folder", saw the first 4 KB of index.md as
5
+ // its only map, and after five months a wiki had 40+ folders, a
6
+ // 300-page `wissen` catch-all, 15 page names living in several folders
7
+ // at once. The rule now, borrowed from well-kept Obsidian vaults: a
8
+ // folder says what KIND of page lives in it, never what a page is
9
+ // about — topics live in links and in index.md. The template below is
10
+ // the starting order every installation gets; a wiki's real folders
11
+ // win over it (src/wiki/map.ts), and the template only proposes where a
12
+ // new page of a kind should go. Adding a language = adding an entry
13
+ // here and in language.ts; nothing else knows the language.
14
+ //
15
+ // Purposes and rationales are written in the wiki's language: they are
16
+ // shown to the model as the meaning of a folder and to people in the
17
+ // structure file (src/wiki/structure-file.ts).
18
+
19
+ import type { WikiLanguage } from './language.ts';
20
+
21
+ export interface TaxonomySubfolder {
22
+ path: string;
23
+ purpose: string;
24
+ }
25
+
26
+ export interface TaxonomyFolder {
27
+ path: string;
28
+ /** One sentence: what kind of page lives here. */
29
+ purpose: string;
30
+ /** Why the order is this way — the part that lets the model place a
31
+ * kind the template did not foresee. */
32
+ rationale: string;
33
+ subfolders?: readonly TaxonomySubfolder[];
34
+ }
35
+
36
+ export interface WikiTaxonomy {
37
+ language: WikiLanguage;
38
+ /** Bumped when the template changes in a way a migration should notice. */
39
+ version: number;
40
+ folders: readonly TaxonomyFolder[];
41
+ /** Folder names grown wikis commonly have, and the template folder
42
+ * their pages belong in — the migration's rule-based moves. Anything
43
+ * not listed here is judged page by page. */
44
+ aliases: Readonly<Record<string, string>>;
45
+ }
46
+
47
+ const DE: WikiTaxonomy = {
48
+ language: 'de',
49
+ version: 1,
50
+ folders: [
51
+ { path: 'personen', purpose: 'Menschen: Familie, Freunde, Geschäftskontakte — eine Seite pro Mensch.', rationale: 'Ein Mensch ist eine Entität mit vielen Themen; die Themen verweisen auf ihn, nicht umgekehrt.' },
52
+ { path: 'unternehmen', purpose: 'Firmen, Beteiligungen, Kanzleien, Lieferanten — eine Seite pro Firma.', rationale: 'Wie Personen: eine Firma ist eine Adresse für alles, was sie betrifft.' },
53
+ { path: 'projekte', purpose: 'Abgegrenzte Vorhaben mit Anfang und Ziel — Software, Bau, Deal, Umzug; eine Seite pro Vorhaben, datierte Arbeitsberichte sind Einträge in deren Zeitleiste, keine eigenen Seiten.', rationale: 'Ein Projekt sammelt seinen Verlauf an einem Ort; verstreute Berichtsseiten werden nie wieder gefunden.' },
54
+ { path: 'infrastruktur', purpose: 'Geräte, Rechner, laufende Dienste, Netzwerk, Zugänge bei Anbietern.', rationale: 'Technik, die betrieben wird, unabhängig vom Projekt, das sie nutzt.', subfolders: [
55
+ { path: 'infrastruktur/geraete', purpose: 'Physische Geräte: Rechner, Server, Netzwerkhardware, Peripherie.' },
56
+ { path: 'infrastruktur/hosts', purpose: 'Betriebene Rechner und VMs als Betriebseinheit: was darauf läuft, wie man hinkommt.' },
57
+ { path: 'infrastruktur/dienste', purpose: 'Laufende Dienste und Anwendungen: Adresse, Zweck, Betrieb.' },
58
+ { path: 'infrastruktur/konten', purpose: 'Zugänge und Konten bei Anbietern (APIs, Cloud, Abos) — ohne Geheimnisse.' },
59
+ ] },
60
+ { path: 'finanzen', purpose: 'Konten, Depot, Aktien, Krypto, Immobilien als Anlage, Kredite, Bewertungen.', rationale: 'Geldpositionen haben eigene Sorten; ein Ordner je Sorte hält sie nebeneinander.', subfolders: [
61
+ { path: 'finanzen/konten', purpose: 'Bank- und Zahlungskonten.' },
62
+ { path: 'finanzen/depot', purpose: 'Wertpapiere, Aktien, Fonds, Beobachtungslisten.' },
63
+ { path: 'finanzen/krypto', purpose: 'Kryptowährungen und Wallets.' },
64
+ { path: 'finanzen/immobilien', purpose: 'Immobilien als Anlage: Objekt, Erträge, Bewertung.' },
65
+ { path: 'finanzen/kredite', purpose: 'Darlehen, Kredite, Leasing.' },
66
+ ] },
67
+ { path: 'besitz', purpose: 'Dinge, die einem gehören und keine Anlage sind: Autos, Ausstattung, Wohnung als Zuhause.', rationale: 'Besitz wird gepflegt, nicht bewertet — anders als eine Anlage.' },
68
+ { path: 'orte', purpose: 'Häuser, Standorte, Städte, Reiseziele.', rationale: 'Ein Ort ist eine Adresse für Ereignisse und Dinge, die dort sind.' },
69
+ { path: 'ereignisse', purpose: 'Vorfälle, Termine, Chronik — was wann passiert ist.', rationale: 'Ereignisse sind datiert und abgeschlossen; sie gehören zusammen, nicht unter das Thema.' },
70
+ { path: 'wissen', purpose: 'Sachwissen ohne Bezug auf eine konkrete Person oder Firma: Konzepte, Anleitungen, Vergleiche, Werkzeuge — nur echtes Wissen, kein Sammelbecken.', rationale: 'Wissen ist wiederverwendbar; alles mit Bezug auf eine Entität gehört zu der Entität.', subfolders: [
71
+ { path: 'wissen/konzepte', purpose: 'Was etwas ist und wie es funktioniert.' },
72
+ { path: 'wissen/anleitungen', purpose: 'Wie man etwas macht, Schritt für Schritt.' },
73
+ { path: 'wissen/vergleiche', purpose: 'X gegen Y: Bewertungen und Entscheidungsgrundlagen.' },
74
+ ] },
75
+ { path: 'regeln', purpose: 'Vorgaben, Präferenzen, Vereinbarungen, rechtliche Rahmen — was Agenten beachten sollen.', rationale: 'Regeln gelten quer über alle Themen; als eigene Art sind sie auffindbar und prüfbar.' },
76
+ { path: 'agenten', purpose: 'Nur Steckbriefe: was ein Agent ist, kann und darf. Keine Arbeitsberichte.', rationale: 'Ein Agent ist eine Entität; seine Arbeit gehört zu den Projekten, an denen er arbeitet.' },
77
+ { path: 'privat', purpose: 'Interessen, Hobbys, Haustiere, Gesundheit, Wohnen — das Leben abseits von Arbeit und Geld.', rationale: 'Persönliches braucht einen eigenen Ort, damit es weder unter Wissen noch unter Projekte rutscht.' },
78
+ ],
79
+ aliases: {
80
+ hardware: 'infrastruktur/geraete', geraete: 'infrastruktur/geraete', hosts: 'infrastruktur/hosts', server: 'infrastruktur/hosts', homelab: 'infrastruktur', netzwerk: 'infrastruktur', dienste: 'infrastruktur/dienste', konten: 'infrastruktur/konten', zugaenge: 'infrastruktur/konten',
81
+ aktien: 'finanzen/depot', depot: 'finanzen/depot', portfolio: 'finanzen/depot', watchlist: 'finanzen/depot', investments: 'finanzen/depot', investment: 'finanzen/depot', krypto: 'finanzen/krypto', immobilien: 'finanzen/immobilien', kredite: 'finanzen/kredite',
82
+ haustiere: 'privat', tiere: 'privat', interessen: 'privat', hobbys: 'privat', wohnen: 'privat', gesundheit: 'privat',
83
+ reisen: 'ereignisse', vorfaelle: 'ereignisse', vorfall: 'ereignisse', sicherheit: 'ereignisse', termine: 'ereignisse',
84
+ praeferenzen: 'regeln', vorgaben: 'regeln', rechtliches: 'regeln', recht: 'regeln', vereinbarungen: 'regeln',
85
+ konzepte: 'wissen/konzepte', anleitungen: 'wissen/anleitungen', runbooks: 'wissen/anleitungen', howto: 'wissen/anleitungen', skills: 'wissen/anleitungen', vergleiche: 'wissen/vergleiche', werkzeuge: 'wissen', tools: 'wissen',
86
+ firmen: 'unternehmen', kontakte: 'personen', leute: 'personen', menschen: 'personen', standorte: 'orte', fahrzeuge: 'besitz', autos: 'besitz',
87
+ },
88
+ };
89
+
90
+ const EN: WikiTaxonomy = {
91
+ language: 'en',
92
+ version: 1,
93
+ folders: [
94
+ { path: 'people', purpose: 'Humans: family, friends, business contacts — one page per person.', rationale: 'A person is an entity with many topics; the topics point at the person, not the other way round.' },
95
+ { path: 'companies', purpose: 'Companies, holdings, firms, suppliers — one page per company.', rationale: 'Like people: a company is one address for everything that concerns it.' },
96
+ { path: 'projects', purpose: 'Bounded undertakings with a start and a goal — software, construction, a deal, a move; one page per undertaking, dated work reports are timeline entries on that page, not pages of their own.', rationale: 'A project collects its history in one place; scattered report pages are never found again.' },
97
+ { path: 'infrastructure', purpose: 'Devices, machines, running services, network, accounts with providers.', rationale: 'Technology that is operated, independent of the project that uses it.', subfolders: [
98
+ { path: 'infrastructure/devices', purpose: 'Physical devices: computers, servers, network hardware, peripherals.' },
99
+ { path: 'infrastructure/hosts', purpose: 'Operated machines and VMs as units: what runs there, how to reach them.' },
100
+ { path: 'infrastructure/services', purpose: 'Running services and applications: address, purpose, operation.' },
101
+ { path: 'infrastructure/accounts', purpose: 'Access and accounts with providers (APIs, cloud, subscriptions) — never secrets.' },
102
+ ] },
103
+ { path: 'finances', purpose: 'Accounts, portfolio, stocks, crypto, real estate as investment, loans, valuations.', rationale: 'Money positions come in kinds; one folder per kind keeps them side by side.', subfolders: [
104
+ { path: 'finances/accounts', purpose: 'Bank and payment accounts.' },
105
+ { path: 'finances/portfolio', purpose: 'Securities, stocks, funds, watchlists.' },
106
+ { path: 'finances/crypto', purpose: 'Cryptocurrencies and wallets.' },
107
+ { path: 'finances/real-estate', purpose: 'Real estate as investment: property, yields, valuation.' },
108
+ { path: 'finances/loans', purpose: 'Loans, credit, leasing.' },
109
+ ] },
110
+ { path: 'possessions', purpose: 'Things one owns that are not investments: cars, equipment, the home as a home.', rationale: 'Possessions are maintained, not valued — unlike an investment.' },
111
+ { path: 'places', purpose: 'Houses, sites, cities, travel destinations.', rationale: 'A place is an address for events and things that are there.' },
112
+ { path: 'events', purpose: 'Incidents, appointments, chronicle — what happened when.', rationale: 'Events are dated and closed; they belong together, not under the topic.' },
113
+ { path: 'knowledge', purpose: 'Subject knowledge with no tie to a specific person or company: concepts, how-tos, comparisons, tools — real knowledge only, not a catch-all.', rationale: 'Knowledge is reusable; anything tied to an entity belongs with that entity.', subfolders: [
114
+ { path: 'knowledge/concepts', purpose: 'What something is and how it works.' },
115
+ { path: 'knowledge/how-tos', purpose: 'How to do something, step by step.' },
116
+ { path: 'knowledge/comparisons', purpose: 'X versus Y: evaluations and decision bases.' },
117
+ ] },
118
+ { path: 'rules', purpose: 'Directives, preferences, agreements, legal frames — what agents must respect.', rationale: 'Rules cut across all topics; as a kind of their own they can be found and checked.' },
119
+ { path: 'agents', purpose: 'Profiles only: what an agent is, can and may do. No work reports.', rationale: 'An agent is an entity; its work belongs to the projects it works on.' },
120
+ { path: 'personal', purpose: 'Interests, hobbies, pets, health, living — life apart from work and money.', rationale: 'Personal matters need a place of their own so they slide neither under knowledge nor under projects.' },
121
+ ],
122
+ aliases: {
123
+ hardware: 'infrastructure/devices', devices: 'infrastructure/devices', hosts: 'infrastructure/hosts', servers: 'infrastructure/hosts', homelab: 'infrastructure', network: 'infrastructure', services: 'infrastructure/services', accounts: 'infrastructure/accounts',
124
+ stocks: 'finances/portfolio', portfolio: 'finances/portfolio', watchlist: 'finances/portfolio', investments: 'finances/portfolio', crypto: 'finances/crypto', 'real-estate': 'finances/real-estate', property: 'finances/real-estate', loans: 'finances/loans',
125
+ pets: 'personal', interests: 'personal', hobbies: 'personal', living: 'personal', health: 'personal',
126
+ travel: 'events', trips: 'events', incidents: 'events', security: 'events', appointments: 'events',
127
+ preferences: 'rules', legal: 'rules', agreements: 'rules',
128
+ concepts: 'knowledge/concepts', 'how-tos': 'knowledge/how-tos', howto: 'knowledge/how-tos', runbooks: 'knowledge/how-tos', skills: 'knowledge/how-tos', comparisons: 'knowledge/comparisons', tools: 'knowledge',
129
+ firms: 'companies', contacts: 'people', locations: 'places', vehicles: 'possessions', cars: 'possessions',
130
+ },
131
+ };
132
+
133
+ export function taxonomyFor(language: WikiLanguage): WikiTaxonomy {
134
+ return language === 'en' ? EN : DE;
135
+ }
136
+
137
+ /** Every folder path the template names, subfolders included. */
138
+ export function taxonomyPaths(t: WikiTaxonomy): string[] {
139
+ return t.folders.flatMap((f) => [f.path, ...(f.subfolders ?? []).map((s) => s.path)]);
140
+ }
@@ -0,0 +1,163 @@
1
+ // Page-format definitions for the somora wiki.
2
+ //
3
+ // This module is the single source of truth for what a wiki page
4
+ // looks like (frontmatter fields, section names) and how to parse
5
+ // and (re-)build one.
6
+ //
7
+ // Used by Deep (memory→wiki consolidation) for promotion writes and
8
+ // merge-updates.
9
+ //
10
+ // As of v2.2 the stub-pattern is gone — memory files no longer get
11
+ // converted to pointer-stubs after Deep promotion; they are deleted.
12
+ // Wiki is the single source of truth for consolidated knowledge.
13
+ //
14
+ // See `private/dream-system-v2.md`.
15
+
16
+ import matter from 'gray-matter';
17
+ import { dump as yamlDump } from 'js-yaml';
18
+
19
+ import { wikiSchemaFor, type WikiLanguage, type WikiSections } from './language.ts';
20
+
21
+ // ─── Wiki-Page ───────────────────────────────────────────────────────
22
+
23
+ /** Allowed `type` values in wiki-page frontmatter, both languages
24
+ * (see src/wiki/language.ts). Non-exhaustive — Deep may introduce new
25
+ * types when it creates new subdirs. Validation: warn on unknown
26
+ * types, don't reject. */
27
+ export const KNOWN_WIKI_TYPES = [
28
+ ...wikiSchemaFor('de').types,
29
+ ...wikiSchemaFor('en').types,
30
+ ] as const;
31
+ export type KnownWikiType = (typeof KNOWN_WIKI_TYPES)[number];
32
+
33
+ export interface WikiPageFrontmatter {
34
+ slug: string;
35
+ /** Loose enum — see KNOWN_WIKI_TYPES. */
36
+ type: string;
37
+ /** ISO date (YYYY-MM-DD). When the page was first created. */
38
+ created: string;
39
+ /** ISO date (YYYY-MM-DD). Last update by Deep or user. */
40
+ updated: string;
41
+ /** Source pointers: `<agent>/<memory-slug>` strings. */
42
+ sources?: string[];
43
+ /** Cross-refs to other wiki pages (path without .md). */
44
+ related?: string[];
45
+ /** Free-form additional metadata Deep may want to track. */
46
+ [extra: string]: unknown;
47
+ }
48
+
49
+ /** Section titles Deep prefers when generating new pages, per wiki
50
+ * language. User may introduce others; Deep respects existing
51
+ * structure. */
52
+ export function wikiSectionTitles(language: WikiLanguage = 'de'): WikiSections {
53
+ return wikiSchemaFor(language).sections;
54
+ }
55
+
56
+ export interface WikiPage {
57
+ frontmatter: WikiPageFrontmatter;
58
+ /** Page body (everything after frontmatter), with `# Title` heading
59
+ * and `## Sektionen` preserved verbatim. */
60
+ body: string;
61
+ }
62
+
63
+ export function parseWikiPage(raw: string): WikiPage {
64
+ const parsed = matter(raw);
65
+ const data = (parsed.data ?? {}) as Record<string, unknown>;
66
+ return {
67
+ frontmatter: {
68
+ slug: typeof data.slug === 'string' ? data.slug : '',
69
+ type: typeof data.type === 'string' ? data.type : '',
70
+ created: coerceWikiDate(data.created),
71
+ updated: coerceWikiDate(data.updated),
72
+ ...(Array.isArray(data.sources) ? { sources: data.sources as string[] } : {}),
73
+ ...(Array.isArray(data.related) ? { related: data.related as string[] } : {}),
74
+ ...stripStandardFields(data),
75
+ },
76
+ body: parsed.content,
77
+ };
78
+ }
79
+
80
+ export function buildWikiPage(page: WikiPage): string {
81
+ // Use yaml-dump (not gray-matter's stringify) for deterministic field
82
+ // order and clean array rendering.
83
+ const fm = page.frontmatter;
84
+ const ordered: Record<string, unknown> = {
85
+ slug: fm.slug,
86
+ type: fm.type,
87
+ created: fm.created,
88
+ updated: fm.updated,
89
+ };
90
+ if (fm.sources?.length) ordered.sources = fm.sources;
91
+ if (fm.related?.length) ordered.related = fm.related;
92
+ for (const [k, v] of Object.entries(fm)) {
93
+ if (['slug', 'type', 'created', 'updated', 'sources', 'related'].includes(k)) continue;
94
+ ordered[k] = v;
95
+ }
96
+ const yaml = yamlDump(ordered, { lineWidth: 100, noRefs: true }).trimEnd();
97
+ const body = page.body.startsWith('\n') ? page.body : '\n' + page.body;
98
+ return `---\n${yaml}\n---\n${body}`;
99
+ }
100
+
101
+ /** Build an initial wiki-page from minimum input. Helper for Deep's
102
+ * first-promotion path. */
103
+ export function buildInitialWikiPage(args: {
104
+ slug: string;
105
+ type: string;
106
+ title: string;
107
+ body: string;
108
+ sources?: string[];
109
+ related?: string[];
110
+ }): string {
111
+ const today = isoDate();
112
+ return buildWikiPage({
113
+ frontmatter: {
114
+ slug: args.slug,
115
+ type: args.type,
116
+ created: today,
117
+ updated: today,
118
+ ...(args.sources?.length ? { sources: args.sources } : {}),
119
+ ...(args.related?.length ? { related: args.related } : {}),
120
+ },
121
+ body: `# ${args.title}\n\n${args.body.trimStart()}\n`,
122
+ });
123
+ }
124
+
125
+ // ─── Helpers ─────────────────────────────────────────────────────────
126
+
127
+ function isoDate(): string {
128
+ // YYYY-MM-DD in UTC. Wiki dates are calendar-day granularity.
129
+ const d = new Date();
130
+ return formatUtcDate(d);
131
+ }
132
+
133
+ function formatUtcDate(d: Date): string {
134
+ const y = d.getUTCFullYear();
135
+ const m = String(d.getUTCMonth() + 1).padStart(2, '0');
136
+ const day = String(d.getUTCDate()).padStart(2, '0');
137
+ return `${y}-${m}-${day}`;
138
+ }
139
+
140
+ /** Coerce a frontmatter date field to a YYYY-MM-DD string.
141
+ *
142
+ * Obsidian writes dates UNQUOTED (`created: 2026-05-01`), so js-yaml
143
+ * parses them into a `Date` object rather than a string. The old code
144
+ * only kept `typeof === 'string'` values and blanked everything else,
145
+ * so a Date-valued `created` became '' — and the next `wiki_edit`
146
+ * replaced the blank with today's date, silently destroying the real
147
+ * creation date on every edit. Coercing the Date back to its calendar
148
+ * day here makes the read path robust regardless of how the page was
149
+ * authored (quoted, unquoted, or via somora's own writer). */
150
+ export function coerceWikiDate(v: unknown): string {
151
+ if (typeof v === 'string') return v;
152
+ if (v instanceof Date && !Number.isNaN(v.getTime())) return formatUtcDate(v);
153
+ return '';
154
+ }
155
+
156
+ function stripStandardFields(data: Record<string, unknown>): Record<string, unknown> {
157
+ const out: Record<string, unknown> = {};
158
+ for (const [k, v] of Object.entries(data)) {
159
+ if (['slug', 'type', 'created', 'updated', 'sources', 'related'].includes(k)) continue;
160
+ out[k] = v;
161
+ }
162
+ return out;
163
+ }
@@ -0,0 +1,133 @@
1
+ // Deep-Phase types: candidates, plans, dispatcher interface.
2
+ //
3
+ // See `private/dream-system-v2.md` for the design.
4
+ //
5
+ // As of v2.2 the stub-with-observations variant is gone. All candidates
6
+ // are 'fresh' memory files; merge-vs-promote is decided by Deep at
7
+ // processing time (collision-detection on slug-write).
8
+
9
+ import type { ResolvedModel, ThinkingLevel } from '../config/types.ts';
10
+
11
+ /** A memory file that's a candidate for promotion or merge. */
12
+ export interface PromotionCandidate {
13
+ agent: string;
14
+ /** Slug of the memory file (no extension). */
15
+ slug: string;
16
+ /** Absolute path to the memory file. */
17
+ path: string;
18
+ /** Full markdown including frontmatter. */
19
+ raw: string;
20
+ /** Parsed frontmatter (may be empty). */
21
+ frontmatter: Record<string, unknown>;
22
+ /** Body without frontmatter. */
23
+ body: string;
24
+ /** mtime at read time — used for optimistic-concurrency on later writes. */
25
+ mtimeMs: number;
26
+ }
27
+
28
+ /** Unified Deep-decision for one memory candidate. Single LLM call
29
+ * picks one of three outcomes — see `src/dream/deep-prompts.ts`. */
30
+ export type MemoryFateDecision =
31
+ | {
32
+ kind: 'skip';
33
+ reason: string;
34
+ /** Set when the skip is the result of a transient failure
35
+ * (LLM call error, JSON parse failure, schema mismatch) — i.e.
36
+ * NOT a deliberate skip-decision from the model. The runner
37
+ * must not record transient skips into the per-agent skip-cache,
38
+ * or the memory file gets stuck across runs (verified bug
39
+ * 2026-05-09: mac-studio-korrektur stuck on parser-failure).
40
+ * Genuine model-emitted skips (transient unset) are stable and
41
+ * cacheable. */
42
+ transient?: true;
43
+ }
44
+ | {
45
+ kind: 'promote';
46
+ /** Wiki sub-folder (relative to wiki root, e.g. 'personen'). */
47
+ subfolder: string;
48
+ /** Slug for the new wiki page (filename without .md). May
49
+ * contain `/` for nested paths within the subfolder. */
50
+ slug: string;
51
+ /** Wiki frontmatter `type` (person | projekt | konzept | ...). */
52
+ type: string;
53
+ /** Suggested H1 title for the wiki page. */
54
+ title: string;
55
+ /** Body markdown for the wiki page (no frontmatter, no H1 — the
56
+ * builder adds those). */
57
+ body: string;
58
+ /** Optional cross-reference targets (wiki paths without .md). */
59
+ related?: string[];
60
+ /** A folder the model created for this page, with the one-sentence
61
+ * purpose the structure file keeps (src/wiki/map.ts rules). */
62
+ newFolder?: { path: string; purpose: string };
63
+ }
64
+ | {
65
+ kind: 'merge';
66
+ /** Existing wiki page slug (without .md) to update. */
67
+ wikiPath: string;
68
+ /** Updated body for the wiki page (no frontmatter — caller
69
+ * preserves frontmatter, only refreshes `updated`). */
70
+ body: string;
71
+ /** Optional updated cross-references. */
72
+ related?: string[];
73
+ /** One-line summary for the wiki log. */
74
+ logSummary: string;
75
+ };
76
+
77
+ /** What a single candidate produced — the shape used by orchestrator
78
+ * for log entries and index regeneration. */
79
+ export type CandidateOutcome =
80
+ | {
81
+ kind: 'promoted';
82
+ agent: string;
83
+ memorySlug: string;
84
+ wikiPath: string; // relative to wiki root, no .md
85
+ logSummary: string;
86
+ }
87
+ | {
88
+ kind: 'merged';
89
+ agent: string;
90
+ memorySlug: string;
91
+ wikiPath: string;
92
+ logSummary: string;
93
+ }
94
+ | {
95
+ kind: 'skipped';
96
+ agent: string;
97
+ memorySlug: string;
98
+ reason: string;
99
+ /** When true, the skip resulted from a transient failure (LLM
100
+ * call/parse error, schema mismatch, mtime conflict, write
101
+ * failure) — not a stable model-emitted skip-decision. The
102
+ * runner uses this to gate the per-agent skip-cache so a
103
+ * one-off failure can't lock a memory file out forever. */
104
+ transient?: true;
105
+ }
106
+ | {
107
+ kind: 'failed';
108
+ agent: string;
109
+ memorySlug: string;
110
+ error: string;
111
+ };
112
+
113
+ /** Dispatcher interface — wraps the LLM call so smoke tests can mock.
114
+ * Single decision point per candidate; LLM decides skip/promote/merge
115
+ * based on the wiki context provided. */
116
+ export interface PromotionDispatcher {
117
+ decideMemoryFate(args: {
118
+ candidate: PromotionCandidate;
119
+ /** The wiki map (src/wiki/map.ts): folders, what kind of page lives
120
+ * in each, page counts, the template's proposals — or a one-line
121
+ * note in the single-page recovery calls. Always present. */
122
+ wikiMap: string;
123
+ /** Full bodies of N most-relevant existing wiki pages
124
+ * (embedding-matched against the candidate's memory body). */
125
+ relevantPages: Array<{ slug: string; markdown: string }>;
126
+ workerModel: ResolvedModel;
127
+ timeoutMs: number;
128
+ signal?: AbortSignal;
129
+ /** Optional thinking-level forwarded into the LLM call. Set from
130
+ * `config.wiki.deep.thinking` by the runner. */
131
+ thinking?: ThinkingLevel;
132
+ }): Promise<MemoryFateDecision>;
133
+ }
@@ -0,0 +1,24 @@
1
+ # somora templates/skills
2
+
3
+ Source of truth for skills somora ships in its own package.
4
+
5
+ ## Layout
6
+
7
+ - **Top-level folders (e.g. `skill-author/`)** — Built-in skills. Seeded into `~/.somora/skills/<slug>/` at server start if the user copy does not exist. If the user later edits their copy, somora detects the edit (via SHA-256 content hash recorded in `~/.somora/.skill-seed-state.json`) and stops re-seeding that slug on future updates. To force a re-seed, run `somora skill update <slug>`.
8
+
9
+ - **`_templates/`** — Reserved namespace. Holds templates consumed by `somora skill add <slug> --template <name>`. Each subfolder is one template (`default`, `cli-wrapper`, `api-wrapper`, ...). These are NEVER loaded as skills directly — the leading underscore makes the dir name fail the slug regex (`^[a-z0-9]+(-[a-z0-9]+)*$`).
10
+
11
+ Placeholders inside template files use `__SLUG__`, `__DESCRIPTION__`, `__WHEN_TO_USE__`, `__BIN_NAME__`. The CLI substitutes these before writing.
12
+
13
+ ## Adding a new built-in
14
+
15
+ 1. Create `templates/skills/<slug>/SKILL.md` (and optional sub-resources).
16
+ 2. Make sure the body passes `lintSkillBody()` (run `somora skill check <slug>` after a manual seed if unsure).
17
+ 3. Bump somora version. On the next install + server start, every user gets the new skill at `~/.somora/skills/<slug>/`.
18
+ 4. If you later modify the bundled file, users who haven't edited their copy will get the update on next server start; users who edited theirs see a `skills.builtin_user_edited` warning and have to opt in via `somora skill update <slug>`.
19
+
20
+ ## Adding a new template
21
+
22
+ 1. Create `templates/skills/_templates/<name>/SKILL.md` (plus optional siblings like `BOOTSTRAP.md`).
23
+ 2. Use the `__PLACEHOLDER__` substitution conventions.
24
+ 3. The CLI auto-discovers templates by listing `_templates/`.