spatial-views 0.1.0 → 0.2.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 (223) hide show
  1. package/README.md +201 -19
  2. package/dist/app/assets/{abnfDiagram-S7VZAUFO-BVgtb0Hw.js → abnfDiagram-S7VZAUFO-CFbb_Sz2.js} +1 -1
  3. package/dist/app/assets/{architecture-WOLXFQ4H-DxylGHqT.js → architecture-WOLXFQ4H-CsBD__5a.js} +1 -1
  4. package/dist/app/assets/architectureDiagram-YGSQEFNW-C0ic4ib1.js +36 -0
  5. package/dist/app/assets/{blockDiagram-APKKGZFW-C7fb3MCE.js → blockDiagram-APKKGZFW-BZDPbzAG.js} +1 -1
  6. package/dist/app/assets/{c4Diagram-KJ2TOQU5-Bkb_0fbd.js → c4Diagram-KJ2TOQU5-BilBWuq5.js} +1 -1
  7. package/dist/app/assets/{chunk-6MUBBAK2-DU4vZ03M.js → chunk-6MUBBAK2-BBl-4tQr.js} +1 -1
  8. package/dist/app/assets/{chunk-AXFCVDMN-De96BVTB.js → chunk-AXFCVDMN-BhsttQ-k.js} +1 -1
  9. package/dist/app/assets/{chunk-BG4553SI-J33jsRLV.js → chunk-BG4553SI-mWcPcFZr.js} +2 -2
  10. package/dist/app/assets/{chunk-DQASFODM-Bh85SSGO.js → chunk-DQASFODM-7FKe2gLt.js} +1 -1
  11. package/dist/app/assets/{chunk-HFQBQIA3-CCklgplR.js → chunk-HFQBQIA3-nXrQ08BL.js} +1 -1
  12. package/dist/app/assets/{chunk-KQLB2F66-B04qR8ED.js → chunk-KQLB2F66-swukhFmZ.js} +1 -1
  13. package/dist/app/assets/{chunk-KS47KZWR-BsqDyyAt.js → chunk-KS47KZWR-DkDkwO82.js} +1 -1
  14. package/dist/app/assets/{chunk-LEVMRMFU-DwxrBz2u.js → chunk-LEVMRMFU-DXH6iXv3.js} +1 -1
  15. package/dist/app/assets/{chunk-M57EVK23-D9YIHjps.js → chunk-M57EVK23-B-kEyOJF.js} +1 -1
  16. package/dist/app/assets/{chunk-OY52VR5R-WB63DeTA.js → chunk-OY52VR5R-DweG7qYw.js} +1 -1
  17. package/dist/app/assets/{chunk-QB3YPZ4I-cHzzKdtb.js → chunk-QB3YPZ4I-DyozK3lV.js} +1 -1
  18. package/dist/app/assets/{chunk-R3KSYZAL-C7rDagaa.js → chunk-R3KSYZAL-BEXCUN6J.js} +1 -1
  19. package/dist/app/assets/{chunk-STOXU5M4-CG6pnJtH.js → chunk-STOXU5M4-BaTlty4O.js} +1 -1
  20. package/dist/app/assets/{chunk-TU62E6Q5-BbcGYfy_.js → chunk-TU62E6Q5-_rcUP1Fh.js} +1 -1
  21. package/dist/app/assets/chunk-X3CZISLH-NOpCnvgE.js +1 -0
  22. package/dist/app/assets/{chunk-X4PVCEUW-BUI1Oi3q.js → chunk-X4PVCEUW-DGxTL3kB.js} +1 -1
  23. package/dist/app/assets/{chunk-XXDRQBXY-DYhK5YW-.js → chunk-XXDRQBXY-C02Gpej2.js} +1 -1
  24. package/dist/app/assets/{classDiagram-v2-L25IHNXF-K-k5GTUn.js → classDiagram-v2-L25IHNXF-DLEBwpvk.js} +1 -1
  25. package/dist/app/assets/cose-bilkent-JH36ORCC-kNCXOm8k.js +1 -0
  26. package/dist/app/assets/cynefin-EF2NZ3EQ-6MWNLbuF.js +1 -0
  27. package/dist/app/assets/{cynefinDiagram-L36ESFBY-mkV33_Xx.js → cynefinDiagram-L36ESFBY-CLFstukD.js} +1 -1
  28. package/dist/app/assets/{d3-scale-ygdFCUH8.js → d3-scale-CaJQQYkF.js} +1 -1
  29. package/dist/app/assets/{dagre-SPEB5RXH-BNIymLsu.js → dagre-SPEB5RXH-BaSAny1T.js} +1 -1
  30. package/dist/app/assets/{diagram-3B7GL73J-CGOiolFW.js → diagram-3B7GL73J-DJNlt5Sg.js} +1 -1
  31. package/dist/app/assets/{diagram-DNEMPZML-DZFkHNly.js → diagram-DNEMPZML-DEHeuILB.js} +1 -1
  32. package/dist/app/assets/{diagram-L3MUGCDN-B42GAYLq.js → diagram-L3MUGCDN-ob5Ka2Xc.js} +1 -1
  33. package/dist/app/assets/{diagram-LA4NIPWU-BYuLRYId.js → diagram-LA4NIPWU-DNESzFAc.js} +1 -1
  34. package/dist/app/assets/{diagram-MHCOC4E2-DGzI6TJG.js → diagram-MHCOC4E2-CVi9zKjG.js} +1 -1
  35. package/dist/app/assets/{diagram-XPFHEONP-CTBEgDQ8.js → diagram-XPFHEONP-DInT4C7e.js} +1 -1
  36. package/dist/app/assets/dist-CjvHN74u.js +1 -0
  37. package/dist/app/assets/{ebnfDiagram-UZSYDL2S-GuMdOCvL.js → ebnfDiagram-UZSYDL2S-CRCZNsji.js} +1 -1
  38. package/dist/app/assets/{elk-XV6XMXQE-BpY3loT5.js → elk-XV6XMXQE-D4fsWI2l.js} +1 -1
  39. package/dist/app/assets/{erDiagram-EYBAPDEH-nDZ2PMGl.js → erDiagram-EYBAPDEH-YQNM5StV.js} +1 -1
  40. package/dist/app/assets/{eventmodeling-K75KTNOO-BN42Mgwh.js → eventmodeling-K75KTNOO-Bev08J2F.js} +1 -1
  41. package/dist/app/assets/flowDiagram-MALGAFMO-BhJ554DH.js +1 -0
  42. package/dist/app/assets/ganttDiagram-23REXITY-CkaBMYM4.js +292 -0
  43. package/dist/app/assets/gitGraph-VSP46ZUC-CtbZ0sIS.js +1 -0
  44. package/dist/app/assets/{gitGraphDiagram-STJD7YCW-CDkKLrvO.js → gitGraphDiagram-STJD7YCW-D15ZdQ-Z.js} +1 -1
  45. package/dist/app/assets/index-Bn6_wHEp.js +98 -0
  46. package/dist/app/assets/index-H-Z7MFhZ.css +1 -0
  47. package/dist/app/assets/info-OHQRW6UA-CfUW1XFR.js +1 -0
  48. package/dist/app/assets/{infoDiagram-KBXO4MBG-B92P8pjY.js → infoDiagram-KBXO4MBG-DT7LbBRQ.js} +1 -1
  49. package/dist/app/assets/{ishikawaDiagram-M35NCXHK-BRZsbCvK.js → ishikawaDiagram-M35NCXHK-CF51lhjB.js} +1 -1
  50. package/dist/app/assets/{journeyDiagram-OPLOXDXO-Bppwb1oF.js → journeyDiagram-OPLOXDXO-_36FonKk.js} +1 -1
  51. package/dist/app/assets/{kanban-definition-BZKZHSQY-ByD_x5cm.js → kanban-definition-BZKZHSQY-tLk_OlQ-.js} +1 -1
  52. package/dist/app/assets/{mermaid-parser.core-CKmnV0Md.js → mermaid-parser.core-_3Vo8x6b.js} +3 -3
  53. package/dist/app/assets/mermaid.core-y-x1CYxC.js +44 -0
  54. package/dist/app/assets/{mindmap-definition-I2QAS2VK-fRbUh23C.js → mindmap-definition-I2QAS2VK-BCI4HRX3.js} +1 -1
  55. package/dist/app/assets/packet-JDAUHWVQ-Cco3UoaI.js +1 -0
  56. package/dist/app/assets/{pegDiagram-FD4XPPHP-qIABf6H8.js → pegDiagram-FD4XPPHP-BOzSoNji.js} +1 -1
  57. package/dist/app/assets/pie-XZMESJXO-reOB2GXn.js +1 -0
  58. package/dist/app/assets/{pieDiagram-J4AKIIQI-Bb4RBdrc.js → pieDiagram-J4AKIIQI-PlHpwT_c.js} +1 -1
  59. package/dist/app/assets/{quadrantDiagram-XTYBLID2-B0CpcVWE.js → quadrantDiagram-XTYBLID2-CdxZ0ael.js} +1 -1
  60. package/dist/app/assets/radar-ABXABTNO-DfCl8uV2.js +1 -0
  61. package/dist/app/assets/railroad-I3PHUGI6-4s14UyW1.js +1 -0
  62. package/dist/app/assets/{railroad-abnf-LNEFI6M7-BUhw7Iuo.js → railroad-abnf-LNEFI6M7-C49jJE4Y.js} +1 -1
  63. package/dist/app/assets/{railroad-ebnf-DWYD2UWJ-nQNF56LJ.js → railroad-ebnf-DWYD2UWJ-Bx-pcPc7.js} +1 -1
  64. package/dist/app/assets/{railroad-peg-JR7BVNR7-CwvbVIo6.js → railroad-peg-JR7BVNR7-DjBPSCKV.js} +1 -1
  65. package/dist/app/assets/{railroadDiagram-MRQ6NCDL-Dwr-mPZL.js → railroadDiagram-MRQ6NCDL-wGcmIMqq.js} +1 -1
  66. package/dist/app/assets/{requirementDiagram-Y7LWUY3S-Ctv2DKJM.js → requirementDiagram-Y7LWUY3S-DprFI03z.js} +1 -1
  67. package/dist/app/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  68. package/dist/app/assets/{sankeyDiagram-WGJFYUXA-BvKX0eIe.js → sankeyDiagram-WGJFYUXA-DygYWLTR.js} +1 -1
  69. package/dist/app/assets/{sequenceDiagram-5NDRBG5M-Y4YqU2Xt.js → sequenceDiagram-5NDRBG5M-BzIr2DBO.js} +1 -1
  70. package/dist/app/assets/{stateDiagram-v2-FJ4FJNEA-DmjIjn4u.js → stateDiagram-v2-FJ4FJNEA-MGCqKnm_.js} +1 -1
  71. package/dist/app/assets/{swimlanes-UMQ2AFYF-B2O5JCjs.js → swimlanes-UMQ2AFYF-CIEH82Zt.js} +1 -1
  72. package/dist/app/assets/swimlanesDiagram-OMPLPG4O-YWNJjl0g.js +8 -0
  73. package/dist/app/assets/{timeline-definition-SEUHKTQE-DJJdixAI.js → timeline-definition-SEUHKTQE-BGYSqup2.js} +1 -1
  74. package/dist/app/assets/treeView-D4JQ5SDB-B39o1sJo.js +1 -0
  75. package/dist/app/assets/treemap-SAJKECNS-BoGxrUH4.js +1 -0
  76. package/dist/app/assets/{usecaseDiagram-AFA6YXN4-Bp8pXgvR.js → usecaseDiagram-AFA6YXN4-dy6oVOke.js} +1 -1
  77. package/dist/app/assets/{vennDiagram-NNMJR3RB-DYSfZMWT.js → vennDiagram-NNMJR3RB-CUyuhcAk.js} +1 -1
  78. package/dist/app/assets/wardley-7MLQ67FV-sYPAvQ06.js +1 -0
  79. package/dist/app/assets/{wardleyDiagram-S7YFUSEH-CGJ8qg76.js → wardleyDiagram-S7YFUSEH-DYtxYUHe.js} +1 -1
  80. package/dist/app/assets/{xychartDiagram-GGNKY7IX-CRSvraFc.js → xychartDiagram-GGNKY7IX-ClR06AlB.js} +1 -1
  81. package/dist/app/index.html +3 -2
  82. package/dist/cli/index.js +281 -53
  83. package/dist/core/api.js +262 -51
  84. package/dist/core/approvals.js +426 -0
  85. package/dist/core/context.js +68 -3
  86. package/dist/core/diff.js +156 -0
  87. package/dist/core/docs.js +9 -3
  88. package/dist/core/doctor.js +152 -0
  89. package/dist/core/doctypes.js +79 -0
  90. package/dist/core/edit.js +25 -0
  91. package/dist/core/flags.js +13 -0
  92. package/dist/core/gaps.js +7 -2
  93. package/dist/core/heading.js +4 -0
  94. package/dist/core/history.js +36 -5
  95. package/dist/core/home.js +345 -0
  96. package/dist/core/lanes.js +134 -0
  97. package/dist/core/launch.js +34 -0
  98. package/dist/core/layout.js +362 -0
  99. package/dist/core/newdoc.js +66 -0
  100. package/dist/core/open-folder.js +30 -0
  101. package/dist/core/openspec.js +6 -6
  102. package/dist/core/paths.js +71 -4
  103. package/dist/core/project.js +392 -0
  104. package/dist/core/route.js +420 -0
  105. package/dist/core/scan.js +514 -0
  106. package/dist/core/schema.js +170 -1
  107. package/dist/core/scope.js +126 -0
  108. package/dist/core/setup.js +134 -0
  109. package/dist/core/skills.js +92 -14
  110. package/dist/core/storage/config.js +74 -0
  111. package/dist/core/storage/events.js +54 -0
  112. package/dist/core/storage/folder-watch.js +147 -0
  113. package/dist/core/storage/folder.js +469 -0
  114. package/dist/core/storage/index.js +8 -0
  115. package/dist/core/storage/local.js +22 -0
  116. package/dist/core/storage/migrate.js +48 -0
  117. package/dist/core/storage/postgres.js +290 -0
  118. package/dist/core/storage/types.js +101 -0
  119. package/dist/core/storage.js +483 -77
  120. package/dist/core/suggest.js +283 -0
  121. package/dist/core/tree.js +254 -0
  122. package/dist/core/types.js +583 -0
  123. package/dist/core/version.js +1 -1
  124. package/dist/core/versions.js +245 -0
  125. package/dist/core/watch.js +2 -136
  126. package/dist/core/xml.js +23 -5
  127. package/dist/demo/args.js +58 -0
  128. package/dist/demo/browser.js +301 -0
  129. package/dist/demo/platform.js +147 -0
  130. package/dist/demo/run.js +198 -0
  131. package/dist/demo/steps.js +328 -0
  132. package/dist/mcp/project-tools.js +193 -0
  133. package/dist/mcp/server.js +493 -65
  134. package/examples/platform/README.md +33 -0
  135. package/examples/platform/api/package.json +8 -0
  136. package/examples/platform/api/src/auth-middleware.js +16 -0
  137. package/examples/platform/api/src/proxy.js +7 -0
  138. package/examples/platform/api/src/rate-limit.js +13 -0
  139. package/examples/platform/api/src/server.js +40 -0
  140. package/examples/platform/auth/package.json +9 -0
  141. package/examples/platform/auth/src/server.js +24 -0
  142. package/examples/platform/auth/src/tokens.js +19 -0
  143. package/examples/platform/auth/src/users.js +16 -0
  144. package/examples/platform/docs/api/PRD.md +10 -0
  145. package/examples/platform/docs/api/SDD.md +15 -0
  146. package/examples/platform/docs/auth/PRD.md +10 -0
  147. package/examples/platform/docs/auth/SDD.md +8 -0
  148. package/examples/platform/docs/frontend/PRD.md +18 -0
  149. package/examples/platform/docs/frontend/SDD.md +13 -0
  150. package/examples/platform/docs/pricing/PRD.md +9 -0
  151. package/examples/platform/docs/pricing/SDD.md +8 -0
  152. package/examples/platform/docs/products/PRD.md +9 -0
  153. package/examples/platform/docs/products/SDD.md +8 -0
  154. package/examples/platform/frontend/package.json +8 -0
  155. package/examples/platform/frontend/src/api-client.js +21 -0
  156. package/examples/platform/frontend/src/main.js +21 -0
  157. package/examples/platform/frontend/src/pages/products.js +12 -0
  158. package/examples/platform/frontend/src/pages/sign-in.js +14 -0
  159. package/examples/platform/frontend/src/session.js +11 -0
  160. package/examples/platform/pricing/package.json +9 -0
  161. package/examples/platform/pricing/src/cache.js +19 -0
  162. package/examples/platform/pricing/src/product-events.js +17 -0
  163. package/examples/platform/pricing/src/rules.js +19 -0
  164. package/examples/platform/pricing/src/server.js +32 -0
  165. package/examples/platform/products/package.json +9 -0
  166. package/examples/platform/products/src/catalog.js +20 -0
  167. package/examples/platform/products/src/events.js +11 -0
  168. package/examples/platform/products/src/search.js +9 -0
  169. package/examples/platform/products/src/server.js +31 -0
  170. package/migrations/postgres/001_init.sql +55 -0
  171. package/migrations/postgres/002_view_versions.sql +18 -0
  172. package/package.json +18 -2
  173. package/schema/approval.schema.json +173 -0
  174. package/schema/gap.schema.json +3 -0
  175. package/schema/project.schema.json +93 -0
  176. package/schema/settings.schema.json +86 -0
  177. package/schema/toolbox.schema.json +206 -0
  178. package/schema/type.schema.json +121 -0
  179. package/schema/view.schema.json +106 -0
  180. package/skills/claude/build-gap/SKILL.md +7 -0
  181. package/skills/claude/check-ui/SKILL.md +40 -0
  182. package/skills/claude/draw-system/SKILL.md +24 -9
  183. package/skills/claude/gap-from-view/SKILL.md +7 -0
  184. package/skills/claude/post-audit/SKILL.md +58 -0
  185. package/skills/claude/pre-audit/SKILL.md +82 -0
  186. package/skills/claude/update-state/SKILL.md +56 -0
  187. package/skills/cursor/check-ui.mdc +40 -0
  188. package/skills/cursor/draw-system.mdc +24 -9
  189. package/skills/cursor/post-audit.mdc +44 -0
  190. package/skills/cursor/pre-audit.mdc +49 -0
  191. package/skills/cursor/update-state.mdc +45 -0
  192. package/skills/windsurf/spatial-views.md +182 -36
  193. package/toolboxes/aws.yaml +43 -0
  194. package/toolboxes/azure.yaml +41 -0
  195. package/toolboxes/cloud.yaml +95 -0
  196. package/toolboxes/docs.yaml +111 -0
  197. package/toolboxes/software.yaml +114 -0
  198. package/toolboxes/types/docs/gap.yaml +15 -0
  199. package/toolboxes/types/docs/mdd.yaml +19 -0
  200. package/toolboxes/types/docs/plain.yaml +7 -0
  201. package/toolboxes/types/docs/prd.yaml +17 -0
  202. package/dist/app/assets/architectureDiagram-YGSQEFNW-BrBCHqUH.js +0 -36
  203. package/dist/app/assets/chunk-X3CZISLH-FMl4PpWt.js +0 -1
  204. package/dist/app/assets/cose-bilkent-JH36ORCC-BJmLLpaN.js +0 -1
  205. package/dist/app/assets/cynefin-EF2NZ3EQ-DrzwMKdm.js +0 -1
  206. package/dist/app/assets/dist-1Q8ng3tu.js +0 -1
  207. package/dist/app/assets/flowDiagram-MALGAFMO-BCwwiLzb.js +0 -1
  208. package/dist/app/assets/ganttDiagram-23REXITY-xMRHaU3y.js +0 -292
  209. package/dist/app/assets/gitGraph-VSP46ZUC-DyGq5mdd.js +0 -1
  210. package/dist/app/assets/index-BY66fc8Q.js +0 -95
  211. package/dist/app/assets/index-ByetEVbs.css +0 -1
  212. package/dist/app/assets/info-OHQRW6UA-DOBf-fQH.js +0 -1
  213. package/dist/app/assets/mermaid.core-BoRvk1Q-.js +0 -44
  214. package/dist/app/assets/packet-JDAUHWVQ-CgHq03Zj.js +0 -1
  215. package/dist/app/assets/pie-XZMESJXO-DtNh3cDE.js +0 -1
  216. package/dist/app/assets/radar-ABXABTNO-BS0FcsIX.js +0 -1
  217. package/dist/app/assets/railroad-I3PHUGI6-lO8vfGdI.js +0 -1
  218. package/dist/app/assets/swimlanesDiagram-OMPLPG4O-DhCl-Cjg.js +0 -8
  219. package/dist/app/assets/treeView-D4JQ5SDB-Dd1no4eE.js +0 -1
  220. package/dist/app/assets/treemap-SAJKECNS-t6wtsaki.js +0 -1
  221. package/dist/app/assets/wardley-7MLQ67FV-Bx60QTuu.js +0 -1
  222. package/skills/cursor/build-gap.mdc +0 -21
  223. package/skills/cursor/gap-from-view.mdc +0 -22
@@ -1,20 +1,54 @@
1
- import { stat } from "node:fs/promises";
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
2
5
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
6
  import { z, ZodError } from "zod";
4
7
  import { buildContext, contextToJson, contextToXml } from "../core/context.js";
5
8
  import { importDocs } from "../core/docs.js";
6
9
  import { addFilePointer, addModule, connect, findModule, moveModule, removeConnection, removeModule, updateModule, } from "../core/edit.js";
7
10
  import { UserError } from "../core/errors.js";
11
+ import { addMessage, assignLane, removeMessage, setLanes } from "../core/lanes.js";
8
12
  import { createGap, listGaps, resolveGap, updateGap } from "../core/gaps.js";
9
13
  import { linkModule, slugId, unlinkModule } from "../core/links.js";
10
14
  import { resolveChangePath } from "../core/openspec.js";
11
- import { absPath, repoPath } from "../core/paths.js";
15
+ import { approvalState, outcome, Staging, summarizeApproval } from "../core/approvals.js";
16
+ import { docExists, resolveDocPath } from "../core/project.js";
12
17
  import { resolveModule, resolveView } from "../core/resolve.js";
13
- import { GapStateSchema, summarize, ViewTypeSchema } from "../core/schema.js";
14
- import { Spatial } from "../core/storage.js";
18
+ import { GapStateSchema, MessageKindSchema, summarize, ViewKindSchema, ViewTypeSchema, } from "../core/schema.js";
19
+ import { Session, Workspace } from "../core/home.js";
15
20
  import { VERSION } from "../core/version.js";
16
21
  import { viewToXml } from "../core/xml.js";
17
- /** Every tool the server registers (PRD §7, plus link_module / unlink_module). */
22
+ import { PROJECT_TOOL_NAMES, registerProjectTools } from "./project-tools.js";
23
+ import { parseSkill, skillNames, skillText } from "../core/skills.js";
24
+ import { experimental } from "../core/flags.js";
25
+ import { afterAiChange, layoutView, typeLayout } from "../core/layout.js";
26
+ import { checkProperties, ColorTokenSchema, createToolbox, createType, DocEntrySchema, findType, IconSchema, leanType, loadToolbox, PropertyDefSchema, TIER_MAX, TypeEntrySchema, userToolboxDir, } from "../core/types.js";
27
+ import { createDoc } from "../core/newdoc.js";
28
+ /**
29
+ * The Skills, served as MCP prompts, so a global install needs no per-repo
30
+ * rule files: Cursor, Claude Code and Windsurf list them from the server.
31
+ */
32
+ function registerSkillPrompts(server, exp) {
33
+ const dir = fileURLToPath(new URL("../../skills/claude/", import.meta.url));
34
+ for (const name of skillNames(exp)) {
35
+ let skill;
36
+ try {
37
+ skill = parseSkill(skillText(readFileSync(join(dir, name, "SKILL.md"), "utf8"), exp));
38
+ }
39
+ catch {
40
+ continue; // not bundled (a partial install): the tools still work
41
+ }
42
+ const body = skill.body;
43
+ server.registerPrompt(name, {
44
+ description: skill.description,
45
+ argsSchema: { args: z.string().optional().describe("e.g. the project name and paths: shop c:\\git\\api c:\\git\\web") },
46
+ }, ({ args }) => ({
47
+ messages: [{ role: "user", content: { type: "text", text: `${body}\n\n---\nRun: ${name}${args ? ` ${args}` : ""}` } }],
48
+ }));
49
+ }
50
+ }
51
+ /** Every tool the server registers (PRD §7, plus link_module / unlink_module, plus the §9 Project tools). */
18
52
  export const TOOL_NAMES = [
19
53
  "list_views",
20
54
  "get_view",
@@ -27,6 +61,12 @@ export const TOOL_NAMES = [
27
61
  "remove",
28
62
  "link_module",
29
63
  "unlink_module",
64
+ "layout_view",
65
+ "list_toolboxes",
66
+ "list_types",
67
+ "create_type",
68
+ "create_toolbox",
69
+ "create_doc",
30
70
  "create_gap",
31
71
  "list_gaps",
32
72
  "update_gap",
@@ -35,7 +75,21 @@ export const TOOL_NAMES = [
35
75
  "get_context",
36
76
  "add_file_pointer",
37
77
  "import_docs",
78
+ "list_versions",
79
+ "get_version",
80
+ "restore_version",
81
+ "name_version",
82
+ "set_lanes",
83
+ "assign_lane",
84
+ "add_message",
85
+ "list_approvals",
86
+ "get_approval",
87
+ ...PROJECT_TOOL_NAMES,
38
88
  ];
89
+ /** Tools served only with SPATIAL_VIEWS_EXPERIMENTAL=1: Gaps. Swim lanes are always served. */
90
+ export const EXPERIMENTAL_TOOLS = ["create_gap", "list_gaps", "update_gap", "get_context"];
91
+ /** The tools a server serves, with or without the experimental flag. */
92
+ export const toolNames = (exp = experimental()) => TOOL_NAMES.filter((t) => exp || !EXPERIMENTAL_TOOLS.includes(t));
39
93
  const text = (t) => ({ content: [{ type: "text", text: t }] });
40
94
  const json = (data) => text(JSON.stringify(data, null, 2));
41
95
  const fail = (t) => ({ content: [{ type: "text", text: t }], isError: true });
@@ -57,25 +111,81 @@ const Ref = {
57
111
  module: z.string().describe("module id or name"),
58
112
  in_view: z.string().optional().describe("the View the module is in, when its name is not unique"),
59
113
  format: z.enum(["xml", "json"]).optional().describe("xml (default) or json"),
114
+ layout: z
115
+ .enum(["auto", "keep"])
116
+ .optional()
117
+ .describe("auto (default): a View the AI drew is laid out again (layered, orthogonal); on a View a person has arranged, only modules added without x/y are placed and nothing else moves. keep: move nothing"),
60
118
  };
61
- /** The Spatial Views MCP server: the AI draws Views, makes Gaps and pins docs in .spatial/. */
119
+ /**
120
+ * The Spatial Views MCP server: the AI draws Views, makes Gaps and pins docs in .spatial/.
121
+ * With "AI changes need approval" on (the default, the project's settings.json), every write lands
122
+ * at once as a pending change in this session's Approval item instead (one agent run, one
123
+ * item; no send step), and reads see it on top of the live files.
124
+ */
62
125
  export function createServer(opts = {}) {
63
- const spatial = new Spatial(opts.root ?? process.cwd());
64
- const { views } = spatial;
126
+ const session = opts.session ?? new Session(opts.global ? { ...(opts.home ? { home: opts.home } : {}) } : { repo: opts.root ?? process.cwd(), ...(opts.home ? { home: opts.home } : {}) });
65
127
  const server = new McpServer({ name: "spatial-views", version: VERSION });
128
+ const exp = opts.experimental ?? experimental();
129
+ // The tool being run, and the Approval it wrote to (if any).
130
+ const call = new AsyncLocalStorage();
131
+ // One Staging per project: this session's writes in a project wait in that project's Approvals.
132
+ const stagings = new Map();
133
+ /** The active project, with its writes going through this session's Staging for it. */
134
+ const ws = () => {
135
+ const live = session.current;
136
+ let hit = stagings.get(live.spatial.dataDir);
137
+ if (!hit || hit.ws.slug !== live.slug) {
138
+ const staging = new Staging(live.spatial, () => server.server.getClientVersion()?.name || "AI", () => call.getStore()?.tool);
139
+ staging.onWrite = (p) => {
140
+ const ctx = call.getStore();
141
+ if (ctx)
142
+ ctx.approval = p;
143
+ };
144
+ hit = { staging, ws: new Workspace(live.kind, live.slug, live.spatial.withStage(staging, () => server.server.getClientVersion()?.name || "AI")) };
145
+ stagings.set(live.spatial.dataDir, hit);
146
+ }
147
+ return hit.ws;
148
+ };
149
+ /** The active project's data (staged); refuses with "pick a project" until one is in use. */
150
+ const sp = () => ws().spatial;
151
+ const staging = () => stagings.get(ws().spatial.dataDir).staging;
152
+ /** The toolboxes: built-in, the user's (in this session's home folder), the project's. */
153
+ const toolboxes = () => loadToolbox(sp().dataDir, { user: userToolboxDir(session.home.dir) });
154
+ const loadTypes = async () => (await toolboxes()).types;
155
+ // Every tool runs with its name in `call`; a reply to a staged write says so.
156
+ const register = server.registerTool.bind(server);
157
+ // Without the experimental flag, the Gap tools are not served at all.
158
+ server.registerTool = ((name, config, cb) => !exp && EXPERIMENTAL_TOOLS.includes(name)
159
+ ? undefined
160
+ : register(name, config, (async (...a) => {
161
+ const ctx = { tool: name };
162
+ const res = (await call.run(ctx, () => cb(...a)));
163
+ if (ctx.approval && !res?.isError && Array.isArray(res?.content))
164
+ res.content.push({
165
+ type: "text",
166
+ text: `(pending in Approvals as ${ctx.approval.id}: not live until a person approves it; ${approvalState(ctx.approval)}; get_approval for the outcome)`,
167
+ });
168
+ return res;
169
+ })));
66
170
  /** Load a View by ref, change it, save it. */
67
- const editView = async (ref, change) => {
68
- const v = resolveView(await views.listViews(), ref);
69
- return views.save(change(v));
171
+ const editView = async (ref, change, layout, fresh) => {
172
+ const v = resolveView(await sp().views.listViews(), ref);
173
+ const next = change(v);
174
+ return sp().views.save(await afterAiChange(next, layout, fresh, typeLayout(next, await loadTypes())));
175
+ };
176
+ /** A module type by id or name, and its property values checked against it. */
177
+ const typed = async (type, properties) => {
178
+ const t = type ? findType(await loadTypes(), type) : undefined;
179
+ return { type: t?.id, properties: properties ? checkProperties(t, properties) : undefined, def: t };
70
180
  };
71
181
  // ---- Read and show ------------------------------------------------------
72
- server.registerTool("list_views", { description: "List the Views in .spatial/ (id, name, type, module count)." }, async () => json(await views.list()));
182
+ server.registerTool("list_views", { description: "List the Views in .spatial/ (id, name, type, module count)." }, async () => guard(async () => json(await sp().views.list())));
73
183
  server.registerTool("get_view", {
74
184
  description: "Read one View, as XML by default or format=json. A linked module carries its sub-view " +
75
185
  "(LinkedView / LinkedViewName in XML, linked_view_id in JSON); a link to a missing View says Missing.",
76
186
  inputSchema: { view: Ref.view, format: Ref.format },
77
187
  }, async ({ view, format }) => guard(async () => {
78
- const all = await views.listViews();
188
+ const all = await sp().views.listViews();
79
189
  const v = resolveView(all, view);
80
190
  if (format === "json")
81
191
  return json(v);
@@ -85,35 +195,47 @@ export function createServer(opts = {}) {
85
195
  description: "Show a View on the canvas (npx spatial-views must be running for this repo).",
86
196
  inputSchema: { view: Ref.view },
87
197
  }, async ({ view }) => guard(async () => {
88
- const v = resolveView(await views.listViews(), view);
89
- await spatial.requestOpen(v.id);
198
+ const v = resolveView(await sp().views.listViews(), view);
199
+ await sp().requestOpen(v.id);
90
200
  return text(`asked the canvas to open ${v.name} (${v.id})`);
91
201
  }));
92
202
  // ---- Draw ----------------------------------------------------------------
93
203
  server.registerTool("create_view", {
94
204
  description: "Create an empty View. Give from_module (and in_view) to link that module to it, so it becomes " +
95
- "the module's sub-view (double-click drills into it).",
205
+ "the module's sub-view (double-click drills into it). kind: sequence makes a sequence View: add " +
206
+ "its participants with add_module (left to right) and its calls with add_message.",
96
207
  inputSchema: {
97
208
  name: z.string().min(1),
98
209
  type: ViewTypeSchema.optional().describe("high-level, repo, sub-view (default) or feature"),
210
+ kind: ViewKindSchema.optional().describe("flow (default) or sequence"),
99
211
  id: z.string().optional().describe("a file-safe id; made from the name if left out"),
100
212
  from_module: z.string().optional().describe("a module to link to the new View"),
101
213
  in_view: Ref.in_view,
214
+ layout: Ref.layout,
102
215
  },
103
- }, async ({ name, type, id, from_module, in_view }) => guard(async () => {
104
- const all = await views.listViews();
216
+ }, async ({ name, type, kind, id, from_module, in_view, layout }) => guard(async () => {
217
+ const all = await sp().views.listViews();
105
218
  const newId = id ?? slugId(name, all.map((v) => v.id));
106
219
  if (all.some((v) => v.id === newId))
107
220
  throw new UserError(`a View ${newId} already exists`);
108
221
  const parent = from_module ? resolveModule(all, from_module, in_view) : null;
109
- const v = await views.save({ id: newId, name, type: type ?? "sub-view", modules: [], connections: [] });
222
+ const v = await sp().views.save({
223
+ id: newId,
224
+ name,
225
+ type: type ?? "sub-view",
226
+ ...(kind === "sequence" ? { kind, messages: [] } : {}),
227
+ // A View the AI draws is laid out as it grows, until a person moves something.
228
+ ...(kind !== "sequence" && layout !== "keep" ? { auto_layout: true } : {}),
229
+ modules: [],
230
+ connections: [],
231
+ });
110
232
  if (parent)
111
- await views.save(linkModule(parent.view, parent.module.id, v.id));
112
- return text(`created ${v.type} View ${v.name} (${v.id})` +
233
+ await sp().views.save(linkModule(parent.view, parent.module.id, v.id));
234
+ return text(`created ${v.kind === "sequence" ? "sequence " : ""}${v.type} View ${v.name} (${v.id})` +
113
235
  (parent ? `, linked from ${parent.module.name} (${parent.view.id})` : ""));
114
236
  }));
115
237
  server.registerTool("add_module", {
116
- description: "Add a module to a View. Without x/y it goes in the next free slot.",
238
+ description: "Add a module to a View. Leave out x/y and it is placed by the layout (layout: auto), or in the next free slot (layout: keep).",
117
239
  inputSchema: {
118
240
  view: Ref.view,
119
241
  name: z.string().min(1),
@@ -121,14 +243,26 @@ export function createServer(opts = {}) {
121
243
  description: z.string().optional(),
122
244
  x: z.number().optional(),
123
245
  y: z.number().optional(),
246
+ type: z.string().optional().describe("a module type id or name from list_types (Service, Frontend, API, Database, ...)"),
247
+ properties: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional().describe("values for the type's properties"),
248
+ layout: Ref.layout,
124
249
  },
125
- }, async ({ view, ...input }) => guard(async () => {
250
+ }, async ({ view, layout, type, properties, ...rest }) => guard(async () => {
251
+ const t = await typed(type, properties);
252
+ const input = { ...rest, ...(t.type ? { type: t.type } : {}), ...(t.properties ? { properties: t.properties } : {}) };
126
253
  let added = "";
254
+ const fresh = new Set();
127
255
  const v = await editView(view, (cur) => {
128
256
  const r = addModule(cur, input);
129
257
  added = `${r.module.name} (${r.module.id})`;
130
- return r.view;
131
- });
258
+ if (input.x === undefined && input.y === undefined) {
259
+ fresh.add(r.module.id);
260
+ return r.view;
261
+ }
262
+ // Placed on purpose: the View's positions are no longer the layout's to change.
263
+ const { auto_layout: _auto, ...placed } = r.view;
264
+ return placed;
265
+ }, layout, fresh);
132
266
  return text(`added ${added} to ${v.id}`);
133
267
  }));
134
268
  server.registerTool("connect", {
@@ -138,60 +272,85 @@ export function createServer(opts = {}) {
138
272
  from: z.string().describe("module id or name"),
139
273
  to: z.string().describe("module id or name"),
140
274
  label: z.string().optional(),
275
+ layout: Ref.layout,
141
276
  },
142
- }, async ({ view, from, to, label }) => guard(async () => {
277
+ }, async ({ view, from, to, label, layout }) => guard(async () => {
143
278
  let id = "";
144
279
  const v = await editView(view, (cur) => {
145
280
  const r = connect(cur, from, to, label);
146
281
  id = r.connection.id;
147
282
  return r.view;
148
- });
283
+ }, layout);
149
284
  return text(`connected ${from} -> ${to} on ${v.id} (${id})`);
150
285
  }));
151
286
  server.registerTool("move_module", {
152
- description: "Move a module to x, y on its View.",
287
+ description: "Move a module to x, y on its View. The View is then no longer re-laid out automatically (only what you add is placed).",
153
288
  inputSchema: { module: Ref.module, in_view: Ref.in_view, x: z.number(), y: z.number() },
154
289
  }, async ({ module, in_view, x, y }) => guard(async () => {
155
- const hit = resolveModule(await views.listViews(), module, in_view);
156
- await views.save(moveModule(hit.view, hit.module.id, x, y));
290
+ const hit = resolveModule(await sp().views.listViews(), module, in_view);
291
+ const { auto_layout: _auto, ...placed } = moveModule(hit.view, hit.module.id, x, y);
292
+ await sp().views.save(placed);
157
293
  return text(`moved ${hit.module.name} to ${Math.round(x)}, ${Math.round(y)}`);
158
294
  }));
159
295
  server.registerTool("update_module", {
160
- description: "Rename a module or set its description (an empty description clears it).",
296
+ description: "Rename a module, set its description (empty clears it), its type (empty clears it) or its properties " +
297
+ "(merged into the ones it has; an empty string clears one).",
161
298
  inputSchema: {
162
299
  module: Ref.module,
163
300
  in_view: Ref.in_view,
164
301
  name: z.string().optional(),
165
302
  description: z.string().optional(),
303
+ type: z.string().optional().describe("a module type id or name from list_types"),
304
+ properties: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional(),
166
305
  },
167
- }, async ({ module, in_view, name, description }) => guard(async () => {
168
- const hit = resolveModule(await views.listViews(), module, in_view);
169
- await views.save(updateModule(hit.view, hit.module.id, { name, description }));
306
+ }, async ({ module, in_view, name, description, type, properties }) => guard(async () => {
307
+ const hit = resolveModule(await sp().views.listViews(), module, in_view);
308
+ const t = await typed(type || (type === undefined ? hit.module.type : undefined), undefined);
309
+ let props;
310
+ if (properties) {
311
+ const merged = { ...(hit.module.properties ?? {}), ...properties };
312
+ for (const [k, v] of Object.entries(merged))
313
+ if (v === "")
314
+ delete merged[k];
315
+ props = checkProperties(t.def, merged);
316
+ }
317
+ await sp().views.save(updateModule(hit.view, hit.module.id, {
318
+ name,
319
+ description,
320
+ ...(type !== undefined ? { type: type ? t.type : null } : {}),
321
+ ...(props !== undefined ? { properties: props } : {}),
322
+ }));
170
323
  return text(`updated ${hit.module.id} on ${hit.view.id}`);
171
324
  }));
172
325
  server.registerTool("remove", {
173
- description: "Remove a module (with its connections), a connection (by id), or, with neither, the whole View. " +
326
+ description: "Remove a module (with its connections and messages), a connection or a message (by id), or, with " +
327
+ "none of them, the whole View. " +
174
328
  "Removing a View needs confirm_view set to its id.",
175
329
  inputSchema: {
176
330
  view: Ref.view,
177
331
  module: z.string().optional().describe("module id or name"),
178
332
  connection: z.string().optional().describe("connection id"),
333
+ message: z.string().optional().describe("message id (sequence Views)"),
179
334
  confirm_view: z.string().optional(),
180
335
  },
181
- }, async ({ view, module, connection, confirm_view }) => guard(async () => {
182
- const v = resolveView(await views.listViews(), view);
336
+ }, async ({ view, module, connection, message, confirm_view }) => guard(async () => {
337
+ const v = resolveView(await sp().views.listViews(), view);
183
338
  if (module) {
184
339
  const m = findModule(v, module);
185
- await views.save(removeModule(v, m.id));
340
+ await sp().views.save(removeModule(v, m.id));
186
341
  return text(`removed ${m.name} (${m.id}) from ${v.id}`);
187
342
  }
188
343
  if (connection) {
189
- await views.save(removeConnection(v, connection));
344
+ await sp().views.save(removeConnection(v, connection));
190
345
  return text(`removed connection ${connection} from ${v.id}`);
191
346
  }
347
+ if (message) {
348
+ await sp().views.save(removeMessage(v, message));
349
+ return text(`removed message ${message} from ${v.id}`);
350
+ }
192
351
  if (confirm_view !== v.id)
193
352
  throw new UserError(`to remove the View itself, pass confirm_view: "${v.id}"`);
194
- await views.remove(v.id);
353
+ await sp().views.remove(v.id);
195
354
  return text(`removed View ${v.name} (${v.id})`);
196
355
  }));
197
356
  server.registerTool("link_module", {
@@ -199,31 +358,206 @@ export function createServer(opts = {}) {
199
358
  "Linking an already linked module changes its link.",
200
359
  inputSchema: { module: Ref.module, view: z.string().describe("the target View, id or name"), in_view: Ref.in_view },
201
360
  }, async ({ module, view, in_view }) => guard(async () => {
202
- const all = await views.listViews();
361
+ const all = await sp().views.listViews();
203
362
  const target = resolveView(all, view);
204
363
  const hit = resolveModule(all, module, in_view);
205
- await views.save(linkModule(hit.view, hit.module.id, target.id));
364
+ await sp().views.save(linkModule(hit.view, hit.module.id, target.id));
206
365
  return text(`linked ${hit.module.name} (${hit.view.id}) to ${target.name} (${target.id})`);
207
366
  }));
208
367
  server.registerTool("unlink_module", {
209
368
  description: "Remove a module's link to its sub-view. The sub-view itself is kept.",
210
369
  inputSchema: { module: Ref.module, in_view: Ref.in_view },
211
370
  }, async ({ module, in_view }) => guard(async () => {
212
- const hit = resolveModule(await views.listViews(), module, in_view);
371
+ const hit = resolveModule(await sp().views.listViews(), module, in_view);
213
372
  if (!hit.module.linked_view_id)
214
373
  return text(`${hit.module.name} has no link`);
215
- await views.save(unlinkModule(hit.view, hit.module.id));
374
+ await sp().views.save(unlinkModule(hit.view, hit.module.id));
216
375
  return text(`removed the link from ${hit.module.name} (${hit.view.id})`);
217
376
  }));
218
377
  server.registerTool("add_file_pointer", {
219
- description: "Record a source file (repo-relative) on a module, so get_context can point at it.",
378
+ description: "Record a source file on a module, so get_context can point at it: repo-relative, or in a project " +
379
+ "<source_id>:<path> for a file in one of its sources.",
220
380
  inputSchema: { module: Ref.module, in_view: Ref.in_view, path: z.string().min(1) },
221
381
  }, async ({ module, in_view, path }) => guard(async () => {
222
- const rel = repoPath(spatial.root, path);
223
- const hit = resolveModule(await views.listViews(), module, in_view);
224
- await views.save(addFilePointer(hit.view, hit.module.id, rel));
382
+ const rel = (await resolveDocPath(sp(), path)).rel;
383
+ const hit = resolveModule(await sp().views.listViews(), module, in_view);
384
+ await sp().views.save(addFilePointer(hit.view, hit.module.id, rel));
225
385
  return text(`${rel} is on ${hit.module.name} (${hit.view.id})`);
226
386
  }));
387
+ server.registerTool("list_toolboxes", {
388
+ description: "List the toolboxes (one icon each on the canvas's right-hand bar): Software, Cloud, AWS, Azure, Docs and " +
389
+ "any of the user's (~/SpatialViews/toolboxes) or the project's (<project>/toolboxes). Each has its id, name, " +
390
+ "icon, where it came from (built-in, user, project), its files, whether Settings has it on, and its type ids. " +
391
+ "errors lists problems in toolbox files, by file and line.",
392
+ }, async () => guard(async () => {
393
+ const tb = await toolboxes();
394
+ return json({
395
+ toolboxes: tb.toolboxes.map(({ types, docs, icon_svg: _svg, ...t }) => ({ ...t, types: types.map((x) => x.id), docs: docs.map((x) => x.id) })),
396
+ errors: tb.errors,
397
+ });
398
+ }));
399
+ server.registerTool("list_types", {
400
+ description: "List the module types (id, name, icon, colour, default size, tier (its row, top to bottom) or side, properties with name, type, default, options) " +
401
+ "and doc types (id, name, icon, folder, markdown template), each with its toolbox. Use a module type's id in " +
402
+ "add_module, a doc type's in create_doc. toolbox narrows it to one toolbox (e.g. aws).",
403
+ inputSchema: { toolbox: z.string().optional().describe("a toolbox id from list_toolboxes") },
404
+ }, async ({ toolbox }) => guard(async () => {
405
+ const tb = await toolboxes();
406
+ if (toolbox && !tb.toolboxes.some((t) => t.id === toolbox))
407
+ throw new UserError(`no toolbox ${toolbox} (have: ${tb.toolboxes.map((t) => t.id).join(", ")})`);
408
+ const pick = (xs) => xs.filter((x) => !toolbox || x.toolbox === toolbox).map(leanType);
409
+ return json({ types: pick(tb.types), docs: pick(tb.docs) });
410
+ }));
411
+ server.registerTool("create_type", {
412
+ description: "Make a type for the user, or change one by id, in a toolbox. It is written to the project's " +
413
+ "toolboxes/<toolbox>.yaml (a built-in toolbox id such as aws or software extends that toolbox; a new id makes a " +
414
+ "new toolbox). kind module (default): used by add_module. kind doc: a markdown template ({{title}}, {{module}}, " +
415
+ "{{view}}, {{date}}), used by create_doc. Start a new type's id with its toolbox's id (gcp-run). It shows on " +
416
+ "the canvas's bar and in list_types at once.",
417
+ inputSchema: {
418
+ toolbox: z.string().optional().describe("the toolbox id (default: custom for a module type, docs for a doc type)"),
419
+ kind: z.enum(["module", "doc"]).optional(),
420
+ name: z.string().min(1),
421
+ id: z.string().optional().describe("lower-case id; made from the name if left out"),
422
+ description: z.string().optional(),
423
+ icon: IconSchema.optional(),
424
+ color: ColorTokenSchema.optional(),
425
+ size: z.object({ w: z.number(), h: z.number() }).optional().describe("module types only"),
426
+ tier: z
427
+ .number()
428
+ .int()
429
+ .min(0)
430
+ .max(TIER_MAX)
431
+ .optional()
432
+ .describe("module types only: its row, top to bottom: 0 users, 1 frontend, 2 gateway, 3 API, 4 service, 5 worker or queue, 6 data"),
433
+ side: z.enum(["right"]).optional().describe("module types only: right, drawn in the column right of the rest, like an external"),
434
+ properties: z.array(PropertyDefSchema).optional().describe("module types only"),
435
+ template: z.string().optional().describe("doc types only: the new doc's markdown"),
436
+ folder: z.string().optional().describe("doc types only: where new docs go (default docs)"),
437
+ title: z.string().optional().describe("doc types only: the default title, e.g. '{{module}} {{type}}'"),
438
+ scope: z.enum(["project", "user"]).optional().describe("project (default): this project's toolboxes. user: every project's"),
439
+ },
440
+ }, async ({ kind, scope, template, folder, title, size, tier, side, properties, ...input }) => guard(async () => {
441
+ if (kind === "doc" && (size || properties || tier !== undefined || side))
442
+ throw new UserError("size, tier, side and properties are for module types; a doc type has a template");
443
+ if (kind !== "doc" && (template || folder || title))
444
+ throw new UserError("template, folder and title are for doc types (kind: doc)");
445
+ const extra = kind === "doc" ? { template, folder, title } : { size, tier, side, properties };
446
+ const made = await createType(sp().dataDir, { ...input, ...extra }, {
447
+ kind: kind ?? "module",
448
+ ...(scope === "user" ? { dir: userToolboxDir(session.home.dir) } : {}),
449
+ });
450
+ return json(made);
451
+ }));
452
+ server.registerTool("create_toolbox", {
453
+ description: "Make a new toolbox for the user (a new icon on the canvas's bar), with its module types and doc types, in " +
454
+ "the project's toolboxes/<id>.yaml (scope user: ~/SpatialViews/toolboxes). Types are as in create_type, each " +
455
+ "with an id (start it with the toolbox id). To add types to a toolbox that already exists, use create_type.",
456
+ inputSchema: {
457
+ name: z.string().min(1),
458
+ id: z.string().optional().describe("lower-case id; made from the name if left out"),
459
+ icon: IconSchema.optional(),
460
+ description: z.string().optional(),
461
+ order: z.number().optional().describe("place on the bar, lower first (Software 10, Cloud 20, AWS 30, Azure 40, Docs 90; default 100)"),
462
+ types: z.array(TypeEntrySchema).optional(),
463
+ docs: z.array(DocEntrySchema).optional(),
464
+ scope: z.enum(["project", "user"]).optional(),
465
+ },
466
+ }, async ({ scope, ...input }) => guard(async () => {
467
+ const made = await createToolbox(sp().dataDir, input, scope === "user" ? { dir: userToolboxDir(session.home.dir) } : {});
468
+ const tb = (await toolboxes()).toolboxes.find((t) => t.id === made.id);
469
+ return json({ ...made, types: tb?.types.map((t) => t.id) ?? [], docs: tb?.docs.map((t) => t.id) ?? [] });
470
+ }));
471
+ server.registerTool("create_doc", {
472
+ description: "Make a doc from a doc type's template (list_types: PRD, SDD, MDD, Feature doc, ADR, Runbook, Plain doc) " +
473
+ "and pin it to a module (module + view) or a View (view alone). It goes in the type's folder (docs/ by " +
474
+ "default), named from the title; an existing file is never overwritten. The same as dropping a doc type " +
475
+ "from the Toolbox onto a module. Returns the path and the pin.",
476
+ inputSchema: {
477
+ type: z.string().min(1).describe("a doc type id or name from list_types"),
478
+ title: z.string().optional().describe("default: the module's name and the type, e.g. 'Payments PRD'"),
479
+ view: Ref.view.optional().describe("the View to pin to (or the module's View)"),
480
+ module: z.string().optional().describe("module id or name to pin to"),
481
+ path: z.string().optional().describe("the repo path, e.g. docs/payments/prd.md (default: <folder>/<title>.md)"),
482
+ },
483
+ }, async ({ type, title, view, module, path }) => guard(async () => {
484
+ const all = await sp().views.listViews();
485
+ const hit = module ? resolveModule(all, module, view) : null;
486
+ const v = hit?.view ?? (view ? resolveView(all, view) : undefined);
487
+ const made = await createDoc(sp(), {
488
+ dirs: { user: userToolboxDir(session.home.dir) },
489
+ type,
490
+ ...(title ? { title } : {}),
491
+ ...(path ? { path } : {}),
492
+ ...(v ? { view: v } : {}),
493
+ ...(hit ? { module: hit.module } : {}),
494
+ });
495
+ return json({ path: made.path, type: made.type.id, title: made.title, ...(made.pin ? { pin: made.pin } : {}) });
496
+ }));
497
+ server.registerTool("layout_view", {
498
+ description: "Lay out a whole View again, as an architect draws it: top down, one row per module type's tier (users, " +
499
+ "frontend, gateway, API, services side by side, workers and queues, data at the bottom), externals in a " +
500
+ "column on the right, even spacing, connections leaving from the bottom and entering from the top " +
501
+ "(direction: right for left to right). It moves every module, including ones a person placed, so use it only when a person " +
502
+ "asks to tidy the View. To add to a View, use add_module and connect (layout: auto places only what you add).",
503
+ inputSchema: { view: Ref.view, direction: z.enum(["right", "down"]).optional() },
504
+ }, async ({ view, direction }) => guard(async () => {
505
+ const v = resolveView(await sp().views.listViews(), view);
506
+ if (v.kind === "sequence")
507
+ throw new UserError(`${v.id} is a sequence View: its participants are laid out left to right already`);
508
+ const hints = typeLayout(v, await loadTypes());
509
+ const laid = await sp().views.save({ ...(await layoutView(v, { ...hints, ...(direction ? { direction } : {}) })), auto_layout: true });
510
+ return text(`laid out ${laid.modules.length} modules on ${laid.id}`);
511
+ }));
512
+ // ---- Swim lanes and sequences (M1) -----------------------------------------
513
+ server.registerTool("set_lanes", {
514
+ description: "Set a View's swim lanes, top to bottom: one per team or person (e.g. Engineer A, Engineer B). " +
515
+ "Lanes are drawn as horizontal bands; a connection between modules in different lanes is drawn " +
516
+ "as a dependency. Modules in a lane that goes lose their lane. An empty list removes the lanes.",
517
+ inputSchema: {
518
+ view: Ref.view,
519
+ lanes: z
520
+ .array(z.union([z.string(), z.object({ id: z.string().optional(), label: z.string() })]))
521
+ .describe("labels, or {id, label}"),
522
+ },
523
+ }, async ({ view, lanes }) => guard(async () => {
524
+ const v = await editView(view, (cur) => setLanes(cur, lanes));
525
+ return text(v.lanes ? `lanes on ${v.id}: ${v.lanes.map((l) => `${l.label} (${l.id})`).join(", ")}` : `no lanes on ${v.id}`);
526
+ }));
527
+ server.registerTool("assign_lane", {
528
+ description: "Put a module in a swim lane (lane id or label), or take it out with an empty lane. On a flow View " +
529
+ "the module moves into the lane's band.",
530
+ inputSchema: { module: Ref.module, in_view: Ref.in_view, lane: z.string().describe("lane id or label; empty clears") },
531
+ }, async ({ module, in_view, lane }) => guard(async () => {
532
+ const hit = resolveModule(await sp().views.listViews(), module, in_view);
533
+ const v = await sp().views.save(assignLane(hit.view, hit.module.id, lane.trim() ? lane : null));
534
+ const m = v.modules.find((x) => x.id === hit.module.id);
535
+ const label = v.lanes?.find((l) => l.id === m.lane)?.label;
536
+ return text(label ? `${m.name} is in lane ${label} (${v.id})` : `${m.name} is in no lane (${v.id})`);
537
+ }));
538
+ server.registerTool("add_message", {
539
+ description: "Add a message to a sequence View: from one participant (module) to another, with its text " +
540
+ "(e.g. POST /orders, order.created). kind: sync (default), async or reply. at: a 1-based position; " +
541
+ "left out, it goes last.",
542
+ inputSchema: {
543
+ view: Ref.view,
544
+ from: z.string().describe("participant: module id or name"),
545
+ to: z.string().describe("participant: module id or name"),
546
+ text: z.string(),
547
+ kind: MessageKindSchema.optional(),
548
+ at: z.number().int().positive().optional(),
549
+ },
550
+ }, async ({ view, ...input }) => guard(async () => {
551
+ let id = "";
552
+ let order = 0;
553
+ const v = await editView(view, (cur) => {
554
+ const r = addMessage(cur, input);
555
+ id = r.message.id;
556
+ order = r.view.messages.indexOf(r.message) + 1;
557
+ return r.view;
558
+ });
559
+ return text(`added message ${id} (#${order}) to ${v.id}`);
560
+ }));
227
561
  // ---- Gaps ----------------------------------------------------------------
228
562
  server.registerTool("create_gap", {
229
563
  description: "Create a Gap from selected modules on a View. When the repo uses OpenSpec, this also creates the " +
@@ -236,12 +570,13 @@ export function createServer(opts = {}) {
236
570
  modules: z.array(z.string()).min(1).describe("module ids or names on that View"),
237
571
  milestone: z.string().optional(),
238
572
  openspec: z.boolean().optional().describe("force the OpenSpec change on or off"),
573
+ draft: z.boolean().optional().describe("a draft Gap, raised by an audit for a person to confirm (no OpenSpec change)"),
239
574
  },
240
- }, async (input) => guard(async () => json(await createGap(spatial, input))));
575
+ }, async (input) => guard(async () => json(await createGap(sp(), input))));
241
576
  server.registerTool("list_gaps", {
242
577
  description: "List Gaps (JSON), optionally for one View, state or milestone. States follow their OpenSpec change.",
243
578
  inputSchema: { view: Ref.view.optional(), state: GapStateSchema.optional(), milestone: z.string().optional() },
244
- }, async (filter) => guard(async () => json(await listGaps(spatial, filter))));
579
+ }, async (filter) => guard(async () => json(await listGaps(sp(), filter))));
245
580
  server.registerTool("update_gap", {
246
581
  description: "Change a Gap: title, intent, state (open, building, done, cancelled), milestone or modules. " +
247
582
  "A Gap with an OpenSpec change is done once the change is archived.",
@@ -252,25 +587,29 @@ export function createServer(opts = {}) {
252
587
  state: GapStateSchema.optional(),
253
588
  milestone: z.string().optional().describe("empty clears it"),
254
589
  modules: z.array(z.string()).optional(),
590
+ draft: z.boolean().optional().describe("false confirms a draft Gap"),
255
591
  },
256
- }, async ({ gap, ...patch }) => guard(async () => json(await updateGap(spatial, gap, patch))));
592
+ }, async ({ gap, ...patch }) => guard(async () => json(await updateGap(sp(), gap, patch))));
257
593
  server.registerTool("get_context", {
258
594
  description: "Everything one Gap needs, and nothing else: the Big Picture (top View), the path down to the Gap's " +
259
595
  "View, its modules with connections and files, and the specs, changes and docs pinned to them " +
260
596
  "(their text included). XML by default, or format=json. Tokens is an estimate.",
261
597
  inputSchema: { gap: z.string().describe("Gap id or title"), format: Ref.format },
262
598
  }, async ({ gap, format }) => guard(async () => {
263
- const ctx = await buildContext(spatial, gap);
599
+ const ctx = await buildContext(sp(), gap);
264
600
  if (format === "json")
265
601
  return text(contextToJson(ctx));
266
- return text(contextToXml(ctx, await views.list()));
602
+ return text(contextToXml(ctx, await sp().views.list()));
267
603
  }));
268
604
  // ---- Pins and docs --------------------------------------------------------
269
605
  server.registerTool("pin", {
270
606
  description: "Pin a spec, change folder or doc (repo path) to a View, a module, a Feature or a Gap. Pins go in " +
271
607
  ".spatial/pins.json; the doc is never rewritten. unpin: true removes the pin.",
272
608
  inputSchema: {
273
- path: z.string().min(1).describe("e.g. openspec/specs/auth/spec.md, openspec/changes/add-x, docs/prd.md"),
609
+ path: z
610
+ .string()
611
+ .min(1)
612
+ .describe("e.g. openspec/specs/auth/spec.md, docs/prd.md; in a project, a file in a source is <source_id>:<path> (docs:prd.md)"),
274
613
  view: Ref.view.optional().describe("the View (alone: pin to the View; with module/feature: where they are)"),
275
614
  module: z.string().optional(),
276
615
  feature: z.string().optional().describe("Feature id or name"),
@@ -278,14 +617,16 @@ export function createServer(opts = {}) {
278
617
  unpin: z.boolean().optional(),
279
618
  },
280
619
  }, async ({ path, view, module, feature, gap, unpin }) => guard(async () => {
281
- const rel = repoPath(spatial.root, path);
282
- if (!unpin && !(await stat(absPath(spatial.root, await resolveChangePath(spatial.root, rel))).catch(() => null)))
620
+ const doc = await resolveDocPath(sp(), path);
621
+ const rel = doc.rel;
622
+ const real = doc.source || doc.report ? doc : await resolveDocPath(sp(), await resolveChangePath(sp().root, rel));
623
+ if (!unpin && !(await docExists(sp(), real)))
283
624
  throw new UserError(`${rel} does not exist`);
284
- const all = await views.listViews();
625
+ const all = await sp().views.listViews();
285
626
  let pin;
286
627
  let label;
287
628
  if (gap) {
288
- const g = resolveGap(await spatial.gaps.all(), gap);
629
+ const g = resolveGap(await sp().gaps.all(), gap);
289
630
  pin = { path: rel, kind: "gap", gap_id: g.id };
290
631
  label = `Gap ${g.title}`;
291
632
  }
@@ -312,10 +653,10 @@ export function createServer(opts = {}) {
312
653
  else
313
654
  throw new UserError("say what to pin to: view, module, feature or gap");
314
655
  if (unpin) {
315
- const n = await spatial.pins.remove(pin);
656
+ const n = await sp().pins.remove(pin);
316
657
  return text(n ? `unpinned ${rel} from ${label}` : `${rel} was not pinned to ${label}`);
317
658
  }
318
- const added = await spatial.pins.add(pin);
659
+ const added = await sp().pins.add(pin);
319
660
  return text(added ? `pinned ${rel} to ${label}` : `${rel} is already pinned to ${label}`);
320
661
  }));
321
662
  server.registerTool("list_pins", {
@@ -327,8 +668,8 @@ export function createServer(opts = {}) {
327
668
  path: z.string().optional(),
328
669
  },
329
670
  }, async ({ view, module, gap, path }) => guard(async () => {
330
- let pins = await spatial.pins.list();
331
- const all = await views.listViews();
671
+ let pins = await sp().pins.list();
672
+ const all = await sp().views.listViews();
332
673
  if (view && !module) {
333
674
  const v = resolveView(all, view);
334
675
  pins = pins.filter((p) => "view_id" in p && p.view_id === v.id);
@@ -338,11 +679,11 @@ export function createServer(opts = {}) {
338
679
  pins = pins.filter((p) => p.kind === "module" && p.view_id === hit.view.id && p.module_id === hit.module.id);
339
680
  }
340
681
  if (gap) {
341
- const g = resolveGap(await spatial.gaps.all(), gap);
682
+ const g = resolveGap(await sp().gaps.all(), gap);
342
683
  pins = pins.filter((p) => p.kind === "gap" && p.gap_id === g.id);
343
684
  }
344
685
  if (path) {
345
- const rel = repoPath(spatial.root, path);
686
+ const rel = (await resolveDocPath(sp(), path)).rel;
346
687
  pins = pins.filter((p) => p.path === rel || p.path.startsWith(`${rel}/`));
347
688
  }
348
689
  return json(pins);
@@ -352,6 +693,93 @@ export function createServer(opts = {}) {
352
693
  "the canvas. Reports the docs, OpenSpec specs and changes, and Mermaid flowcharts found. With " +
353
694
  "draft_views, each flowchart becomes a draft View.",
354
695
  inputSchema: { path: z.string().min(1), draft_views: z.boolean().optional() },
355
- }, async ({ path, draft_views }) => guard(async () => json(await importDocs(spatial, path, draft_views === true))));
696
+ }, async ({ path, draft_views }) => guard(async () => json(await importDocs(sp(), path, draft_views === true))));
697
+ // ---- Versions ---------------------------------------------------------------
698
+ const Target = {
699
+ view: z.string().optional().describe("View id or name (this, or doc)"),
700
+ doc: z.string().optional().describe("a doc's path in the project (this, or view)"),
701
+ };
702
+ /** The View or doc a version tool is about: exactly one of them. */
703
+ const target = async (a) => {
704
+ sp(); // "pick a project" comes first
705
+ if (!!a.view === !!a.doc)
706
+ throw new UserError("pass view or doc (one of them)");
707
+ if (a.view)
708
+ return { kind: "view", id: resolveView(await sp().views.listViews(), a.view).id };
709
+ return { kind: "doc", id: sp().docs.rel(a.doc) };
710
+ };
711
+ server.registerTool("list_versions", {
712
+ description: "Every saved version of a View or doc, newest first: n, when, by (human, or the AI client), its name " +
713
+ "and a one-line summary (modules added, changed, removed). Every save writes one; nothing is deleted.",
714
+ inputSchema: Target,
715
+ }, async (a) => guard(async () => {
716
+ const t = await target(a);
717
+ return json(t.kind === "view" ? await sp().views.versions.history(t.id) : await sp().docs.history.history(t.id));
718
+ }));
719
+ server.registerTool("get_version", {
720
+ description: "Read one version of a View (XML by default, or format=json) or doc (its markdown). Read only: the live one does not change.",
721
+ inputSchema: { ...Target, n: z.number().int().positive(), format: Ref.format },
722
+ }, async ({ n, format, ...a }) => guard(async () => {
723
+ const t = await target(a);
724
+ if (t.kind === "doc") {
725
+ const v = await sp().docs.history.get(t.id, n);
726
+ return format === "json" ? json(v) : text(v.data);
727
+ }
728
+ const v = await sp().views.versions.get(t.id, n);
729
+ if (format === "json")
730
+ return json(v);
731
+ return text(viewToXml(v.data, (await sp().views.listViews()).map(summarize)));
732
+ }));
733
+ server.registerTool("restore_version", {
734
+ description: "Restore a View or doc to version n: it is written as a NEW version (\"restored from v12\"); nothing " +
735
+ "is deleted. With AI changes needing approval it waits in Approvals like any other write.",
736
+ inputSchema: { ...Target, n: z.number().int().positive(), note: z.string().optional() },
737
+ }, async ({ n, note, ...a }) => guard(async () => {
738
+ const t = await target(a);
739
+ if (t.kind === "view") {
740
+ const v = await sp().views.restore(t.id, n, note ? { note } : {});
741
+ return text(`restored ${v.name} (${v.id}) from v${n}`);
742
+ }
743
+ await sp().docs.restore(t.id, n, note ? { note } : {});
744
+ return text(`restored ${t.id} from v${n}`);
745
+ }));
746
+ server.registerTool("name_version", {
747
+ description: "Name a version (\"before pre-audit\") so it is easy to find and never pruned. Without n: snapshot the " +
748
+ "View or doc as it is now (saved as a new version if none holds it), e.g. before a big change. " +
749
+ "An empty name clears it.",
750
+ inputSchema: { ...Target, name: z.string(), n: z.number().int().positive().optional() },
751
+ }, async ({ name, n, ...a }) => guard(async () => {
752
+ const t = await target(a);
753
+ const by = server.server.getClientVersion()?.name || "AI";
754
+ const v = t.kind === "view" ? await sp().views.nameVersion(t.id, name, n, by) : await sp().docs.nameVersion(t.id, name, n, by);
755
+ const { data: _d, ...head } = v;
756
+ return json(head);
757
+ }));
758
+ // ---- Approvals (M1) ---------------------------------------------------------
759
+ server.registerTool("list_approvals", {
760
+ description: "List Approvals, newest first: one draft per View or Doc, e.g. \"#12 Cursor: amended View Checkout\", " +
761
+ "with its status (pending, approved, denied), its number of revisions and the changed Views and docs. " +
762
+ "Every write to approved content lands in Approvals at once (a write to a file with a pending " +
763
+ "Approval amends that one); there is nothing to send.",
764
+ inputSchema: { status: z.enum(["pending", "approved", "denied"]).optional() },
765
+ }, async ({ status }) => guard(async () => json((await staging().store.list()).filter((p) => !status || p.status === status).map(summarizeApproval))));
766
+ server.registerTool("get_approval", {
767
+ description: "Read an Approval: its state in words (\"amended pending approval #12 (3 revisions, from v4)\"), its " +
768
+ "outcome (pending, approved, approved in part, denied), the reviewer's note, its base version, its " +
769
+ "revisions (at, by, summary) and each change (target, ref, op, decision). Without id: the one this " +
770
+ "session last wrote to. full: true adds each change's before (the base) and after (the head).",
771
+ inputSchema: { id: z.string().optional(), full: z.boolean().optional() },
772
+ }, async ({ id, full }) => guard(async () => {
773
+ const pid = id ?? staging().lastId;
774
+ if (!pid)
775
+ throw new UserError("this session has no Approval yet; pass id (see list_approvals)");
776
+ const p = await staging().store.get(pid);
777
+ const changes = p.changes.map(({ before, after, ...c }) => (full ? { ...c, before, after } : c));
778
+ const { changes: _c, ...rest } = p;
779
+ return json({ ...rest, rev: p.revisions.length, state: approvalState(p), outcome: outcome(p), changes });
780
+ }));
781
+ // ---- Projects (M1) ----------------------------------------------------------
782
+ registerProjectTools(server, session, guard, json, text, ws, async () => !!(await staging().current()));
783
+ registerSkillPrompts(server, exp);
356
784
  return server;
357
785
  }