spatial-views 0.0.0-stage → 0.1.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 (125) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +63 -2
  3. package/dist/app/assets/abnfDiagram-S7VZAUFO-BVgtb0Hw.js +1 -0
  4. package/dist/app/assets/architecture-WOLXFQ4H-DxylGHqT.js +1 -0
  5. package/dist/app/assets/architectureDiagram-YGSQEFNW-BrBCHqUH.js +36 -0
  6. package/dist/app/assets/blockDiagram-APKKGZFW-C7fb3MCE.js +140 -0
  7. package/dist/app/assets/bpmnIcons-APHXDYXF-C0jbCElo.js +1 -0
  8. package/dist/app/assets/c4Diagram-KJ2TOQU5-Bkb_0fbd.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-DU4vZ03M.js +2 -0
  12. package/dist/app/assets/chunk-AXFCVDMN-De96BVTB.js +62 -0
  13. package/dist/app/assets/chunk-BG4553SI-J33jsRLV.js +127 -0
  14. package/dist/app/assets/chunk-DQASFODM-Bh85SSGO.js +10 -0
  15. package/dist/app/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
  16. package/dist/app/assets/chunk-HFQBQIA3-CCklgplR.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-B04qR8ED.js +2 -0
  20. package/dist/app/assets/chunk-KS47KZWR-BsqDyyAt.js +1 -0
  21. package/dist/app/assets/chunk-LEVMRMFU-DwxrBz2u.js +1 -0
  22. package/dist/app/assets/chunk-M57EVK23-D9YIHjps.js +1 -0
  23. package/dist/app/assets/chunk-NGNAAXSQ-DI_UYJZ4.js +136 -0
  24. package/dist/app/assets/chunk-OY52VR5R-WB63DeTA.js +88 -0
  25. package/dist/app/assets/chunk-QB3YPZ4I-cHzzKdtb.js +213 -0
  26. package/dist/app/assets/chunk-R3KSYZAL-C7rDagaa.js +1 -0
  27. package/dist/app/assets/chunk-STOXU5M4-CG6pnJtH.js +72 -0
  28. package/dist/app/assets/chunk-TU62E6Q5-BbcGYfy_.js +1 -0
  29. package/dist/app/assets/chunk-X3CZISLH-FMl4PpWt.js +1 -0
  30. package/dist/app/assets/chunk-X4PVCEUW-BUI1Oi3q.js +1 -0
  31. package/dist/app/assets/chunk-XXDRQBXY-DYhK5YW-.js +1 -0
  32. package/dist/app/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
  33. package/dist/app/assets/classDiagram-v2-L25IHNXF-K-k5GTUn.js +217 -0
  34. package/dist/app/assets/cose-bilkent-JH36ORCC-BJmLLpaN.js +1 -0
  35. package/dist/app/assets/cynefin-EF2NZ3EQ-DrzwMKdm.js +1 -0
  36. package/dist/app/assets/cynefinDiagram-L36ESFBY-mkV33_Xx.js +62 -0
  37. package/dist/app/assets/cytoscape.esm-nTrd5EVq.js +321 -0
  38. package/dist/app/assets/d3-scale-ygdFCUH8.js +1 -0
  39. package/dist/app/assets/dagre-SPEB5RXH-BNIymLsu.js +4 -0
  40. package/dist/app/assets/diagram-3B7GL73J-CGOiolFW.js +200 -0
  41. package/dist/app/assets/diagram-DNEMPZML-DZFkHNly.js +24 -0
  42. package/dist/app/assets/diagram-L3MUGCDN-B42GAYLq.js +41 -0
  43. package/dist/app/assets/diagram-LA4NIPWU-BYuLRYId.js +24 -0
  44. package/dist/app/assets/diagram-MHCOC4E2-DGzI6TJG.js +3 -0
  45. package/dist/app/assets/diagram-XPFHEONP-CTBEgDQ8.js +30 -0
  46. package/dist/app/assets/dist-1Q8ng3tu.js +1 -0
  47. package/dist/app/assets/ebnfDiagram-UZSYDL2S-GuMdOCvL.js +1 -0
  48. package/dist/app/assets/elk-XV6XMXQE-BpY3loT5.js +2 -0
  49. package/dist/app/assets/erDiagram-EYBAPDEH-nDZ2PMGl.js +99 -0
  50. package/dist/app/assets/eventmodeling-K75KTNOO-BN42Mgwh.js +1 -0
  51. package/dist/app/assets/flowDiagram-MALGAFMO-BCwwiLzb.js +1 -0
  52. package/dist/app/assets/ganttDiagram-23REXITY-xMRHaU3y.js +292 -0
  53. package/dist/app/assets/gitGraph-VSP46ZUC-DyGq5mdd.js +1 -0
  54. package/dist/app/assets/gitGraphDiagram-STJD7YCW-CDkKLrvO.js +106 -0
  55. package/dist/app/assets/graphlib-DS17s2tU.js +1 -0
  56. package/dist/app/assets/index-BY66fc8Q.js +95 -0
  57. package/dist/app/assets/index-ByetEVbs.css +1 -0
  58. package/dist/app/assets/info-OHQRW6UA-DOBf-fQH.js +1 -0
  59. package/dist/app/assets/infoDiagram-KBXO4MBG-B92P8pjY.js +2 -0
  60. package/dist/app/assets/ishikawaDiagram-M35NCXHK-BRZsbCvK.js +70 -0
  61. package/dist/app/assets/journeyDiagram-OPLOXDXO-Bppwb1oF.js +139 -0
  62. package/dist/app/assets/kanban-definition-BZKZHSQY-ByD_x5cm.js +89 -0
  63. package/dist/app/assets/katex-MEuSR36T.js +257 -0
  64. package/dist/app/assets/mermaid-parser.core-CKmnV0Md.js +7 -0
  65. package/dist/app/assets/mermaid.core-BoRvk1Q-.js +44 -0
  66. package/dist/app/assets/mindmap-definition-I2QAS2VK-fRbUh23C.js +98 -0
  67. package/dist/app/assets/packet-JDAUHWVQ-CgHq03Zj.js +1 -0
  68. package/dist/app/assets/pegDiagram-FD4XPPHP-qIABf6H8.js +1 -0
  69. package/dist/app/assets/pie-XZMESJXO-DtNh3cDE.js +1 -0
  70. package/dist/app/assets/pieDiagram-J4AKIIQI-Bb4RBdrc.js +39 -0
  71. package/dist/app/assets/quadrantDiagram-XTYBLID2-B0CpcVWE.js +7 -0
  72. package/dist/app/assets/radar-ABXABTNO-BS0FcsIX.js +1 -0
  73. package/dist/app/assets/railroad-I3PHUGI6-lO8vfGdI.js +1 -0
  74. package/dist/app/assets/railroad-abnf-LNEFI6M7-BUhw7Iuo.js +1 -0
  75. package/dist/app/assets/railroad-ebnf-DWYD2UWJ-nQNF56LJ.js +1 -0
  76. package/dist/app/assets/railroad-peg-JR7BVNR7-CwvbVIo6.js +1 -0
  77. package/dist/app/assets/railroadDiagram-MRQ6NCDL-Dwr-mPZL.js +1 -0
  78. package/dist/app/assets/requirementDiagram-Y7LWUY3S-Ctv2DKJM.js +84 -0
  79. package/dist/app/assets/rough.esm-Dy-Kn_BL.js +1 -0
  80. package/dist/app/assets/sankeyDiagram-WGJFYUXA-BvKX0eIe.js +40 -0
  81. package/dist/app/assets/sequenceDiagram-5NDRBG5M-Y4YqU2Xt.js +169 -0
  82. package/dist/app/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
  83. package/dist/app/assets/stateDiagram-v2-FJ4FJNEA-DmjIjn4u.js +291 -0
  84. package/dist/app/assets/swimlanes-UMQ2AFYF-B2O5JCjs.js +1 -0
  85. package/dist/app/assets/swimlanesDiagram-OMPLPG4O-DhCl-Cjg.js +8 -0
  86. package/dist/app/assets/timeline-definition-SEUHKTQE-DJJdixAI.js +120 -0
  87. package/dist/app/assets/treeView-D4JQ5SDB-Dd1no4eE.js +1 -0
  88. package/dist/app/assets/treemap-SAJKECNS-t6wtsaki.js +1 -0
  89. package/dist/app/assets/usecaseDiagram-AFA6YXN4-Bp8pXgvR.js +328 -0
  90. package/dist/app/assets/vennDiagram-NNMJR3RB-DYSfZMWT.js +34 -0
  91. package/dist/app/assets/wardley-7MLQ67FV-Bx60QTuu.js +1 -0
  92. package/dist/app/assets/wardleyDiagram-S7YFUSEH-CGJ8qg76.js +78 -0
  93. package/dist/app/assets/xychartDiagram-GGNKY7IX-CRSvraFc.js +7 -0
  94. package/dist/app/index.html +13 -0
  95. package/dist/cli/index.js +110 -0
  96. package/dist/core/api.js +209 -0
  97. package/dist/core/context.js +194 -0
  98. package/dist/core/docs.js +134 -0
  99. package/dist/core/edit.js +105 -0
  100. package/dist/core/errors.js +3 -0
  101. package/dist/core/gaps.js +114 -0
  102. package/dist/core/history.js +19 -0
  103. package/dist/core/links.js +68 -0
  104. package/dist/core/mermaid.js +175 -0
  105. package/dist/core/openspec.js +120 -0
  106. package/dist/core/paths.js +23 -0
  107. package/dist/core/resolve.js +35 -0
  108. package/dist/core/schema.js +101 -0
  109. package/dist/core/skills.js +103 -0
  110. package/dist/core/storage.js +183 -0
  111. package/dist/core/version.js +1 -0
  112. package/dist/core/watch.js +136 -0
  113. package/dist/core/xml.js +50 -0
  114. package/dist/mcp/server.js +357 -0
  115. package/package.json +53 -4
  116. package/schema/gap.schema.json +53 -0
  117. package/schema/pins.schema.json +122 -0
  118. package/schema/view.schema.json +134 -0
  119. package/skills/claude/build-gap/SKILL.md +21 -0
  120. package/skills/claude/draw-system/SKILL.md +23 -0
  121. package/skills/claude/gap-from-view/SKILL.md +22 -0
  122. package/skills/cursor/build-gap.mdc +21 -0
  123. package/skills/cursor/draw-system.mdc +23 -0
  124. package/skills/cursor/gap-from-view.mdc +22 -0
  125. package/skills/windsurf/spatial-views.md +66 -0
@@ -0,0 +1,209 @@
1
+ import { readFile, stat } from "node:fs/promises";
2
+ import { z, ZodError } from "zod";
3
+ import { pathTo, rootView } from "./context.js";
4
+ import { docSources, draftViewFromDoc, importDocs, mermaidBlocks, walkMarkdown } from "./docs.js";
5
+ import { UserError } from "./errors.js";
6
+ import { createGap, listGaps, updateGap } from "./gaps.js";
7
+ import { findChange, hasOpenSpec, listChanges, listSpecs, readChange, resolveChangePath, taskProgress } from "./openspec.js";
8
+ import { absPath, repoPath } from "./paths.js";
9
+ import { GapStateSchema, PinSchema, ViewSchema } from "./schema.js";
10
+ import { NotFoundError } from "./storage.js";
11
+ /**
12
+ * The canvas's local HTTP API over `.spatial/` (127.0.0.1 only):
13
+ * GET /api/views summaries
14
+ * GET /api/views/:id one View (JSON)
15
+ * PUT /api/views/:id save a View
16
+ * GET /api/open the View open_view asked for, with its breadcrumb trail
17
+ * GET /api/trail?view= the breadcrumb trail from the top View down to a View
18
+ * GET /api/gaps every Gap (states follow their OpenSpec change)
19
+ * POST /api/gaps create a Gap from modules (and its OpenSpec change)
20
+ * PATCH /api/gaps/:id change a Gap
21
+ * GET /api/pins the pin map
22
+ * POST /api/pins add a pin; POST /api/pins/remove removes one
23
+ * GET /api/docs doc sources, their .md files, and OpenSpec specs and changes
24
+ * GET /api/doc?path= one .md file, with its Mermaid blocks
25
+ * GET /api/openspec/changes/:id a change: proposal, tasks, design and delta specs
26
+ * POST /api/import import a docs folder ({path})
27
+ * POST /api/draft-view a draft View from a Mermaid flowchart ({path, index})
28
+ * GET /api/events Server-Sent Events, one per change in .spatial/, from
29
+ * MCP or anyone: `view` and `gap` ({id, removed}),
30
+ * `pins`, and `open_view` (open_view asked to show a View)
31
+ * Returns false for any other path, so the caller can serve the app.
32
+ *
33
+ * Only requests addressed to this machine are answered (a Host check against
34
+ * DNS rebinding), and writes must be JSON (so another site's page can't post here).
35
+ */
36
+ export function createApiHandler(spatial, watcher) {
37
+ const store = spatial.views;
38
+ return async function handle(req, res) {
39
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
40
+ const path = url.pathname;
41
+ if (!path.startsWith("/api/"))
42
+ return false;
43
+ const send = (status, body) => {
44
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
45
+ res.end(JSON.stringify(body));
46
+ };
47
+ const host = (req.headers.host ?? "").replace(/:\d+$/, "");
48
+ if (host && !["127.0.0.1", "localhost", "[::1]"].includes(host))
49
+ return send(403, { error: "local only" }), true;
50
+ if (req.method !== "GET" && !(req.headers["content-type"] ?? "").includes("application/json"))
51
+ return send(415, { error: "send JSON" }), true;
52
+ if (path === "/api/events" && req.method === "GET" && watcher) {
53
+ res.writeHead(200, {
54
+ "content-type": "text/event-stream; charset=utf-8",
55
+ "cache-control": "no-cache",
56
+ connection: "keep-alive",
57
+ });
58
+ res.write("retry: 1000\n: connected\n\n");
59
+ // `open` is EventSource's own connection event, so open_view requests go out as `open_view`.
60
+ const name = (e) => (e.type === "open" ? "open_view" : e.type);
61
+ const off = watcher.subscribe((e) => res.write(`event: ${name(e)}\ndata: ${JSON.stringify(e)}\n\n`));
62
+ const ping = setInterval(() => res.write(": ping\n\n"), 25_000);
63
+ req.on("close", () => (off(), clearInterval(ping)));
64
+ return true;
65
+ }
66
+ const route = `${req.method} ${path}`;
67
+ try {
68
+ if (route === "GET /api/open") {
69
+ const raw = await readFile(spatial.openFile, "utf8").catch(() => null);
70
+ const want = raw ? JSON.parse(raw) : {};
71
+ if (!want.view_id || !(await store.has(want.view_id)))
72
+ return send(404, { error: "nothing to open" }), true;
73
+ const views = await store.listViews();
74
+ const root = rootView(views);
75
+ const steps = root ? pathTo(views, root.id, want.view_id) : [];
76
+ return send(200, { view_id: want.view_id, at: want.at, trail: [...steps.map((s) => s.view_id), want.view_id] }), true;
77
+ }
78
+ if (route === "GET /api/trail") {
79
+ const target = url.searchParams.get("view") ?? "";
80
+ if (!(await store.has(target)))
81
+ throw new NotFoundError(`no View ${target}`);
82
+ const views = await store.listViews();
83
+ const root = rootView(views);
84
+ const steps = root ? pathTo(views, root.id, target) : [];
85
+ return send(200, [...steps.map((s) => s.view_id), target]), true;
86
+ }
87
+ // ---- Gaps
88
+ if (route === "GET /api/gaps")
89
+ return send(200, await listGaps(spatial)), true;
90
+ if (route === "POST /api/gaps") {
91
+ const body = z
92
+ .object({
93
+ title: z.string(),
94
+ intent: z.string().optional(),
95
+ view: z.string(),
96
+ modules: z.array(z.string()),
97
+ milestone: z.string().optional(),
98
+ })
99
+ .parse(await readJson(req));
100
+ return send(201, await createGap(spatial, body)), true;
101
+ }
102
+ const gapM = /^PATCH \/api\/gaps\/([^/]+)$/.exec(route);
103
+ if (gapM) {
104
+ const patch = z
105
+ .object({
106
+ title: z.string().optional(),
107
+ intent: z.string().optional(),
108
+ state: GapStateSchema.optional(),
109
+ milestone: z.string().optional(),
110
+ modules: z.array(z.string()).optional(),
111
+ })
112
+ .parse(await readJson(req));
113
+ return send(200, await updateGap(spatial, decodeURIComponent(gapM[1]), patch)), true;
114
+ }
115
+ // ---- Pins
116
+ if (route === "GET /api/pins")
117
+ return send(200, await spatial.pins.read()), true;
118
+ if (route === "POST /api/pins" || route === "POST /api/pins/remove") {
119
+ const pin = PinSchema.parse(await readJson(req));
120
+ pin.path = repoPath(spatial.root, pin.path);
121
+ if (route.endsWith("/remove"))
122
+ return send(200, { removed: await spatial.pins.remove(pin) }), true;
123
+ if (!(await stat(absPath(spatial.root, await resolveChangePath(spatial.root, pin.path))).catch(() => null)))
124
+ throw new UserError(`${pin.path} does not exist`);
125
+ return send(200, { added: await spatial.pins.add(pin) }), true;
126
+ }
127
+ // ---- Docs and OpenSpec
128
+ if (route === "GET /api/docs") {
129
+ const sources = await docSources(spatial);
130
+ const docs = [];
131
+ for (const s of sources)
132
+ docs.push({ source: s, files: await walkMarkdown(spatial.root, s) });
133
+ let openspec = null;
134
+ if (await hasOpenSpec(spatial.root)) {
135
+ const changes = [];
136
+ for (const c of await listChanges(spatial.root)) {
137
+ const tasks = await readFile(absPath(spatial.root, `${c.path}/tasks.md`), "utf8").catch(() => "");
138
+ changes.push({ ...c, progress: taskProgress(tasks) });
139
+ }
140
+ openspec = { specs: await listSpecs(spatial.root), changes };
141
+ }
142
+ return send(200, { sources, docs, openspec }), true;
143
+ }
144
+ if (route === "GET /api/doc") {
145
+ const rel = await resolveChangePath(spatial.root, repoPath(spatial.root, url.searchParams.get("path") ?? ""));
146
+ if (!rel.toLowerCase().endsWith(".md") || rel.startsWith(".spatial-local/"))
147
+ throw new UserError("only .md docs are served");
148
+ const text = await readFile(absPath(spatial.root, rel), "utf8").catch(() => {
149
+ throw new NotFoundError(`no doc ${rel}`);
150
+ });
151
+ const mermaid = mermaidBlocks(text).map(({ index, title, flowchart }) => ({ index, title, flowchart }));
152
+ return send(200, { path: rel, text, mermaid }), true;
153
+ }
154
+ const chM = /^GET \/api\/openspec\/changes\/([^/]+)$/.exec(route);
155
+ if (chM) {
156
+ const entry = await findChange(spatial.root, decodeURIComponent(chM[1]));
157
+ if (!entry)
158
+ throw new NotFoundError(`no OpenSpec change ${chM[1]}`);
159
+ return send(200, await readChange(spatial.root, entry)), true;
160
+ }
161
+ if (route === "POST /api/import") {
162
+ const { path: p } = z.object({ path: z.string() }).parse(await readJson(req));
163
+ return send(200, await importDocs(spatial, p, false)), true;
164
+ }
165
+ if (route === "POST /api/draft-view") {
166
+ const b = z.object({ path: z.string(), index: z.number().int().min(1) }).parse(await readJson(req));
167
+ return send(200, await draftViewFromDoc(spatial, b.path, b.index)), true;
168
+ }
169
+ // ---- Views
170
+ const m = /^\/api\/views(?:\/([^/]+))?$/.exec(path);
171
+ if (!m)
172
+ return send(404, { error: "not found" }), true;
173
+ const id = m[1] ? decodeURIComponent(m[1]) : undefined;
174
+ if (req.method === "GET" && !id)
175
+ return send(200, await store.list()), true;
176
+ if (req.method === "GET" && id)
177
+ return send(200, await store.get(id)), true;
178
+ if (req.method === "PUT" && id) {
179
+ const view = ViewSchema.parse(await readJson(req));
180
+ if (view.id !== id)
181
+ return send(400, { error: "the body's id must match the path" }), true;
182
+ return send(200, await store.save(view)), true;
183
+ }
184
+ return send(405, { error: "method not allowed" }), true;
185
+ }
186
+ catch (err) {
187
+ if (err instanceof NotFoundError)
188
+ return send(404, { error: err.message }), true;
189
+ if (err instanceof UserError)
190
+ return send(400, { error: err.message }), true;
191
+ if (err instanceof ZodError)
192
+ return send(400, { error: err.issues.map((i) => i.message).join("; ") }), true;
193
+ if (err instanceof SyntaxError)
194
+ return send(400, { error: String(err.message) }), true;
195
+ return send(500, { error: "internal error" }), true;
196
+ }
197
+ };
198
+ }
199
+ async function readJson(req) {
200
+ const chunks = [];
201
+ let size = 0;
202
+ for await (const chunk of req) {
203
+ size += chunk.length;
204
+ if (size > 5_000_000)
205
+ throw new SyntaxError("body too large");
206
+ chunks.push(chunk);
207
+ }
208
+ return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
209
+ }
@@ -0,0 +1,194 @@
1
+ import { readFile, readdir, stat } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { resolveGap, syncGap } from "./gaps.js";
4
+ import { resolveChangePath } from "./openspec.js";
5
+ import { absPath } from "./paths.js";
6
+ import { attr, cdata, esc, viewToXml } from "./xml.js";
7
+ const MAX_FILE = 100_000;
8
+ const MAX_DIR_FILES = 25;
9
+ /** A rough token count (about four characters a token), so callers can see the cost. */
10
+ export const countTokens = (s) => Math.ceil(s.length / 4);
11
+ export function pinKind(path) {
12
+ if (path.startsWith("openspec/specs/"))
13
+ return "spec";
14
+ if (path.startsWith("openspec/changes/"))
15
+ return "change";
16
+ return path.toLowerCase().endsWith(".md") ? "doc" : "file";
17
+ }
18
+ /** The top of the picture: the high-level View, else a View no other View links to. */
19
+ export function rootView(views) {
20
+ const linked = new Set(views.flatMap((v) => v.modules.map((m) => m.linked_view_id).filter(Boolean)));
21
+ return views.find((v) => v.type === "high-level") ?? views.find((v) => !linked.has(v.id)) ?? views[0] ?? null;
22
+ }
23
+ /** The modules to drill through, from the root down to `targetId` (empty if it is the root or not reachable). */
24
+ export function pathTo(views, rootId, targetId) {
25
+ const byId = new Map(views.map((v) => [v.id, v]));
26
+ const prev = new Map();
27
+ const queue = [rootId];
28
+ const seen = new Set(queue);
29
+ while (queue.length) {
30
+ const v = byId.get(queue.shift());
31
+ if (!v)
32
+ continue;
33
+ for (const m of v.modules) {
34
+ const next = m.linked_view_id;
35
+ if (!next || seen.has(next))
36
+ continue;
37
+ seen.add(next);
38
+ prev.set(next, { view: v, module: m });
39
+ queue.push(next);
40
+ }
41
+ }
42
+ const steps = [];
43
+ for (let at = targetId; prev.has(at);) {
44
+ const p = prev.get(at);
45
+ steps.unshift({ view_id: p.view.id, view_name: p.view.name, module_id: p.module.id, module_name: p.module.name });
46
+ at = p.view.id;
47
+ }
48
+ return steps;
49
+ }
50
+ /** Which pins touch a Gap: its own, its View's, its modules', and Features that hold its modules. */
51
+ export function pinsForGap(pins, gap, view) {
52
+ const mods = new Set(gap.module_ids);
53
+ const features = new Set((view?.features ?? []).filter((f) => f.module_ids.some((id) => mods.has(id))).map((f) => f.id));
54
+ const out = new Map();
55
+ const add = (path, to) => out.set(path, [...(out.get(path) ?? []), to]);
56
+ for (const p of pins) {
57
+ if (p.kind === "gap" && p.gap_id === gap.id)
58
+ add(p.path, `gap:${gap.id}`);
59
+ if (p.kind === "view" && p.view_id === gap.view_id)
60
+ add(p.path, `view:${p.view_id}`);
61
+ if (p.kind === "module" && p.view_id === gap.view_id && mods.has(p.module_id))
62
+ add(p.path, `module:${p.module_id}`);
63
+ if (p.kind === "feature" && p.view_id === gap.view_id && features.has(p.feature_id))
64
+ add(p.path, `feature:${p.feature_id}`);
65
+ }
66
+ if (gap.openspec_change) {
67
+ const change = `openspec/changes/${gap.openspec_change}`;
68
+ if (!out.has(change))
69
+ add(change, `gap:${gap.id}`);
70
+ }
71
+ return out;
72
+ }
73
+ /** Read a pinned path: a file, or the .md files of a folder (an OpenSpec change, say). */
74
+ async function readPinned(root, path) {
75
+ const real = await resolveChangePath(root, path);
76
+ let abs;
77
+ try {
78
+ abs = absPath(root, real);
79
+ }
80
+ catch {
81
+ return [];
82
+ }
83
+ const s = await stat(abs).catch(() => null);
84
+ if (!s)
85
+ return [];
86
+ const one = async (rel, file) => {
87
+ const text = await readFile(file, "utf8").catch(() => "");
88
+ return text.length > MAX_FILE
89
+ ? { path: rel, text: text.slice(0, MAX_FILE), truncated: true }
90
+ : { path: rel, text };
91
+ };
92
+ if (s.isFile())
93
+ return [await one(real, abs)];
94
+ const files = [];
95
+ const walk = async (rel) => {
96
+ const entries = await readdir(join(root, rel), { withFileTypes: true }).catch(() => []);
97
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
98
+ if (files.length >= MAX_DIR_FILES)
99
+ return;
100
+ if (e.isDirectory())
101
+ await walk(`${rel}/${e.name}`);
102
+ else if (e.name.toLowerCase().endsWith(".md"))
103
+ files.push(`${rel}/${e.name}`);
104
+ }
105
+ };
106
+ await walk(real);
107
+ return Promise.all(files.map((f) => one(f, join(root, f))));
108
+ }
109
+ export async function buildContext(spatial, gapRef) {
110
+ const gap = await syncGap(spatial, resolveGap(await spatial.gaps.all(), gapRef));
111
+ const views = await spatial.views.listViews();
112
+ const view = views.find((v) => v.id === gap.view_id) ?? null;
113
+ const root = rootView(views);
114
+ const mods = new Set(gap.module_ids);
115
+ const modules = gap.module_ids.map((id) => view?.modules.find((m) => m.id === id) ?? { id, name: id, x: 0, y: 0, missing: true });
116
+ const nameIn = (id) => view?.modules.find((m) => m.id === id)?.name ?? id;
117
+ const connections = (view?.connections ?? [])
118
+ .filter((c) => mods.has(c.from) || mods.has(c.to))
119
+ .map((c) => ({
120
+ from: c.from,
121
+ to: c.to,
122
+ from_name: nameIn(c.from),
123
+ to_name: nameIn(c.to),
124
+ ...(c.label ? { label: c.label } : {}),
125
+ outside: !(mods.has(c.from) && mods.has(c.to)),
126
+ }));
127
+ const docs = [];
128
+ for (const [path, pinned_to] of pinsForGap(await spatial.pins.list(), gap, view)) {
129
+ docs.push({ path, kind: pinKind(path), pinned_to, files: await readPinned(spatial.root, path) });
130
+ }
131
+ return {
132
+ gap,
133
+ big_picture: root && root.id !== gap.view_id ? root : null,
134
+ path: root ? pathTo(views, root.id, gap.view_id) : [],
135
+ view: view ? { id: view.id, name: view.name, type: view.type } : { id: gap.view_id, name: gap.view_id, type: "missing" },
136
+ modules,
137
+ connections,
138
+ docs,
139
+ tokens: 0,
140
+ };
141
+ }
142
+ export function contextToJson(ctx) {
143
+ const body = JSON.stringify({ ...ctx, tokens: 0 }, null, 2);
144
+ return JSON.stringify({ ...ctx, tokens: countTokens(body) }, null, 2);
145
+ }
146
+ export function contextToXml(ctx, all = []) {
147
+ const { gap } = ctx;
148
+ const L = [];
149
+ L.push(` <Gap${attr("Id", gap.id)}${attr("Title", gap.title)}${attr("State", gap.state)}` +
150
+ `${attr("Milestone", gap.milestone)}${attr("OpenSpecChange", gap.openspec_change)}>`);
151
+ if (gap.intent)
152
+ L.push(` <Intent>${esc(gap.intent)}</Intent>`);
153
+ L.push(` </Gap>`);
154
+ if (ctx.big_picture)
155
+ L.push(` <BigPicture>`, viewToXml(ctx.big_picture, all, " "), ` </BigPicture>`);
156
+ if (ctx.path.length) {
157
+ L.push(` <Path>`);
158
+ for (const s of ctx.path)
159
+ L.push(` <Step${attr("View", s.view_name)}${attr("ViewId", s.view_id)}${attr("Module", s.module_name)}${attr("ModuleId", s.module_id)}/>`);
160
+ L.push(` </Path>`);
161
+ }
162
+ L.push(` <Scope${attr("View", ctx.view.name)}${attr("ViewId", ctx.view.id)}${attr("Type", ctx.view.type)}>`);
163
+ for (const m of ctx.modules) {
164
+ L.push(` <Module${attr("Id", m.id)}${attr("Name", m.name)}${m.missing ? ` Missing="true"` : ""}>`);
165
+ if (m.description)
166
+ L.push(` <Description>${esc(m.description)}</Description>`);
167
+ for (const f of m.files ?? [])
168
+ L.push(` <File${attr("Path", f)}/>`);
169
+ for (const c of ctx.connections.filter((c) => c.from === m.id))
170
+ L.push(` <Connection${attr("GoTo", c.to_name)}${attr("Value", c.label)}${c.outside ? ` Outside="true"` : ""}/>`);
171
+ for (const c of ctx.connections.filter((c) => c.to === m.id && c.outside))
172
+ L.push(` <ConnectionFrom${attr("From", c.from_name)}${attr("Value", c.label)} Outside="true"/>`);
173
+ L.push(` </Module>`);
174
+ }
175
+ L.push(` </Scope>`);
176
+ if (ctx.docs.length) {
177
+ L.push(` <Pinned>`);
178
+ for (const d of ctx.docs) {
179
+ const head = ` <Doc${attr("Path", d.path)}${attr("Kind", d.kind)}${attr("PinnedTo", d.pinned_to.join(" "))}`;
180
+ if (d.files.length === 0) {
181
+ L.push(`${head} Missing="true"/>`);
182
+ continue;
183
+ }
184
+ L.push(`${head}>`);
185
+ for (const f of d.files)
186
+ L.push(` <File${attr("Path", f.path)}${f.truncated ? ` Truncated="true"` : ""}>${cdata(f.text)}</File>`);
187
+ L.push(` </Doc>`);
188
+ }
189
+ L.push(` </Pinned>`);
190
+ }
191
+ const body = L.join("\n");
192
+ const tokens = countTokens(body) + 12;
193
+ return `<Context${attr("Gap", gap.id)} Tokens="${tokens}">\n${body}\n</Context>`;
194
+ }
@@ -0,0 +1,134 @@
1
+ import { readFile, readdir, stat } from "node:fs/promises";
2
+ import { basename, join } from "node:path";
3
+ import { UserError } from "./errors.js";
4
+ import { slugId } from "./links.js";
5
+ import { flowToView, isFlowchart, parseFlowchart } from "./mermaid.js";
6
+ import { hasOpenSpec, listChanges, listSpecs } from "./openspec.js";
7
+ import { absPath, repoPath } from "./paths.js";
8
+ /** Doc folders: docs/ and openspec/ when they exist, plus any import_docs added. */
9
+ export const DEFAULT_SOURCES = ["docs", "openspec"];
10
+ const SKIP_DIRS = new Set(["node_modules", ".git", ".spatial", ".spatial-local", "dist"]);
11
+ const MAX_FILES = 2000;
12
+ const isDir = async (p) => (await stat(p).catch(() => null))?.isDirectory() === true;
13
+ /** Every .md under a repo folder (repo-relative, sorted). */
14
+ export async function walkMarkdown(root, rel) {
15
+ const out = [];
16
+ const walk = async (dir) => {
17
+ if (out.length >= MAX_FILES)
18
+ return;
19
+ const entries = await readdir(join(root, dir), { withFileTypes: true }).catch(() => []);
20
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
21
+ const p = dir === "." ? e.name : `${dir}/${e.name}`;
22
+ if (e.isDirectory() && !SKIP_DIRS.has(e.name))
23
+ await walk(p);
24
+ else if (e.isFile() && e.name.toLowerCase().endsWith(".md") && out.length < MAX_FILES)
25
+ out.push(p);
26
+ }
27
+ };
28
+ await walk(rel);
29
+ return out;
30
+ }
31
+ export async function docSources(spatial) {
32
+ const extra = (await spatial.pins.read()).sources;
33
+ const all = [...new Set([...DEFAULT_SOURCES, ...extra])];
34
+ const out = [];
35
+ for (const s of all)
36
+ if (await isDir(join(spatial.root, s)))
37
+ out.push(s);
38
+ return out;
39
+ }
40
+ export function mermaidBlocks(md) {
41
+ const out = [];
42
+ let heading;
43
+ let inBlock = null;
44
+ for (const line of md.split("\n")) {
45
+ const fence = /^\s*(```|~~~)\s*([\w-]*)/.exec(line);
46
+ if (inBlock) {
47
+ if (fence && !fence[2]) {
48
+ if (inBlock.lang === "mermaid") {
49
+ const code = inBlock.lines.join("\n");
50
+ out.push({ index: out.length + 1, code, flowchart: isFlowchart(code), ...(heading ? { title: heading } : {}) });
51
+ }
52
+ inBlock = null;
53
+ }
54
+ else
55
+ inBlock.lines.push(line);
56
+ continue;
57
+ }
58
+ if (fence) {
59
+ inBlock = { lang: fence[2].toLowerCase(), lines: [] };
60
+ continue;
61
+ }
62
+ const h = /^#{1,6}\s+(.+?)\s*#*\s*$/.exec(line);
63
+ if (h)
64
+ heading = h[1];
65
+ }
66
+ return out;
67
+ }
68
+ /** A draft View from the n-th Mermaid block of a doc. */
69
+ export async function draftViewFromDoc(spatial, path, index) {
70
+ const rel = repoPath(spatial.root, path);
71
+ const md = await readFile(absPath(spatial.root, rel), "utf8").catch(() => {
72
+ throw new UserError(`cannot read ${rel}`);
73
+ });
74
+ const block = mermaidBlocks(md).find((b) => b.index === index);
75
+ if (!block)
76
+ throw new UserError(`${rel} has no Mermaid block ${index}`);
77
+ const flow = block.flowchart ? parseFlowchart(block.code) : null;
78
+ if (!flow)
79
+ throw new UserError(`Mermaid block ${index} in ${rel} is not a flowchart`);
80
+ const source = `${rel}#${index}`;
81
+ const views = await spatial.views.listViews();
82
+ // Drafting the same block again opens the View made before; it is never overwritten.
83
+ const existing = views.find((v) => v.source === source);
84
+ if (existing)
85
+ return existing;
86
+ const name = block.title ?? basename(rel, ".md");
87
+ const id = slugId(`${basename(rel, ".md")}-${name}`, views.map((v) => v.id));
88
+ return spatial.views.save(flowToView(flow, { id, name, source }));
89
+ }
90
+ /**
91
+ * Import an existing docs/ or openspec/ folder: it is read as-is (nothing is
92
+ * rewritten) and added to the doc sources. With draftViews, every Mermaid
93
+ * flowchart becomes a draft View (one per block; importing again keeps it).
94
+ */
95
+ export async function importDocs(spatial, path, draftViews = false) {
96
+ const rel = repoPath(spatial.root, path);
97
+ if (!(await isDir(join(spatial.root, rel))))
98
+ throw new UserError(`${rel} is not a folder`);
99
+ if (!DEFAULT_SOURCES.includes(rel) && rel !== ".")
100
+ await spatial.pins.addSource(rel);
101
+ const docs = await walkMarkdown(spatial.root, rel);
102
+ const report = { source: rel, docs, flowcharts: [], draft_views: [] };
103
+ if (rel === "openspec" || (rel === "." && (await hasOpenSpec(spatial.root)))) {
104
+ const changes = await listChanges(spatial.root);
105
+ report.openspec = {
106
+ specs: (await listSpecs(spatial.root)).length,
107
+ changes: changes.filter((c) => !c.archived).length,
108
+ archived: changes.filter((c) => c.archived).length,
109
+ };
110
+ }
111
+ const views = await spatial.views.listViews();
112
+ for (const doc of docs) {
113
+ const md = await readFile(join(spatial.root, doc), "utf8");
114
+ for (const b of mermaidBlocks(md).filter((b) => b.flowchart)) {
115
+ const source = `${doc}#${b.index}`;
116
+ const entry = { source, ...(b.title ? { title: b.title } : {}) };
117
+ const have = views.find((v) => v.source === source);
118
+ if (draftViews) {
119
+ try {
120
+ const v = await draftViewFromDoc(spatial, doc, b.index);
121
+ entry.view_id = v.id;
122
+ report.draft_views.push(v.id);
123
+ }
124
+ catch {
125
+ // A flowchart we cannot read is listed without a View.
126
+ }
127
+ }
128
+ else if (have)
129
+ entry.view_id = have.id;
130
+ report.flowcharts.push(entry);
131
+ }
132
+ }
133
+ return report;
134
+ }
@@ -0,0 +1,105 @@
1
+ import { UserError } from "./errors.js";
2
+ import { slugId } from "./links.js";
3
+ /**
4
+ * Drawing a View: pure functions shared by the MCP tools and the canvas.
5
+ * Every change returns a new View; nothing is mutated.
6
+ */
7
+ /** A module on this View, by id or else by name (case-insensitive). */
8
+ export function findModule(view, ref) {
9
+ const byId = view.modules.find((m) => m.id === ref);
10
+ if (byId)
11
+ return byId;
12
+ const byName = view.modules.filter((m) => m.name.toLowerCase() === ref.toLowerCase());
13
+ if (byName.length === 1)
14
+ return byName[0];
15
+ if (byName.length > 1)
16
+ throw new UserError(`more than one module on ${view.id} is named "${ref}"; use the id`);
17
+ throw new UserError(`no module "${ref}" on View ${view.id}`);
18
+ }
19
+ /** The next free grid slot, so modules added without a position don't stack. */
20
+ function nextSlot(view) {
21
+ const n = view.modules.length;
22
+ return { x: (n % 4) * 240, y: Math.floor(n / 4) * 140 };
23
+ }
24
+ export function addModule(view, input) {
25
+ const name = input.name.trim();
26
+ if (!name)
27
+ throw new UserError("a module needs a name");
28
+ const taken = view.modules.map((m) => m.id);
29
+ if (input.id && taken.includes(input.id))
30
+ throw new UserError(`module id ${input.id} is taken on ${view.id}`);
31
+ const slot = nextSlot(view);
32
+ const module = {
33
+ id: input.id ?? slugId(name, taken),
34
+ name,
35
+ x: input.x ?? slot.x,
36
+ y: input.y ?? slot.y,
37
+ ...(input.description ? { description: input.description } : {}),
38
+ };
39
+ return { view: { ...view, modules: [...view.modules, module] }, module };
40
+ }
41
+ export function connect(view, fromRef, toRef, label) {
42
+ const from = findModule(view, fromRef);
43
+ const to = findModule(view, toRef);
44
+ const ids = new Set(view.connections.map((c) => c.id));
45
+ let n = view.connections.length + 1;
46
+ while (ids.has(`c${n}`))
47
+ n++;
48
+ const connection = { id: `c${n}`, from: from.id, to: to.id, ...(label ? { label } : {}) };
49
+ return { view: { ...view, connections: [...view.connections, connection] }, connection };
50
+ }
51
+ function withModule(view, ref, change) {
52
+ const target = findModule(view, ref);
53
+ return { ...view, modules: view.modules.map((m) => (m.id === target.id ? change(m) : m)) };
54
+ }
55
+ export function moveModule(view, ref, x, y) {
56
+ return withModule(view, ref, (m) => ({ ...m, x: Math.round(x), y: Math.round(y) }));
57
+ }
58
+ export function updateModule(view, ref, patch) {
59
+ return withModule(view, ref, (m) => {
60
+ const next = { ...m };
61
+ if (patch.name !== undefined) {
62
+ if (!patch.name.trim())
63
+ throw new UserError("a module needs a name");
64
+ next.name = patch.name.trim();
65
+ }
66
+ if (patch.description !== undefined) {
67
+ if (patch.description)
68
+ next.description = patch.description;
69
+ else
70
+ delete next.description;
71
+ }
72
+ return next;
73
+ });
74
+ }
75
+ /** Remove a module, its connections, and its place in any Feature. */
76
+ export function removeModule(view, ref) {
77
+ const target = findModule(view, ref);
78
+ const features = view.features?.map((f) => ({ ...f, module_ids: f.module_ids.filter((id) => id !== target.id) }));
79
+ return {
80
+ ...view,
81
+ modules: view.modules.filter((m) => m.id !== target.id),
82
+ connections: view.connections.filter((c) => c.from !== target.id && c.to !== target.id),
83
+ ...(features ? { features } : {}),
84
+ };
85
+ }
86
+ export function removeConnection(view, id) {
87
+ if (!view.connections.some((c) => c.id === id))
88
+ throw new UserError(`no connection ${id} on View ${view.id}`);
89
+ return { ...view, connections: view.connections.filter((c) => c.id !== id) };
90
+ }
91
+ /** Add a source file to a module (repo-relative); adding it again is a no-op. */
92
+ export function addFilePointer(view, ref, path) {
93
+ return withModule(view, ref, (m) => (m.files?.includes(path) ? m : { ...m, files: [...(m.files ?? []), path] }));
94
+ }
95
+ /** A Feature from selected modules (the lasso). */
96
+ export function addFeature(view, name, moduleRefs) {
97
+ if (!name.trim())
98
+ throw new UserError("a Feature needs a name");
99
+ if (moduleRefs.length === 0)
100
+ throw new UserError("select at least one module");
101
+ const module_ids = [...new Set(moduleRefs.map((r) => findModule(view, r).id))];
102
+ const taken = (view.features ?? []).map((f) => f.id);
103
+ const feature = { id: slugId(name, taken), name: name.trim(), module_ids };
104
+ return { view: { ...view, features: [...(view.features ?? []), feature] }, feature };
105
+ }
@@ -0,0 +1,3 @@
1
+ /** An error the caller made (bad id, bad path, ...): reported back, never a crash. */
2
+ export class UserError extends Error {
3
+ }