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,426 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { join } from "node:path";
3
+ import { UserError } from "./errors.js";
4
+ import { ApprovalSchema, SettingsSchema, } from "./schema.js";
5
+ import { ConflictError, folderRef, keepVersions, NotFoundError, Spatial } from "./storage.js";
6
+ import { canonical } from "./storage/types.js";
7
+ import { summarizeDoc, summarizeView, Versions, withVersion } from "./versions.js";
8
+ const ID = /^[A-Za-z0-9_-]+$/;
9
+ // Key order is not data: Postgres (jsonb) hands objects back with their keys reordered.
10
+ const same = (a, b) => canonical(a ?? null) === canonical(b ?? null);
11
+ export function refOf(t) {
12
+ if (typeof t === "string")
13
+ return folderRef(t);
14
+ return t instanceof Spatial ? t.ref : t;
15
+ }
16
+ /** A project's settings (`<data>/settings.json` in the folder store). */
17
+ export const settingsFile = (dataDir) => join(dataDir, "settings.json");
18
+ export async function readSettings(at) {
19
+ const ref = refOf(at);
20
+ const it = await ref.storage.get("settings", ref.project, "settings").catch(() => null);
21
+ if (!it)
22
+ return SettingsSchema.parse({});
23
+ try {
24
+ return SettingsSchema.parse(it.data);
25
+ }
26
+ catch {
27
+ return SettingsSchema.parse({});
28
+ }
29
+ }
30
+ export async function writeSettings(at, patch) {
31
+ const ref = refOf(at);
32
+ const next = SettingsSchema.parse({ ...(await readSettings(ref)), ...patch });
33
+ await ref.storage.put("settings", ref.project, "settings", next);
34
+ return next;
35
+ }
36
+ // ---- The approvals ---------------------------------------------------------------
37
+ export class ApprovalStore {
38
+ ref;
39
+ /** The project's data (a Spatial, or the folder store's data folder). */
40
+ constructor(at) {
41
+ this.ref = refOf(at);
42
+ }
43
+ check(id) {
44
+ if (!ID.test(id))
45
+ throw new NotFoundError(`no approval ${id}`);
46
+ return id;
47
+ }
48
+ async get(id) {
49
+ const it = await this.ref.storage.get("approval", this.ref.project, this.check(id));
50
+ if (!it)
51
+ throw new NotFoundError(`no approval ${id}`);
52
+ return ApprovalSchema.parse(it.data);
53
+ }
54
+ async save(p) {
55
+ const clean = ApprovalSchema.parse(p);
56
+ await this.ref.storage.put("approval", this.ref.project, this.check(clean.id), clean);
57
+ return clean;
58
+ }
59
+ /** Drop an Approval that holds nothing any more (no-op when it was never saved). */
60
+ async remove(id) {
61
+ if (await this.ref.storage.get("approval", this.ref.project, this.check(id)))
62
+ await this.ref.storage.delete("approval", this.ref.project, id);
63
+ }
64
+ /** Newest first. */
65
+ async list() {
66
+ const out = [];
67
+ for (const it of await this.ref.storage.list("approval", this.ref.project)) {
68
+ try {
69
+ out.push(ApprovalSchema.parse(it.data));
70
+ }
71
+ catch {
72
+ // A broken item must not hide the others.
73
+ }
74
+ }
75
+ return out.sort((a, b) => (a.created < b.created ? 1 : a.created > b.created ? -1 : a.id < b.id ? 1 : -1));
76
+ }
77
+ }
78
+ /** A short summary of an Approval, for lists. */
79
+ export function summarizeApproval(p) {
80
+ return {
81
+ id: p.id,
82
+ ...(p.n ? { n: p.n } : {}),
83
+ title: p.title,
84
+ author: p.author,
85
+ created: p.created,
86
+ status: p.status,
87
+ ...(p.decided ? { decided: p.decided } : {}),
88
+ changes: p.changes.length,
89
+ revisions: p.revisions.length,
90
+ views: [...new Set(p.changes.filter((c) => c.target === "view").map((c) => c.ref))],
91
+ docs: [...new Set(p.changes.filter((c) => c.target === "doc").map((c) => c.ref))],
92
+ };
93
+ }
94
+ /** What an agent should do next, in words a Skill can act on. */
95
+ export function outcome(p) {
96
+ switch (p.status) {
97
+ case "pending":
98
+ return "pending: waiting for a person to approve or deny it";
99
+ case "approved": {
100
+ const denied = p.changes.filter((c) => c.decision === "denied").length;
101
+ return denied ? `approved in part: ${p.changes.length - denied} applied, ${denied} denied` : "approved: every change is live";
102
+ }
103
+ case "denied":
104
+ return "denied: nothing was applied";
105
+ }
106
+ }
107
+ /** Its name for people: "#12" (older Approvals have no number: their id). */
108
+ export const approvalName = (p) => (p.n ? `#${p.n}` : p.id);
109
+ /**
110
+ * Where a pending draft stands, in words a Skill can repeat: "amended pending
111
+ * approval #12 (3 revisions, from v4)". Decided ones say their outcome.
112
+ */
113
+ export function approvalState(p) {
114
+ if (p.status !== "pending")
115
+ return `approval ${approvalName(p)}: ${outcome(p)}`;
116
+ const revs = p.revisions.length;
117
+ const verb = revs > 1 ? "amended pending approval" : "pending approval";
118
+ const base = p.base_version ? `, from v${p.base_version}` : "";
119
+ return `${verb} ${approvalName(p)} (${revs} ${revs === 1 ? "revision" : "revisions"}${base})`;
120
+ }
121
+ /** The refusal when a person approves a draft that has changed since they opened it. */
122
+ export const STALE = "Updated since you opened it: reload diff";
123
+ /** An approve for a draft that moved on: nothing is applied (the API answers 409). */
124
+ export class StaleError extends UserError {
125
+ rev;
126
+ constructor(rev) {
127
+ super(STALE);
128
+ this.rev = rev;
129
+ }
130
+ }
131
+ const newId = (prefix) => `${prefix}_${Date.now().toString(36)}${randomBytes(3).toString("hex")}`;
132
+ // ---- The item's title ------------------------------------------------------------
133
+ const AGENTS = {
134
+ "claude-code": "Claude Code",
135
+ "claude-ai": "Claude",
136
+ cursor: "Cursor",
137
+ "cursor-vscode": "Cursor",
138
+ windsurf: "Windsurf",
139
+ vscode: "VS Code",
140
+ "visual-studio-code": "VS Code",
141
+ };
142
+ /** The agent's name as people say it: cursor -> Cursor, claude-code -> Claude Code. */
143
+ export function agentName(client) {
144
+ const k = client.trim().toLowerCase();
145
+ if (AGENTS[k])
146
+ return AGENTS[k];
147
+ return k ? k.split(/[-_\s]+/).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ") : "AI";
148
+ }
149
+ const NOUN = {
150
+ view: ["View", "Views"],
151
+ gap: ["Gap", "Gaps"],
152
+ doc: ["Doc", "Docs"],
153
+ pins: ["pin map", "pin maps"],
154
+ };
155
+ const VERB = { create: "new", update: "amended", delete: "deleted" };
156
+ /** What an Approval holds, in a line: "Cursor: 2 new Views, 1 amended Doc". */
157
+ export function approvalTitle(author, changes) {
158
+ const counts = new Map();
159
+ for (const c of changes) {
160
+ const k = `${c.op} ${c.target}`;
161
+ const e = counts.get(k) ?? { n: 0, op: c.op, target: c.target };
162
+ e.n++;
163
+ counts.set(k, e);
164
+ }
165
+ const order = ["view", "gap", "doc", "pins"].flatMap((t) => ["create", "update", "delete"].map((o) => `${o} ${t}`));
166
+ const parts = order.filter((k) => counts.has(k)).map((k) => {
167
+ const e = counts.get(k);
168
+ return `${e.n} ${VERB[e.op]} ${NOUN[e.target][e.n === 1 ? 0 : 1]}`;
169
+ });
170
+ return `${agentName(author)}: ${parts.join(", ") || "no changes"}`;
171
+ }
172
+ /** A draft's title: "Cursor: amended View Checkout" (several changes: the counts). */
173
+ export function draftTitle(author, changes) {
174
+ if (changes.length !== 1)
175
+ return approvalTitle(author, changes);
176
+ const c = changes[0];
177
+ const v = (c.after ?? c.before);
178
+ const name = c.target === "view" ? v?.name ?? c.ref : c.target === "gap" ? v?.title ?? c.ref : c.target === "pins" ? "" : c.ref;
179
+ return `${agentName(author)}: ${VERB[c.op]} ${NOUN[c.target][0]}${name ? ` ${name}` : ""}`;
180
+ }
181
+ /** One revision's summary: what this write changed on top of the draft before it. */
182
+ function revisionSummary(target, before, after) {
183
+ if (after === null)
184
+ return "deleted";
185
+ if (target === "view")
186
+ return summarizeView(before, after);
187
+ if (target === "doc")
188
+ return summarizeDoc(before, after);
189
+ return before === null ? "created" : "updated";
190
+ }
191
+ // ---- Staging: where an agent run's writes to approved content go ------------------
192
+ /**
193
+ * An agent run's writes to approved content. Each View or Doc (or Gap, or the
194
+ * pin map) gets one pending Approval, a draft: the first write opens it, and
195
+ * every later write to the same file, from this run or any other, folds into
196
+ * THAT Approval as a new revision. Reads see the drafts on top of the live
197
+ * files. Once a person decides it, the next write opens a new one. It is
198
+ * re-read from the store on each call, so a decision made on the canvas is
199
+ * seen straight away.
200
+ */
201
+ export class Staging {
202
+ who;
203
+ tool;
204
+ store;
205
+ session = newId("s");
206
+ lock = Promise.resolve();
207
+ /** Called after each staged write (the server uses it to note the tool and the Approval). */
208
+ onWrite;
209
+ /** The project's data: its approvals and settings are used. */
210
+ constructor(at, who, tool) {
211
+ this.who = who;
212
+ this.tool = tool;
213
+ this.store = new ApprovalStore(at);
214
+ }
215
+ async active() {
216
+ return (await readSettings(this.store.ref)).ai_changes === "approval";
217
+ }
218
+ /** The id of the Approval this run last wrote to (pending or decided). */
219
+ lastId = null;
220
+ /** This run's latest Approval, if it is still pending. */
221
+ async current() {
222
+ if (!this.lastId)
223
+ return null;
224
+ const p = await this.store.get(this.lastId).catch(() => null);
225
+ return p && p.status === "pending" ? p : null;
226
+ }
227
+ /** The pending draft of one file (anyone's), newest first. */
228
+ async draftOf(target, ref) {
229
+ return (await this.store.list()).find((p) => p.status === "pending" && p.changes.some((x) => x.target === target && x.ref === ref)) ?? null;
230
+ }
231
+ async read(target, ref) {
232
+ const c = (await this.draftOf(target, ref))?.changes.find((x) => x.target === target && x.ref === ref);
233
+ return c ? { value: c.after } : undefined;
234
+ }
235
+ async all(target) {
236
+ const out = new Map();
237
+ // Oldest first, so the newest draft of a file wins.
238
+ for (const p of (await this.store.list()).reverse())
239
+ if (p.status === "pending")
240
+ for (const c of p.changes)
241
+ if (c.target === target)
242
+ out.set(c.ref, c.after);
243
+ return [...out].map(([ref, value]) => ({ ref, value }));
244
+ }
245
+ async pending(target, ref) {
246
+ return (await this.draftOf(target, ref)) !== null;
247
+ }
248
+ write(target, ref, before, after) {
249
+ const run = this.lock.then(() => this.record(target, ref, before ?? null, after ?? null));
250
+ this.lock = run.catch(() => undefined);
251
+ return run;
252
+ }
253
+ /** The live content's newest version: the base a new draft starts from (Views and Docs). */
254
+ async baseVersion(target, ref) {
255
+ if (target !== "view" && target !== "doc")
256
+ return null;
257
+ const kind = target === "view" ? "view_version" : "doc_version";
258
+ const v = await new Versions(this.store.ref.storage, this.store.ref.project, kind, (x) => x, () => "").latest(ref).catch(() => null);
259
+ return v?.n ?? null;
260
+ }
261
+ async record(target, ref, before, after) {
262
+ const now = new Date().toISOString();
263
+ const by = this.who();
264
+ let p = await this.draftOf(target, ref);
265
+ if (!p) {
266
+ // Nothing to review: no Approval (an audit that changes nothing makes nothing).
267
+ if (same(before, after))
268
+ return;
269
+ const n = (await this.store.list()).reduce((m, x) => Math.max(m, x.n ?? 0), 0) + 1;
270
+ p = {
271
+ id: newId("a"),
272
+ n,
273
+ title: "",
274
+ author: by,
275
+ created: now,
276
+ status: "pending",
277
+ session: this.session,
278
+ base_version: await this.baseVersion(target, ref),
279
+ revisions: [],
280
+ changes: [{ id: "c1", target, ref, op: "update", before, after: before, tools: [], at: now }],
281
+ };
282
+ }
283
+ const tool = this.tool();
284
+ let c = p.changes.find((x) => x.target === target && x.ref === ref);
285
+ if (!c) {
286
+ // An older Approval holding several files: this one joins it.
287
+ const k = p.changes.reduce((m, x) => Math.max(m, Number(/^c(\d+)$/.exec(x.id)?.[1] ?? 0)), 0) + 1;
288
+ c = { id: `c${k}`, target, ref, op: "update", before, after: before, tools: [], at: now };
289
+ p.changes.push(c);
290
+ }
291
+ const prev = c.after;
292
+ if (same(prev, after))
293
+ return; // the draft already says this
294
+ c.after = after;
295
+ c.at = now;
296
+ if (tool)
297
+ c.tools.push(tool);
298
+ c.op = c.before === null ? "create" : c.after === null ? "delete" : "update";
299
+ p.revisions.push({ n: p.revisions.length + 1, at: now, by, summary: revisionSummary(target, prev, after), ...(tool ? { tool } : {}) });
300
+ p.session = this.session;
301
+ // Made then removed, or put back as it was: nothing left to review.
302
+ if ((c.before === null && c.after === null) || same(c.before, c.after))
303
+ p.changes = p.changes.filter((x) => x !== c);
304
+ if (!p.changes.length) {
305
+ await this.store.remove(p.id);
306
+ return;
307
+ }
308
+ p.title = draftTitle(p.author, p.changes);
309
+ const saved = await this.store.save(p);
310
+ this.lastId = saved.id;
311
+ this.onWrite?.(saved, c);
312
+ }
313
+ }
314
+ // ---- Review --------------------------------------------------------------------
315
+ const undecided = (p) => {
316
+ if (p.status === "approved" || p.status === "denied")
317
+ throw new UserError(`Approval ${p.id} is already ${p.status}`);
318
+ };
319
+ /** Approve or deny one change (null: back to undecided). Nothing is applied until the Approval is approved. */
320
+ export async function decideChange(store, id, changeId, decision) {
321
+ const p = await store.get(id);
322
+ undecided(p);
323
+ const c = p.changes.find((x) => x.id === changeId);
324
+ if (!c)
325
+ throw new NotFoundError(`no change ${changeId} in approval ${id}`);
326
+ if (decision)
327
+ c.decision = decision;
328
+ else
329
+ delete c.decision;
330
+ return store.save(p);
331
+ }
332
+ /** Deny the whole Approval: the draft is discarded and the live content (the base) stays. */
333
+ export async function denyItem(store, id, note) {
334
+ const p = await store.get(id);
335
+ undecided(p);
336
+ p.status = "denied";
337
+ p.decided = new Date().toISOString();
338
+ for (const c of p.changes)
339
+ c.decision = "denied";
340
+ if (note?.trim())
341
+ p.note = note.trim();
342
+ return store.save(p);
343
+ }
344
+ /** What is live for one change now (its value and version), and the writes that apply it. */
345
+ async function plan(spatial, c, meta) {
346
+ switch (c.target) {
347
+ case "view":
348
+ case "gap": {
349
+ const store = c.target === "view" ? spatial.views : spatial.gaps;
350
+ const after = c.after === null ? null : c.after;
351
+ if (after && after.id !== c.ref)
352
+ throw new UserError(`change ${c.id}: the ${c.target === "view" ? "View" : "Gap"}'s id is not ${c.ref}`);
353
+ const cur = await store.liveItem(c.ref).catch(() => null);
354
+ // A View's new version goes in the same transaction, saved as the AI that made it.
355
+ const ops = c.target === "view" ? await spatial.views.ops(c.ref, c.after, cur?.version ?? null, meta) : [store.op(c.ref, c.after, cur?.version ?? null)];
356
+ return { live: cur?.value ?? null, ops };
357
+ }
358
+ case "pins": {
359
+ const cur = await spatial.pins.liveItem().catch(() => null);
360
+ return { live: cur?.value ?? null, ops: [spatial.pins.op(c.after, cur?.version ?? null)] };
361
+ }
362
+ case "doc": {
363
+ const rel = spatial.docs.rel(c.ref);
364
+ if (c.after !== null && typeof c.after !== "string")
365
+ throw new UserError(`change ${c.id}: a doc change holds text`);
366
+ const cur = await spatial.docs.liveItem(rel);
367
+ return { live: cur?.value ?? null, ops: await spatial.docs.ops([{ rel, text: c.after, expected: cur?.version ?? null }], meta) };
368
+ }
369
+ }
370
+ }
371
+ /**
372
+ * Approve: apply every change not denied (a draft's head), all or nothing, as a
373
+ * new version of each View and Doc, in one transaction
374
+ * of the store. Each change must still start from what is live (else it is a
375
+ * conflict and nothing is written), and each write expects the version that was
376
+ * checked, so a write by anyone in between fails the lot too.
377
+ * `spatial` must be a live (unstaged) Spatial.
378
+ */
379
+ export async function approveItem(spatial, store, id, note, rev) {
380
+ if (spatial.stage)
381
+ throw new Error("approve needs the live store");
382
+ const p = await store.get(id);
383
+ undecided(p);
384
+ // Approve applies the head the person saw: if the AI amended it since, refuse.
385
+ if (rev !== undefined && rev !== p.revisions.length)
386
+ throw new StaleError(p.revisions.length);
387
+ const chosen = p.changes.filter((c) => c.decision !== "denied");
388
+ if (!chosen.length)
389
+ throw new UserError("every change is denied: deny the Approval instead");
390
+ const meta = { by: p.author, note: `approved ${p.id}` };
391
+ const build = async () => {
392
+ const conflicts = [];
393
+ const ops = [];
394
+ for (const c of chosen) {
395
+ const s = await plan(spatial, c, meta);
396
+ if (!same(s.live, c.before === undefined ? null : c.before))
397
+ conflicts.push(`${c.target} ${c.ref}`);
398
+ ops.push(...s.ops);
399
+ }
400
+ if (conflicts.length)
401
+ throw new UserError(`changed since the Approval was made, nothing applied: ${conflicts.join(", ")}`);
402
+ return ops;
403
+ };
404
+ try {
405
+ // A version number another client took first is retried; any other miss fails the lot.
406
+ await withVersion(spatial.storage, build, `approval ${p.id}`);
407
+ }
408
+ catch (err) {
409
+ if (err instanceof ConflictError)
410
+ throw new UserError(`changed since the Approval was made, nothing applied: ${err.kind} ${err.id}`);
411
+ throw err instanceof UserError ? err : new UserError(`could not apply the Approval, nothing changed: ${err.message}`);
412
+ }
413
+ for (const c of chosen) {
414
+ if (c.target === "view" && c.after !== null)
415
+ await spatial.views.versions.prune(c.ref, await keepVersions(spatial.ref));
416
+ if (c.target === "doc" && c.after !== null)
417
+ await spatial.docs.history.prune(spatial.docs.rel(c.ref), await keepVersions(spatial.ref));
418
+ }
419
+ p.status = "approved";
420
+ p.decided = new Date().toISOString();
421
+ for (const c of chosen)
422
+ c.decision = "approved";
423
+ if (note?.trim())
424
+ p.note = note.trim();
425
+ return store.save(p);
426
+ }
@@ -0,0 +1,259 @@
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 { readDoc, resolveDocPath } from "./project.js";
7
+ import { attr, cdata, esc, viewToXml } from "./xml.js";
8
+ const MAX_FILE = 100_000;
9
+ const MAX_DIR_FILES = 25;
10
+ /** A rough token count (about four characters a token), so callers can see the cost. */
11
+ export const countTokens = (s) => Math.ceil(s.length / 4);
12
+ export function pinKind(path) {
13
+ if (path.startsWith("openspec/specs/"))
14
+ return "spec";
15
+ if (path.startsWith("openspec/changes/"))
16
+ return "change";
17
+ return path.toLowerCase().endsWith(".md") ? "doc" : "file";
18
+ }
19
+ /** The top of the picture: the high-level View, else a View no other View links to. */
20
+ export function rootView(views) {
21
+ const linked = new Set(views.flatMap((v) => v.modules.map((m) => m.linked_view_id).filter(Boolean)));
22
+ return views.find((v) => v.type === "high-level") ?? views.find((v) => !linked.has(v.id)) ?? views[0] ?? null;
23
+ }
24
+ /** The View id a project opens on when project.json names none. */
25
+ export const DEFAULT_ROOT_VIEW = "system-overview";
26
+ /**
27
+ * The View a project ALWAYS opens on: project.json's root_view_id, else the System Overview, else the
28
+ * top View (one no other View links to). Never the newest or the last one saved or opened.
29
+ */
30
+ export function landingView(views, rootId) {
31
+ const byId = (id) => (id ? views.find((v) => v.id === id) : undefined);
32
+ const linked = new Set(views.flatMap((v) => v.modules.filter((m) => m.linked_view_id !== v.id).map((m) => m.linked_view_id).filter(Boolean)));
33
+ const top = views.filter((v) => !linked.has(v.id));
34
+ return byId(rootId) ?? byId(DEFAULT_ROOT_VIEW) ?? top.find((v) => v.type === "high-level") ?? top[0] ?? rootView(views);
35
+ }
36
+ /** The modules to drill through, from the root down to `targetId` (empty if it is the root or not reachable). */
37
+ export function pathTo(views, rootId, targetId) {
38
+ const byId = new Map(views.map((v) => [v.id, v]));
39
+ const prev = new Map();
40
+ const queue = [rootId];
41
+ const seen = new Set(queue);
42
+ while (queue.length) {
43
+ const v = byId.get(queue.shift());
44
+ if (!v)
45
+ continue;
46
+ for (const m of v.modules) {
47
+ const next = m.linked_view_id;
48
+ if (!next || seen.has(next))
49
+ continue;
50
+ seen.add(next);
51
+ prev.set(next, { view: v, module: m });
52
+ queue.push(next);
53
+ }
54
+ }
55
+ const steps = [];
56
+ for (let at = targetId; prev.has(at);) {
57
+ const p = prev.get(at);
58
+ steps.unshift({ view_id: p.view.id, view_name: p.view.name, module_id: p.module.id, module_name: p.module.name });
59
+ at = p.view.id;
60
+ }
61
+ return steps;
62
+ }
63
+ /**
64
+ * The breadcrumb trail to a View, from the data alone (never click history): climb from the View
65
+ * to the modules that link to it, and their Views, up to the System Overview (else the root View,
66
+ * else the topmost View that nothing links to). Shortest way up wins. Ends with `targetId`.
67
+ */
68
+ export function trailTo(views, targetId, rootId) {
69
+ const top = landingView(views, rootId);
70
+ const parents = new Map();
71
+ for (const v of views)
72
+ for (const m of v.modules)
73
+ if (m.linked_view_id && m.linked_view_id !== v.id)
74
+ parents.set(m.linked_view_id, [...(parents.get(m.linked_view_id) ?? []), v.id]);
75
+ // Breadth first, upwards: `down` says, for each ancestor, the next View on the way down to the target.
76
+ const down = new Map();
77
+ const seen = new Set([targetId]);
78
+ const queue = [targetId];
79
+ let highest = null;
80
+ let end = top && top.id === targetId ? targetId : null;
81
+ while (queue.length && !end) {
82
+ const at = queue.shift();
83
+ const ups = parents.get(at) ?? [];
84
+ if (!ups.length && !highest)
85
+ highest = at;
86
+ for (const p of ups) {
87
+ if (seen.has(p))
88
+ continue;
89
+ seen.add(p);
90
+ down.set(p, at);
91
+ if (p === top?.id)
92
+ end = p;
93
+ queue.push(p);
94
+ }
95
+ }
96
+ const from = end ?? highest ?? targetId;
97
+ const trail = [from];
98
+ for (let at = from; at !== targetId;)
99
+ trail.push((at = down.get(at)));
100
+ return trail;
101
+ }
102
+ /** Which pins touch a Gap: its own, its View's, its modules', and Features that hold its modules. */
103
+ export function pinsForGap(pins, gap, view) {
104
+ const mods = new Set(gap.module_ids);
105
+ const features = new Set((view?.features ?? []).filter((f) => f.module_ids.some((id) => mods.has(id))).map((f) => f.id));
106
+ const out = new Map();
107
+ const add = (path, to) => out.set(path, [...(out.get(path) ?? []), to]);
108
+ for (const p of pins) {
109
+ if (p.kind === "gap" && p.gap_id === gap.id)
110
+ add(p.path, `gap:${gap.id}`);
111
+ if (p.kind === "view" && p.view_id === gap.view_id)
112
+ add(p.path, `view:${p.view_id}`);
113
+ if (p.kind === "module" && p.view_id === gap.view_id && mods.has(p.module_id))
114
+ add(p.path, `module:${p.module_id}`);
115
+ if (p.kind === "feature" && p.view_id === gap.view_id && features.has(p.feature_id))
116
+ add(p.path, `feature:${p.feature_id}`);
117
+ }
118
+ if (gap.openspec_change) {
119
+ const change = `openspec/changes/${gap.openspec_change}`;
120
+ if (!out.has(change))
121
+ add(change, `gap:${gap.id}`);
122
+ }
123
+ return out;
124
+ }
125
+ /** Read a pinned path: a file, or the .md files of a folder (an OpenSpec change, say). */
126
+ async function readPinned(spatial, path) {
127
+ const root = spatial.root;
128
+ // Only what the project may read: a pin outside its sources (a source taken off, a symlink out) reads as nothing.
129
+ const doc = await resolveDocPath(spatial, path).catch(() => null);
130
+ if (!doc)
131
+ return [];
132
+ // A file in one of the project's sources (`docs:prd.md`): read it where it is.
133
+ if (doc.source || doc.report) {
134
+ // A report is project data (read through the store); a source file is read where it is.
135
+ const text = (await readDoc(spatial, doc)) ?? "";
136
+ if (!text)
137
+ return [];
138
+ return [text.length > MAX_FILE ? { path: doc.rel, text: text.slice(0, MAX_FILE), truncated: true } : { path: doc.rel, text }];
139
+ }
140
+ const real = await resolveChangePath(root, path);
141
+ let abs;
142
+ try {
143
+ abs = absPath(root, real);
144
+ }
145
+ catch {
146
+ return [];
147
+ }
148
+ const s = await stat(abs).catch(() => null);
149
+ if (!s)
150
+ return [];
151
+ const one = async (rel, file) => {
152
+ const text = await readFile(file, "utf8").catch(() => "");
153
+ return text.length > MAX_FILE
154
+ ? { path: rel, text: text.slice(0, MAX_FILE), truncated: true }
155
+ : { path: rel, text };
156
+ };
157
+ if (s.isFile())
158
+ return [await one(real, abs)];
159
+ const files = [];
160
+ const walk = async (rel) => {
161
+ const entries = await readdir(join(root, rel), { withFileTypes: true }).catch(() => []);
162
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
163
+ if (files.length >= MAX_DIR_FILES)
164
+ return;
165
+ if (e.isDirectory())
166
+ await walk(`${rel}/${e.name}`);
167
+ else if (e.isFile() && e.name.toLowerCase().endsWith(".md"))
168
+ files.push(`${rel}/${e.name}`);
169
+ }
170
+ };
171
+ await walk(real);
172
+ return Promise.all(files.map((f) => one(f, join(root, f))));
173
+ }
174
+ export async function buildContext(spatial, gapRef) {
175
+ const gap = await syncGap(spatial, resolveGap(await spatial.gaps.all(), gapRef));
176
+ const views = await spatial.views.listViews();
177
+ const view = views.find((v) => v.id === gap.view_id) ?? null;
178
+ const root = rootView(views);
179
+ const mods = new Set(gap.module_ids);
180
+ const modules = gap.module_ids.map((id) => view?.modules.find((m) => m.id === id) ?? { id, name: id, x: 0, y: 0, missing: true });
181
+ const nameIn = (id) => view?.modules.find((m) => m.id === id)?.name ?? id;
182
+ const connections = (view?.connections ?? [])
183
+ .filter((c) => mods.has(c.from) || mods.has(c.to))
184
+ .map((c) => ({
185
+ from: c.from,
186
+ to: c.to,
187
+ from_name: nameIn(c.from),
188
+ to_name: nameIn(c.to),
189
+ ...(c.label ? { label: c.label } : {}),
190
+ outside: !(mods.has(c.from) && mods.has(c.to)),
191
+ }));
192
+ const docs = [];
193
+ for (const [path, pinned_to] of pinsForGap(await spatial.pins.list(), gap, view)) {
194
+ docs.push({ path, kind: pinKind(path), pinned_to, files: await readPinned(spatial, path) });
195
+ }
196
+ return {
197
+ gap,
198
+ big_picture: root && root.id !== gap.view_id ? root : null,
199
+ path: root ? pathTo(views, root.id, gap.view_id) : [],
200
+ view: view ? { id: view.id, name: view.name, type: view.type } : { id: gap.view_id, name: gap.view_id, type: "missing" },
201
+ modules,
202
+ connections,
203
+ docs,
204
+ tokens: 0,
205
+ };
206
+ }
207
+ export function contextToJson(ctx) {
208
+ const body = JSON.stringify({ ...ctx, tokens: 0 }, null, 2);
209
+ return JSON.stringify({ ...ctx, tokens: countTokens(body) }, null, 2);
210
+ }
211
+ export function contextToXml(ctx, all = []) {
212
+ const { gap } = ctx;
213
+ const L = [];
214
+ L.push(` <Gap${attr("Id", gap.id)}${attr("Title", gap.title)}${attr("State", gap.state)}` +
215
+ `${attr("Milestone", gap.milestone)}${attr("OpenSpecChange", gap.openspec_change)}>`);
216
+ if (gap.intent)
217
+ L.push(` <Intent>${esc(gap.intent)}</Intent>`);
218
+ L.push(` </Gap>`);
219
+ if (ctx.big_picture)
220
+ L.push(` <BigPicture>`, viewToXml(ctx.big_picture, all, " "), ` </BigPicture>`);
221
+ if (ctx.path.length) {
222
+ L.push(` <Path>`);
223
+ for (const s of ctx.path)
224
+ L.push(` <Step${attr("View", s.view_name)}${attr("ViewId", s.view_id)}${attr("Module", s.module_name)}${attr("ModuleId", s.module_id)}/>`);
225
+ L.push(` </Path>`);
226
+ }
227
+ L.push(` <Scope${attr("View", ctx.view.name)}${attr("ViewId", ctx.view.id)}${attr("Type", ctx.view.type)}>`);
228
+ for (const m of ctx.modules) {
229
+ L.push(` <Module${attr("Id", m.id)}${attr("Name", m.name)}${m.missing ? ` Missing="true"` : ""}>`);
230
+ if (m.description)
231
+ L.push(` <Description>${esc(m.description)}</Description>`);
232
+ for (const f of m.files ?? [])
233
+ L.push(` <File${attr("Path", f)}/>`);
234
+ for (const c of ctx.connections.filter((c) => c.from === m.id))
235
+ L.push(` <Connection${attr("GoTo", c.to_name)}${attr("Value", c.label)}${c.outside ? ` Outside="true"` : ""}/>`);
236
+ for (const c of ctx.connections.filter((c) => c.to === m.id && c.outside))
237
+ L.push(` <ConnectionFrom${attr("From", c.from_name)}${attr("Value", c.label)} Outside="true"/>`);
238
+ L.push(` </Module>`);
239
+ }
240
+ L.push(` </Scope>`);
241
+ if (ctx.docs.length) {
242
+ L.push(` <Pinned>`);
243
+ for (const d of ctx.docs) {
244
+ const head = ` <Doc${attr("Path", d.path)}${attr("Kind", d.kind)}${attr("PinnedTo", d.pinned_to.join(" "))}`;
245
+ if (d.files.length === 0) {
246
+ L.push(`${head} Missing="true"/>`);
247
+ continue;
248
+ }
249
+ L.push(`${head}>`);
250
+ for (const f of d.files)
251
+ L.push(` <File${attr("Path", f.path)}${f.truncated ? ` Truncated="true"` : ""}>${cdata(f.text)}</File>`);
252
+ L.push(` </Doc>`);
253
+ }
254
+ L.push(` </Pinned>`);
255
+ }
256
+ const body = L.join("\n");
257
+ const tokens = countTokens(body) + 12;
258
+ return `<Context${attr("Gap", gap.id)} Tokens="${tokens}">\n${body}\n</Context>`;
259
+ }