@engenty/wizards-runtime 0.14.2 → 0.16.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 (263) hide show
  1. package/apps/runtime/dist/agents/studio-assistant.js +180 -4
  2. package/apps/runtime/dist/agents/website.js +10 -5
  3. package/apps/runtime/dist/app.js +27 -2
  4. package/apps/runtime/dist/auth/index.js +5 -0
  5. package/apps/runtime/dist/broker/account.js +5 -0
  6. package/apps/runtime/dist/broker/call.js +2 -0
  7. package/apps/runtime/dist/broker/host.js +1 -0
  8. package/apps/runtime/dist/broker/index.js +5 -0
  9. package/apps/runtime/dist/broker/rwx.js +293 -11
  10. package/apps/runtime/dist/cli/main.js +7 -0
  11. package/apps/runtime/dist/cli/move-files.js +68 -0
  12. package/apps/runtime/dist/cli/move-folder-sources.js +120 -0
  13. package/apps/runtime/dist/connectors/plugin-connections.js +74 -4
  14. package/apps/runtime/dist/db/migrations/tenant/0040_rwx_elements.sql +21 -0
  15. package/apps/runtime/dist/db/migrations/tenant/0041_broker_log_client.sql +1 -0
  16. package/apps/runtime/dist/db/migrations/tenant/0042_client_spaces.sql +16 -0
  17. package/apps/runtime/dist/db/migrations/tenant/0043_space_member_invite.sql +19 -0
  18. package/apps/runtime/dist/db/migrations/tenant/0044_client_portal.sql +8 -0
  19. package/apps/runtime/dist/db/migrations/tenant/0045_client_portal_no_slug.sql +2 -0
  20. package/apps/runtime/dist/db/migrations/tenant/0046_space_file_hash.sql +2 -0
  21. package/apps/runtime/dist/db/migrations/tenant/0047_knowledge_folders.sql +3 -0
  22. package/apps/runtime/dist/db/migrations/tenant/0048_space_chunk_kind.sql +1 -0
  23. package/apps/runtime/dist/db/migrations/tenant/0049_knowledge_sources.sql +57 -0
  24. package/apps/runtime/dist/db/migrations/tenant/0050_dateien.sql +71 -0
  25. package/apps/runtime/dist/db/migrations/tenant/0051_dateien_drafts.sql +23 -0
  26. package/apps/runtime/dist/db/migrations/tenant/0052_dateien_plugin_kinds.sql +5 -0
  27. package/apps/runtime/dist/db/migrations/tenant/0053_dateien_file_title.sql +3 -0
  28. package/apps/runtime/dist/db/migrations/tenant/0054_dateien_ocr.sql +14 -0
  29. package/apps/runtime/dist/db/migrations/tenant/0055_dateien_doc_reread.sql +3 -0
  30. package/apps/runtime/dist/db/migrations/tenant/meta/0040_snapshot.json +5153 -0
  31. package/apps/runtime/dist/db/migrations/tenant/meta/0041_snapshot.json +5160 -0
  32. package/apps/runtime/dist/db/migrations/tenant/meta/0042_snapshot.json +5286 -0
  33. package/apps/runtime/dist/db/migrations/tenant/meta/0043_snapshot.json +5293 -0
  34. package/apps/runtime/dist/db/migrations/tenant/meta/0044_snapshot.json +5344 -0
  35. package/apps/runtime/dist/db/migrations/tenant/meta/0045_snapshot.json +5329 -0
  36. package/apps/runtime/dist/db/migrations/tenant/meta/0046_snapshot.json +5343 -0
  37. package/apps/runtime/dist/db/migrations/tenant/meta/0047_snapshot.json +5391 -0
  38. package/apps/runtime/dist/db/migrations/tenant/meta/0048_snapshot.json +5398 -0
  39. package/apps/runtime/dist/db/migrations/tenant/meta/0049_snapshot.json +5793 -0
  40. package/apps/runtime/dist/db/migrations/tenant/meta/0050_snapshot.json +6288 -0
  41. package/apps/runtime/dist/db/migrations/tenant/meta/0051_snapshot.json +6461 -0
  42. package/apps/runtime/dist/db/migrations/tenant/meta/0052_snapshot.json +6497 -0
  43. package/apps/runtime/dist/db/migrations/tenant/meta/0053_snapshot.json +6504 -0
  44. package/apps/runtime/dist/db/migrations/tenant/meta/0054_snapshot.json +6504 -0
  45. package/apps/runtime/dist/db/migrations/tenant/meta/0055_snapshot.json +6504 -0
  46. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +112 -0
  47. package/apps/runtime/dist/db/schema.js +296 -5
  48. package/apps/runtime/dist/docs/dev/api.md +49 -2
  49. package/apps/runtime/dist/docs/dev/architecture.md +13 -2
  50. package/apps/runtime/dist/docs/dev/plugins/connections.md +30 -2
  51. package/apps/runtime/dist/docs/dev/plugins/index.md +1 -1
  52. package/apps/runtime/dist/docs/dev/plugins/reference.md +7 -4
  53. package/apps/runtime/dist/docs/dev/plugins/server.md +11 -5
  54. package/apps/runtime/dist/docs/dev/plugins/space.md +130 -4
  55. package/apps/runtime/dist/docs/dev/plugins/studio.md +13 -3
  56. package/apps/runtime/dist/docs/user-guide/command-line.md +2 -0
  57. package/apps/runtime/dist/docs/user-guide/plugins.md +1 -1
  58. package/apps/runtime/dist/docs/user-guide/space.md +6 -6
  59. package/apps/runtime/dist/docs/user-guide/steps.md +1 -1
  60. package/apps/runtime/dist/documents/ocr.js +72 -0
  61. package/apps/runtime/dist/documents/parse.js +81 -12
  62. package/apps/runtime/dist/elements/caller.js +47 -0
  63. package/apps/runtime/dist/elements/catalogue.js +14 -0
  64. package/apps/runtime/dist/elements/connections.js +60 -0
  65. package/apps/runtime/dist/elements/gate.js +81 -0
  66. package/apps/runtime/dist/elements/knowledge.js +308 -0
  67. package/apps/runtime/dist/elements/outside.js +103 -0
  68. package/apps/runtime/dist/elements/specs.js +102 -0
  69. package/apps/runtime/dist/elements/wizards.js +72 -0
  70. package/apps/runtime/dist/engenty/connections-google/connectors/drive.js +3 -0
  71. package/apps/runtime/dist/engenty/connections-microsoft/onedrive.js +3 -0
  72. package/apps/runtime/dist/engenty/connections-s3/s3.js +6 -0
  73. package/apps/runtime/dist/engine/runner.js +19 -2
  74. package/apps/runtime/dist/engine/steps.js +1 -1
  75. package/apps/runtime/dist/env.js +11 -2
  76. package/apps/runtime/dist/files/blobs.js +57 -1
  77. package/apps/runtime/dist/files/objects.js +1 -0
  78. package/apps/runtime/dist/files/pictures.js +41 -0
  79. package/apps/runtime/dist/files/storage.js +14 -26
  80. package/apps/runtime/dist/files/thumbs.js +77 -0
  81. package/apps/runtime/dist/files/upload-check.js +2 -2
  82. package/apps/runtime/dist/index.js +22 -0
  83. package/apps/runtime/dist/live/views.js +2 -1
  84. package/apps/runtime/dist/manage.js +4 -1
  85. package/apps/runtime/dist/mcp/elements.js +88 -0
  86. package/apps/runtime/dist/mcp/handler.js +2 -0
  87. package/apps/runtime/dist/mcp/scopes.js +5 -0
  88. package/apps/runtime/dist/mcp/tools.js +5 -0
  89. package/apps/runtime/dist/models.js +82 -13
  90. package/apps/runtime/dist/mounts/cache.js +71 -0
  91. package/apps/runtime/dist/mounts/drafts.js +367 -0
  92. package/apps/runtime/dist/mounts/folder.js +148 -0
  93. package/apps/runtime/dist/mounts/mounts.js +1315 -0
  94. package/apps/runtime/dist/mounts/source.js +179 -0
  95. package/apps/runtime/dist/mounts/units.js +97 -0
  96. package/apps/runtime/dist/move-files.js +4 -0
  97. package/apps/runtime/dist/plugins/loader.js +73 -1
  98. package/apps/runtime/dist/plugins/registry.js +2 -0
  99. package/apps/runtime/dist/prompts/authoring.md +2 -2
  100. package/apps/runtime/dist/prompts/goose.md +13 -1
  101. package/apps/runtime/dist/prompts/tools.md +8 -2
  102. package/apps/runtime/dist/render/convert.js +188 -1
  103. package/apps/runtime/dist/routes/api.js +7 -2
  104. package/apps/runtime/dist/routes/client-contract.js +164 -0
  105. package/apps/runtime/dist/routes/client-spaces.js +58 -0
  106. package/apps/runtime/dist/routes/dateien.js +173 -0
  107. package/apps/runtime/dist/routes/elements.js +76 -0
  108. package/apps/runtime/dist/routes/plugins.js +2 -1
  109. package/apps/runtime/dist/routes/runs.js +24 -10
  110. package/apps/runtime/dist/routes/studio.js +168 -8
  111. package/apps/runtime/dist/secrets/signing.js +16 -0
  112. package/apps/runtime/dist/services/client-portal.js +439 -0
  113. package/apps/runtime/dist/services/client-spaces.js +228 -0
  114. package/apps/runtime/dist/services/cloud.js +2 -0
  115. package/apps/runtime/dist/services/knowledge-model.js +24 -8
  116. package/apps/runtime/dist/services/knowledge.js +72 -42
  117. package/apps/runtime/dist/services/links.js +17 -0
  118. package/apps/runtime/dist/services/members-studio.js +5 -1
  119. package/apps/runtime/dist/services/page-pictures.js +162 -0
  120. package/apps/runtime/dist/services/runs.js +22 -6
  121. package/apps/runtime/dist/services/space-categories.js +41 -5
  122. package/apps/runtime/dist/services/space-data.js +165 -8
  123. package/apps/runtime/dist/services/space-files.js +102 -19
  124. package/apps/runtime/dist/services/space-index.js +384 -41
  125. package/apps/runtime/dist/services/space-origin.js +25 -1
  126. package/apps/runtime/dist/services/space-sources.js +937 -0
  127. package/apps/runtime/dist/services/spaces.js +60 -12
  128. package/apps/runtime/dist/services/synced-spaces.js +10 -1
  129. package/apps/runtime/dist/services/work-ai.js +53 -24
  130. package/apps/runtime/dist/services/work-chats.js +3 -2
  131. package/apps/runtime/dist/services/work-connections.js +2 -2
  132. package/apps/runtime/dist/sharing/index.js +2 -0
  133. package/apps/runtime/dist/store/index.js +29 -8
  134. package/apps/runtime/dist/store/shared-lists.js +30 -17
  135. package/apps/runtime/dist/sync/records.js +22 -27
  136. package/apps/runtime/dist/texts.js +4 -0
  137. package/apps/runtime/dist/tools/index.js +5 -4
  138. package/apps/runtime/dist/tools/pages.js +1 -1
  139. package/apps/runtime/dist/tools/skills.js +80 -54
  140. package/apps/runtime/dist/tools/space.js +8 -152
  141. package/apps/runtime/dist/widgets/step.js +2 -1
  142. package/apps/web/dist/assets/AboutDialog-0q4P80yv.js +1 -0
  143. package/apps/web/dist/assets/BlockEditor-CUYFH_CU.js +173 -0
  144. package/apps/web/dist/assets/BlockEditor-CtW6lw0y.css +1 -0
  145. package/apps/web/dist/assets/CapabilitiesPage-BlZP8DYb.js +2 -0
  146. package/apps/web/dist/assets/{ChangelogDialog-D_dQOMIq.js → ChangelogDialog-CDN7kMs1.js} +1 -1
  147. package/apps/web/dist/assets/{CodeEditor-nxoOt8ge.js → CodeEditor-D-Y16fdk.js} +1 -1
  148. package/apps/web/dist/assets/EditorPage-CrMVsgUt.js +3 -0
  149. package/apps/web/dist/assets/{FlowPreview-aMfwcPul.js → FlowPreview-DXnk7m9P.js} +1 -1
  150. package/apps/web/dist/assets/{LangSwitch-DpD0inR4.js → LangSwitch-Dkd0FBIH.js} +1 -1
  151. package/apps/web/dist/assets/Marketplace-Cty40VwG.js +2 -0
  152. package/apps/web/dist/assets/NewWizardChannels-Czool7s1.js +1 -0
  153. package/apps/web/dist/assets/NewWizardPage-CfVe_4a2.js +7 -0
  154. package/apps/web/dist/assets/OnboardingPage-D3SEpTmt.js +1 -0
  155. package/apps/web/dist/assets/PreviewPane-CQDKQO6z.js +7 -0
  156. package/apps/web/dist/assets/PublicRunner-BDZNnlQw.js +1 -0
  157. package/apps/web/dist/assets/ReadOnly-B7MUySpC.js +1 -0
  158. package/apps/web/dist/assets/SettingsPage-Bgurv3l2.js +2 -0
  159. package/apps/web/dist/assets/SetupPage-C3km8vqv.js +1 -0
  160. package/apps/web/dist/assets/{SharePage-N80EhoD7.js → SharePage-UwEJBIzq.js} +1 -1
  161. package/apps/web/dist/assets/SkillEditor-BaEiqqXl.js +1 -0
  162. package/apps/web/dist/assets/Skills-Bv6XbKxc.js +9 -0
  163. package/apps/web/dist/assets/SpacePage-D9PXLSU_.js +2 -0
  164. package/apps/web/dist/assets/UpdateCheck-C7I43zFZ.js +2 -0
  165. package/apps/web/dist/assets/changelog-DwgWiSZb.js +1 -0
  166. package/apps/web/dist/assets/circle-check-DDLzlcXP.js +1 -0
  167. package/apps/web/dist/assets/code-DsnwzN1x.js +1 -0
  168. package/apps/web/dist/assets/code-editor-Ca5EAxmd.js +2 -0
  169. package/apps/web/dist/assets/code-xml-S4IFi5Jc.js +1 -0
  170. package/apps/web/dist/assets/connection-sign-in-hI3HXhq4.js +1 -0
  171. package/apps/web/dist/assets/{dist-H1UN89OA.js → dist-B3Ray2U5.js} +1 -1
  172. package/apps/web/dist/assets/dist-CQpLJoQZ.js +10 -0
  173. package/apps/web/dist/assets/{dist-GlRRx9Xl.js → dist-D1uGQ_tB.js} +1 -1
  174. package/apps/web/dist/assets/{dist-BdDd1FxP.js → dist-DFI-tsfx.js} +1 -1
  175. package/apps/web/dist/assets/eye-TJSuiHHO.js +1 -0
  176. package/apps/web/dist/assets/floating-ui.dom-pwdNGv4b.js +1 -0
  177. package/apps/web/dist/assets/host-D5hNHbhF.js +125 -0
  178. package/apps/web/dist/assets/i18n-BBzMbGoo.js +55 -0
  179. package/apps/web/dist/assets/index-CyBrvupM.js +10 -0
  180. package/apps/web/dist/assets/index-w-3J3ZJ9.css +1 -0
  181. package/apps/web/dist/assets/{json-CEsfHdlZ.js → json-Ce3iHrtf.js} +1 -1
  182. package/apps/web/dist/assets/link-CPL8pB1P.js +1 -0
  183. package/apps/web/dist/assets/list-checks-DaxmUPqK.js +1 -0
  184. package/apps/web/dist/assets/{markdown-5-I9_izp.js → markdown-hqKQy2pp.js} +1 -1
  185. package/apps/web/dist/assets/marked.esm-DQ7XA7AC.js +67 -0
  186. package/apps/web/dist/assets/oss-credits-BrwV0a4F.js +1 -0
  187. package/apps/web/dist/assets/pdf-Dg-raaUo.js +54 -0
  188. package/apps/web/dist/assets/pdf.worker.min-68CMzziE.js +1 -0
  189. package/apps/web/dist/assets/pdf.worker.min-CjEcRF4W.mjs +28 -0
  190. package/apps/web/dist/assets/phone-B4uKDBFq.js +1 -0
  191. package/apps/web/dist/assets/read-aloud-Bfp9_bUY.js +1 -0
  192. package/apps/web/dist/assets/{runners-CyIvJIHr.js → runners-CUpBpSji.js} +1 -1
  193. package/apps/web/dist/assets/scroll-text-BEnPzQEi.js +1 -0
  194. package/apps/web/dist/assets/session-CMQo8P-G.js +2 -0
  195. package/apps/web/dist/assets/table-5B9G3oA6.js +1 -0
  196. package/apps/web/dist/assets/theme-CdX0marK.js +11 -0
  197. package/apps/web/dist/assets/ui-BCfu5sia.js +16 -0
  198. package/apps/web/dist/assets/upload-CAlHC232.js +1 -0
  199. package/apps/web/dist/assets/{useMutation-DEkZhp5c.js → useMutation-1fV4Nnxq.js} +1 -1
  200. package/apps/web/dist/assets/viewers-ChriFcRy.js +2 -0
  201. package/apps/web/dist/assets/volume-2-BqlBtCIJ.js +1 -0
  202. package/apps/web/dist/assets/w3c-keyname-BOAvb0qz.js +1 -0
  203. package/apps/web/dist/assets/xlsx-CuSbHU4R.js +141 -0
  204. package/apps/web/dist/index.html +19 -14
  205. package/apps/web/dist/mcp/flow.html +2 -2
  206. package/node_modules/@engenty/wizards/dist/plugin/index.d.ts +223 -4
  207. package/node_modules/@engenty/wizards/dist/plugin/mount.d.ts +123 -0
  208. package/node_modules/@engenty/wizards/dist/plugin/mount.js +7 -0
  209. package/node_modules/@engenty/wizards/dist/plugin/studio.d.ts +110 -1
  210. package/node_modules/@engenty/wizards-shared/dist/connectors.d.ts +1 -1
  211. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +24 -0
  212. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +24 -0
  213. package/node_modules/@engenty/wizards-shared/dist/knowledge.d.ts +33 -4
  214. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +6 -0
  215. package/node_modules/@engenty/wizards-shared/dist/run.js +12 -0
  216. package/node_modules/@engenty/wizards-shared/dist/rwx.d.ts +21 -4
  217. package/node_modules/@engenty/wizards-shared/dist/rwx.js +30 -3
  218. package/node_modules/@engenty/wizards-shared/dist/spaces.d.ts +11 -1
  219. package/node_modules/@engenty/wizards-shared/dist/spaces.js +9 -2
  220. package/node_modules/@engenty/wizards-shared/dist/text-merge.d.ts +6 -0
  221. package/node_modules/@engenty/wizards-shared/dist/text-merge.js +25 -0
  222. package/package.json +3 -1
  223. package/plugin/.claude-plugin/plugin.json +1 -1
  224. package/plugin/README.md +3 -0
  225. package/plugin/plugin.json +1 -1
  226. package/plugin/skills/work-in-space/SKILL.md +16 -0
  227. package/apps/web/dist/assets/AboutDialog-Cag3RJuT.js +0 -1
  228. package/apps/web/dist/assets/CapabilitiesPage-BQYiN0gT.js +0 -2
  229. package/apps/web/dist/assets/EditorPage-C4_8LsQN.js +0 -3
  230. package/apps/web/dist/assets/Marketplace-CpzD9pNQ.js +0 -2
  231. package/apps/web/dist/assets/NewWizardChannels-CcE3UMVb.js +0 -1
  232. package/apps/web/dist/assets/NewWizardPage-BzN7zrQx.js +0 -7
  233. package/apps/web/dist/assets/OnboardingPage-ztHT01ah.js +0 -1
  234. package/apps/web/dist/assets/PreviewPane-BabMbBZI.js +0 -9
  235. package/apps/web/dist/assets/PublicRunner-D-JmtqCi.js +0 -1
  236. package/apps/web/dist/assets/ReadOnly-GAORKKqV.js +0 -1
  237. package/apps/web/dist/assets/SettingsPage-BKAiYmXl.js +0 -2
  238. package/apps/web/dist/assets/SetupPage-C1EZZHIp.js +0 -1
  239. package/apps/web/dist/assets/SkillEditor-CqQMg2MC.js +0 -1
  240. package/apps/web/dist/assets/Skills-CnhpgoOA.js +0 -9
  241. package/apps/web/dist/assets/SpacePage-CRR8JvV1.js +0 -2
  242. package/apps/web/dist/assets/UpdateCheck-CfXZBQNv.js +0 -2
  243. package/apps/web/dist/assets/changelog-6MqC8Vy8.js +0 -1
  244. package/apps/web/dist/assets/circle-alert-C8Ma-bPY.js +0 -1
  245. package/apps/web/dist/assets/circle-check-Bu9Z3mlJ.js +0 -1
  246. package/apps/web/dist/assets/code-editor-CfTGqOpp.js +0 -2
  247. package/apps/web/dist/assets/code-xml-B4kLFZSj.js +0 -1
  248. package/apps/web/dist/assets/connection-sign-in-B2D0O8W-.js +0 -1
  249. package/apps/web/dist/assets/dist-EBVTpvRr.js +0 -10
  250. package/apps/web/dist/assets/eye-BpoKpIdt.js +0 -1
  251. package/apps/web/dist/assets/host-BlKXX7YK.js +0 -118
  252. package/apps/web/dist/assets/i18n-BJ7Ld6O6.js +0 -55
  253. package/apps/web/dist/assets/index-66tE1oti.js +0 -10
  254. package/apps/web/dist/assets/index-D18DvnxX.css +0 -1
  255. package/apps/web/dist/assets/oss-credits-IdX5bc71.js +0 -1
  256. package/apps/web/dist/assets/phone-Ctvf-Am-.js +0 -1
  257. package/apps/web/dist/assets/read-aloud-Da_RSm2S.js +0 -1
  258. package/apps/web/dist/assets/scroll-text-ChrjRu9Y.js +0 -1
  259. package/apps/web/dist/assets/session-SXPtTWRK.js +0 -2
  260. package/apps/web/dist/assets/theme-Br1S0j5h.js +0 -11
  261. package/apps/web/dist/assets/ui-Uqnx1UpK.js +0 -82
  262. package/apps/web/dist/assets/upload-BchUnQGV.js +0 -1
  263. package/apps/web/dist/assets/volume-2-CU_oy81Z.js +0 -1
@@ -1,8 +1,8 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { featureOn } from "@engenty/wizards-shared/features";
3
3
  import { note } from "@engenty/wizards-shared/run";
4
- import { RWX_ALL, RWX_LIMITS, RWX_ROLES, } from "@engenty/wizards-shared/rwx";
5
- import { and, eq, inArray } from "drizzle-orm";
4
+ import { AUDIENCES, RWX_ALL, RWX_LIMITS, RWX_ROLES, } from "@engenty/wizards-shared/rwx";
5
+ import { and, eq, inArray, isNull } from "drizzle-orm";
6
6
  import { nanoid } from "nanoid";
7
7
  import { db, schema } from "../db/client.js";
8
8
  import { currentFeatures } from "../features.js";
@@ -11,8 +11,19 @@ import { notFound, ServiceError } from "../services/errors.js";
11
11
  import { ownedSpace } from "../services/spaces.js";
12
12
  import { currentTenant } from "../tenants/tenant.js";
13
13
  import { logRuleChange } from "./log.js";
14
- /** The resource kinds this runtime asks the broker about today; the others wait for their reader. */
15
- export const ENFORCED = ["document", "table", "page"];
14
+ /**
15
+ * The resource kinds this runtime asks the broker about today; the others wait for their reader.
16
+ * A wizard is run (`x`) and listed (`r`) through the tool catalogue (elements/), a skill read
17
+ * (`r`) and its scripts placed to run (`x`), a space's setup written (`w`) by Goose.
18
+ */
19
+ export const ENFORCED = [
20
+ "document",
21
+ "table",
22
+ "page",
23
+ "wizard",
24
+ "skill",
25
+ "setup",
26
+ ];
16
27
  export async function brokerOn() {
17
28
  return featureOn(await currentFeatures(), "broker");
18
29
  }
@@ -27,6 +38,8 @@ export async function brokerOn() {
27
38
  */
28
39
  export const SYSTEM = Object.freeze({ kind: "system", id: null });
29
40
  export const subjectsOfGuest = () => [{ kind: "guest", id: null }];
41
+ /** An AI working for a person: a Work chat, a client's chat, Claude or Codex through MCP. */
42
+ export const AGENT = Object.freeze({ kind: "agent", id: null });
30
43
  /** A signed-in person: their own rows, and their role's. */
31
44
  export const subjectsOfPerson = (userId, role) => [
32
45
  { kind: "person", id: userId },
@@ -90,7 +103,10 @@ export async function runHolder(run) {
90
103
  return { kind: "guest", id: run.visitorId ?? run.id };
91
104
  }
92
105
  // --- deciding --------------------------------------------------------------------------------
93
- const about = (rule, subjects) => subjects.some((s) => s.kind === rule.subjectKind && (s.id ?? null) === (rule.subjectId ?? null));
106
+ /** A rule is about a subject of its kind with its id; a wizard rule on `*` about every wizard. */
107
+ const about = (rule, subjects) => subjects.some((s) => s.kind === rule.subjectKind &&
108
+ ((s.id ?? null) === (rule.subjectId ?? null) ||
109
+ (rule.subjectKind === "wizard" && rule.subjectId === RWX_ALL)));
94
110
  const names = (rule, resource) => rule.resourceKind === resource.kind &&
95
111
  (rule.resourceId === RWX_ALL || rule.resourceId === resource.id);
96
112
  /** The first rule about the subjects and the resource that says `flag` for `perm`. */
@@ -101,7 +117,8 @@ const matching = (rules, subjects, resource, perm, flag) => rules.find((r) => ab
101
117
  */
102
118
  function decideSystem(rules, others, resource, perm) {
103
119
  const behind = resource.fileId ? [{ kind: "document", id: resource.fileId }] : [];
104
- for (const r of [{ kind: resource.kind, id: resource.id }, ...behind]) {
120
+ const folders = (resource.folders ?? []).map((id) => ({ kind: "page", id }));
121
+ for (const r of [{ kind: resource.kind, id: resource.id }, ...behind, ...folders]) {
105
122
  const deny = matching(rules, others, r, perm, "deny");
106
123
  if (deny) {
107
124
  return { ok: false, rule: deny.id, reason: `${r.kind} ${r.id}: denied`, of: r };
@@ -143,7 +160,38 @@ export function decideWith(rules, subjects, resource, perm) {
143
160
  const others = subjects.filter((s) => s !== SYSTEM);
144
161
  return decideSystem(rules, others, resource, perm);
145
162
  }
146
- const own = decideOne(rules, subjects, resource, perm);
163
+ // A folder's rule names it by id: its deny closes what lies in it, its allow opens it.
164
+ const inFolder = (flag) => {
165
+ for (const id of resource.folders ?? []) {
166
+ const r = rules.find((x) => about(x, subjects) &&
167
+ x.resourceKind === "page" &&
168
+ x.resourceId === id &&
169
+ x[perm] === flag);
170
+ if (r) {
171
+ return { rule: r, id };
172
+ }
173
+ }
174
+ return null;
175
+ };
176
+ const closed = inFolder("deny");
177
+ if (closed) {
178
+ return {
179
+ ok: false,
180
+ rule: closed.rule.id,
181
+ reason: `${resource.kind} ${resource.id}: denied in folder ${closed.id}`,
182
+ of: { kind: resource.kind, id: resource.id },
183
+ };
184
+ }
185
+ let own = decideOne(rules, subjects, resource, perm);
186
+ const opened = own.ok ? null : inFolder("allow");
187
+ if (opened && !own.rule) {
188
+ own = {
189
+ ok: true,
190
+ rule: opened.rule.id,
191
+ reason: `${resource.kind} ${resource.id}: allowed in folder ${opened.id}`,
192
+ of: own.of,
193
+ };
194
+ }
147
195
  if (!(own.ok && resource.fileId)) {
148
196
  return own;
149
197
  }
@@ -164,7 +212,56 @@ export async function decide(spaceId, subjects, resource, perm) {
164
212
  if (!(await brokerOn())) {
165
213
  return { ok: true, reason: "off", of: { kind: resource.kind, id: resource.id } };
166
214
  }
167
- return decideWith(await rulesOf(spaceId), subjects, resource, perm);
215
+ const rules = await rulesOf(spaceId);
216
+ const [item] = await withFolders(spaceId, rules, [resource]);
217
+ return decideWith(rules, subjects, item, perm);
218
+ }
219
+ const KNOWLEDGE_KINDS = new Set(["document", "page", "table"]);
220
+ /**
221
+ * The items with the folders they lie in, where the space has a rule on a folder: a rule on a
222
+ * page by its id. Without one, nothing is looked up.
223
+ */
224
+ async function withFolders(spaceId, rules, items) {
225
+ const onFolders = rules.some((r) => r.resourceKind === "page" && r.resourceId !== RWX_ALL);
226
+ const asked = items.filter((i) => KNOWLEDGE_KINDS.has(i.kind) && !i.folders);
227
+ if (!(onFolders && asked.length)) {
228
+ return items;
229
+ }
230
+ const ids = (kind) => asked.filter((i) => i.kind === kind).map((i) => i.id);
231
+ const [pages, files, tables] = await Promise.all([
232
+ db.query.spacePage.findMany({
233
+ where: eq(schema.spacePage.spaceId, spaceId),
234
+ columns: { id: true, parentId: true },
235
+ }),
236
+ ids("document").length
237
+ ? db.query.spaceFile.findMany({
238
+ where: inArray(schema.spaceFile.id, ids("document")),
239
+ columns: { id: true, parentId: true },
240
+ })
241
+ : [],
242
+ ids("table").length
243
+ ? db.query.spaceTable.findMany({
244
+ where: inArray(schema.spaceTable.id, ids("table")),
245
+ columns: { id: true, parentId: true },
246
+ })
247
+ : [],
248
+ ]);
249
+ const parentOf = new Map(pages.map((p) => [p.id, p.parentId]));
250
+ const parentOfItem = new Map([
251
+ ...files.map((f) => [`document:${f.id}`, f.parentId]),
252
+ ...tables.map((t) => [`table:${t.id}`, t.parentId]),
253
+ ...pages.map((p) => [`page:${p.id}`, p.parentId]),
254
+ ]);
255
+ const chain = (from) => {
256
+ const out = [];
257
+ for (let at = from; at && !out.includes(at); at = parentOf.get(at)) {
258
+ out.push(at);
259
+ }
260
+ return out;
261
+ };
262
+ return items.map((i) => KNOWLEDGE_KINDS.has(i.kind) && !i.folders
263
+ ? { ...i, folders: chain(parentOfItem.get(`${i.kind}:${i.id}`)) }
264
+ : i);
168
265
  }
169
266
  const WHAT = {
170
267
  document: "rwxDocument",
@@ -174,6 +271,10 @@ const WHAT = {
174
271
  mail: "rwxMail",
175
272
  host: "rwxHost",
176
273
  sandbox: "rwxSandbox",
274
+ wizard: "rwxWizard",
275
+ skill: "rwxSkill",
276
+ setup: "rwxSetup",
277
+ mount: "rwxMount",
177
278
  };
178
279
  const VERB = { r: "rwxRead", w: "rwxWrite", x: "rwxRun" };
179
280
  /** The refusal: *verboten*, the resource's kind and id, nothing of its content. */
@@ -191,13 +292,34 @@ export async function readable(spaceId, subjects, items) {
191
292
  return new Set(items.map((i) => i.id));
192
293
  }
193
294
  const rules = await rulesOf(spaceId);
194
- return new Set(items.filter((i) => decideWith(rules, subjects, i, "r").ok).map((i) => i.id));
295
+ const known = await withFolders(spaceId, rules, items);
296
+ return new Set(known.filter((i) => decideWith(rules, subjects, i, "r").ok).map((i) => i.id));
195
297
  }
196
298
  /** The ids of `kind` among `ids` the subjects may read, in their order. */
197
299
  export async function readableIds(spaceId, subjects, kind, ids) {
198
300
  const ok = await readable(spaceId, subjects, ids.map((id) => ({ kind, id })));
199
301
  return ids.filter((id) => ok.has(id));
200
302
  }
303
+ /**
304
+ * The mounts of Dateien among `ids` the subjects may read: the people (a person, Goose, a guest)
305
+ * by their rules, and a run's wizard by its own as well. A mount's rules are written with it
306
+ * (mounts/mounts.ts): who in the space sees it, which wizards may use it.
307
+ */
308
+ export async function readableMounts(spaceId, subjects, ids) {
309
+ if (!(await brokerOn())) {
310
+ return new Set(ids);
311
+ }
312
+ const rules = await rulesOf(spaceId);
313
+ // The person, the run's wizard and an AI working for the person each need the mount's rules.
314
+ const wizards = subjects.filter((s) => s.kind === "wizard");
315
+ const agents = subjects.filter((s) => s.kind === "agent");
316
+ const people = subjects.filter((s) => s.kind !== "wizard" && s.kind !== "agent");
317
+ const ok = (who, id) => decideWith(rules, who, { kind: "mount", id }, "r").ok;
318
+ return new Set(ids.filter((id) => subjects.length > 0 &&
319
+ (!people.length || ok(people, id)) &&
320
+ (!wizards.length || ok(wizards, id)) &&
321
+ (!agents.length || ok(agents, id))));
322
+ }
201
323
  /** Pages by id with the document behind each, for `readable`. */
202
324
  export async function pageResources(pageIds) {
203
325
  if (!pageIds.length) {
@@ -241,18 +363,59 @@ export async function readsEverything(spaceId, subjects) {
241
363
  */
242
364
  export async function seedRwx(spaceId) {
243
365
  const seeded = [];
366
+ const space = await db.query.space.findFirst({
367
+ columns: { kind: true },
368
+ where: eq(schema.space.id, spaceId),
369
+ });
244
370
  for (const kind of ENFORCED) {
245
371
  for (const role of ["admin", "owner"]) {
246
372
  seeded.push(rule("role", role, kind, { r: "allow", w: "allow", x: "allow" }));
247
373
  }
248
- seeded.push(rule("role", "member", kind, { r: "allow", w: "allow", x: null }));
249
- seeded.push(rule("guest", null, kind, { r: "allow", w: null, x: null }));
374
+ seeded.push(rule("role", "member", kind, MEMBER_SEED[kind] ?? MEMBER_DATA));
375
+ const guest = GUEST_SEED[kind];
376
+ if (guest) {
377
+ seeded.push(rule("guest", null, kind, guest));
378
+ }
379
+ // A client space's clients work with their own data, and run what the space lets them. A
380
+ // space gets no rule for clients: what of it a client reads, a rule opens item by item.
381
+ const client = space?.kind === "client" ? CLIENT_SEED[kind] : undefined;
382
+ if (client) {
383
+ seeded.push(rule("role", "client", kind, client));
384
+ }
250
385
  }
251
386
  await db
252
387
  .insert(schema.rwxRule)
253
388
  .values(seeded.map((r) => row(spaceId, r, "seed")))
254
389
  .onConflictDoNothing();
255
390
  }
391
+ /**
392
+ * A member's seed: documents, tables and pages read and written; a wizard read and run (building
393
+ * it is the studio's, by the members' studio rule); a skill read and its scripts run; the space's
394
+ * setup read and written. The same as the migration 0040 writes for spaces seeded before.
395
+ */
396
+ const MEMBER_DATA = { r: "allow", w: "allow", x: null };
397
+ const MEMBER_SEED = {
398
+ wizard: { r: "allow", w: null, x: "allow" },
399
+ skill: { r: "allow", w: null, x: "allow" },
400
+ };
401
+ /**
402
+ * A client's seed in their client space (docs/plans/client-spaces.md): its data read and written,
403
+ * wizards and skills read and run; never its setup.
404
+ */
405
+ const CLIENT_SEED = {
406
+ document: { r: "allow", w: "allow", x: null },
407
+ table: { r: "allow", w: "allow", x: null },
408
+ page: { r: "allow", w: "allow", x: null },
409
+ wizard: { r: "allow", w: null, x: "allow" },
410
+ skill: { r: "allow", w: null, x: "allow" },
411
+ };
412
+ /** A guest's seed: data read, a skill read and run in its run; no wizard, no setup. */
413
+ const GUEST_SEED = {
414
+ document: { r: "allow", w: null, x: null },
415
+ table: { r: "allow", w: null, x: null },
416
+ page: { r: "allow", w: null, x: null },
417
+ skill: { r: "allow", w: null, x: "allow" },
418
+ };
256
419
  const rule = (subjectKind, subjectId, resourceKind, flags) => ({ subjectKind, subjectId, resourceKind, resourceId: RWX_ALL, ...flags });
257
420
  const row = (spaceId, r, createdBy) => ({
258
421
  id: nanoid(12),
@@ -365,3 +528,122 @@ export async function deleteRule(userId, spaceId, ruleId) {
365
528
  reason: "An RWX rule was deleted.",
366
529
  });
367
530
  }
531
+ /**
532
+ * Opens one item of a space to the clients of its client spaces, or closes it again
533
+ * (docs/plans/client-spaces.md): a rule for the role `client` on that item, read (and run for a
534
+ * wizard). Its admins decide; the change is a line of the log.
535
+ */
536
+ export async function setOpenToClients(userId, spaceId, resource, open) {
537
+ const space = await ownedSpace(userId, spaceId);
538
+ await requireBroker();
539
+ requireRuleAdmin();
540
+ await rulesOf(space.id);
541
+ const where = and(eq(schema.rwxRule.spaceId, space.id), eq(schema.rwxRule.subjectKind, "role"), eq(schema.rwxRule.subjectId, "client"), eq(schema.rwxRule.resourceKind, resource.kind), eq(schema.rwxRule.resourceId, resource.id));
542
+ await db.delete(schema.rwxRule).where(where);
543
+ if (open) {
544
+ const opened = {
545
+ subjectKind: "role",
546
+ subjectId: "client",
547
+ resourceKind: resource.kind,
548
+ resourceId: resource.id,
549
+ r: "allow",
550
+ w: null,
551
+ x: resource.kind === "wizard" ? "allow" : null,
552
+ };
553
+ await db.insert(schema.rwxRule).values(row(space.id, opened, userId));
554
+ }
555
+ await logRuleChange({
556
+ userId,
557
+ spaceId: space.id,
558
+ connectionId: "rwx",
559
+ summary: { [resource.kind]: resource.id, clients: open },
560
+ reason: `${resource.kind} ${resource.id} ${open ? "opened to" : "closed to"} the space's clients.`,
561
+ });
562
+ }
563
+ /**
564
+ * The rules a Wissen folder's audience writes, on the folder (a page) by its id: the team and
565
+ * guests read by the space's seed, so leaving them out closes the folder to them; clients read
566
+ * nothing of the space by their seed, so taking them in opens it. What lies in the folder follows
567
+ * (`withFolders`).
568
+ */
569
+ function folderRules(folderId, see) {
570
+ const on = (subjectKind, subjectId, flags) => ({
571
+ subjectKind,
572
+ subjectId,
573
+ resourceKind: "page",
574
+ resourceId: folderId,
575
+ r: null,
576
+ w: null,
577
+ x: null,
578
+ ...flags,
579
+ });
580
+ return [
581
+ ...(see.includes("team") ? [] : [on("role", "member", { r: "deny", w: "deny" })]),
582
+ ...(see.includes("guests") ? [] : [on("guest", null, { r: "deny" })]),
583
+ ...(see.includes("clients") ? [on("role", "client", { r: "allow" })] : []),
584
+ ];
585
+ }
586
+ const AUDIENCE_SUBJECTS = [
587
+ ["role", "member"],
588
+ ["role", "client"],
589
+ ["guest", null],
590
+ ];
591
+ async function knowledgeFolder(userId, spaceId, folderId) {
592
+ const space = await ownedSpace(userId, spaceId);
593
+ const folder = await db.query.spacePage.findFirst({
594
+ columns: { id: true },
595
+ where: and(eq(schema.spacePage.spaceId, space.id), eq(schema.spacePage.id, folderId)),
596
+ });
597
+ if (!folder) {
598
+ throw notFound();
599
+ }
600
+ return { space, folder };
601
+ }
602
+ /** Who besides the admins sees a Wissen folder, as its rules say. */
603
+ export async function folderAudience(userId, spaceId, folderId) {
604
+ const { space, folder } = await knowledgeFolder(userId, spaceId, folderId);
605
+ const rules = (await rulesOf(space.id)).filter((r) => r.resourceKind === "page" && r.resourceId === folder.id);
606
+ const has = (kind, id, flag) => rules.some((r) => r.subjectKind === kind && (r.subjectId ?? null) === id && r.r === flag);
607
+ return AUDIENCES.filter((a) => a === "team"
608
+ ? !has("role", "member", "deny")
609
+ : a === "guests"
610
+ ? !has("guest", null, "deny")
611
+ : has("role", "client", "allow"));
612
+ }
613
+ /** Sets who besides the admins sees a Wissen folder and everything in it. Admins only. */
614
+ export async function setFolderAudience(userId, spaceId, folderId, see) {
615
+ const { space, folder } = await knowledgeFolder(userId, spaceId, folderId);
616
+ await requireBroker();
617
+ requireRuleAdmin();
618
+ await rulesOf(space.id);
619
+ const r = schema.rwxRule;
620
+ for (const [kind, id] of AUDIENCE_SUBJECTS) {
621
+ await db
622
+ .delete(r)
623
+ .where(and(eq(r.spaceId, space.id), eq(r.resourceKind, "page"), eq(r.resourceId, folder.id), eq(r.subjectKind, kind), id === null ? isNull(r.subjectId) : eq(r.subjectId, id)));
624
+ }
625
+ const rules = folderRules(folder.id, see);
626
+ if (rules.length) {
627
+ await db.insert(r).values(rules.map((x) => row(space.id, x, userId)));
628
+ }
629
+ await logRuleChange({
630
+ userId,
631
+ spaceId: space.id,
632
+ connectionId: "rwx",
633
+ summary: { page: folder.id, see: see.join(",") || "admins" },
634
+ reason: `Folder ${folder.id} seen by ${see.length ? see.join(", ") : "the admins alone"}.`,
635
+ });
636
+ }
637
+ /** The ids of each kind a space opened to its clients. */
638
+ export async function openToClients(spaceId) {
639
+ const rows = await db.query.rwxRule.findMany({
640
+ where: and(eq(schema.rwxRule.spaceId, spaceId), eq(schema.rwxRule.subjectKind, "role"), eq(schema.rwxRule.subjectId, "client")),
641
+ });
642
+ const out = { document: [], table: [], page: [], wizard: [] };
643
+ for (const r of rows) {
644
+ if (r.resourceKind in out && r.resourceId !== RWX_ALL && r.r === "allow") {
645
+ out[r.resourceKind].push(r.resourceId);
646
+ }
647
+ }
648
+ return out;
649
+ }
@@ -56,6 +56,8 @@ ${line(`${command()} disconnect`, "remove your wizards from those apps (same nam
56
56
  ${line(`${command()} mcp`, "run the MCP server over stdio (AI apps start this)")}
57
57
  ${line(`${command()} uninstall`, "take it off this computer: shows the plan, asks about your data (kept by default)")}
58
58
  ${more("--dry-run only shows it; --yes asks nothing and keeps your data; --yes --delete-data")}
59
+ ${line(`${command()} move-files`, "move the spaces’ files to where 0.16 keeps them; runs by itself at start, by hand for a second try")}
60
+ ${line(`${command()} move-folder-sources`, "once with Dateien on: the Sources plugin’s folders become mounts, taken into Wissen from there")}
59
61
  ${line(`${command()} validate`, "check wizards without the studio: .wizard files, unpacked packages, wizard JSON")}
60
62
  ${more("--json prints the issues as JSON. A space’s connectors and plugins are checked on import.")}
61
63
 
@@ -219,6 +221,11 @@ async function main(argv) {
219
221
  return mcp(paths);
220
222
  case "features":
221
223
  return featuresCommand(args.apps);
224
+ case "move-files":
225
+ // Opens the databases: loaded only for this command.
226
+ return (await import("./move-files.js")).moveFiles();
227
+ case "move-folder-sources":
228
+ return (await import("./move-folder-sources.js")).moveFolderSources();
222
229
  case "validate":
223
230
  // The paths are the person's, from where they typed the command (install-env.ts).
224
231
  process.chdir(startedIn);
@@ -0,0 +1,68 @@
1
+ import { eq, isNull } from "drizzle-orm";
2
+ import { db, knownTenants, migrateControlDb, schema, withTenant } from "../db/client.js";
3
+ import { blobThumb, putBlob } from "../files/blobs.js";
4
+ import { objects } from "../files/objects.js";
5
+ /**
6
+ * `wizards move-files` — once, after the update to 0.16: a space file's bytes move from the
7
+ * asset it lived in (`assets/<id>.<ext>`) to the blob store by their hash (`blobs/`), with the
8
+ * thumbnail of a picture or PDF, for every tenant this runtime knows. Until then such a file
9
+ * doesn't open. What moved is not moved again, so a second run moves only what the first could
10
+ * not reach. The runtime runs it by itself when it starts (`moveFilesAtStart`); by hand it is
11
+ * for a second try. In the cloud it runs as `node apps/runtime/dist/move-files.js`, with the
12
+ * runtime's environment.
13
+ */
14
+ export async function moveFiles() {
15
+ await migrateControlDb();
16
+ let failed = 0;
17
+ for (const tenant of await knownTenants()) {
18
+ const { moved, missing } = await withTenant(tenant, moveTenantFiles);
19
+ if (moved || missing.length) {
20
+ console.log(`${tenant}: ${moved} moved${missing.length ? `, ${missing.length} without their bytes` : ""}`);
21
+ }
22
+ for (const file of missing) {
23
+ console.log(` ${file}`);
24
+ }
25
+ failed += missing.length;
26
+ }
27
+ console.log(failed ? "Done; the files listed have no bytes to move." : "Done.");
28
+ return failed ? 1 : 0;
29
+ }
30
+ /**
31
+ * At the start of a runtime that serves the studio, after the tenants' databases are current:
32
+ * the files of before 0.16 move, so nobody has to run a command after the update. Quiet when
33
+ * there is nothing to move.
34
+ */
35
+ export async function moveFilesAtStart() {
36
+ for (const tenant of await knownTenants()) {
37
+ try {
38
+ const { moved, missing } = await withTenant(tenant, moveTenantFiles);
39
+ if (moved || missing.length) {
40
+ console.log(`[move-files] ${tenant}: ${moved} moved${missing.length ? `, ${missing.length} without their bytes: ${missing.join("; ")}` : ""}`);
41
+ }
42
+ }
43
+ catch (err) {
44
+ console.error(`[move-files] ${tenant}:`, err.message);
45
+ }
46
+ }
47
+ }
48
+ async function moveTenantFiles() {
49
+ const rows = await db.query.spaceFile.findMany({ where: isNull(schema.spaceFile.hash) });
50
+ let moved = 0;
51
+ const missing = [];
52
+ for (const row of rows) {
53
+ const asset = await db.query.asset.findFirst({ where: eq(schema.asset.id, row.id) });
54
+ const bytes = asset ? await objects.get(`assets/${asset.path}`) : null;
55
+ if (!asset || !bytes) {
56
+ missing.push(`${row.name} (${row.id}, space ${row.spaceId})`);
57
+ continue;
58
+ }
59
+ const hash = await putBlob(bytes);
60
+ await db.update(schema.spaceFile).set({ hash }).where(eq(schema.spaceFile.id, row.id));
61
+ // The file reads from the blob now; its asset goes.
62
+ await db.delete(schema.asset).where(eq(schema.asset.id, asset.id));
63
+ await objects.remove(`assets/${asset.path}`);
64
+ await blobThumb(hash, row.mime);
65
+ moved++;
66
+ }
67
+ return { moved, missing };
68
+ }
@@ -0,0 +1,120 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { stat } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { relative, resolve, sep } from "node:path";
5
+ import { featureOn } from "@engenty/wizards-shared/features";
6
+ import { and, eq, like, sql } from "drizzle-orm";
7
+ import { nanoid } from "nanoid";
8
+ import { db, knownTenants, migrateControlDb, schema, withTenant } from "../db/client.js";
9
+ import { currentFeatures } from "../features.js";
10
+ import { addMount } from "../mounts/mounts.js";
11
+ import { addressOf, KIND } from "../mounts/source.js";
12
+ import { removeOrigin } from "../services/space-data.js";
13
+ import { CORE } from "../services/space-sources.js";
14
+ import { currentTenant } from "../tenants/tenant.js";
15
+ const ORIGIN = "data-sourcer";
16
+ export async function moveFolderSources() {
17
+ await migrateControlDb();
18
+ let failed = 0;
19
+ for (const tenant of await knownTenants()) {
20
+ failed += await withTenant(tenant, moveTenantSources);
21
+ }
22
+ console.log(failed ? "Done; the sources listed stay as they were." : "Done.");
23
+ return failed ? 1 : 0;
24
+ }
25
+ async function moveTenantSources() {
26
+ const tenant = currentTenant();
27
+ const table = await db.all(sql `SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'data_sourcer_source'`);
28
+ if (!table.length) {
29
+ return 0;
30
+ }
31
+ const old = await db.all(sql `SELECT * FROM data_sourcer_source WHERE kind = 'folder' ORDER BY created_at`);
32
+ if (!old.length) {
33
+ return 0;
34
+ }
35
+ const features = await currentFeatures();
36
+ if (!(featureOn(features, "dateien") && featureOn(features, "knowledgeTree"))) {
37
+ console.log(`${tenant}: ${old.length} folder sources wait: switch on dateien and knowledgeTree first (wizards features).`);
38
+ return old.length;
39
+ }
40
+ let failed = 0;
41
+ for (const source of old) {
42
+ const path = resolve(source.address.replace(/^~(?=$|\/)/, homedir()));
43
+ if (!(await stat(path).catch(() => null))?.isDirectory()) {
44
+ console.log(`${tenant}: “${source.label}”: there is no folder ${path} on this computer.`);
45
+ failed++;
46
+ continue;
47
+ }
48
+ // A mount that holds the folder already takes it; else the folder is mounted, for admins.
49
+ const mounts = await db.query.spaceMount.findMany({
50
+ where: eq(schema.spaceMount.spaceId, source.space_id),
51
+ });
52
+ const folders = mounts.flatMap((m) => m.kind === "folder" ? [{ ...m, path: m.source.path }] : []);
53
+ const holding = folders.find((m) => path === m.path || path.startsWith(m.path + sep));
54
+ const mount = holding
55
+ ? { slug: holding.slug, name: holding.name }
56
+ : await addMount("local", source.space_id, {
57
+ path,
58
+ see: [],
59
+ wizards: "none",
60
+ agents: "read",
61
+ });
62
+ const folder = holding ? relative(holding.path, path).split(sep).join("/") : "";
63
+ const address = addressOf(mount.slug, folder);
64
+ if (source.state === "taken") {
65
+ await db.insert(schema.spaceSource).values({
66
+ id: nanoid(12),
67
+ tenantId: tenant,
68
+ spaceId: source.space_id,
69
+ kind: KIND,
70
+ plugin: CORE,
71
+ address,
72
+ label: source.label,
73
+ state: "taken",
74
+ rules: JSON.parse(source.rules || "[]"),
75
+ categories: JSON.parse(source.categories || "[]"),
76
+ everyHours: 24,
77
+ token: randomBytes(18).toString("base64url"),
78
+ status: "idle",
79
+ error: null,
80
+ lastRunAt: null,
81
+ createdAt: new Date(),
82
+ updatedAt: new Date(),
83
+ });
84
+ await dropWritten(source);
85
+ }
86
+ await db.run(sql `DELETE FROM data_sourcer_run WHERE source_id = ${source.id}`);
87
+ await db.run(sql `DELETE FROM data_sourcer_entry WHERE source_id = ${source.id}`);
88
+ await db.run(sql `DELETE FROM data_sourcer_source WHERE id = ${source.id}`);
89
+ console.log(`${tenant}: “${source.label}” → Dateien › ${mount.name}${source.state === "taken" ? `, and Wissen takes ${address} from it` : ""}`);
90
+ }
91
+ return failed;
92
+ }
93
+ /**
94
+ * What the old source wrote, under its keys `<source>:<entry>`: what a person took over becomes
95
+ * the space's own, the rest goes.
96
+ */
97
+ async function dropWritten(source) {
98
+ const prefix = `${source.id}:%`;
99
+ const keys = new Set();
100
+ for (const t of [schema.spacePage, schema.spaceTable, schema.spaceFile]) {
101
+ const rows = await db
102
+ .select({ key: t.originKey })
103
+ .from(t)
104
+ .where(and(eq(t.spaceId, source.space_id), eq(t.origin, ORIGIN), like(t.originKey, prefix)));
105
+ for (const r of rows) {
106
+ if (r.key) {
107
+ keys.add(r.key);
108
+ }
109
+ }
110
+ }
111
+ for (const t of [schema.spacePage, schema.spaceTable]) {
112
+ await db
113
+ .update(t)
114
+ .set({ origin: null, originKey: null, originLabel: null })
115
+ .where(and(eq(t.spaceId, source.space_id), eq(t.origin, ORIGIN), eq(t.kept, true), like(t.originKey, prefix)));
116
+ }
117
+ for (const key of keys) {
118
+ await removeOrigin(ORIGIN, source.space_id, key);
119
+ }
120
+ }