spatial-views 0.0.0-stage → 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 (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +245 -2
  3. package/dist/app/assets/abnfDiagram-S7VZAUFO-CFbb_Sz2.js +1 -0
  4. package/dist/app/assets/architecture-WOLXFQ4H-CsBD__5a.js +1 -0
  5. package/dist/app/assets/architectureDiagram-YGSQEFNW-C0ic4ib1.js +36 -0
  6. package/dist/app/assets/blockDiagram-APKKGZFW-BZDPbzAG.js +140 -0
  7. package/dist/app/assets/bpmnIcons-APHXDYXF-C0jbCElo.js +1 -0
  8. package/dist/app/assets/c4Diagram-KJ2TOQU5-BilBWuq5.js +38 -0
  9. package/dist/app/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
  10. package/dist/app/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
  11. package/dist/app/assets/chunk-6MUBBAK2-BBl-4tQr.js +2 -0
  12. package/dist/app/assets/chunk-AXFCVDMN-BhsttQ-k.js +62 -0
  13. package/dist/app/assets/chunk-BG4553SI-mWcPcFZr.js +127 -0
  14. package/dist/app/assets/chunk-DQASFODM-7FKe2gLt.js +10 -0
  15. package/dist/app/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
  16. package/dist/app/assets/chunk-HFQBQIA3-nXrQ08BL.js +1 -0
  17. package/dist/app/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
  18. package/dist/app/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
  19. package/dist/app/assets/chunk-KQLB2F66-swukhFmZ.js +2 -0
  20. package/dist/app/assets/chunk-KS47KZWR-DkDkwO82.js +1 -0
  21. package/dist/app/assets/chunk-LEVMRMFU-DXH6iXv3.js +1 -0
  22. package/dist/app/assets/chunk-M57EVK23-B-kEyOJF.js +1 -0
  23. package/dist/app/assets/chunk-NGNAAXSQ-DI_UYJZ4.js +136 -0
  24. package/dist/app/assets/chunk-OY52VR5R-DweG7qYw.js +88 -0
  25. package/dist/app/assets/chunk-QB3YPZ4I-DyozK3lV.js +213 -0
  26. package/dist/app/assets/chunk-R3KSYZAL-BEXCUN6J.js +1 -0
  27. package/dist/app/assets/chunk-STOXU5M4-BaTlty4O.js +72 -0
  28. package/dist/app/assets/chunk-TU62E6Q5-_rcUP1Fh.js +1 -0
  29. package/dist/app/assets/chunk-X3CZISLH-NOpCnvgE.js +1 -0
  30. package/dist/app/assets/chunk-X4PVCEUW-DGxTL3kB.js +1 -0
  31. package/dist/app/assets/chunk-XXDRQBXY-C02Gpej2.js +1 -0
  32. package/dist/app/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
  33. package/dist/app/assets/classDiagram-v2-L25IHNXF-DLEBwpvk.js +217 -0
  34. package/dist/app/assets/cose-bilkent-JH36ORCC-kNCXOm8k.js +1 -0
  35. package/dist/app/assets/cynefin-EF2NZ3EQ-6MWNLbuF.js +1 -0
  36. package/dist/app/assets/cynefinDiagram-L36ESFBY-CLFstukD.js +62 -0
  37. package/dist/app/assets/cytoscape.esm-nTrd5EVq.js +321 -0
  38. package/dist/app/assets/d3-scale-CaJQQYkF.js +1 -0
  39. package/dist/app/assets/dagre-SPEB5RXH-BaSAny1T.js +4 -0
  40. package/dist/app/assets/diagram-3B7GL73J-DJNlt5Sg.js +200 -0
  41. package/dist/app/assets/diagram-DNEMPZML-DEHeuILB.js +24 -0
  42. package/dist/app/assets/diagram-L3MUGCDN-ob5Ka2Xc.js +41 -0
  43. package/dist/app/assets/diagram-LA4NIPWU-DNESzFAc.js +24 -0
  44. package/dist/app/assets/diagram-MHCOC4E2-CVi9zKjG.js +3 -0
  45. package/dist/app/assets/diagram-XPFHEONP-DInT4C7e.js +30 -0
  46. package/dist/app/assets/dist-CjvHN74u.js +1 -0
  47. package/dist/app/assets/ebnfDiagram-UZSYDL2S-CRCZNsji.js +1 -0
  48. package/dist/app/assets/elk-XV6XMXQE-D4fsWI2l.js +2 -0
  49. package/dist/app/assets/erDiagram-EYBAPDEH-YQNM5StV.js +99 -0
  50. package/dist/app/assets/eventmodeling-K75KTNOO-Bev08J2F.js +1 -0
  51. package/dist/app/assets/flowDiagram-MALGAFMO-BhJ554DH.js +1 -0
  52. package/dist/app/assets/ganttDiagram-23REXITY-CkaBMYM4.js +292 -0
  53. package/dist/app/assets/gitGraph-VSP46ZUC-CtbZ0sIS.js +1 -0
  54. package/dist/app/assets/gitGraphDiagram-STJD7YCW-D15ZdQ-Z.js +106 -0
  55. package/dist/app/assets/graphlib-DS17s2tU.js +1 -0
  56. package/dist/app/assets/index-Bn6_wHEp.js +98 -0
  57. package/dist/app/assets/index-H-Z7MFhZ.css +1 -0
  58. package/dist/app/assets/info-OHQRW6UA-CfUW1XFR.js +1 -0
  59. package/dist/app/assets/infoDiagram-KBXO4MBG-DT7LbBRQ.js +2 -0
  60. package/dist/app/assets/ishikawaDiagram-M35NCXHK-CF51lhjB.js +70 -0
  61. package/dist/app/assets/journeyDiagram-OPLOXDXO-_36FonKk.js +139 -0
  62. package/dist/app/assets/kanban-definition-BZKZHSQY-tLk_OlQ-.js +89 -0
  63. package/dist/app/assets/katex-MEuSR36T.js +257 -0
  64. package/dist/app/assets/mermaid-parser.core-_3Vo8x6b.js +7 -0
  65. package/dist/app/assets/mermaid.core-y-x1CYxC.js +44 -0
  66. package/dist/app/assets/mindmap-definition-I2QAS2VK-BCI4HRX3.js +98 -0
  67. package/dist/app/assets/packet-JDAUHWVQ-Cco3UoaI.js +1 -0
  68. package/dist/app/assets/pegDiagram-FD4XPPHP-BOzSoNji.js +1 -0
  69. package/dist/app/assets/pie-XZMESJXO-reOB2GXn.js +1 -0
  70. package/dist/app/assets/pieDiagram-J4AKIIQI-PlHpwT_c.js +39 -0
  71. package/dist/app/assets/quadrantDiagram-XTYBLID2-CdxZ0ael.js +7 -0
  72. package/dist/app/assets/radar-ABXABTNO-DfCl8uV2.js +1 -0
  73. package/dist/app/assets/railroad-I3PHUGI6-4s14UyW1.js +1 -0
  74. package/dist/app/assets/railroad-abnf-LNEFI6M7-C49jJE4Y.js +1 -0
  75. package/dist/app/assets/railroad-ebnf-DWYD2UWJ-Bx-pcPc7.js +1 -0
  76. package/dist/app/assets/railroad-peg-JR7BVNR7-DjBPSCKV.js +1 -0
  77. package/dist/app/assets/railroadDiagram-MRQ6NCDL-wGcmIMqq.js +1 -0
  78. package/dist/app/assets/requirementDiagram-Y7LWUY3S-DprFI03z.js +84 -0
  79. package/dist/app/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  80. package/dist/app/assets/rough.esm-Dy-Kn_BL.js +1 -0
  81. package/dist/app/assets/sankeyDiagram-WGJFYUXA-DygYWLTR.js +40 -0
  82. package/dist/app/assets/sequenceDiagram-5NDRBG5M-BzIr2DBO.js +169 -0
  83. package/dist/app/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
  84. package/dist/app/assets/stateDiagram-v2-FJ4FJNEA-MGCqKnm_.js +291 -0
  85. package/dist/app/assets/swimlanes-UMQ2AFYF-CIEH82Zt.js +1 -0
  86. package/dist/app/assets/swimlanesDiagram-OMPLPG4O-YWNJjl0g.js +8 -0
  87. package/dist/app/assets/timeline-definition-SEUHKTQE-BGYSqup2.js +120 -0
  88. package/dist/app/assets/treeView-D4JQ5SDB-B39o1sJo.js +1 -0
  89. package/dist/app/assets/treemap-SAJKECNS-BoGxrUH4.js +1 -0
  90. package/dist/app/assets/usecaseDiagram-AFA6YXN4-dy6oVOke.js +328 -0
  91. package/dist/app/assets/vennDiagram-NNMJR3RB-CUyuhcAk.js +34 -0
  92. package/dist/app/assets/wardley-7MLQ67FV-sYPAvQ06.js +1 -0
  93. package/dist/app/assets/wardleyDiagram-S7YFUSEH-DYtxYUHe.js +78 -0
  94. package/dist/app/assets/xychartDiagram-GGNKY7IX-ClR06AlB.js +7 -0
  95. package/dist/app/index.html +14 -0
  96. package/dist/cli/index.js +338 -0
  97. package/dist/core/api.js +420 -0
  98. package/dist/core/approvals.js +426 -0
  99. package/dist/core/context.js +259 -0
  100. package/dist/core/diff.js +156 -0
  101. package/dist/core/docs.js +140 -0
  102. package/dist/core/doctor.js +152 -0
  103. package/dist/core/doctypes.js +79 -0
  104. package/dist/core/edit.js +130 -0
  105. package/dist/core/errors.js +3 -0
  106. package/dist/core/flags.js +13 -0
  107. package/dist/core/gaps.js +119 -0
  108. package/dist/core/heading.js +4 -0
  109. package/dist/core/history.js +50 -0
  110. package/dist/core/home.js +345 -0
  111. package/dist/core/lanes.js +134 -0
  112. package/dist/core/launch.js +34 -0
  113. package/dist/core/layout.js +362 -0
  114. package/dist/core/links.js +68 -0
  115. package/dist/core/mermaid.js +175 -0
  116. package/dist/core/newdoc.js +66 -0
  117. package/dist/core/open-folder.js +30 -0
  118. package/dist/core/openspec.js +120 -0
  119. package/dist/core/paths.js +90 -0
  120. package/dist/core/project.js +392 -0
  121. package/dist/core/resolve.js +35 -0
  122. package/dist/core/route.js +420 -0
  123. package/dist/core/scan.js +514 -0
  124. package/dist/core/schema.js +270 -0
  125. package/dist/core/scope.js +126 -0
  126. package/dist/core/setup.js +134 -0
  127. package/dist/core/skills.js +181 -0
  128. package/dist/core/storage/config.js +74 -0
  129. package/dist/core/storage/events.js +54 -0
  130. package/dist/core/storage/folder-watch.js +147 -0
  131. package/dist/core/storage/folder.js +469 -0
  132. package/dist/core/storage/index.js +8 -0
  133. package/dist/core/storage/local.js +22 -0
  134. package/dist/core/storage/migrate.js +48 -0
  135. package/dist/core/storage/postgres.js +290 -0
  136. package/dist/core/storage/types.js +101 -0
  137. package/dist/core/storage.js +589 -0
  138. package/dist/core/suggest.js +283 -0
  139. package/dist/core/tree.js +254 -0
  140. package/dist/core/types.js +583 -0
  141. package/dist/core/version.js +1 -0
  142. package/dist/core/versions.js +245 -0
  143. package/dist/core/watch.js +2 -0
  144. package/dist/core/xml.js +68 -0
  145. package/dist/demo/args.js +58 -0
  146. package/dist/demo/browser.js +301 -0
  147. package/dist/demo/platform.js +147 -0
  148. package/dist/demo/run.js +198 -0
  149. package/dist/demo/steps.js +328 -0
  150. package/dist/mcp/project-tools.js +193 -0
  151. package/dist/mcp/server.js +785 -0
  152. package/examples/platform/README.md +33 -0
  153. package/examples/platform/api/package.json +8 -0
  154. package/examples/platform/api/src/auth-middleware.js +16 -0
  155. package/examples/platform/api/src/proxy.js +7 -0
  156. package/examples/platform/api/src/rate-limit.js +13 -0
  157. package/examples/platform/api/src/server.js +40 -0
  158. package/examples/platform/auth/package.json +9 -0
  159. package/examples/platform/auth/src/server.js +24 -0
  160. package/examples/platform/auth/src/tokens.js +19 -0
  161. package/examples/platform/auth/src/users.js +16 -0
  162. package/examples/platform/docs/api/PRD.md +10 -0
  163. package/examples/platform/docs/api/SDD.md +15 -0
  164. package/examples/platform/docs/auth/PRD.md +10 -0
  165. package/examples/platform/docs/auth/SDD.md +8 -0
  166. package/examples/platform/docs/frontend/PRD.md +18 -0
  167. package/examples/platform/docs/frontend/SDD.md +13 -0
  168. package/examples/platform/docs/pricing/PRD.md +9 -0
  169. package/examples/platform/docs/pricing/SDD.md +8 -0
  170. package/examples/platform/docs/products/PRD.md +9 -0
  171. package/examples/platform/docs/products/SDD.md +8 -0
  172. package/examples/platform/frontend/package.json +8 -0
  173. package/examples/platform/frontend/src/api-client.js +21 -0
  174. package/examples/platform/frontend/src/main.js +21 -0
  175. package/examples/platform/frontend/src/pages/products.js +12 -0
  176. package/examples/platform/frontend/src/pages/sign-in.js +14 -0
  177. package/examples/platform/frontend/src/session.js +11 -0
  178. package/examples/platform/pricing/package.json +9 -0
  179. package/examples/platform/pricing/src/cache.js +19 -0
  180. package/examples/platform/pricing/src/product-events.js +17 -0
  181. package/examples/platform/pricing/src/rules.js +19 -0
  182. package/examples/platform/pricing/src/server.js +32 -0
  183. package/examples/platform/products/package.json +9 -0
  184. package/examples/platform/products/src/catalog.js +20 -0
  185. package/examples/platform/products/src/events.js +11 -0
  186. package/examples/platform/products/src/search.js +9 -0
  187. package/examples/platform/products/src/server.js +31 -0
  188. package/migrations/postgres/001_init.sql +55 -0
  189. package/migrations/postgres/002_view_versions.sql +18 -0
  190. package/package.json +69 -4
  191. package/schema/approval.schema.json +173 -0
  192. package/schema/gap.schema.json +56 -0
  193. package/schema/pins.schema.json +122 -0
  194. package/schema/project.schema.json +93 -0
  195. package/schema/settings.schema.json +86 -0
  196. package/schema/toolbox.schema.json +206 -0
  197. package/schema/type.schema.json +121 -0
  198. package/schema/view.schema.json +240 -0
  199. package/skills/claude/build-gap/SKILL.md +28 -0
  200. package/skills/claude/check-ui/SKILL.md +40 -0
  201. package/skills/claude/draw-system/SKILL.md +38 -0
  202. package/skills/claude/gap-from-view/SKILL.md +29 -0
  203. package/skills/claude/post-audit/SKILL.md +58 -0
  204. package/skills/claude/pre-audit/SKILL.md +82 -0
  205. package/skills/claude/update-state/SKILL.md +56 -0
  206. package/skills/cursor/check-ui.mdc +40 -0
  207. package/skills/cursor/draw-system.mdc +38 -0
  208. package/skills/cursor/post-audit.mdc +44 -0
  209. package/skills/cursor/pre-audit.mdc +49 -0
  210. package/skills/cursor/update-state.mdc +45 -0
  211. package/skills/windsurf/spatial-views.md +212 -0
  212. package/toolboxes/aws.yaml +43 -0
  213. package/toolboxes/azure.yaml +41 -0
  214. package/toolboxes/cloud.yaml +95 -0
  215. package/toolboxes/docs.yaml +111 -0
  216. package/toolboxes/software.yaml +114 -0
  217. package/toolboxes/types/docs/gap.yaml +15 -0
  218. package/toolboxes/types/docs/mdd.yaml +19 -0
  219. package/toolboxes/types/docs/plain.yaml +7 -0
  220. package/toolboxes/types/docs/prd.yaml +17 -0
@@ -0,0 +1,589 @@
1
+ import { z } from "zod";
2
+ import { basename, join, relative, resolve, sep } from "node:path";
3
+ import { repoPath } from "./paths.js";
4
+ import { UserError } from "./errors.js";
5
+ import { GapSchema, PinsFileSchema, ViewSchema, summarize, } from "./schema.js";
6
+ import { FolderStore } from "./storage/folder.js";
7
+ import { writeOpen } from "./storage/local.js";
8
+ import { canonical, ConflictError } from "./storage/types.js";
9
+ import { HUMAN, Versions, summarizeDoc, summarizeView, withVersion } from "./versions.js";
10
+ export { jsonText, writeJson, writeText } from "./storage/folder.js";
11
+ export { ConflictError } from "./storage/types.js";
12
+ export class NotFoundError extends UserError {
13
+ }
14
+ const ID = /^[A-Za-z0-9_-]+$/;
15
+ /** The folder store over one data folder (the default, and the 0.1.0 single-repo layout). */
16
+ export function folderRef(dataDir, root = dataDir, slug = basename(resolve(root))) {
17
+ return { storage: FolderStore.single({ dataDir, root, slug }), project: slug };
18
+ }
19
+ /**
20
+ * Has a person ever approved this content? Yes when a version of it was saved
21
+ * by a person (the canvas) or by approving an Approval, or when it has no
22
+ * versions at all (it was there before versions were kept). Content only the
23
+ * AI has written (new in this project, or new from pre-audit) has not: AI
24
+ * writes to it apply directly, with no Approval.
25
+ */
26
+ export function everApproved(versions) {
27
+ return !versions.length || versions.some((v) => v.by === HUMAN || /^approved /.test(v.note ?? ""));
28
+ }
29
+ /** One object per item (a JSON file in the folder store, a row in Postgres), validated on read and on write. */
30
+ class JsonDir {
31
+ dir;
32
+ schema;
33
+ noun;
34
+ target;
35
+ kind;
36
+ ref;
37
+ stage;
38
+ constructor(dir, schema, noun, target, kind, ref, stage) {
39
+ this.dir = dir;
40
+ this.schema = schema;
41
+ this.noun = noun;
42
+ this.target = target;
43
+ this.kind = kind;
44
+ this.ref = ref;
45
+ this.stage = stage;
46
+ }
47
+ async staging() {
48
+ return !!this.stage && (await this.stage.active());
49
+ }
50
+ /**
51
+ * Does a write to this item wait in Approvals? Only when approvals are on and
52
+ * it changes approved content (or a pending Approval already holds it). New
53
+ * content, and content no person has approved yet, is written directly.
54
+ */
55
+ async stages(id) {
56
+ if (!(await this.staging()))
57
+ return false;
58
+ return (await this.stage.pending(this.target, id)) || (await this.approved(id));
59
+ }
60
+ /** Has a person approved this item? (No item: no.) Views look at their versions. */
61
+ async approved(id) {
62
+ return (await this.ref.storage.get(this.kind, this.ref.project, this.check(id))) !== null;
63
+ }
64
+ check(id) {
65
+ if (!ID.test(id))
66
+ throw new NotFoundError(`no ${this.noun} ${id}`);
67
+ return id;
68
+ }
69
+ async all() {
70
+ const live = await this.liveAll();
71
+ if (!(await this.staging()))
72
+ return live;
73
+ const staged = new Map((await this.stage.all(this.target)).map((x) => [x.ref, x.value]));
74
+ const out = live.filter((x) => !staged.has(x.id) || staged.get(x.id) !== null).map((x) => (staged.has(x.id) ? this.schema.parse(staged.get(x.id)) : x));
75
+ const have = new Set(live.map((x) => x.id));
76
+ for (const [ref, value] of [...staged].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
77
+ if (!have.has(ref) && value !== null)
78
+ out.push(this.schema.parse(value));
79
+ return out;
80
+ }
81
+ /** Every item in the store, ignoring any approval. */
82
+ async liveAll() {
83
+ const items = [];
84
+ for (const it of await this.ref.storage.list(this.kind, this.ref.project)) {
85
+ try {
86
+ items.push(this.schema.parse(it.data));
87
+ }
88
+ catch {
89
+ // A broken item is left alone; it must not hide the others.
90
+ }
91
+ }
92
+ return items;
93
+ }
94
+ async get(id) {
95
+ if (await this.staging()) {
96
+ const hit = await this.stage.read(this.target, id);
97
+ if (hit) {
98
+ if (hit.value === null)
99
+ throw new NotFoundError(`no ${this.noun} ${id}`);
100
+ return this.schema.parse(hit.value);
101
+ }
102
+ }
103
+ return this.liveGet(id);
104
+ }
105
+ /** The item and its version (for a save with an expected version), ignoring any approval. */
106
+ async liveItem(id) {
107
+ const it = await this.ref.storage.get(this.kind, this.ref.project, this.check(id));
108
+ if (!it)
109
+ throw new NotFoundError(`no ${this.noun} ${id}`);
110
+ return { value: this.schema.parse(it.data), version: it.version };
111
+ }
112
+ /** The item in the store, ignoring any approval. */
113
+ async liveGet(id) {
114
+ return (await this.liveItem(id)).value;
115
+ }
116
+ async has(id) {
117
+ try {
118
+ await this.get(id);
119
+ return true;
120
+ }
121
+ catch {
122
+ return false;
123
+ }
124
+ }
125
+ /** Save; with `expected` (a version from liveItem, or null for new) it is refused with a ConflictError if someone saved first. */
126
+ async save(item, opts = {}) {
127
+ const clean = this.schema.parse(item);
128
+ this.check(clean.id);
129
+ if (await this.stages(clean.id)) {
130
+ await this.stage.write(this.target, clean.id, await this.liveGet(clean.id).catch(() => null), clean);
131
+ return clean;
132
+ }
133
+ await this.ref.storage.put(this.kind, this.ref.project, clean.id, clean, opts);
134
+ return clean;
135
+ }
136
+ /** The version of the item now (null: none), for an approval's conflict check. */
137
+ async version(id) {
138
+ return (await this.ref.storage.get(this.kind, this.ref.project, this.check(id)))?.version ?? null;
139
+ }
140
+ async remove(id) {
141
+ this.check(id);
142
+ if (!(await this.has(id)))
143
+ throw new NotFoundError(`no ${this.noun} ${id}`);
144
+ if (await this.stages(id)) {
145
+ await this.stage.write(this.target, id, await this.liveGet(id).catch(() => null), null);
146
+ return;
147
+ }
148
+ await this.ref.storage.delete(this.kind, this.ref.project, id);
149
+ }
150
+ /** The write that puts `value` live (null removes it), for an atomic approve. */
151
+ op(id, value, expected) {
152
+ this.check(id);
153
+ return value === null
154
+ ? { op: "delete", kind: this.kind, project: this.ref.project, id, expected }
155
+ : { op: "put", kind: this.kind, project: this.ref.project, id, data: this.schema.parse(value), expected };
156
+ }
157
+ }
158
+ /** How many unnamed versions each View keeps (settings `keep_versions`; undefined: all of them). */
159
+ export async function keepVersions(ref) {
160
+ const it = await ref.storage.get("settings", ref.project, "settings").catch(() => null);
161
+ const n = it?.data?.keep_versions;
162
+ return typeof n === "number" && Number.isInteger(n) && n > 0 ? n : undefined;
163
+ }
164
+ /**
165
+ * Views live one per file in `<data>/views/<id>.json` (`<repo>/.spatial/views/` for a repo).
166
+ * Every live save also writes a version (`views/<id>/versions/<n>.json`), in the same transaction.
167
+ */
168
+ export class ViewStore extends JsonDir {
169
+ actor;
170
+ versions;
171
+ constructor(repoRoot, dataDir = join(repoRoot, ".spatial"), stage, ref = folderRef(dataDir, repoRoot),
172
+ /** Who saves: "human" for the canvas, the AI client's name for MCP. */
173
+ actor = () => HUMAN) {
174
+ super(join(dataDir, "views"), ViewSchema, "View", "view", "view", ref, stage);
175
+ this.actor = actor;
176
+ this.versions = new Versions(ref.storage, ref.project, "view_version", (x) => ViewSchema.parse(x), summarizeView);
177
+ }
178
+ async approved(id) {
179
+ if (!(await super.approved(id)))
180
+ return false;
181
+ return everApproved(await this.versions.history(id));
182
+ }
183
+ /** Save, and write the new version with it (staged saves are versioned when approved). */
184
+ async save(item, opts = {}) {
185
+ if (await this.stages(item.id))
186
+ return super.save(item);
187
+ const clean = ViewSchema.parse(item);
188
+ this.check(clean.id);
189
+ const meta = { by: opts.by || this.actor(), ...(opts.note ? { note: opts.note } : {}), ...(opts.restored_from ? { restored_from: opts.restored_from } : {}) };
190
+ await withVersion(this.ref.storage, () => this.ops(clean.id, clean, opts.expected, meta), meta.by);
191
+ await this.versions.prune(clean.id, await keepVersions(this.ref));
192
+ return clean;
193
+ }
194
+ /** The writes that put a View live (null removes it; its versions stay) and record its version. */
195
+ async ops(id, value, expected, meta = {}) {
196
+ this.check(id);
197
+ if (value === null)
198
+ return [{ op: "delete", kind: "view", project: this.ref.project, id, ...(expected !== undefined ? { expected } : {}) }];
199
+ const clean = ViewSchema.parse(value);
200
+ const ops = [{ op: "put", kind: "view", project: this.ref.project, id, data: clean, ...(expected !== undefined ? { expected } : {}) }];
201
+ const v = await this.versions.op(id, clean, { by: meta.by || this.actor(), ...meta });
202
+ if (v)
203
+ ops.push(v);
204
+ return ops;
205
+ }
206
+ /**
207
+ * Delete a View (the Project panel's Delete). It is kept as a version first
208
+ * (when the newest version isn't it already), so it can be restored. Modules
209
+ * in other Views that link to it lose the link, each as a new version of
210
+ * its View, in the same write.
211
+ */
212
+ async delete(id, by) {
213
+ const cur = await this.liveGet(this.check(id));
214
+ const who = by || this.actor();
215
+ const linking = (await this.liveAll()).filter((v) => v.id !== id && v.modules.some((m) => m.linked_view_id === id));
216
+ await withVersion(this.ref.storage, async () => {
217
+ const keep = await this.versions.op(id, cur, { by: who, note: "deleted" });
218
+ const unlink = [];
219
+ for (const v of linking) {
220
+ const next = { ...v, modules: v.modules.map((m) => (m.linked_view_id === id ? (({ linked_view_id: _drop, ...rest }) => rest)(m) : m)) };
221
+ unlink.push(...(await this.ops(v.id, next, undefined, { by: who, note: `link to ${cur.name} removed (deleted)` })));
222
+ }
223
+ return [...(keep ? [keep] : []), { op: "delete", kind: "view", project: this.ref.project, id }, ...unlink];
224
+ }, who);
225
+ }
226
+ /** Restore: write version `n` as a new version ("restored from vN"). Nothing is deleted. */
227
+ async restore(id, n, opts = {}) {
228
+ const v = await this.versions.get(this.check(id), n);
229
+ return this.save({ ...v.data, id }, { ...opts, note: opts.note?.trim() || `restored from v${n}`, restored_from: n });
230
+ }
231
+ /**
232
+ * Name a version. Without `n`: the View as it is now (a snapshot, "before
233
+ * pre-audit"), written as a new version first if no version holds it yet.
234
+ */
235
+ async nameVersion(id, name, n, by) {
236
+ this.check(id);
237
+ if (n === undefined) {
238
+ const cur = await this.liveGet(id);
239
+ const who = by || this.actor();
240
+ await withVersion(this.ref.storage, async () => {
241
+ const op = await this.versions.op(id, cur, { by: who, note: "snapshot" });
242
+ return op ? [op] : [];
243
+ }, who);
244
+ n = (await this.versions.latest(id)).n;
245
+ }
246
+ return this.versions.name(id, n, name);
247
+ }
248
+ listViews() {
249
+ return this.all();
250
+ }
251
+ async list() {
252
+ return (await this.all()).map(summarize);
253
+ }
254
+ }
255
+ /** Gaps live one per file in `<data>/gaps/<id>.json`. */
256
+ export class GapStore extends JsonDir {
257
+ constructor(repoRoot, dataDir = join(repoRoot, ".spatial"), stage, ref = folderRef(dataDir, repoRoot)) {
258
+ super(join(dataDir, "gaps"), GapSchema, "Gap", "gap", "gap", ref, stage);
259
+ }
260
+ }
261
+ export function samePin(a, b) {
262
+ return JSON.stringify(normalPin(a)) === JSON.stringify(normalPin(b));
263
+ }
264
+ function normalPin(p) {
265
+ switch (p.kind) {
266
+ case "view":
267
+ return { path: p.path, kind: p.kind, view_id: p.view_id };
268
+ case "module":
269
+ return { path: p.path, kind: p.kind, view_id: p.view_id, module_id: p.module_id };
270
+ case "feature":
271
+ return { path: p.path, kind: p.kind, view_id: p.view_id, feature_id: p.feature_id };
272
+ case "gap":
273
+ return { path: p.path, kind: p.kind, gap_id: p.gap_id };
274
+ }
275
+ }
276
+ /** The pin map (`<data>/pins.json` in the folder store). */
277
+ export class PinStore {
278
+ stage;
279
+ ref;
280
+ viewApproved;
281
+ file;
282
+ constructor(repoRoot, dataDir = join(repoRoot, ".spatial"), stage, ref = folderRef(dataDir, repoRoot),
283
+ /** Has a person approved this View? A pin on one that hasn't is written directly. */
284
+ viewApproved = async () => true) {
285
+ this.stage = stage;
286
+ this.ref = ref;
287
+ this.viewApproved = viewApproved;
288
+ this.file = join(dataDir, "pins.json");
289
+ }
290
+ async staging() {
291
+ return !!this.stage && (await this.stage.active());
292
+ }
293
+ /**
294
+ * Does this pin map wait in Approvals? Only when it changes pins on a View a
295
+ * person has approved, or the sources (or a pending Approval holds the map).
296
+ */
297
+ async stages(next) {
298
+ if (!(await this.staging()))
299
+ return false;
300
+ if (await this.stage.pending("pins", "pins"))
301
+ return true;
302
+ const live = await this.liveItem().then((x) => x?.value ?? { sources: [], pins: [] }, () => ({ sources: [], pins: [] }));
303
+ if (live.sources.length && canonical(live.sources) !== canonical(next.sources))
304
+ return true;
305
+ const changed = [...live.pins.filter((p) => !next.pins.some((q) => samePin(p, q))), ...next.pins.filter((p) => !live.pins.some((q) => samePin(p, q)))];
306
+ // A pin on a Gap waits for approval like the Gap.
307
+ if (changed.some((p) => p.kind === "gap"))
308
+ return true;
309
+ for (const id of new Set(changed.flatMap((p) => (p.kind === "gap" ? [] : [p.view_id]))))
310
+ if (await this.viewApproved(id))
311
+ return true;
312
+ return false;
313
+ }
314
+ async read() {
315
+ if (await this.staging()) {
316
+ const hit = await this.stage.read("pins", "pins");
317
+ if (hit && hit.value !== null)
318
+ return PinsFileSchema.parse(hit.value);
319
+ }
320
+ return this.liveRead();
321
+ }
322
+ /** The pin map in the store, ignoring any approval. */
323
+ async liveRead() {
324
+ return (await this.liveItem())?.value ?? { sources: [], pins: [] };
325
+ }
326
+ async liveItem() {
327
+ const it = await this.ref.storage.get("pins", this.ref.project, "pins");
328
+ return it ? { value: PinsFileSchema.parse(it.data), version: it.version } : null;
329
+ }
330
+ async write(data) {
331
+ const clean = PinsFileSchema.parse(data);
332
+ if (await this.stages(clean)) {
333
+ const live = await this.liveItem().then((x) => x?.value ?? null, () => null);
334
+ await this.stage.write("pins", "pins", live, clean);
335
+ return clean;
336
+ }
337
+ await this.ref.storage.put("pins", this.ref.project, "pins", clean);
338
+ return clean;
339
+ }
340
+ /**
341
+ * Read, change and write the map. Live, it retries if another client wrote in
342
+ * between (an expected-version put), so two canvases adding pins keep both.
343
+ */
344
+ async change(fn) {
345
+ if (await this.staging()) {
346
+ const r = fn(await this.read());
347
+ if (!r.next)
348
+ return r.out;
349
+ if (await this.stages(PinsFileSchema.parse(r.next))) {
350
+ await this.write(r.next);
351
+ return r.out;
352
+ }
353
+ // Not approved content: written directly, below.
354
+ }
355
+ for (let n = 1;; n++) {
356
+ const cur = await this.liveItem();
357
+ const r = fn(cur ? structuredClone(cur.value) : { sources: [], pins: [] });
358
+ if (!r.next)
359
+ return r.out;
360
+ try {
361
+ await this.ref.storage.put("pins", this.ref.project, "pins", PinsFileSchema.parse(r.next), { expected: cur?.version ?? null });
362
+ return r.out;
363
+ }
364
+ catch (err) {
365
+ if (!(err instanceof ConflictError) || n >= 5)
366
+ throw err;
367
+ }
368
+ }
369
+ }
370
+ async list() {
371
+ return (await this.read()).pins;
372
+ }
373
+ /** Add a pin; pinning the same path to the same target again is a no-op. Returns false then. */
374
+ add(pin) {
375
+ return this.change((data) => {
376
+ if (data.pins.some((p) => samePin(p, pin)))
377
+ return { next: null, out: false };
378
+ data.pins.push(normalPin(pin));
379
+ return { next: data, out: true };
380
+ });
381
+ }
382
+ /** Remove matching pins; returns how many went. */
383
+ remove(pin) {
384
+ return this.change((data) => {
385
+ const kept = data.pins.filter((p) => !samePin(p, pin));
386
+ const gone = data.pins.length - kept.length;
387
+ return { next: gone ? { ...data, pins: kept } : null, out: gone };
388
+ });
389
+ }
390
+ addSource(path) {
391
+ return this.change((data) => {
392
+ if (data.sources.includes(path))
393
+ return { next: null, out: false };
394
+ data.sources.push(path);
395
+ return { next: data, out: true };
396
+ });
397
+ }
398
+ op(value, expected) {
399
+ return value === null
400
+ ? { op: "delete", kind: "pins", project: this.ref.project, id: "pins", expected }
401
+ : { op: "put", kind: "pins", project: this.ref.project, id: "pins", data: PinsFileSchema.parse(value), expected };
402
+ }
403
+ }
404
+ /**
405
+ * Docs the tools write (OpenSpec change files, audit reports), by path under the
406
+ * project's root. Only .md files inside it, never in .git/ or the local hand-off folder.
407
+ * Every write keeps a version (DocVersion), in the same transaction.
408
+ */
409
+ export class DocFiles {
410
+ root;
411
+ stage;
412
+ localRel;
413
+ ref;
414
+ actor;
415
+ constructor(root, stage, localRel = ".spatial-local", ref = folderRef(join(root, ".spatial"), root), actor = () => HUMAN) {
416
+ this.root = root;
417
+ this.stage = stage;
418
+ this.localRel = localRel;
419
+ this.ref = ref;
420
+ this.actor = actor;
421
+ this.history = new Versions(ref.storage, ref.project, "doc_version", (x) => z.string().parse(x), summarizeDoc);
422
+ }
423
+ /** Every saved version of every doc, by path. */
424
+ history;
425
+ /** The checked repo path of a doc. */
426
+ rel(path) {
427
+ const rel = repoPath(this.root, path);
428
+ if (!rel.toLowerCase().endsWith(".md") || /^\.git(\/|$)/.test(rel) || rel === this.localRel || rel.startsWith(`${this.localRel}/`) || rel.split("/").includes(".."))
429
+ throw new UserError(`${path}: only .md docs in the project can be written`);
430
+ return rel;
431
+ }
432
+ async liveRead(path) {
433
+ return (await this.liveItem(path))?.value ?? null;
434
+ }
435
+ async liveItem(path) {
436
+ const it = await this.ref.storage.get("doc", this.ref.project, this.rel(path));
437
+ return it ? { value: it.data, version: it.version } : null;
438
+ }
439
+ /** Has a person approved this doc (see everApproved)? A doc that isn't there: no. */
440
+ async approved(path) {
441
+ const rel = this.rel(path);
442
+ if ((await this.liveItem(rel)) === null)
443
+ return false;
444
+ return everApproved(await this.history.history(rel));
445
+ }
446
+ /** Does a write to this doc wait in Approvals (approvals on, and approved content or already pending)? */
447
+ async stages(rel) {
448
+ if (!this.stage || !(await this.stage.active()))
449
+ return false;
450
+ return (await this.stage.pending("doc", rel)) || (await this.approved(rel));
451
+ }
452
+ async read(path) {
453
+ const rel = this.rel(path);
454
+ if (this.stage && (await this.stage.active())) {
455
+ const hit = await this.stage.read("doc", rel);
456
+ if (hit)
457
+ return hit.value;
458
+ }
459
+ return this.liveRead(rel);
460
+ }
461
+ async write(path, text, by) {
462
+ const rel = this.rel(path);
463
+ if (await this.stages(rel)) {
464
+ await this.stage.write("doc", rel, await this.liveRead(rel), text);
465
+ return rel;
466
+ }
467
+ await this.commit([{ rel, text, expected: undefined }], by ? { by } : {});
468
+ return rel;
469
+ }
470
+ /**
471
+ * Delete a doc. Its text is kept as a version first (when the newest version
472
+ * isn't it already), so it can be restored from its history.
473
+ */
474
+ async remove(path, by) {
475
+ const rel = this.rel(path);
476
+ const cur = await this.liveItem(rel);
477
+ if (!cur)
478
+ throw new NotFoundError(`no doc ${rel}`);
479
+ const who = by || this.actor();
480
+ await withVersion(this.ref.storage, async () => {
481
+ const keep = await this.history.op(rel, cur.value, { by: who, note: "deleted" });
482
+ return [...(keep ? [keep] : []), { op: "delete", kind: "doc", project: this.ref.project, id: rel }];
483
+ }, who);
484
+ return rel;
485
+ }
486
+ /** Every saved version of a doc, oldest first. */
487
+ async versions(path) {
488
+ return this.history.list(this.rel(path));
489
+ }
490
+ /** The writes that put docs live and record their versions (null text removes a doc; its versions stay). */
491
+ async ops(docs, meta = {}) {
492
+ const ops = [];
493
+ const by = meta.by || this.actor();
494
+ for (const d of docs) {
495
+ const rel = this.rel(d.rel);
496
+ if (d.text === null) {
497
+ ops.push({ op: "delete", kind: "doc", project: this.ref.project, id: rel, ...(d.expected !== undefined ? { expected: d.expected } : {}) });
498
+ continue;
499
+ }
500
+ ops.push({ op: "put", kind: "doc", project: this.ref.project, id: rel, data: d.text, ...(d.expected !== undefined ? { expected: d.expected } : {}) });
501
+ const v = await this.history.op(rel, d.text, { ...meta, by });
502
+ if (v)
503
+ ops.push(v);
504
+ }
505
+ return ops;
506
+ }
507
+ /** Write docs and their versions in one transaction (a version number taken by another client is retried). */
508
+ async commit(docs, meta = {}) {
509
+ const by = meta.by || this.actor();
510
+ await withVersion(this.ref.storage, () => this.ops(docs, { ...meta, by }), by);
511
+ for (const d of docs)
512
+ if (d.text !== null)
513
+ await this.history.prune(this.rel(d.rel), await keepVersions(this.ref));
514
+ }
515
+ /** Restore: write version `n` of a doc as a new version ("restored from vN"). */
516
+ async restore(path, n, opts = {}) {
517
+ const rel = this.rel(path);
518
+ const v = await this.history.get(rel, n);
519
+ const meta = { ...opts, note: opts.note?.trim() || `restored from v${n}`, restored_from: n };
520
+ if (await this.stages(rel)) {
521
+ await this.stage.write("doc", rel, await this.liveRead(rel), v.data);
522
+ return rel;
523
+ }
524
+ await this.commit([{ rel, text: v.data, expected: undefined }], meta);
525
+ return rel;
526
+ }
527
+ /** Name a version of a doc; without `n`, the doc as it is now (written as a version first if none holds it). */
528
+ async nameVersion(path, name, n, by) {
529
+ const rel = this.rel(path);
530
+ if (n === undefined) {
531
+ const cur = await this.liveRead(rel);
532
+ if (cur === null)
533
+ throw new NotFoundError(`no doc ${rel}`);
534
+ const who = by || this.actor();
535
+ await withVersion(this.ref.storage, async () => {
536
+ const op = await this.history.op(rel, cur, { by: who, note: "snapshot" });
537
+ return op ? [op] : [];
538
+ }, who);
539
+ n = (await this.history.latest(rel)).n;
540
+ }
541
+ return this.history.name(rel, n, name);
542
+ }
543
+ }
544
+ /**
545
+ * One project's data. For a repo (0.1.0, `init`): the repo's `.spatial/`. For a
546
+ * project in the home folder: `~/SpatialViews/projects/<slug>/`, with `root`
547
+ * the same folder. Everything is read and written through `ref.storage`; with
548
+ * Postgres the folder paths only name things (a doc's path, the local hand-off).
549
+ */
550
+ export class Spatial {
551
+ root;
552
+ views;
553
+ gaps;
554
+ pins;
555
+ docs;
556
+ dataDir;
557
+ localDir;
558
+ mode;
559
+ stage;
560
+ ref;
561
+ actor;
562
+ constructor(root, opts = {}) {
563
+ this.root = root;
564
+ this.dataDir = opts.dataDir ?? join(root, ".spatial");
565
+ this.localDir = opts.localDir ?? join(root, ".spatial-local");
566
+ this.mode = opts.mode ?? "repo";
567
+ this.stage = opts.stage;
568
+ this.ref = opts.ref ?? folderRef(this.dataDir, root);
569
+ this.actor = opts.actor ?? (() => HUMAN);
570
+ this.views = new ViewStore(root, this.dataDir, this.stage, this.ref, this.actor);
571
+ this.gaps = new GapStore(root, this.dataDir, this.stage, this.ref);
572
+ this.pins = new PinStore(root, this.dataDir, this.stage, this.ref, (id) => this.views.approved(id).catch(() => true));
573
+ this.docs = new DocFiles(root, this.stage, relative(resolve(root), resolve(this.localDir)).split(sep).join("/"), this.ref, this.actor);
574
+ }
575
+ get storage() {
576
+ return this.ref.storage;
577
+ }
578
+ /** The same project's data, with writes going through `stage` (and saved as `actor`, when given). */
579
+ withStage(stage, actor = this.actor) {
580
+ return new Spatial(this.root, { dataDir: this.dataDir, localDir: this.localDir, mode: this.mode, stage, ref: this.ref, actor });
581
+ }
582
+ /** The local, never-committed UI hand-off file (open_view writes it, the canvas follows it). */
583
+ get openFile() {
584
+ return join(this.localDir, "open.json");
585
+ }
586
+ async requestOpen(viewId) {
587
+ await writeOpen(this.localDir, viewId);
588
+ }
589
+ }