@documentation-robotics/cli 0.2.0 → 0.4.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 (335) hide show
  1. package/README.md +46 -16
  2. package/dist/analysis/relationship-classifier.js +2 -9
  3. package/dist/analysis/relationship-classifier.js.map +2 -2
  4. package/dist/analyzers/active-analyzer.js +62 -0
  5. package/dist/analyzers/active-analyzer.js.map +7 -0
  6. package/dist/analyzers/call-graph-utils.js +2 -2
  7. package/dist/analyzers/call-graph-utils.js.map +2 -2
  8. package/dist/analyzers/cards/build.js +191 -0
  9. package/dist/analyzers/cards/build.js.map +7 -0
  10. package/dist/analyzers/cards/classify.js +42 -0
  11. package/dist/analyzers/cards/classify.js.map +7 -0
  12. package/dist/analyzers/cards/edge-index.js +44 -0
  13. package/dist/analyzers/cards/edge-index.js.map +7 -0
  14. package/dist/analyzers/cards/extract.js +138 -0
  15. package/dist/analyzers/cards/extract.js.map +7 -0
  16. package/dist/analyzers/cards/facts.js +46 -0
  17. package/dist/analyzers/cards/facts.js.map +7 -0
  18. package/dist/analyzers/cards/graph.js +42 -0
  19. package/dist/analyzers/cards/graph.js.map +7 -0
  20. package/dist/analyzers/cards/index.js +8 -0
  21. package/dist/analyzers/cards/index.js.map +7 -0
  22. package/dist/analyzers/cards/routes.js +96 -0
  23. package/dist/analyzers/cards/routes.js.map +7 -0
  24. package/dist/analyzers/cards/tier0.js +18 -0
  25. package/dist/analyzers/cards/tier0.js.map +7 -0
  26. package/dist/analyzers/cards/types.js +1 -0
  27. package/dist/analyzers/cards/types.js.map +7 -0
  28. package/dist/analyzers/cbm-analyzer.js +270 -174
  29. package/dist/analyzers/cbm-analyzer.js.map +2 -2
  30. package/dist/analyzers/cbm-responses.js +342 -0
  31. package/dist/analyzers/cbm-responses.js.map +7 -0
  32. package/dist/analyzers/code-changes.js +159 -0
  33. package/dist/analyzers/code-changes.js.map +7 -0
  34. package/dist/analyzers/edge-relationships.js +49 -0
  35. package/dist/analyzers/edge-relationships.js.map +7 -0
  36. package/dist/analyzers/extraction-plan.js +541 -0
  37. package/dist/analyzers/extraction-plan.js.map +7 -0
  38. package/dist/analyzers/index-job.js +229 -0
  39. package/dist/analyzers/index-job.js.map +7 -0
  40. package/dist/analyzers/mapping-loader.js +9 -0
  41. package/dist/analyzers/mapping-loader.js.map +2 -2
  42. package/dist/analyzers/tier0-rules.js +153 -0
  43. package/dist/analyzers/tier0-rules.js.map +7 -0
  44. package/dist/analyzers/types.js.map +1 -1
  45. package/dist/audit/relationships/ai/prompts.js +10 -10
  46. package/dist/audit/relationships/ai/prompts.js.map +2 -2
  47. package/dist/audit/relationships/analysis/layer-templates.js +52 -52
  48. package/dist/audit/relationships/analysis/layer-templates.js.map +1 -1
  49. package/dist/cli.js +23 -11
  50. package/dist/cli.js.map +2 -2
  51. package/dist/coding-agents/default-permissions.js +31 -1
  52. package/dist/coding-agents/default-permissions.js.map +2 -2
  53. package/dist/coding-agents/drbot-mcp.js +269 -0
  54. package/dist/coding-agents/drbot-mcp.js.map +7 -0
  55. package/dist/commands/add.js +7 -4
  56. package/dist/commands/add.js.map +2 -2
  57. package/dist/commands/analyzer.js +143 -40
  58. package/dist/commands/analyzer.js.map +2 -2
  59. package/dist/commands/changeset-verify.js +63 -0
  60. package/dist/commands/changeset-verify.js.map +7 -0
  61. package/dist/commands/changeset.js +80 -29
  62. package/dist/commands/changeset.js.map +2 -2
  63. package/dist/commands/delete.js +10 -4
  64. package/dist/commands/delete.js.map +2 -2
  65. package/dist/commands/farm.js +176 -60
  66. package/dist/commands/farm.js.map +2 -2
  67. package/dist/commands/init.js +9 -26
  68. package/dist/commands/init.js.map +2 -2
  69. package/dist/commands/mcp.js +40 -21
  70. package/dist/commands/mcp.js.map +3 -3
  71. package/dist/commands/relationship.js +208 -37
  72. package/dist/commands/relationship.js.map +2 -2
  73. package/dist/commands/reports.js +3 -3
  74. package/dist/commands/reports.js.map +2 -2
  75. package/dist/commands/update.js +52 -32
  76. package/dist/commands/update.js.map +2 -2
  77. package/dist/commands/upgrade.js +99 -103
  78. package/dist/commands/upgrade.js.map +3 -3
  79. package/dist/commands/validate.js +19 -3
  80. package/dist/commands/validate.js.map +2 -2
  81. package/dist/commands/version.js +1 -1
  82. package/dist/commands/visualize.js +34 -15
  83. package/dist/commands/visualize.js.map +2 -2
  84. package/dist/core/annotation-store.js +15 -5
  85. package/dist/core/annotation-store.js.map +2 -2
  86. package/dist/core/catalog-migration.js +34 -0
  87. package/dist/core/catalog-migration.js.map +7 -0
  88. package/dist/core/changeset-analysis.js +421 -0
  89. package/dist/core/changeset-analysis.js.map +7 -0
  90. package/dist/core/changeset-base-index.js +160 -0
  91. package/dist/core/changeset-base-index.js.map +7 -0
  92. package/dist/core/changeset-brief-compact.js +256 -0
  93. package/dist/core/changeset-brief-compact.js.map +7 -0
  94. package/dist/core/changeset-brief-delta.js +102 -0
  95. package/dist/core/changeset-brief-delta.js.map +7 -0
  96. package/dist/core/changeset-graph.js +281 -0
  97. package/dist/core/changeset-graph.js.map +7 -0
  98. package/dist/core/changeset-only-guard.js +32 -0
  99. package/dist/core/changeset-only-guard.js.map +7 -0
  100. package/dist/core/changeset-summary.js +68 -0
  101. package/dist/core/changeset-summary.js.map +7 -0
  102. package/dist/core/changeset-validator.js +66 -20
  103. package/dist/core/changeset-validator.js.map +2 -2
  104. package/dist/core/changeset-verify.js +848 -0
  105. package/dist/core/changeset-verify.js.map +7 -0
  106. package/dist/core/changeset.js +56 -9
  107. package/dist/core/changeset.js.map +2 -2
  108. package/dist/core/element-type-migration.js +145 -0
  109. package/dist/core/element-type-migration.js.map +7 -0
  110. package/dist/core/extraction-observability.js +161 -0
  111. package/dist/core/extraction-observability.js.map +7 -0
  112. package/dist/core/farm-manifest.js +12 -6
  113. package/dist/core/farm-manifest.js.map +2 -2
  114. package/dist/core/farm-sync-engine.js +1 -1
  115. package/dist/core/farm-sync-engine.js.map +2 -2
  116. package/dist/core/farm-sync-state.js +10 -2
  117. package/dist/core/farm-sync-state.js.map +2 -2
  118. package/dist/core/migration-registry.js +88 -47
  119. package/dist/core/migration-registry.js.map +2 -2
  120. package/dist/core/model-upgrade.js +102 -0
  121. package/dist/core/model-upgrade.js.map +7 -0
  122. package/dist/core/model.js +82 -30
  123. package/dist/core/model.js.map +2 -2
  124. package/dist/core/mutation-handler.js +71 -6
  125. package/dist/core/mutation-handler.js.map +2 -2
  126. package/dist/core/project-init.js +53 -0
  127. package/dist/core/project-init.js.map +7 -0
  128. package/dist/core/relationship-migration-table.js +6639 -0
  129. package/dist/core/relationship-migration-table.js.map +7 -0
  130. package/dist/core/relationship-migration.js +272 -0
  131. package/dist/core/relationship-migration.js.map +7 -0
  132. package/dist/core/relationship-prune.js +49 -0
  133. package/dist/core/relationship-prune.js.map +7 -0
  134. package/dist/core/relationship-staging.js +161 -0
  135. package/dist/core/relationship-staging.js.map +7 -0
  136. package/dist/core/relationships.js +26 -4
  137. package/dist/core/relationships.js.map +2 -2
  138. package/dist/core/report-data-model.js +7 -13
  139. package/dist/core/report-data-model.js.map +2 -2
  140. package/dist/core/staged-changeset-storage.js +145 -18
  141. package/dist/core/staged-changeset-storage.js.map +2 -2
  142. package/dist/core/staged-source-reference.js +28 -0
  143. package/dist/core/staged-source-reference.js.map +7 -0
  144. package/dist/core/staging-area.js +166 -24
  145. package/dist/core/staging-area.js.map +2 -2
  146. package/dist/core/upgrade-plan.js +117 -0
  147. package/dist/core/upgrade-plan.js.map +7 -0
  148. package/dist/core/virtual-projection.js +13 -5
  149. package/dist/core/virtual-projection.js.map +2 -2
  150. package/dist/export/archimate-exporter.js +1 -0
  151. package/dist/export/archimate-exporter.js.map +2 -2
  152. package/dist/generated/compiled-validators.js +2 -2
  153. package/dist/generated/compiled-validators.js.map +2 -2
  154. package/dist/generated/layer-registry.js +16 -16
  155. package/dist/generated/layer-registry.js.map +2 -2
  156. package/dist/generated/node-types.js +186 -168
  157. package/dist/generated/node-types.js.map +2 -2
  158. package/dist/generated/relationship-index.js +2468 -7913
  159. package/dist/generated/relationship-index.js.map +2 -2
  160. package/dist/integrations/claude_code/.claude-plugin/plugin.json +24 -0
  161. package/dist/integrations/claude_code/agents/dr-architect.md +30 -3
  162. package/dist/integrations/claude_code/agents/dr-extractor.md +8 -2
  163. package/dist/integrations/claude_code/commands/dr-analyzer.md +565 -0
  164. package/dist/integrations/claude_code/commands/dr-changeset.md +2 -1
  165. package/dist/integrations/claude_code/commands/dr-map.md +20 -1
  166. package/dist/integrations/claude_code/commands/dr-plan.md +66 -0
  167. package/dist/integrations/claude_code/commands/dr-relate.md +106 -96
  168. package/dist/integrations/claude_code/commands/dr-verify.md +45 -2
  169. package/dist/integrations/claude_code/docs/END_TO_END_WALKTHROUGH.md +14 -0
  170. package/dist/integrations/claude_code/docs/MCP_SERVER.md +47 -26
  171. package/dist/integrations/claude_code/docs/QUICK_START.md +37 -8
  172. package/dist/integrations/claude_code/docs/README.md +68 -2
  173. package/dist/integrations/claude_code/plugin-agents/dr-advisor.md +255 -0
  174. package/dist/integrations/claude_code/plugin-agents/dr-architect.md +306 -0
  175. package/dist/integrations/claude_code/skills/dr_01_motivation_layer/SKILL.md +93 -72
  176. package/dist/integrations/claude_code/skills/dr_02_business_layer/SKILL.md +163 -126
  177. package/dist/integrations/claude_code/skills/dr_03_product_layer/SKILL.md +161 -126
  178. package/dist/integrations/claude_code/skills/dr_04_security_layer/SKILL.md +153 -133
  179. package/dist/integrations/claude_code/skills/dr_05_application_layer/SKILL.md +129 -100
  180. package/dist/integrations/claude_code/skills/dr_06_technology_layer/SKILL.md +111 -94
  181. package/dist/integrations/claude_code/skills/dr_07_api_layer/SKILL.md +143 -157
  182. package/dist/integrations/claude_code/skills/dr_08_data_model_layer/SKILL.md +117 -33
  183. package/dist/integrations/claude_code/skills/dr_09_dataset_layer/SKILL.md +74 -25
  184. package/dist/integrations/claude_code/skills/dr_10_ux_layer/SKILL.md +88 -12
  185. package/dist/integrations/claude_code/skills/dr_11_navigation_layer/SKILL.md +83 -24
  186. package/dist/integrations/claude_code/skills/dr_12_apm_layer/SKILL.md +57 -12
  187. package/dist/integrations/claude_code/skills/dr_13_testing_layer/SKILL.md +95 -15
  188. package/dist/integrations/claude_code/skills/dr_change_planning/SKILL.md +178 -0
  189. package/dist/integrations/claude_code/skills/dr_changeset_reviewer/SKILL.md +8 -0
  190. package/dist/integrations/claude_code/skills/dr_engineering_guide/SKILL.md +6 -1
  191. package/dist/integrations/github_copilot/agents/dr-architect.md +3 -1
  192. package/dist/integrations/github_copilot/skills/dr_01_motivation_layer/SKILL.md +182 -102
  193. package/dist/integrations/github_copilot/skills/dr_02_business_layer/SKILL.md +266 -148
  194. package/dist/integrations/github_copilot/skills/dr_03_product_layer/SKILL.md +547 -86
  195. package/dist/integrations/github_copilot/skills/dr_04_security_layer/SKILL.md +164 -169
  196. package/dist/integrations/github_copilot/skills/dr_05_application_layer/SKILL.md +420 -150
  197. package/dist/integrations/github_copilot/skills/dr_06_technology_layer/SKILL.md +331 -138
  198. package/dist/integrations/github_copilot/skills/dr_07_api_layer/SKILL.md +265 -201
  199. package/dist/integrations/github_copilot/skills/dr_08_data_model_layer/SKILL.md +181 -58
  200. package/dist/integrations/github_copilot/skills/dr_09_dataset_layer/SKILL.md +209 -57
  201. package/dist/integrations/github_copilot/skills/dr_10_ux_layer/SKILL.md +277 -112
  202. package/dist/integrations/github_copilot/skills/dr_11_navigation_layer/SKILL.md +219 -70
  203. package/dist/integrations/github_copilot/skills/dr_12_apm_layer/SKILL.md +189 -105
  204. package/dist/integrations/github_copilot/skills/dr_13_testing_layer/SKILL.md +225 -102
  205. package/dist/integrations/github_copilot/skills/dr_change_planning/SKILL.md +177 -0
  206. package/dist/integrations/github_copilot/skills/dr_changeset_reviewer/SKILL.md +3 -0
  207. package/dist/integrations/hash-utils.js.map +2 -2
  208. package/dist/mcp/api-key-manager.js +14 -1
  209. package/dist/mcp/api-key-manager.js.map +2 -2
  210. package/dist/mcp/changeset-only.js +45 -0
  211. package/dist/mcp/changeset-only.js.map +7 -0
  212. package/dist/mcp/project-root.js +85 -0
  213. package/dist/mcp/project-root.js.map +7 -0
  214. package/dist/mcp/server-instructions.js +27 -0
  215. package/dist/mcp/server-instructions.js.map +7 -0
  216. package/dist/mcp/strict-schema.js +52 -0
  217. package/dist/mcp/strict-schema.js.map +7 -0
  218. package/dist/mcp/tool-registry.js +55 -5
  219. package/dist/mcp/tool-registry.js.map +2 -2
  220. package/dist/mcp/tools/changeset-analysis-tools.js +98 -0
  221. package/dist/mcp/tools/changeset-analysis-tools.js.map +7 -0
  222. package/dist/mcp/tools/changeset-commit.js +224 -0
  223. package/dist/mcp/tools/changeset-commit.js.map +7 -0
  224. package/dist/mcp/tools/changeset-editing.js +260 -0
  225. package/dist/mcp/tools/changeset-editing.js.map +7 -0
  226. package/dist/mcp/tools/changeset-lifecycle.js +83 -0
  227. package/dist/mcp/tools/changeset-lifecycle.js.map +7 -0
  228. package/dist/mcp/tools/changeset-shared.js +31 -0
  229. package/dist/mcp/tools/changeset-shared.js.map +7 -0
  230. package/dist/mcp/tools/changeset-show.js +17 -1
  231. package/dist/mcp/tools/changeset-show.js.map +2 -2
  232. package/dist/mcp/tools/changeset-verify.js +49 -0
  233. package/dist/mcp/tools/changeset-verify.js.map +7 -0
  234. package/dist/mcp/tools/codebase-extract.js +836 -0
  235. package/dist/mcp/tools/codebase-extract.js.map +7 -0
  236. package/dist/mcp/tools/codebase-index.js +125 -0
  237. package/dist/mcp/tools/codebase-index.js.map +7 -0
  238. package/dist/mcp/tools/codebase-shared.js +265 -0
  239. package/dist/mcp/tools/codebase-shared.js.map +7 -0
  240. package/dist/mcp/tools/codebase-verify.js +48 -0
  241. package/dist/mcp/tools/codebase-verify.js.map +7 -0
  242. package/dist/mcp/tools/index.js +34 -1
  243. package/dist/mcp/tools/index.js.map +2 -2
  244. package/dist/mcp/tools/model-add.js +191 -74
  245. package/dist/mcp/tools/model-add.js.map +2 -2
  246. package/dist/mcp/tools/model-delete.js +2 -2
  247. package/dist/mcp/tools/model-delete.js.map +2 -2
  248. package/dist/mcp/tools/model-search.js +14 -0
  249. package/dist/mcp/tools/model-search.js.map +2 -2
  250. package/dist/mcp/tools/model-show.js +29 -2
  251. package/dist/mcp/tools/model-show.js.map +2 -2
  252. package/dist/mcp/tools/model-trace.js +93 -30
  253. package/dist/mcp/tools/model-trace.js.map +2 -2
  254. package/dist/mcp/tools/model-update.js +46 -26
  255. package/dist/mcp/tools/model-update.js.map +2 -2
  256. package/dist/mcp/tools/model-validate.js +46 -4
  257. package/dist/mcp/tools/model-validate.js.map +2 -2
  258. package/dist/mcp/tools/project-status-collectors.js +381 -0
  259. package/dist/mcp/tools/project-status-collectors.js.map +7 -0
  260. package/dist/mcp/tools/project-status.js +237 -0
  261. package/dist/mcp/tools/project-status.js.map +7 -0
  262. package/dist/mcp/tools/project-tools.js +505 -0
  263. package/dist/mcp/tools/project-tools.js.map +7 -0
  264. package/dist/mcp/tools/relationship-tools.js +167 -0
  265. package/dist/mcp/tools/relationship-tools.js.map +7 -0
  266. package/dist/mcp/tools/review-open.js +210 -0
  267. package/dist/mcp/tools/review-open.js.map +7 -0
  268. package/dist/mcp/tools/shared.js +35 -4
  269. package/dist/mcp/tools/shared.js.map +2 -2
  270. package/dist/mcp/tools/spec-type.js +90 -0
  271. package/dist/mcp/tools/spec-type.js.map +7 -0
  272. package/dist/reports/model-report-orchestrator.js +31 -2
  273. package/dist/reports/model-report-orchestrator.js.map +2 -2
  274. package/dist/schemas/bundled/analyzers/cbm.json +1200 -70
  275. package/dist/schemas/bundled/analyzers/manifest.json +2 -2
  276. package/dist/schemas/bundled/api.json +1029 -1658
  277. package/dist/schemas/bundled/apm.json +499 -734
  278. package/dist/schemas/bundled/application.json +735 -371
  279. package/dist/schemas/bundled/base.json +3 -220
  280. package/dist/schemas/bundled/business.json +452 -366
  281. package/dist/schemas/bundled/data-model.json +395 -411
  282. package/dist/schemas/bundled/data-store.json +334 -558
  283. package/dist/schemas/bundled/manifest.json +18 -18
  284. package/dist/schemas/bundled/motivation.json +349 -368
  285. package/dist/schemas/bundled/navigation.json +415 -731
  286. package/dist/schemas/bundled/product.json +325 -159
  287. package/dist/schemas/bundled/security.json +864 -1232
  288. package/dist/schemas/bundled/technology.json +574 -703
  289. package/dist/schemas/bundled/testing.json +865 -1646
  290. package/dist/schemas/bundled/ux.json +739 -1352
  291. package/dist/server/schemas.js +8 -0
  292. package/dist/server/schemas.js.map +2 -2
  293. package/dist/server/server.js +686 -231
  294. package/dist/server/server.js.map +3 -3
  295. package/dist/server/viewer-registry.js +264 -0
  296. package/dist/server/viewer-registry.js.map +7 -0
  297. package/dist/server-entry.js +2 -1
  298. package/dist/server-entry.js.map +2 -2
  299. package/dist/telemetry/index.js +1 -1
  300. package/dist/utils/ansi-suppressor.js +6 -8
  301. package/dist/utils/ansi-suppressor.js.map +2 -2
  302. package/dist/utils/attribute-patch.js +41 -0
  303. package/dist/utils/attribute-patch.js.map +7 -0
  304. package/dist/utils/error-hints.js +29 -0
  305. package/dist/utils/error-hints.js.map +7 -0
  306. package/dist/utils/errors.js +9 -3
  307. package/dist/utils/errors.js.map +2 -2
  308. package/dist/utils/id-generator.js +5 -2
  309. package/dist/utils/id-generator.js.map +2 -2
  310. package/dist/utils/project-paths.js +26 -1
  311. package/dist/utils/project-paths.js.map +2 -2
  312. package/dist/utils/source-reference.js +64 -31
  313. package/dist/utils/source-reference.js.map +2 -2
  314. package/dist/utils/spec-version.js +2 -2
  315. package/dist/utils/spec-version.js.map +1 -1
  316. package/dist/validators/composed-reference-validator.js +5 -27
  317. package/dist/validators/composed-reference-validator.js.map +2 -2
  318. package/dist/validators/model-warnings.js +28 -0
  319. package/dist/validators/model-warnings.js.map +7 -0
  320. package/dist/validators/reference-validator.js +0 -7
  321. package/dist/validators/reference-validator.js.map +2 -2
  322. package/dist/validators/relationship-schema-validator.js +3 -3
  323. package/dist/validators/relationship-schema-validator.js.map +2 -2
  324. package/dist/validators/schema-validator.js +27 -9
  325. package/dist/validators/schema-validator.js.map +2 -2
  326. package/dist/validators/types.js.map +1 -1
  327. package/dist/viewer/README.md +6 -6
  328. package/dist/viewer/assets/main-CUOQGGRA.css +1 -0
  329. package/dist/viewer/assets/main-DvH3gYrI.js +84 -0
  330. package/dist/viewer/index.html +2 -2
  331. package/dist/viewer/manifest.json +10 -10
  332. package/dist/viewer/version.json +1 -1
  333. package/package.json +2 -1
  334. package/dist/viewer/assets/main-B7AOQXXX.js +0 -81
  335. package/dist/viewer/assets/main-vdrFrG7q.css +0 -1
@@ -0,0 +1,117 @@
1
+ import { getSpecReferencePath, getModelPath } from "../utils/project-paths.js";
2
+ import { getCliBundledSpecVersion, getInstalledSpecVersion, getModelSpecVersion } from "../utils/spec-version.js";
3
+ import { MigrationRegistry } from "./migration-registry.js";
4
+ import { Model } from "./model.js";
5
+ import { applyCatalogMigrations } from "./catalog-migration.js";
6
+ import { getErrorMessage } from "../utils/errors.js";
7
+ class UpgradeScanError extends Error {
8
+ constructor(message) {
9
+ super(message), this.name = "UpgradeScanError";
10
+ }
11
+ }
12
+ async function scanUpgrades(projectRoot, options = {}) {
13
+ const bundledSpecVersion = getCliBundledSpecVersion(), actions = [], scan = {
14
+ projectRoot,
15
+ bundledSpecVersion,
16
+ installedSpecVersion: null,
17
+ model: { state: "missing" },
18
+ actions,
19
+ steps: []
20
+ }, drPath = await getSpecReferencePath(projectRoot);
21
+ let currentSpecVersion = null;
22
+ if (!drPath)
23
+ actions.push({
24
+ type: "spec",
25
+ description: "Install spec reference",
26
+ toVersion: bundledSpecVersion,
27
+ details: ["Create .dr/ folder", "Install schema files", `Set spec version to ${bundledSpecVersion}`]
28
+ });
29
+ else {
30
+ let installedSpecVersion = null;
31
+ try {
32
+ installedSpecVersion = await getInstalledSpecVersion(drPath);
33
+ } catch (error) {
34
+ throw new UpgradeScanError(getErrorMessage(error));
35
+ }
36
+ currentSpecVersion = installedSpecVersion, scan.installedSpecVersion = installedSpecVersion, installedSpecVersion ? (installedSpecVersion !== bundledSpecVersion || options.force) && actions.push({
37
+ type: "spec",
38
+ description: installedSpecVersion !== bundledSpecVersion ? "Upgrade spec reference" : "Reinstall spec reference (forced)",
39
+ fromVersion: installedSpecVersion,
40
+ toVersion: bundledSpecVersion,
41
+ details: ["Update schema files", "Update .dr/manifest.json"]
42
+ }) : actions.push({
43
+ type: "spec",
44
+ description: "Reinstall spec reference (manifest missing)",
45
+ toVersion: bundledSpecVersion,
46
+ details: ["Recreate .dr/manifest.json", "Update schema files", `Set spec version to ${bundledSpecVersion}`]
47
+ });
48
+ }
49
+ const modelPath = await getModelPath(projectRoot);
50
+ if (!modelPath)
51
+ return scan;
52
+ let modelSpecVersion = null;
53
+ try {
54
+ modelSpecVersion = await getModelSpecVersion(modelPath);
55
+ } catch (error) {
56
+ throw new UpgradeScanError(getErrorMessage(error));
57
+ }
58
+ if (!modelSpecVersion)
59
+ return scan.model = { state: "no-spec-version" }, scan;
60
+ const targetSpecVersion = options.targetBundledSpec ? bundledSpecVersion : currentSpecVersion || bundledSpecVersion;
61
+ if (scan.model = { state: "found", specVersion: modelSpecVersion, targetSpecVersion }, modelSpecVersion !== targetSpecVersion) {
62
+ const registry = new MigrationRegistry(), summary = registry.getMigrationSummary(modelSpecVersion, targetSpecVersion);
63
+ if (summary.migrationsNeeded === 0)
64
+ return options.force ? actions.push({
65
+ type: "model",
66
+ description: "Force-update model spec version (no migration required)",
67
+ fromVersion: modelSpecVersion,
68
+ toVersion: targetSpecVersion,
69
+ details: ["Update manifest.yaml specVersion (no data changes needed)"],
70
+ versionBumpOnly: !0
71
+ }) : scan.noMigrationPath = {
72
+ from: modelSpecVersion,
73
+ to: targetSpecVersion,
74
+ available: registry.getMigrationSummary("0.5.0").migrations
75
+ }, scan;
76
+ scan.steps = summary.migrations, actions.push({
77
+ type: "model",
78
+ description: "Migrate model data",
79
+ fromVersion: modelSpecVersion,
80
+ toVersion: targetSpecVersion,
81
+ details: summary.migrations.map((m) => `${m.from} \u2192 ${m.to}: ${m.description}`)
82
+ });
83
+ } else {
84
+ try {
85
+ scan.catalogPreview = await previewCatalogMigration(projectRoot);
86
+ } catch (error) {
87
+ scan.catalogCheckError = getErrorMessage(error);
88
+ }
89
+ const catalogAction = scan.catalogPreview ? catalogActionFor(scan.catalogPreview, targetSpecVersion) : null;
90
+ catalogAction && actions.push(catalogAction);
91
+ }
92
+ return scan;
93
+ }
94
+ async function previewCatalogMigration(projectRoot) {
95
+ return applyCatalogMigrations(await Model.load(projectRoot, { lazyLoad: !1 }), { dryRun: !0 });
96
+ }
97
+ function catalogActionFor(preview, version) {
98
+ const elementTypes = preview.details.elementTypeChanges.length, relationships = preview.details.relationshipChanges.length, stagedRelationships = preview.details.stagedRelationshipChanges.length, details = [
99
+ ...elementTypes > 0 ? [`Rename ${elementTypes} element(s) whose type was renamed`] : [],
100
+ ...relationships > 0 ? [`Rewrite or drop ${relationships} relationship(s) of retired types`] : [],
101
+ ...stagedRelationships > 0 ? [`Rewrite ${stagedRelationships} staged relationship change(s)`] : []
102
+ ];
103
+ return details.length === 0 ? null : {
104
+ type: "model",
105
+ description: `Apply catalog changes to the model (spec v${version})`,
106
+ fromVersion: version,
107
+ toVersion: version,
108
+ details,
109
+ catalogOnly: !0
110
+ };
111
+ }
112
+ export {
113
+ UpgradeScanError,
114
+ previewCatalogMigration,
115
+ scanUpgrades
116
+ };
117
+ //# sourceMappingURL=upgrade-plan.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/core/upgrade-plan.ts"],
4
+ "sourcesContent": ["/**\n * Upgrade plan - what `dr upgrade` and the `project_upgrade` MCP tool would change in a project,\n * as data. The CLI prints it and asks; the MCP tool returns it as the preview.\n *\n * It covers the spec reference (.dr/) and the model. Installed integrations (Claude Code,\n * Copilot) are scanned by `dr upgrade` itself: the MCP tool leaves them alone.\n */\n\nimport { getSpecReferencePath, getModelPath } from \"../utils/project-paths.js\";\nimport { getCliBundledSpecVersion, getInstalledSpecVersion, getModelSpecVersion } from \"../utils/spec-version.js\";\nimport { MigrationRegistry } from \"./migration-registry.js\";\nimport { Model } from \"./model.js\";\nimport { applyCatalogMigrations, type CatalogMigrationResult } from \"./catalog-migration.js\";\nimport { getErrorMessage } from \"../utils/errors.js\";\n\nexport interface UpgradeAction {\n type: \"spec\" | \"model\" | \"integration\";\n description: string;\n fromVersion?: string;\n toVersion: string;\n details?: string[];\n integrationName?: \"claude\" | \"copilot\";\n versionBumpOnly?: boolean;\n /** Model already at the target version, but with catalog changes it has not received */\n catalogOnly?: boolean;\n}\n\n/** A migration step between two spec versions */\nexport interface UpgradeStep {\n from: string;\n to: string;\n description: string;\n /** The step renames element types and rewrites relationships from the generated table */\n rewritesCatalog?: boolean;\n}\n\nexport type UpgradeModelState =\n | { state: \"missing\" }\n | { state: \"no-spec-version\" }\n | { state: \"found\"; specVersion: string; targetSpecVersion: string };\n\nexport interface UpgradeScan {\n projectRoot: string;\n bundledSpecVersion: string;\n /** The spec reference's (.dr/) version; null when it is missing or has no manifest */\n installedSpecVersion: string | null;\n model: UpgradeModelState;\n /** Spec reference and model actions, in the order they run. Integrations are not included. */\n actions: UpgradeAction[];\n /** The migration steps from the model's version to the target; empty when there are none */\n steps: UpgradeStep[];\n /** Set when the model is behind and no migration leads to the target (and force is off) */\n noMigrationPath?: { from: string; to: string; available: UpgradeStep[] };\n /**\n * The catalog dry run, when the scan ran one: a model at the target version is checked for\n * element types and relationships the catalog has retired\n */\n catalogPreview?: CatalogMigrationResult;\n /** The catalog check failed; the scan goes on without a catalog action */\n catalogCheckError?: string;\n}\n\nexport interface UpgradeScanOptions {\n force?: boolean;\n /**\n * Migrate the model to the spec version this CLI carries even when the installed spec\n * reference is older. `dr upgrade` targets the installed reference's version (a stale\n * reference is upgraded in the same run, and the model follows on the next run); the MCP\n * tool moves both in one step.\n */\n targetBundledSpec?: boolean;\n}\n\n/** An error reading the spec reference or model manifest; `dr upgrade` prints it before failing. */\nexport class UpgradeScanError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"UpgradeScanError\";\n }\n}\n\n/** Scan the project at projectRoot for spec reference and model upgrades. Changes nothing. */\nexport async function scanUpgrades(projectRoot: string, options: UpgradeScanOptions = {}): Promise<UpgradeScan> {\n const bundledSpecVersion = getCliBundledSpecVersion();\n const actions: UpgradeAction[] = [];\n const scan: UpgradeScan = {\n projectRoot,\n bundledSpecVersion,\n installedSpecVersion: null,\n model: { state: \"missing\" },\n actions,\n steps: [],\n };\n\n // Spec reference (.dr/ folder)\n const drPath = await getSpecReferencePath(projectRoot);\n let currentSpecVersion: string | null = null;\n\n if (!drPath) {\n actions.push({\n type: \"spec\",\n description: \"Install spec reference\",\n toVersion: bundledSpecVersion,\n details: [\"Create .dr/ folder\", \"Install schema files\", `Set spec version to ${bundledSpecVersion}`],\n });\n } else {\n let installedSpecVersion: string | null = null;\n try {\n installedSpecVersion = await getInstalledSpecVersion(drPath);\n } catch (error) {\n // Manifest file exists but is corrupted or unreadable\n throw new UpgradeScanError(getErrorMessage(error));\n }\n currentSpecVersion = installedSpecVersion;\n scan.installedSpecVersion = installedSpecVersion;\n\n if (!installedSpecVersion) {\n actions.push({\n type: \"spec\",\n description: \"Reinstall spec reference (manifest missing)\",\n toVersion: bundledSpecVersion,\n details: [\"Recreate .dr/manifest.json\", \"Update schema files\", `Set spec version to ${bundledSpecVersion}`],\n });\n } else if (installedSpecVersion !== bundledSpecVersion || options.force) {\n actions.push({\n type: \"spec\",\n description:\n installedSpecVersion !== bundledSpecVersion ? \"Upgrade spec reference\" : \"Reinstall spec reference (forced)\",\n fromVersion: installedSpecVersion,\n toVersion: bundledSpecVersion,\n details: [\"Update schema files\", \"Update .dr/manifest.json\"],\n });\n }\n }\n\n // Model\n const modelPath = await getModelPath(projectRoot);\n if (!modelPath) {\n return scan;\n }\n\n let modelSpecVersion: string | null = null;\n try {\n modelSpecVersion = await getModelSpecVersion(modelPath);\n } catch (error) {\n // Manifest file exists but is corrupted or unreadable\n throw new UpgradeScanError(getErrorMessage(error));\n }\n\n if (!modelSpecVersion) {\n scan.model = { state: \"no-spec-version\" };\n return scan;\n }\n\n const targetSpecVersion = options.targetBundledSpec\n ? bundledSpecVersion\n : currentSpecVersion || bundledSpecVersion;\n scan.model = { state: \"found\", specVersion: modelSpecVersion, targetSpecVersion };\n\n if (modelSpecVersion !== targetSpecVersion) {\n const registry = new MigrationRegistry();\n const summary = registry.getMigrationSummary(modelSpecVersion, targetSpecVersion);\n\n if (summary.migrationsNeeded === 0) {\n if (options.force) {\n // No migration path exists, but --force allows bumping the model version directly.\n // This is safe for additive spec changes (new node types / relationships) that\n // require no structural data changes.\n actions.push({\n type: \"model\",\n description: \"Force-update model spec version (no migration required)\",\n fromVersion: modelSpecVersion,\n toVersion: targetSpecVersion,\n details: [\"Update manifest.yaml specVersion (no data changes needed)\"],\n versionBumpOnly: true,\n });\n } else {\n scan.noMigrationPath = {\n from: modelSpecVersion,\n to: targetSpecVersion,\n available: registry.getMigrationSummary(\"0.5.0\").migrations,\n };\n }\n return scan;\n }\n\n scan.steps = summary.migrations;\n actions.push({\n type: \"model\",\n description: \"Migrate model data\",\n fromVersion: modelSpecVersion,\n toVersion: targetSpecVersion,\n details: summary.migrations.map((m) => `${m.from} \u2192 ${m.to}: ${m.description}`),\n });\n } else {\n // Same spec version, but the relationship catalog can change between version bumps: a\n // model stamped with the current version before a catalog change still needs it\n try {\n scan.catalogPreview = await previewCatalogMigration(projectRoot);\n } catch (error) {\n scan.catalogCheckError = getErrorMessage(error);\n }\n const catalogAction = scan.catalogPreview ? catalogActionFor(scan.catalogPreview, targetSpecVersion) : null;\n if (catalogAction) {\n actions.push(catalogAction);\n }\n }\n\n return scan;\n}\n\n/** What the catalog migration would change in the model at projectRoot, without changing it. */\nexport async function previewCatalogMigration(projectRoot: string): Promise<CatalogMigrationResult> {\n return applyCatalogMigrations(await Model.load(projectRoot, { lazyLoad: false }), { dryRun: true });\n}\n\n/**\n * A model action when a model at the current spec version still names element types or\n * relationship types the catalog has retired; null when it is in line with the catalog\n */\nfunction catalogActionFor(preview: CatalogMigrationResult, version: string): UpgradeAction | null {\n const elementTypes = preview.details.elementTypeChanges.length;\n const relationships = preview.details.relationshipChanges.length;\n const stagedRelationships = preview.details.stagedRelationshipChanges.length;\n const details = [\n ...(elementTypes > 0 ? [`Rename ${elementTypes} element(s) whose type was renamed`] : []),\n ...(relationships > 0 ? [`Rewrite or drop ${relationships} relationship(s) of retired types`] : []),\n ...(stagedRelationships > 0 ? [`Rewrite ${stagedRelationships} staged relationship change(s)`] : []),\n ];\n if (details.length === 0) {\n return null;\n }\n return {\n type: \"model\",\n description: `Apply catalog changes to the model (spec v${version})`,\n fromVersion: version,\n toVersion: version,\n details,\n catalogOnly: true,\n };\n}\n"],
5
+ "mappings": "AAQA,SAAS,sBAAsB,oBAAoB;AACnD,SAAS,0BAA0B,yBAAyB,2BAA2B;AACvF,SAAS,yBAAyB;AAClC,SAAS,aAAa;AACtB,SAAS,8BAA2D;AACpE,SAAS,uBAAuB;AA6D1B,MAAO,yBAAyB,MAAK;EACzC,YAAY,SAAe;AACzB,UAAM,OAAO,GACb,KAAK,OAAO;EACd;;AAIF,eAAsB,aAAa,aAAqB,UAA8B,CAAA,GAAE;AACtF,QAAM,qBAAqB,yBAAwB,GAC7C,UAA2B,CAAA,GAC3B,OAAoB;IACxB;IACA;IACA,sBAAsB;IACtB,OAAO,EAAE,OAAO,UAAS;IACzB;IACA,OAAO,CAAA;KAIH,SAAS,MAAM,qBAAqB,WAAW;AACrD,MAAI,qBAAoC;AAExC,MAAI,CAAC;AACH,YAAQ,KAAK;MACX,MAAM;MACN,aAAa;MACb,WAAW;MACX,SAAS,CAAC,sBAAsB,wBAAwB,uBAAuB,kBAAkB,EAAE;KACpG;OACI;AACL,QAAI,uBAAsC;AAC1C,QAAI;AACF,6BAAuB,MAAM,wBAAwB,MAAM;IAC7D,SAAS,OAAO;AAEd,YAAM,IAAI,iBAAiB,gBAAgB,KAAK,CAAC;IACnD;AACA,yBAAqB,s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;KAC/E;EACH,OAAO;AAGL,QAAI;AACF,WAAK,iBAAiB,MAAM,wBAAwB,WAAW;IACjE,SAAS,OAAO;AACd,WAAK,oBAAoB,gBAAgB,KAAK;IAChD;AACA,UAAM,gBAAgB,KAAK,iBAAiB,iBAAiB,KAAK,gBAAgB,iBAAiB,IAAI;AACvG,IAAI,iBACF,QAAQ,KAAK,aAAa;EAE9B;AAEA,SAAO;AACT;AAGA,eAAsB,wBAAwB,aAAmB;AAC/D,SAAO,uBAAuB,MAAM,MAAM,KAAK,aAAa,EAAE,UAAU,GAAK,CAAE,GAAG,EAAE,QAAQ,GAAI,CAAE;AACpG;AAMA,SAAS,iBAAiB,SAAiC,SAAe;AACxE,QAAM,eAAe,QAAQ,QAAQ,mBAAmB,QAClD,gBAAgB,QAAQ,QAAQ,oBAAoB,QACpD,sBAAsB,QAAQ,QAAQ,0BAA0B,QAChE,UAAU;IACd,GAAI,eAAe,IAAI,CAAC,UAAU,YAAY,oCAAoC,IAAI,CAAA;IACtF,GAAI,gBAAgB,IAAI,CAAC,mBAAmB,aAAa,mCAAmC,IAAI,CAAA;IAChG,GAAI,sBAAsB,IAAI,CAAC,WAAW,mBAAmB,gCAAgC,IAAI,CAAA;;AAEnG,SAAI,QAAQ,WAAW,IACd,OAEF;IACL,MAAM;IACN,aAAa,6CAA6C,OAAO;IACjE,aAAa;IACb,WAAW;IACX;IACA,aAAa;;AAEjB;",
6
+ "names": []
7
+ }
@@ -1,5 +1,7 @@
1
+ import { readStagedSourceReference, stagedSourceReference } from "./staged-source-reference.js";
1
2
  import { Layer as LayerClass } from "./layer.js";
2
3
  import { Element as ElementClass } from "./element.js";
4
+ import { withSequenceNumbers } from "./changeset.js";
3
5
  import { StagedChangesetStorage } from "./staged-changeset-storage.js";
4
6
  class VirtualProjectionEngine {
5
7
  stagingAreaManager;
@@ -60,7 +62,10 @@ class VirtualProjectionEngine {
60
62
  },
61
63
  references: Array.isArray(projectedData.references) ? projectedData.references : baseElement.references,
62
64
  relationships: Array.isArray(projectedData.relationships) ? projectedData.relationships : baseElement.relationships,
63
- source_reference: baseElement.source_reference,
65
+ source_reference: (() => {
66
+ const staged = readStagedSourceReference(projectedData);
67
+ return staged.present ? staged.value : baseElement.source_reference;
68
+ })(),
64
69
  metadata: baseElement.metadata
65
70
  };
66
71
  return new ElementClass(mergedData);
@@ -76,7 +81,7 @@ class VirtualProjectionEngine {
76
81
  attributes: typeof projectedData.attributes == "object" ? projectedData.attributes : {},
77
82
  references: Array.isArray(projectedData.references) ? projectedData.references : [],
78
83
  relationships: Array.isArray(projectedData.relationships) ? projectedData.relationships : [],
79
- source_reference: projectedData.source_reference,
84
+ source_reference: stagedSourceReference(projectedData),
80
85
  metadata: projectedData.metadata,
81
86
  layer: lastChange.layerName
82
87
  });
@@ -112,7 +117,7 @@ class VirtualProjectionEngine {
112
117
  const baseLayer = await baseModel.getBaseLayer(layerName), projectedLayer = baseLayer ? this.cloneLayer(baseLayer) : new LayerClass(layerName), changeset = await this.stagingAreaManager.load(changesetId);
113
118
  if (!changeset)
114
119
  throw new Error(`Changeset '${changesetId}' not found`);
115
- const layerChanges = changeset.changes.filter((c) => c.layerName === layerName).sort((a, b) => a.sequenceNumber - b.sequenceNumber);
120
+ const layerChanges = withSequenceNumbers(changeset.changes).filter((c) => c.layerName === layerName).sort((a, b) => a.sequenceNumber - b.sequenceNumber);
116
121
  for (const change of layerChanges)
117
122
  switch (change.type) {
118
123
  case "add":
@@ -128,7 +133,7 @@ class VirtualProjectionEngine {
128
133
  attributes: typeof change.after.attributes == "object" ? change.after.attributes : {},
129
134
  references: Array.isArray(change.after.references) ? change.after.references : [],
130
135
  relationships: Array.isArray(change.after.relationships) ? change.after.relationships : [],
131
- source_reference: change.after.source_reference,
136
+ source_reference: stagedSourceReference(change.after),
132
137
  metadata: change.after.metadata,
133
138
  layer: layerName
134
139
  });
@@ -154,7 +159,10 @@ class VirtualProjectionEngine {
154
159
  references: Array.isArray(change.after.references) ? change.after.references : existing.references,
155
160
  relationships: Array.isArray(change.after.relationships) ? change.after.relationships : existing.relationships,
156
161
  layer: layerName,
157
- source_reference: existing.source_reference,
162
+ source_reference: (() => {
163
+ const staged = readStagedSourceReference(change.after);
164
+ return staged.present ? staged.value : existing.source_reference;
165
+ })(),
158
166
  metadata: existing.metadata
159
167
  });
160
168
  projectedLayer.updateElement(updatedElement);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/core/virtual-projection.ts"],
4
- "sourcesContent": ["/**\n * VirtualProjectionEngine - Computes merged model views by applying staged changes.\n *\n * Creates virtual (temporary) projections of the base model with staged changes applied,\n * without modifying or persisting the base model. Enables safe preview and validation\n * of changes before commit. Includes projection caching with TTL-based expiration.\n *\n * Staging changes are applied in sequence order to compute accurate merged views.\n */\n\nimport type { Model } from \"./model.js\";\nimport type { Layer } from \"./layer.js\";\nimport type { Element } from \"./element.js\";\nimport type { SourceReference, ElementMetadata } from \"../types/index.js\";\nimport type { Manifest } from \"./manifest.js\";\nimport type { Relationships } from \"./relationships.js\";\nimport { Layer as LayerClass } from \"./layer.js\";\nimport { Element as ElementClass } from \"./element.js\";\nimport type { StagedChange, Change } from \"./changeset.js\";\nimport { StagedChangesetStorage } from \"./staged-changeset-storage.js\";\n\n/**\n * Projected model with isProjection flag to prevent accidental saves.\n * This marker interface ensures that projected models are recognized as temporary\n * and cannot be persisted to disk without explicit commit of the underlying changeset.\n */\nexport interface ProjectedModel {\n manifest: Manifest;\n layers: Map<string, Layer>;\n relationships: Relationships;\n loadedLayerFilter?: string[];\n isProjection: true; // Always true; marks this as a temporary virtual projection\n}\n\n/**\n * Model diff categorizing changeset changes by type.\n * Separates staged changes into additions (new elements), modifications (updated attributes),\n * and deletions (removed elements). Used for preview and diff display operations.\n */\nexport interface ModelDiff {\n additions: Array<{\n elementId: string;\n layerName: string;\n data: Record<string, unknown>; // Complete element state (from change.after)\n }>;\n modifications: Array<{\n elementId: string;\n layerName: string;\n before: Record<string, unknown>; // Previous state (from change.before)\n after: Record<string, unknown>; // New state (from change.after)\n }>;\n deletions: Array<{\n elementId: string;\n layerName: string;\n data: Record<string, unknown>; // Element state before deletion (from change.before)\n }>;\n}\n\n/**\n * Single cached layer projection.\n * Stores the computed projected layer and timestamp for cache expiration.\n */\ninterface CacheEntry {\n layer: Layer;\n computedAt: string; // ISO timestamp for age calculation\n}\n\n/**\n * Cache hit/miss metrics for monitoring cache performance.\n * Tracks successful cache hits, misses, and invalidations per changeset.\n */\ninterface CacheMetrics {\n hits: number; // Number of successful cache hits\n misses: number; // Number of cache misses (required computation)\n invalidations: number; // Number of invalidation operations\n lastInvalidation?: string; // ISO timestamp of last invalidation\n}\n\n/**\n * Projection cache for storing computed layer projections.\n * Uses TTL-based expiration to prevent stale projections.\n * Entries are lazily removed when expired on access or during periodic cleanup.\n */\ninterface ProjectionCache {\n cache: Map<string, CacheEntry>; // Key format: `${changesetId}:${layerName}`\n metrics: Map<string, CacheMetrics>; // Cache metrics keyed by changesetId\n maxAge: number; // Cache entry TTL in milliseconds (5 minutes default)\n lastCleanup: number; // Timestamp of last cleanup to limit cleanup frequency\n}\n\n/**\n * VirtualProjectionEngine - Computes merged model views without persisting.\n * Applies staged changes to a cloned base model to compute projections.\n * Uses caching with TTL-based expiration to optimize repeated projections.\n */\nexport class VirtualProjectionEngine {\n private stagingAreaManager: StagedChangesetStorage;\n private projectionCache: ProjectionCache;\n\n /**\n * Create a new projection engine.\n *\n * @param rootPath - Root path to the model (used by StagedChangesetStorage)\n */\n constructor(rootPath: string) {\n this.stagingAreaManager = new StagedChangesetStorage(rootPath);\n this.projectionCache = {\n cache: new Map(),\n metrics: new Map(),\n maxAge: 5 * 60 * 1000, // 5-minute TTL for cached projections\n lastCleanup: Date.now(),\n };\n }\n\n /**\n * Project a single element by applying staged changes to it.\n * Merges the element's base state with staged changes to compute its projected state.\n *\n * @param baseModel - The base model to project from\n * @param changesetId - ID of the changeset containing staged changes\n * @param elementId - ID of the element to project\n * @returns Projected element with staged changes applied, or null if element is deleted\n * @throws Error if changeset not found\n *\n * @remarks\n * If multiple changes exist for the element, the last change determines final state.\n * For 'delete' operations, returns null.\n * For 'add' operations without base element, creates new element from staged data.\n * For 'update' operations, merges staged changes with base element attributes.\n */\n async projectElement(\n baseModel: Model,\n changesetId: string,\n elementId: string\n ): Promise<Element | null> {\n const changeset = await this.stagingAreaManager.load(changesetId);\n if (!changeset) {\n throw new Error(`Changeset '${changesetId}' not found`);\n }\n\n // Find all changes for this element across all layers\n const elementChanges = changeset.changes.filter(\n (c: Change) => c.elementId === elementId\n ) as StagedChange[];\n\n if (elementChanges.length === 0) {\n // No changes, return base element if it exists\n return baseModel.getElementById(elementId) || null;\n }\n\n // Get the last change to determine the element's final state\n const lastChange = elementChanges[elementChanges.length - 1];\n\n if (lastChange.type === \"delete\") {\n return null;\n }\n\n // For add or update, construct the projected element\n const baseElement = baseModel.getElementById(elementId);\n const projectedData = lastChange.after || {};\n\n if (baseElement) {\n // Create a new element with projected data merged with base\n const projectedAttributes =\n typeof projectedData.attributes === \"object\" ? projectedData.attributes : {};\n\n const mergedData = {\n id: baseElement.id,\n path: baseElement.path,\n spec_node_id: baseElement.spec_node_id,\n type: typeof projectedData.type === \"string\" ? projectedData.type : baseElement.type,\n layer_id: baseElement.layer_id,\n name: typeof projectedData.name === \"string\" ? projectedData.name : baseElement.name,\n description:\n typeof projectedData.description === \"string\"\n ? projectedData.description\n : baseElement.description,\n attributes: {\n ...baseElement.attributes,\n ...projectedAttributes,\n },\n references: Array.isArray(projectedData.references)\n ? projectedData.references\n : baseElement.references,\n relationships: Array.isArray(projectedData.relationships)\n ? projectedData.relationships\n : baseElement.relationships,\n source_reference: baseElement.source_reference,\n metadata: baseElement.metadata,\n };\n\n return new ElementClass(mergedData);\n } else if (lastChange.type === \"add\") {\n // New element being added\n return new ElementClass({\n id: (lastChange.after?.id as string) || elementId,\n path: (lastChange.after?.path as string) || elementId,\n spec_node_id: (lastChange.after?.spec_node_id as string) || \"\",\n type: (projectedData.type as string) || \"unknown\",\n layer_id: lastChange.layerName,\n name: (projectedData.name as string) || elementId,\n description: (projectedData.description as string) || \"\",\n attributes: (typeof projectedData.attributes === \"object\"\n ? projectedData.attributes\n : {}) as Record<string, unknown>,\n references: Array.isArray(projectedData.references) ? projectedData.references : [],\n relationships: Array.isArray(projectedData.relationships)\n ? projectedData.relationships\n : [],\n source_reference: projectedData.source_reference as SourceReference | undefined,\n metadata: projectedData.metadata as ElementMetadata | undefined,\n layer: lastChange.layerName,\n });\n }\n\n return null;\n }\n\n /**\n * Project a layer by applying staged changes to a clone of the base layer.\n * Checks cache first; computes and caches result if not found or expired.\n *\n * @param baseModel - The base model to project from\n * @param changesetId - ID of the changeset containing staged changes\n * @param layerName - Name of the layer to project\n * @returns Projected layer with staged changes applied\n * @throws Error if changeset or base layer not found\n *\n * @remarks\n * Computation process:\n * 1. Check projection cache (returns if found and not expired)\n * 2. Clone base layer to avoid mutations\n * 3. Load staged changes filtered to this layer\n * 4. Apply changes in sequence number order (add/update/delete)\n * 5. Cache result with timestamp for TTL tracking\n * 6. Trigger periodic cache cleanup\n */\n async projectLayer(baseModel: Model, changesetId: string, layerName: string): Promise<Layer> {\n // Check cache first\n const cacheKey = `${changesetId}:${layerName}`;\n const cached = this.projectionCache.cache.get(cacheKey);\n\n if (cached) {\n const age = Date.now() - new Date(cached.computedAt).getTime();\n if (age < this.projectionCache.maxAge) {\n // Record cache hit\n this.recordCacheHit(changesetId);\n return cached.layer;\n } else {\n // Invalidate expired entry\n this.projectionCache.cache.delete(cacheKey);\n }\n }\n\n // Record cache miss\n this.recordCacheMiss(changesetId);\n\n // Load the committed base layer \u2014 must use getBaseLayer() (not getLayer()) to avoid\n // infinite recursion: getLayer() calls projectLayer(), which would call getLayer() again.\n const baseLayer = await baseModel.getBaseLayer(layerName);\n const projectedLayer = baseLayer\n ? this.cloneLayer(baseLayer)\n : new LayerClass(layerName);\n\n // Load staged changes for this layer\n const changeset = await this.stagingAreaManager.load(changesetId);\n if (!changeset) {\n throw new Error(`Changeset '${changesetId}' not found`);\n }\n\n const layerChanges = (changeset.changes as StagedChange[])\n .filter((c: StagedChange) => c.layerName === layerName)\n .sort((a: StagedChange, b: StagedChange) => a.sequenceNumber - b.sequenceNumber);\n\n // Apply changes in sequence order\n for (const change of layerChanges) {\n switch (change.type) {\n case \"add\":\n if (change.after) {\n const newElement = new ElementClass({\n id: (change.after.id as string) || change.elementId,\n path: (change.after.path as string) || change.elementId,\n spec_node_id: (change.after.spec_node_id as string) || \"\",\n type: (change.after.type as string) || \"unknown\",\n layer_id: layerName,\n name: (change.after.name as string) || change.elementId,\n description: (change.after.description as string) || \"\",\n attributes: (typeof change.after.attributes === \"object\"\n ? change.after.attributes\n : {}) as Record<string, unknown>,\n references: Array.isArray(change.after.references) ? change.after.references : [],\n relationships: Array.isArray(change.after.relationships)\n ? change.after.relationships\n : [],\n source_reference: change.after.source_reference as SourceReference | undefined,\n metadata: change.after.metadata as ElementMetadata | undefined,\n layer: layerName,\n });\n projectedLayer.addElement(newElement);\n }\n break;\n\n case \"update\":\n if (change.after) {\n // Get the existing element to preserve all state\n const existing = projectedLayer.getElement(change.elementId);\n if (existing) {\n // Create updated element with merged attributes\n const afterAttributes =\n typeof change.after.attributes === \"object\" ? change.after.attributes : {};\n\n const mergedAttributes: Record<string, unknown> = {\n ...existing.attributes,\n ...afterAttributes,\n };\n\n const updatedElement = new ElementClass({\n id: existing.id,\n path: existing.path,\n spec_node_id: existing.spec_node_id,\n layer_id: existing.layer_id,\n type: typeof change.after.type === \"string\" ? change.after.type : existing.type,\n name: typeof change.after.name === \"string\" ? change.after.name : existing.name,\n description:\n typeof change.after.description === \"string\"\n ? change.after.description\n : existing.description,\n attributes: mergedAttributes,\n references: Array.isArray(change.after.references)\n ? change.after.references\n : existing.references,\n relationships: Array.isArray(change.after.relationships)\n ? change.after.relationships\n : existing.relationships,\n layer: layerName,\n source_reference: existing.source_reference,\n metadata: existing.metadata,\n });\n\n projectedLayer.updateElement(updatedElement);\n }\n }\n break;\n\n case \"delete\":\n const existingForDelete = projectedLayer.getElement(change.elementId);\n if (existingForDelete) {\n projectedLayer.deleteElement(existingForDelete.path || existingForDelete.id);\n }\n break;\n\n case \"relationship-add\":\n case \"relationship-delete\":\n // Relationship changes are handled at the model level (model.relationships),\n // not the layer level. Skip here; no layer mutation needed.\n break;\n }\n }\n\n // Cache the result\n const cacheEntry: CacheEntry = {\n layer: projectedLayer,\n computedAt: new Date().toISOString(),\n };\n this.projectionCache.cache.set(cacheKey, cacheEntry);\n\n // Periodic cleanup of expired entries\n this.cleanupExpiredCache();\n\n return projectedLayer;\n }\n\n /**\n * Project entire model by applying staged changes to all layers.\n * Creates a complete projected model view that includes both changed and unchanged layers.\n *\n * @param baseModel - The base model to project from\n * @param changesetId - ID of the changeset containing staged changes\n * @returns ProjectedModel with isProjection=true flag (prevents accidental saves)\n * @throws Error if changeset not found\n *\n * @remarks\n * Projection includes:\n * - All layers mentioned in changeset changes\n * - All layers from base model (to have complete model state)\n * - Base model's manifest (unchanged)\n * Returned model has isProjection=true to prevent accidental persistence.\n */\n async projectModel(baseModel: Model, changesetId: string): Promise<ProjectedModel> {\n const changeset = await this.stagingAreaManager.load(changesetId);\n if (!changeset) {\n throw new Error(`Changeset '${changesetId}' not found`);\n }\n\n const projectedLayers = new Map<string, Layer>();\n\n // Project all layers mentioned in the changeset\n const layerNames = new Set<string>();\n for (const change of changeset.changes) {\n layerNames.add(change.layerName);\n }\n\n // Also include all base layers to get complete model\n for (const baseLayerName of baseModel.getLayerNames()) {\n layerNames.add(baseLayerName);\n }\n\n // Project each layer\n for (const layerName of layerNames) {\n const projectedLayer = await this.projectLayer(baseModel, changesetId, layerName);\n projectedLayers.set(layerName, projectedLayer);\n }\n\n // Create projected model with isProjection flag\n const projectedModel: ProjectedModel = {\n manifest: baseModel.manifest,\n layers: projectedLayers,\n relationships: baseModel.relationships,\n loadedLayerFilter: baseModel.loadedLayerFilter,\n isProjection: true,\n };\n\n return projectedModel;\n }\n\n /**\n * Compute diff by categorizing changeset changes by type.\n * Extracts the staged changes and organizes them into additions, modifications, and deletions.\n *\n * @param _baseModel - The base model (unused; included for interface compatibility)\n * @param changesetId - ID of the changeset to compute diff for\n * @returns ModelDiff with changes categorized by type\n * @throws Error if changeset not found\n *\n * @remarks\n * Diff is computed directly from changeset changes; does not perform deep comparison.\n * Each change's before/after snapshots are included for detailed display.\n */\n async computeDiff(_baseModel: Model, changesetId: string): Promise<ModelDiff> {\n const changeset = await this.stagingAreaManager.load(changesetId);\n if (!changeset) {\n throw new Error(`Changeset '${changesetId}' not found`);\n }\n\n const changes = changeset.changes as StagedChange[];\n\n return {\n additions: changes\n .filter((c: StagedChange) => c.type === \"add\")\n .map((c: StagedChange) => ({\n elementId: c.elementId,\n layerName: c.layerName,\n data: c.after || {},\n })),\n\n modifications: changes\n .filter((c: StagedChange) => c.type === \"update\")\n .map((c: StagedChange) => ({\n elementId: c.elementId,\n layerName: c.layerName,\n before: c.before || {},\n after: c.after || {},\n })),\n\n deletions: changes\n .filter((c: StagedChange) => c.type === \"delete\")\n .map((c: StagedChange) => ({\n elementId: c.elementId,\n layerName: c.layerName,\n data: c.before || {},\n })),\n };\n }\n\n /**\n * Get affected layers for an element in a changeset.\n * Returns all layers that have cached projections and contain changes for the element.\n *\n * @param changesetId - ID of the changeset\n * @param elementId - ID of the element being unstaged\n * @returns Set of affected layer names\n *\n * @remarks\n * When unstaging an element, only the layers where that element was modified\n * need cache invalidation. This enables granular invalidation instead of\n * invalidating the entire changeset cache.\n */\n private async getAffectedLayers(changesetId: string, elementId: string): Promise<Set<string>> {\n const affectedLayers = new Set<string>();\n\n try {\n const changeset = await this.stagingAreaManager.load(changesetId);\n if (!changeset) {\n return affectedLayers;\n }\n\n // Find all layers that have changes for this element\n for (const change of changeset.changes) {\n if (change.elementId === elementId) {\n affectedLayers.add(change.layerName);\n }\n }\n } catch {\n // If changeset can't be loaded, return empty set (no invalidation needed)\n // This handles the case where changeset is deleted or corrupted\n }\n\n return affectedLayers;\n }\n\n /**\n * Record a cache hit for metrics tracking.\n *\n * @param changesetId - ID of the changeset\n */\n private recordCacheHit(changesetId: string): void {\n const metrics = this.projectionCache.metrics.get(changesetId) || {\n hits: 0,\n misses: 0,\n invalidations: 0,\n };\n metrics.hits++;\n this.projectionCache.metrics.set(changesetId, metrics);\n }\n\n /**\n * Record a cache miss for metrics tracking.\n *\n * @param changesetId - ID of the changeset\n */\n private recordCacheMiss(changesetId: string): void {\n const metrics = this.projectionCache.metrics.get(changesetId) || {\n hits: 0,\n misses: 0,\n invalidations: 0,\n };\n metrics.misses++;\n this.projectionCache.metrics.set(changesetId, metrics);\n }\n\n /**\n * Record a cache invalidation for metrics tracking.\n *\n * @param changesetId - ID of the changeset\n */\n private recordInvalidation(changesetId: string): void {\n const metrics = this.projectionCache.metrics.get(changesetId) || {\n hits: 0,\n misses: 0,\n invalidations: 0,\n };\n metrics.invalidations++;\n metrics.lastInvalidation = new Date().toISOString();\n this.projectionCache.metrics.set(changesetId, metrics);\n }\n\n /**\n * Get cache metrics for a changeset (for monitoring and debugging).\n *\n * @param changesetId - ID of the changeset\n * @returns Cache metrics or undefined if no metrics exist\n */\n getCacheMetrics(changesetId: string): CacheMetrics | undefined {\n return this.projectionCache.metrics.get(changesetId);\n }\n\n /**\n * Invalidate projection cache when changes are staged.\n * Removes cached projections to ensure fresh computation next time.\n *\n * @param changesetId - ID of the changeset being modified\n * @param layerName - Optional: specific layer to invalidate (all if omitted)\n *\n * @remarks\n * If layerName is provided, only that layer's projection is invalidated.\n * Otherwise, all projections for the changeset are invalidated.\n */\n invalidateOnStage(changesetId: string, layerName?: string): void {\n if (layerName) {\n // Invalidate specific layer projection\n const cacheKey = `${changesetId}:${layerName}`;\n this.projectionCache.cache.delete(cacheKey);\n this.recordInvalidation(changesetId);\n } else {\n // Invalidate all projections for this changeset\n for (const key of this.projectionCache.cache.keys()) {\n if (key.startsWith(`${changesetId}:`)) {\n this.projectionCache.cache.delete(key);\n }\n }\n this.recordInvalidation(changesetId);\n }\n }\n\n /**\n * Invalidate projection cache when changes are unstaged.\n * Uses layer-specific invalidation for the affected element's layers.\n *\n * @param changesetId - ID of the changeset being modified\n * @param elementId - Optional: ID of element being unstaged (enables granular invalidation)\n *\n * @remarks\n * If elementId is provided, only the layers containing that element are invalidated.\n * This is more efficient than invalidating the entire changeset cache when\n * unstaging elements from a multi-layer changeset.\n * If elementId is omitted, invalidates all projections for the changeset.\n */\n async invalidateOnUnstage(changesetId: string, elementId?: string): Promise<void> {\n if (elementId) {\n // Layer-specific invalidation: only invalidate affected layers\n const affectedLayers = await this.getAffectedLayers(changesetId, elementId);\n for (const layerName of affectedLayers) {\n const cacheKey = `${changesetId}:${layerName}`;\n this.projectionCache.cache.delete(cacheKey);\n }\n if (affectedLayers.size > 0) {\n this.recordInvalidation(changesetId);\n }\n } else {\n // Full invalidation: clear all projections for this changeset\n for (const key of this.projectionCache.cache.keys()) {\n if (key.startsWith(`${changesetId}:`)) {\n this.projectionCache.cache.delete(key);\n }\n }\n this.recordInvalidation(changesetId);\n }\n }\n\n /**\n * Invalidate all projections for a changeset when it's discarded.\n * Clears all cached projections for this changeset to free memory.\n *\n * @param changesetId - ID of the changeset being discarded\n */\n invalidateOnDiscard(changesetId: string): void {\n for (const key of this.projectionCache.cache.keys()) {\n if (key.startsWith(`${changesetId}:`)) {\n this.projectionCache.cache.delete(key);\n }\n }\n }\n\n /**\n * Clone a layer to create an independent copy.\n * Shallow clones all elements and metadata to avoid mutations.\n * Cloned layer is marked clean to prevent unintended saves.\n *\n * @param layer - The layer to clone\n * @returns New layer with cloned elements and metadata\n *\n * @remarks\n * Cloning strategy:\n * 1. Create new Layer with same name\n * 2. Clone each element: shallow copy attributes object and array references\n * 3. Copy layer metadata if present\n * 4. Mark cloned layer as clean to prevent automatic saves\n * This ensures changes to projection don't affect base layer.\n * Note: Shallow cloning is sufficient since attributes are read-only in projections.\n */\n private cloneLayer(layer: Layer): Layer {\n const cloned = new LayerClass(layer.name);\n\n // Clone all elements (shallow copy - read-only in projection)\n for (const element of layer.listElements()) {\n const elementClone = new ElementClass({\n id: element.id,\n path: element.path,\n spec_node_id: element.spec_node_id,\n type: element.type,\n layer_id: element.layer_id,\n name: element.name,\n description: element.description,\n attributes: { ...element.attributes },\n references: [...(element.references || [])],\n relationships: [...(element.relationships || [])],\n layer: element.layer,\n source_reference: element.source_reference,\n metadata: element.metadata,\n });\n cloned.addElement(elementClone);\n }\n\n // Preserve layer metadata if present\n if (layer.metadata) {\n cloned.metadata = { ...layer.metadata };\n }\n\n // Mark as clean to prevent projection from being saved\n cloned.markClean();\n return cloned;\n }\n\n /**\n * Clean up expired cache entries periodically (every 60 seconds).\n * Removes entries that exceed the maxAge TTL.\n * Runs at most once per minute to limit overhead.\n *\n * @remarks\n * Cleanup is triggered after each projection computation.\n * Early exit if last cleanup was less than 60 seconds ago.\n * Entries are marked for deletion based on age calculation from computedAt timestamp.\n */\n private cleanupExpiredCache(): void {\n const now = Date.now();\n\n // Limit cleanup frequency to at most every 60 seconds\n if (now - this.projectionCache.lastCleanup < 60 * 1000) {\n return;\n }\n\n // Remove entries that have exceeded their TTL\n for (const [key, entry] of this.projectionCache.cache.entries()) {\n const age = now - new Date(entry.computedAt).getTime();\n if (age >= this.projectionCache.maxAge) {\n this.projectionCache.cache.delete(key);\n }\n }\n\n this.projectionCache.lastCleanup = now;\n }\n}\n"],
5
- "mappings": "AAgBA,SAAS,SAAS,kBAAkB;AACpC,SAAS,WAAW,oBAAoB;AAExC,SAAS,8BAA8B;AA4EjC,MAAO,wBAAuB;EAC1B;EACA;;;;;;EAOR,YAAY,UAAgB;AAC1B,SAAK,qBAAqB,IAAI,uBAAuB,QAAQ,GAC7D,KAAK,kBAAkB;MACrB,OAAO,oBAAI,IAAG;MACd,SAAS,oBAAI,IAAG;MAChB,QAAQ,IAAI,KAAK;;MACjB,aAAa,KAAK,IAAG;;EAEzB;;;;;;;;;;;;;;;;;EAkBA,M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;QACd,UAAU,QAAQ;QAClB,MAAM,QAAQ;QACd,aAAa,QAAQ;QACrB,YAAY,EAAE,GAAG,QAAQ,WAAU;QACnC,YAAY,CAAC,GAAI,QAAQ,cAAc,CAAA,CAAG;QAC1C,eAAe,CAAC,GAAI,QAAQ,iBAAiB,CAAA,CAAG;QAChD,OAAO,QAAQ;QACf,kBAAkB,QAAQ;QAC1B,UAAU,QAAQ;OACnB;AACD,aAAO,WAAW,YAAY;IAChC;AAGA,WAAI,MAAM,aACR,OAAO,WAAW,EAAE,GAAG,MAAM,SAAQ,IAIvC,OAAO,UAAS,GACT;EACT;;;;;;;;;;;EAYQ,sBAAmB;AACzB,UAAM,MAAM,KAAK,IAAG;AAGpB,QAAI,QAAM,KAAK,gBAAgB,cAAc,KAAK,MAKlD;iBAAW,CAAC,KAAK,KAAK,KAAK,KAAK,gBAAgB,MAAM,QAAO;AAE3D,QADY,MAAM,IAAI,KAAK,MAAM,UAAU,EAAE,QAAO,KACzC,KAAK,gBAAgB,UAC9B,KAAK,gBAAgB,MAAM,OAAO,GAAG;AAIzC,WAAK,gBAAgB,cAAc;;EACrC;;",
4
+ "sourcesContent": ["/**\n * VirtualProjectionEngine - Computes merged model views by applying staged changes.\n *\n * Creates virtual (temporary) projections of the base model with staged changes applied,\n * without modifying or persisting the base model. Enables safe preview and validation\n * of changes before commit. Includes projection caching with TTL-based expiration.\n *\n * Staging changes are applied in sequence order to compute accurate merged views.\n */\n\nimport type { Model } from \"./model.js\";\nimport type { Layer } from \"./layer.js\";\nimport type { Element } from \"./element.js\";\nimport type { ElementMetadata } from \"../types/index.js\";\nimport { readStagedSourceReference, stagedSourceReference } from \"./staged-source-reference.js\";\nimport type { Manifest } from \"./manifest.js\";\nimport type { Relationships } from \"./relationships.js\";\nimport { Layer as LayerClass } from \"./layer.js\";\nimport { Element as ElementClass } from \"./element.js\";\nimport type { StagedChange, Change } from \"./changeset.js\";\nimport { withSequenceNumbers } from \"./changeset.js\";\nimport { StagedChangesetStorage } from \"./staged-changeset-storage.js\";\n\n/**\n * Projected model with isProjection flag to prevent accidental saves.\n * This marker interface ensures that projected models are recognized as temporary\n * and cannot be persisted to disk without explicit commit of the underlying changeset.\n */\nexport interface ProjectedModel {\n manifest: Manifest;\n layers: Map<string, Layer>;\n relationships: Relationships;\n loadedLayerFilter?: string[];\n isProjection: true; // Always true; marks this as a temporary virtual projection\n}\n\n/**\n * Model diff categorizing changeset changes by type.\n * Separates staged changes into additions (new elements), modifications (updated attributes),\n * and deletions (removed elements). Used for preview and diff display operations.\n */\nexport interface ModelDiff {\n additions: Array<{\n elementId: string;\n layerName: string;\n data: Record<string, unknown>; // Complete element state (from change.after)\n }>;\n modifications: Array<{\n elementId: string;\n layerName: string;\n before: Record<string, unknown>; // Previous state (from change.before)\n after: Record<string, unknown>; // New state (from change.after)\n }>;\n deletions: Array<{\n elementId: string;\n layerName: string;\n data: Record<string, unknown>; // Element state before deletion (from change.before)\n }>;\n}\n\n/**\n * Single cached layer projection.\n * Stores the computed projected layer and timestamp for cache expiration.\n */\ninterface CacheEntry {\n layer: Layer;\n computedAt: string; // ISO timestamp for age calculation\n}\n\n/**\n * Cache hit/miss metrics for monitoring cache performance.\n * Tracks successful cache hits, misses, and invalidations per changeset.\n */\ninterface CacheMetrics {\n hits: number; // Number of successful cache hits\n misses: number; // Number of cache misses (required computation)\n invalidations: number; // Number of invalidation operations\n lastInvalidation?: string; // ISO timestamp of last invalidation\n}\n\n/**\n * Projection cache for storing computed layer projections.\n * Uses TTL-based expiration to prevent stale projections.\n * Entries are lazily removed when expired on access or during periodic cleanup.\n */\ninterface ProjectionCache {\n cache: Map<string, CacheEntry>; // Key format: `${changesetId}:${layerName}`\n metrics: Map<string, CacheMetrics>; // Cache metrics keyed by changesetId\n maxAge: number; // Cache entry TTL in milliseconds (5 minutes default)\n lastCleanup: number; // Timestamp of last cleanup to limit cleanup frequency\n}\n\n/**\n * VirtualProjectionEngine - Computes merged model views without persisting.\n * Applies staged changes to a cloned base model to compute projections.\n * Uses caching with TTL-based expiration to optimize repeated projections.\n */\nexport class VirtualProjectionEngine {\n private stagingAreaManager: StagedChangesetStorage;\n private projectionCache: ProjectionCache;\n\n /**\n * Create a new projection engine.\n *\n * @param rootPath - Root path to the model (used by StagedChangesetStorage)\n */\n constructor(rootPath: string) {\n this.stagingAreaManager = new StagedChangesetStorage(rootPath);\n this.projectionCache = {\n cache: new Map(),\n metrics: new Map(),\n maxAge: 5 * 60 * 1000, // 5-minute TTL for cached projections\n lastCleanup: Date.now(),\n };\n }\n\n /**\n * Project a single element by applying staged changes to it.\n * Merges the element's base state with staged changes to compute its projected state.\n *\n * @param baseModel - The base model to project from\n * @param changesetId - ID of the changeset containing staged changes\n * @param elementId - ID of the element to project\n * @returns Projected element with staged changes applied, or null if element is deleted\n * @throws Error if changeset not found\n *\n * @remarks\n * If multiple changes exist for the element, the last change determines final state.\n * For 'delete' operations, returns null.\n * For 'add' operations without base element, creates new element from staged data.\n * For 'update' operations, merges staged changes with base element attributes.\n */\n async projectElement(\n baseModel: Model,\n changesetId: string,\n elementId: string\n ): Promise<Element | null> {\n const changeset = await this.stagingAreaManager.load(changesetId);\n if (!changeset) {\n throw new Error(`Changeset '${changesetId}' not found`);\n }\n\n // Find all changes for this element across all layers\n const elementChanges = changeset.changes.filter(\n (c: Change) => c.elementId === elementId\n ) as StagedChange[];\n\n if (elementChanges.length === 0) {\n // No changes, return base element if it exists\n return baseModel.getElementById(elementId) || null;\n }\n\n // Get the last change to determine the element's final state\n const lastChange = elementChanges[elementChanges.length - 1];\n\n if (lastChange.type === \"delete\") {\n return null;\n }\n\n // For add or update, construct the projected element\n const baseElement = baseModel.getElementById(elementId);\n const projectedData = lastChange.after || {};\n\n if (baseElement) {\n // Create a new element with projected data merged with base\n const projectedAttributes =\n typeof projectedData.attributes === \"object\" ? projectedData.attributes : {};\n\n const mergedData = {\n id: baseElement.id,\n path: baseElement.path,\n spec_node_id: baseElement.spec_node_id,\n type: typeof projectedData.type === \"string\" ? projectedData.type : baseElement.type,\n layer_id: baseElement.layer_id,\n name: typeof projectedData.name === \"string\" ? projectedData.name : baseElement.name,\n description:\n typeof projectedData.description === \"string\"\n ? projectedData.description\n : baseElement.description,\n attributes: {\n ...baseElement.attributes,\n ...projectedAttributes,\n },\n references: Array.isArray(projectedData.references)\n ? projectedData.references\n : baseElement.references,\n relationships: Array.isArray(projectedData.relationships)\n ? projectedData.relationships\n : baseElement.relationships,\n source_reference: (() => {\n const staged = readStagedSourceReference(projectedData);\n return staged.present ? staged.value : baseElement.source_reference;\n })(),\n metadata: baseElement.metadata,\n };\n\n return new ElementClass(mergedData);\n } else if (lastChange.type === \"add\") {\n // New element being added\n return new ElementClass({\n id: (lastChange.after?.id as string) || elementId,\n path: (lastChange.after?.path as string) || elementId,\n spec_node_id: (lastChange.after?.spec_node_id as string) || \"\",\n type: (projectedData.type as string) || \"unknown\",\n layer_id: lastChange.layerName,\n name: (projectedData.name as string) || elementId,\n description: (projectedData.description as string) || \"\",\n attributes: (typeof projectedData.attributes === \"object\"\n ? projectedData.attributes\n : {}) as Record<string, unknown>,\n references: Array.isArray(projectedData.references) ? projectedData.references : [],\n relationships: Array.isArray(projectedData.relationships)\n ? projectedData.relationships\n : [],\n source_reference: stagedSourceReference(projectedData),\n metadata: projectedData.metadata as ElementMetadata | undefined,\n layer: lastChange.layerName,\n });\n }\n\n return null;\n }\n\n /**\n * Project a layer by applying staged changes to a clone of the base layer.\n * Checks cache first; computes and caches result if not found or expired.\n *\n * @param baseModel - The base model to project from\n * @param changesetId - ID of the changeset containing staged changes\n * @param layerName - Name of the layer to project\n * @returns Projected layer with staged changes applied\n * @throws Error if changeset or base layer not found\n *\n * @remarks\n * Computation process:\n * 1. Check projection cache (returns if found and not expired)\n * 2. Clone base layer to avoid mutations\n * 3. Load staged changes filtered to this layer\n * 4. Apply changes in sequence number order (add/update/delete)\n * 5. Cache result with timestamp for TTL tracking\n * 6. Trigger periodic cache cleanup\n */\n async projectLayer(baseModel: Model, changesetId: string, layerName: string): Promise<Layer> {\n // Check cache first\n const cacheKey = `${changesetId}:${layerName}`;\n const cached = this.projectionCache.cache.get(cacheKey);\n\n if (cached) {\n const age = Date.now() - new Date(cached.computedAt).getTime();\n if (age < this.projectionCache.maxAge) {\n // Record cache hit\n this.recordCacheHit(changesetId);\n return cached.layer;\n } else {\n // Invalidate expired entry\n this.projectionCache.cache.delete(cacheKey);\n }\n }\n\n // Record cache miss\n this.recordCacheMiss(changesetId);\n\n // Load the committed base layer \u2014 must use getBaseLayer() (not getLayer()) to avoid\n // infinite recursion: getLayer() calls projectLayer(), which would call getLayer() again.\n const baseLayer = await baseModel.getBaseLayer(layerName);\n const projectedLayer = baseLayer\n ? this.cloneLayer(baseLayer)\n : new LayerClass(layerName);\n\n // Load staged changes for this layer\n const changeset = await this.stagingAreaManager.load(changesetId);\n if (!changeset) {\n throw new Error(`Changeset '${changesetId}' not found`);\n }\n\n const layerChanges = withSequenceNumbers(changeset.changes)\n .filter((c: StagedChange) => c.layerName === layerName)\n .sort((a: StagedChange, b: StagedChange) => a.sequenceNumber - b.sequenceNumber);\n\n // Apply changes in sequence order\n for (const change of layerChanges) {\n switch (change.type) {\n case \"add\":\n if (change.after) {\n const newElement = new ElementClass({\n id: (change.after.id as string) || change.elementId,\n path: (change.after.path as string) || change.elementId,\n spec_node_id: (change.after.spec_node_id as string) || \"\",\n type: (change.after.type as string) || \"unknown\",\n layer_id: layerName,\n name: (change.after.name as string) || change.elementId,\n description: (change.after.description as string) || \"\",\n attributes: (typeof change.after.attributes === \"object\"\n ? change.after.attributes\n : {}) as Record<string, unknown>,\n references: Array.isArray(change.after.references) ? change.after.references : [],\n relationships: Array.isArray(change.after.relationships)\n ? change.after.relationships\n : [],\n source_reference: stagedSourceReference(change.after),\n metadata: change.after.metadata as ElementMetadata | undefined,\n layer: layerName,\n });\n projectedLayer.addElement(newElement);\n }\n break;\n\n case \"update\":\n if (change.after) {\n // Get the existing element to preserve all state\n const existing = projectedLayer.getElement(change.elementId);\n if (existing) {\n // Create updated element with merged attributes\n const afterAttributes =\n typeof change.after.attributes === \"object\" ? change.after.attributes : {};\n\n const mergedAttributes: Record<string, unknown> = {\n ...existing.attributes,\n ...afterAttributes,\n };\n\n const updatedElement = new ElementClass({\n id: existing.id,\n path: existing.path,\n spec_node_id: existing.spec_node_id,\n layer_id: existing.layer_id,\n type: typeof change.after.type === \"string\" ? change.after.type : existing.type,\n name: typeof change.after.name === \"string\" ? change.after.name : existing.name,\n description:\n typeof change.after.description === \"string\"\n ? change.after.description\n : existing.description,\n attributes: mergedAttributes,\n references: Array.isArray(change.after.references)\n ? change.after.references\n : existing.references,\n relationships: Array.isArray(change.after.relationships)\n ? change.after.relationships\n : existing.relationships,\n layer: layerName,\n source_reference: (() => {\n const staged = readStagedSourceReference(change.after);\n return staged.present ? staged.value : existing.source_reference;\n })(),\n metadata: existing.metadata,\n });\n\n projectedLayer.updateElement(updatedElement);\n }\n }\n break;\n\n case \"delete\":\n const existingForDelete = projectedLayer.getElement(change.elementId);\n if (existingForDelete) {\n projectedLayer.deleteElement(existingForDelete.path || existingForDelete.id);\n }\n break;\n\n case \"relationship-add\":\n case \"relationship-delete\":\n // Relationship changes are handled at the model level (model.relationships),\n // not the layer level. Skip here; no layer mutation needed.\n break;\n }\n }\n\n // Cache the result\n const cacheEntry: CacheEntry = {\n layer: projectedLayer,\n computedAt: new Date().toISOString(),\n };\n this.projectionCache.cache.set(cacheKey, cacheEntry);\n\n // Periodic cleanup of expired entries\n this.cleanupExpiredCache();\n\n return projectedLayer;\n }\n\n /**\n * Project entire model by applying staged changes to all layers.\n * Creates a complete projected model view that includes both changed and unchanged layers.\n *\n * @param baseModel - The base model to project from\n * @param changesetId - ID of the changeset containing staged changes\n * @returns ProjectedModel with isProjection=true flag (prevents accidental saves)\n * @throws Error if changeset not found\n *\n * @remarks\n * Projection includes:\n * - All layers mentioned in changeset changes\n * - All layers from base model (to have complete model state)\n * - Base model's manifest (unchanged)\n * Returned model has isProjection=true to prevent accidental persistence.\n */\n async projectModel(baseModel: Model, changesetId: string): Promise<ProjectedModel> {\n const changeset = await this.stagingAreaManager.load(changesetId);\n if (!changeset) {\n throw new Error(`Changeset '${changesetId}' not found`);\n }\n\n const projectedLayers = new Map<string, Layer>();\n\n // Project all layers mentioned in the changeset\n const layerNames = new Set<string>();\n for (const change of changeset.changes) {\n layerNames.add(change.layerName);\n }\n\n // Also include all base layers to get complete model\n for (const baseLayerName of baseModel.getLayerNames()) {\n layerNames.add(baseLayerName);\n }\n\n // Project each layer\n for (const layerName of layerNames) {\n const projectedLayer = await this.projectLayer(baseModel, changesetId, layerName);\n projectedLayers.set(layerName, projectedLayer);\n }\n\n // Create projected model with isProjection flag\n const projectedModel: ProjectedModel = {\n manifest: baseModel.manifest,\n layers: projectedLayers,\n relationships: baseModel.relationships,\n loadedLayerFilter: baseModel.loadedLayerFilter,\n isProjection: true,\n };\n\n return projectedModel;\n }\n\n /**\n * Compute diff by categorizing changeset changes by type.\n * Extracts the staged changes and organizes them into additions, modifications, and deletions.\n *\n * @param _baseModel - The base model (unused; included for interface compatibility)\n * @param changesetId - ID of the changeset to compute diff for\n * @returns ModelDiff with changes categorized by type\n * @throws Error if changeset not found\n *\n * @remarks\n * Diff is computed directly from changeset changes; does not perform deep comparison.\n * Each change's before/after snapshots are included for detailed display.\n */\n async computeDiff(_baseModel: Model, changesetId: string): Promise<ModelDiff> {\n const changeset = await this.stagingAreaManager.load(changesetId);\n if (!changeset) {\n throw new Error(`Changeset '${changesetId}' not found`);\n }\n\n const changes = changeset.changes as StagedChange[];\n\n return {\n additions: changes\n .filter((c: StagedChange) => c.type === \"add\")\n .map((c: StagedChange) => ({\n elementId: c.elementId,\n layerName: c.layerName,\n data: c.after || {},\n })),\n\n modifications: changes\n .filter((c: StagedChange) => c.type === \"update\")\n .map((c: StagedChange) => ({\n elementId: c.elementId,\n layerName: c.layerName,\n before: c.before || {},\n after: c.after || {},\n })),\n\n deletions: changes\n .filter((c: StagedChange) => c.type === \"delete\")\n .map((c: StagedChange) => ({\n elementId: c.elementId,\n layerName: c.layerName,\n data: c.before || {},\n })),\n };\n }\n\n /**\n * Get affected layers for an element in a changeset.\n * Returns all layers that have cached projections and contain changes for the element.\n *\n * @param changesetId - ID of the changeset\n * @param elementId - ID of the element being unstaged\n * @returns Set of affected layer names\n *\n * @remarks\n * When unstaging an element, only the layers where that element was modified\n * need cache invalidation. This enables granular invalidation instead of\n * invalidating the entire changeset cache.\n */\n private async getAffectedLayers(changesetId: string, elementId: string): Promise<Set<string>> {\n const affectedLayers = new Set<string>();\n\n try {\n const changeset = await this.stagingAreaManager.load(changesetId);\n if (!changeset) {\n return affectedLayers;\n }\n\n // Find all layers that have changes for this element\n for (const change of changeset.changes) {\n if (change.elementId === elementId) {\n affectedLayers.add(change.layerName);\n }\n }\n } catch {\n // If changeset can't be loaded, return empty set (no invalidation needed)\n // This handles the case where changeset is deleted or corrupted\n }\n\n return affectedLayers;\n }\n\n /**\n * Record a cache hit for metrics tracking.\n *\n * @param changesetId - ID of the changeset\n */\n private recordCacheHit(changesetId: string): void {\n const metrics = this.projectionCache.metrics.get(changesetId) || {\n hits: 0,\n misses: 0,\n invalidations: 0,\n };\n metrics.hits++;\n this.projectionCache.metrics.set(changesetId, metrics);\n }\n\n /**\n * Record a cache miss for metrics tracking.\n *\n * @param changesetId - ID of the changeset\n */\n private recordCacheMiss(changesetId: string): void {\n const metrics = this.projectionCache.metrics.get(changesetId) || {\n hits: 0,\n misses: 0,\n invalidations: 0,\n };\n metrics.misses++;\n this.projectionCache.metrics.set(changesetId, metrics);\n }\n\n /**\n * Record a cache invalidation for metrics tracking.\n *\n * @param changesetId - ID of the changeset\n */\n private recordInvalidation(changesetId: string): void {\n const metrics = this.projectionCache.metrics.get(changesetId) || {\n hits: 0,\n misses: 0,\n invalidations: 0,\n };\n metrics.invalidations++;\n metrics.lastInvalidation = new Date().toISOString();\n this.projectionCache.metrics.set(changesetId, metrics);\n }\n\n /**\n * Get cache metrics for a changeset (for monitoring and debugging).\n *\n * @param changesetId - ID of the changeset\n * @returns Cache metrics or undefined if no metrics exist\n */\n getCacheMetrics(changesetId: string): CacheMetrics | undefined {\n return this.projectionCache.metrics.get(changesetId);\n }\n\n /**\n * Invalidate projection cache when changes are staged.\n * Removes cached projections to ensure fresh computation next time.\n *\n * @param changesetId - ID of the changeset being modified\n * @param layerName - Optional: specific layer to invalidate (all if omitted)\n *\n * @remarks\n * If layerName is provided, only that layer's projection is invalidated.\n * Otherwise, all projections for the changeset are invalidated.\n */\n invalidateOnStage(changesetId: string, layerName?: string): void {\n if (layerName) {\n // Invalidate specific layer projection\n const cacheKey = `${changesetId}:${layerName}`;\n this.projectionCache.cache.delete(cacheKey);\n this.recordInvalidation(changesetId);\n } else {\n // Invalidate all projections for this changeset\n for (const key of this.projectionCache.cache.keys()) {\n if (key.startsWith(`${changesetId}:`)) {\n this.projectionCache.cache.delete(key);\n }\n }\n this.recordInvalidation(changesetId);\n }\n }\n\n /**\n * Invalidate projection cache when changes are unstaged.\n * Uses layer-specific invalidation for the affected element's layers.\n *\n * @param changesetId - ID of the changeset being modified\n * @param elementId - Optional: ID of element being unstaged (enables granular invalidation)\n *\n * @remarks\n * If elementId is provided, only the layers containing that element are invalidated.\n * This is more efficient than invalidating the entire changeset cache when\n * unstaging elements from a multi-layer changeset.\n * If elementId is omitted, invalidates all projections for the changeset.\n */\n async invalidateOnUnstage(changesetId: string, elementId?: string): Promise<void> {\n if (elementId) {\n // Layer-specific invalidation: only invalidate affected layers\n const affectedLayers = await this.getAffectedLayers(changesetId, elementId);\n for (const layerName of affectedLayers) {\n const cacheKey = `${changesetId}:${layerName}`;\n this.projectionCache.cache.delete(cacheKey);\n }\n if (affectedLayers.size > 0) {\n this.recordInvalidation(changesetId);\n }\n } else {\n // Full invalidation: clear all projections for this changeset\n for (const key of this.projectionCache.cache.keys()) {\n if (key.startsWith(`${changesetId}:`)) {\n this.projectionCache.cache.delete(key);\n }\n }\n this.recordInvalidation(changesetId);\n }\n }\n\n /**\n * Invalidate all projections for a changeset when it's discarded.\n * Clears all cached projections for this changeset to free memory.\n *\n * @param changesetId - ID of the changeset being discarded\n */\n invalidateOnDiscard(changesetId: string): void {\n for (const key of this.projectionCache.cache.keys()) {\n if (key.startsWith(`${changesetId}:`)) {\n this.projectionCache.cache.delete(key);\n }\n }\n }\n\n /**\n * Clone a layer to create an independent copy.\n * Shallow clones all elements and metadata to avoid mutations.\n * Cloned layer is marked clean to prevent unintended saves.\n *\n * @param layer - The layer to clone\n * @returns New layer with cloned elements and metadata\n *\n * @remarks\n * Cloning strategy:\n * 1. Create new Layer with same name\n * 2. Clone each element: shallow copy attributes object and array references\n * 3. Copy layer metadata if present\n * 4. Mark cloned layer as clean to prevent automatic saves\n * This ensures changes to projection don't affect base layer.\n * Note: Shallow cloning is sufficient since attributes are read-only in projections.\n */\n private cloneLayer(layer: Layer): Layer {\n const cloned = new LayerClass(layer.name);\n\n // Clone all elements (shallow copy - read-only in projection)\n for (const element of layer.listElements()) {\n const elementClone = new ElementClass({\n id: element.id,\n path: element.path,\n spec_node_id: element.spec_node_id,\n type: element.type,\n layer_id: element.layer_id,\n name: element.name,\n description: element.description,\n attributes: { ...element.attributes },\n references: [...(element.references || [])],\n relationships: [...(element.relationships || [])],\n layer: element.layer,\n source_reference: element.source_reference,\n metadata: element.metadata,\n });\n cloned.addElement(elementClone);\n }\n\n // Preserve layer metadata if present\n if (layer.metadata) {\n cloned.metadata = { ...layer.metadata };\n }\n\n // Mark as clean to prevent projection from being saved\n cloned.markClean();\n return cloned;\n }\n\n /**\n * Clean up expired cache entries periodically (every 60 seconds).\n * Removes entries that exceed the maxAge TTL.\n * Runs at most once per minute to limit overhead.\n *\n * @remarks\n * Cleanup is triggered after each projection computation.\n * Early exit if last cleanup was less than 60 seconds ago.\n * Entries are marked for deletion based on age calculation from computedAt timestamp.\n */\n private cleanupExpiredCache(): void {\n const now = Date.now();\n\n // Limit cleanup frequency to at most every 60 seconds\n if (now - this.projectionCache.lastCleanup < 60 * 1000) {\n return;\n }\n\n // Remove entries that have exceeded their TTL\n for (const [key, entry] of this.projectionCache.cache.entries()) {\n const age = now - new Date(entry.computedAt).getTime();\n if (age >= this.projectionCache.maxAge) {\n this.projectionCache.cache.delete(key);\n }\n }\n\n this.projectionCache.lastCleanup = now;\n }\n}\n"],
5
+ "mappings": "AAcA,SAAS,2BAA2B,6BAA6B;AAGjE,SAAS,SAAS,kBAAkB;AACpC,SAAS,WAAW,oBAAoB;AAExC,SAAS,2BAA2B;AACpC,SAAS,8BAA8B;AA4EjC,MAAO,wBAAuB;EAC1B;EACA;;;;;;EAOR,YAAY,UAAgB;AAC1B,SAAK,qBAAqB,IAAI,uBAAuB,QAAQ,GAC7D,KAAK,kBAAkB;MACrB,OAAO,oBAAI,IAAG;MACd,SAAS,oBAAI,IAAG;MAChB,QAAQ,IAAI,KAAK;;MACjB,aAAa,KAAK,IAAG;;EAEzB;;;;;;;;;;;;;;;;;EAkBA,MAAM,eACJ,WACA,aACA,WAAiB;AAEjB,UAAM,YAAY,MAAM,KAAK,mBAAmB,KAAK,WAAW;AAChE,QAAI,CAAC;AACH,YAAM,IAAI,MAAM,cAAc,WAAW,aAAa;AAIxD,UAAM,iBAAiB,UAAU,QAAQ,OACvC,CAAC,MAAc,EAAE,cAAc,SAAS;AAG1C,QAAI,eAAe,WAAW;AAE5B,aAAO,UAAU,eAAe,SAAS,KAAK;AAIhD,UAAM,aAAa,eAAe,eAAe,SAAS,CAAC;AAE3D,QAAI,WAAW,SAAS;AACtB,aAAO;AAIT,UAAM,cAAc,UAAU,eAAe,SAAS,GAChD,gBAAgB,WAAW,SAAS,CAAA;AAE1C,QAAI,aAAa;AAEf,YAAM,sBACJ,OAAO,cAAc,cAAe,WAAW,cAAc,aAAa,CAAA,GAEtE,aAAa;QACjB,IAAI,YAAY;QAChB,MAAM,YAAY;QAClB,cAAc,YAAY;QAC1B,MAAM,OAAO,cAAc,QAAS,WAAW,cAAc,OAA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mB;AACzB,UAAM,MAAM,KAAK,IAAG;AAGpB,QAAI,QAAM,KAAK,gBAAgB,cAAc,KAAK,MAKlD;iBAAW,CAAC,KAAK,KAAK,KAAK,KAAK,gBAAgB,MAAM,QAAO;AAE3D,QADY,MAAM,IAAI,KAAK,MAAM,UAAU,EAAE,QAAO,KACzC,KAAK,gBAAgB,UAC9B,KAAK,gBAAgB,MAAM,OAAO,GAAG;AAIzC,WAAK,gBAAgB,cAAc;;EACrC;;",
6
6
  "names": []
7
7
  }
@@ -88,6 +88,7 @@ class ArchiMateExporter {
88
88
  businessevent: "BusinessEvent",
89
89
  businessservice: "BusinessService",
90
90
  businessobject: "BusinessObject",
91
+ businesscapability: "Capability",
91
92
  contract: "Contract",
92
93
  product: "Product",
93
94
  representation: "Representation"
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/export/archimate-exporter.ts"],
4
- "sourcesContent": ["import type { Model } from \"../core/model.js\";\nimport type { Exporter, ExportOptions } from \"./types.js\";\nimport { escapeXml } from \"./types.js\";\nimport { isTelemetryEnabled, startSpan, endSpan } from \"../telemetry/index.js\";\nimport { getErrorMessage } from \"../utils/errors.js\";\n\n/**\n * ArchiMate XML Exporter for layers 1, 2, 5, 6 (Motivation, Business, Application, Technology)\n * Generates valid ArchiMate 3.2 XML format\n * Note: Product layer (layer 3) does not participate in ArchiMate export\n */\nexport class ArchiMateExporter implements Exporter {\n name = \"ArchiMate\";\n supportedLayers = [\"motivation\", \"business\", \"application\", \"technology\"];\n\n async export(model: Model, options: ExportOptions = {}): Promise<string> {\n const span = isTelemetryEnabled\n ? startSpan(\"export.format.archimate\", {\n \"export.layerCount\": options.layers?.length || this.supportedLayers.length,\n })\n : null;\n\n try {\n const lines: string[] = [];\n\n // XML declaration\n lines.push('<?xml version=\"1.0\" encoding=\"UTF-8\"?>');\n\n // Root element with namespaces\n lines.push('<model xmlns=\"http://www.opengroup.org/xsd/archimate/3.0/\"');\n lines.push(' xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"');\n lines.push(\n ' xsi:schemaLocation=\"http://www.opengroup.org/xsd/archimate/3.0/ http://www.opengroup.org/xsd/archimate/3.1/archimate3_Diagram.xsd\">'\n );\n\n // Model metadata\n lines.push(` <name>${escapeXml(model.manifest.name)}</name>`);\n if (model.manifest.description) {\n lines.push(` <documentation>${escapeXml(model.manifest.description)}</documentation>`);\n }\n\n // Export elements - load from each layer directly\n lines.push(\" <elements>\");\n\n const layersToExport = options.layers || this.supportedLayers;\n const elementsByLayer: Array<{ layer: string; element: any }> = [];\n\n // Load elements from each supported layer\n for (const layerName of layersToExport) {\n if (!this.supportedLayers.includes(layerName)) continue;\n\n const layer = await model.getLayer(layerName);\n if (!layer) continue;\n const layerElements = layer.listElements();\n for (const element of layerElements) {\n elementsByLayer.push({ layer: layerName, element });\n }\n }\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"export.elementCount\", elementsByLayer.length);\n }\n\n for (const { layer, element } of elementsByLayer) {\n const archiType = this.mapToArchiMateType(element.type, layer);\n lines.push(` <element identifier=\"${element.path}\" xsi:type=\"${archiType}\">`);\n lines.push(` <name>${escapeXml(element.name)}</name>`);\n\n if (element.description) {\n lines.push(` <documentation>${escapeXml(element.description)}</documentation>`);\n }\n\n // Add properties section\n lines.push(\" <properties>\");\n\n // Handle source_reference from element (if present)\n if (element.source_reference) {\n const flattenedProps = this.flattenSourceReference(element.source_reference);\n for (const [flatKey, flatValue] of Object.entries(flattenedProps)) {\n lines.push(\n ` <property key=\"${escapeXml(flatKey)}\" value=\"${escapeXml(String(flatValue))}\" />`\n );\n }\n }\n\n // Add element attributes as properties\n const attrKeys = Object.keys(element.attributes || {});\n if (attrKeys.length > 0) {\n for (const key of attrKeys) {\n const val = element.attributes?.[key];\n const strValue = this.valueToString(val);\n lines.push(\n ` <property key=\"${escapeXml(key)}\" value=\"${escapeXml(strValue)}\" />`\n );\n }\n }\n\n lines.push(\" </properties>\");\n lines.push(\" </element>\");\n }\n\n lines.push(\" </elements>\");\n\n // Export relationships\n lines.push(\" <relationships>\");\n\n let relationshipCount = 0;\n const elementIds = new Set(elementsByLayer.map((e) => e.element.path));\n\n // Filter relationships to those between exported elements\n for (const rel of model.relationships.getAll()) {\n if (!elementIds.has(rel.source) || !elementIds.has(rel.target)) {\n continue;\n }\n\n const relId = this.escapeId(`${rel.source}-${rel.predicate}-${rel.target}`);\n lines.push(` <relationship identifier=\"${relId}\" `);\n lines.push(` source=\"${rel.source}\" target=\"${rel.target}\" `);\n lines.push(` xsi:type=\"Association\">`);\n lines.push(` <name>${rel.predicate}</name>`);\n lines.push(` </relationship>`);\n relationshipCount++;\n }\n\n lines.push(\" </relationships>\");\n lines.push(\"</model>\");\n\n const result = lines.join(\"\\n\");\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"export.relationshipCount\", relationshipCount);\n (span as any).setAttribute(\"export.size\", result.length);\n (span as any).setStatus({ code: 0 });\n }\n\n return result;\n } catch (error) {\n if (isTelemetryEnabled && span) {\n (span as any).recordException(error as Error);\n (span as any).setStatus({\n code: 2,\n message: getErrorMessage(error),\n });\n }\n throw error;\n } finally {\n endSpan(span);\n }\n }\n\n /**\n * Map element type and layer to ArchiMate type\n */\n private mapToArchiMateType(type: string, layer: string): string {\n const mapping: Record<string, Record<string, string>> = {\n motivation: {\n stakeholder: \"Stakeholder\",\n driver: \"Driver\",\n assessment: \"Assessment\",\n goal: \"Goal\",\n outcome: \"Outcome\",\n principle: \"Principle\",\n requirement: \"Requirement\",\n constraint: \"Constraint\",\n meaning: \"Meaning\",\n value: \"Value\",\n },\n business: {\n businessactor: \"BusinessActor\",\n businessrole: \"BusinessRole\",\n businesscollaboration: \"BusinessCollaboration\",\n businessinterface: \"BusinessInterface\",\n businessprocess: \"BusinessProcess\",\n businessfunction: \"BusinessFunction\",\n businessinteraction: \"BusinessInteraction\",\n businessevent: \"BusinessEvent\",\n businessservice: \"BusinessService\",\n businessobject: \"BusinessObject\",\n contract: \"Contract\",\n product: \"Product\",\n representation: \"Representation\",\n },\n application: {\n applicationcomponent: \"ApplicationComponent\",\n applicationcollaboration: \"ApplicationCollaboration\",\n applicationinterface: \"ApplicationInterface\",\n applicationfunction: \"ApplicationFunction\",\n applicationinteraction: \"ApplicationInteraction\",\n applicationprocess: \"ApplicationProcess\",\n applicationevent: \"ApplicationEvent\",\n applicationservice: \"ApplicationService\",\n dataobject: \"DataObject\",\n },\n technology: {\n node: \"Node\",\n device: \"Device\",\n systemsoftware: \"SystemSoftware\",\n technologycollaboration: \"TechnologyCollaboration\",\n technologyinterface: \"TechnologyInterface\",\n path: \"Path\",\n communicationnetwork: \"CommunicationNetwork\",\n technologyfunction: \"TechnologyFunction\",\n technologyprocess: \"TechnologyProcess\",\n technologyinteraction: \"TechnologyInteraction\",\n technologyevent: \"TechnologyEvent\",\n technologyservice: \"TechnologyService\",\n artifact: \"Artifact\",\n },\n };\n\n return mapping[layer]?.[type] || \"Element\";\n }\n\n /**\n * Escape ID characters for use in identifiers\n */\n private escapeId(str: string): string {\n return str.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n }\n\n /**\n * Convert value to string representation\n */\n private valueToString(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\") return String(value);\n if (typeof value === \"boolean\") return String(value);\n if (Array.isArray(value)) return `[${value.map((v) => this.valueToString(v)).join(\", \")}]`;\n if (value && typeof value === \"object\") {\n return JSON.stringify(value);\n }\n return String(value);\n }\n\n /**\n * Flatten source reference structure into ArchiMate properties\n * Converts nested structure like { provenance: \"extracted\", locations: [...] }\n * into flat properties like \"source.provenance\", \"source.file.0\", etc.\n */\n private flattenSourceReference(sourceRef: any): Record<string, string> {\n const props: Record<string, string> = {};\n\n if (!sourceRef || typeof sourceRef !== \"object\") {\n return props;\n }\n\n // Add provenance\n if (sourceRef.provenance) {\n props[\"source.provenance\"] = sourceRef.provenance;\n }\n\n // Add locations\n if (Array.isArray(sourceRef.locations)) {\n sourceRef.locations.forEach((location: any, index: number) => {\n if (location.file) {\n props[`source.file.${index}`] = location.file;\n }\n if (location.symbol) {\n props[`source.symbol.${index}`] = location.symbol;\n }\n if (location.line !== undefined) {\n props[`source.line.${index}`] = String(location.line);\n }\n if (location.column !== undefined) {\n props[`source.column.${index}`] = String(location.column);\n }\n });\n }\n\n // Add repository info\n if (sourceRef.repository) {\n if (sourceRef.repository.url) {\n props[\"source.repository.url\"] = sourceRef.repository.url;\n }\n if (sourceRef.repository.commit) {\n props[\"source.repository.commit\"] = sourceRef.repository.commit;\n }\n if (sourceRef.repository.branch) {\n props[\"source.repository.branch\"] = sourceRef.repository.branch;\n }\n }\n\n return props;\n }\n}\n"],
5
- "mappings": "AAEA,SAAS,iBAAiB;AAC1B,SAAS,oBAAoB,WAAW,eAAe;AACvD,SAAS,uBAAuB;AAO1B,MAAO,kBAAiB;EAC5B,OAAO;EACP,kBAAkB,CAAC,cAAc,YAAY,eAAe,YAAY;EAExE,MAAM,OAAO,OAAc,UAAyB,CAAA,GAAE;AACpD,UAAM,OAAO,qBACT,UAAU,2BAA2B;MACnC,qBAAqB,QAAQ,QAAQ,UAAU,KAAK,gBAAgB;KACrE,IACD;AAEJ,QAAI;AACF,YAAM,QAAkB,CAAA;AAGxB,YAAM,KAAK,wCAAwC,GAGnD,MAAM,KAAK,4DAA4D,GACvE,MAAM,KAAK,8DAA8D,GACzE,MAAM,KACJ,4IAA4I,GAI9I,MAAM,KAAK,WAAW,UAAU,MAAM,SAAS,IAAI,CAAC,SAAS,GACzD,MAAM,SAAS,eACjB,MAAM,KAAK,oBAAoB,UAAU,MAAM,SAAS,WAAW,CAAC,kBAAkB,GAIxF,MAAM,KAAK,cAAc;AAEzB,YAAM,iBAAiB,QAAQ,UAAU,KAAK,iBACxC,kBAA0D,CAAA;AAGhE,iBAAW,aAAa,gBAAgB;AACtC,YAAI,CAAC,KAAK,gBAAgB,SAAS,SAAS;AAAG;AAE/C,cAAM,QAAQ,MAAM,MAAM,SAAS,SAAS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pD,UAAU,WAAW,WACvB,MAAM,0BAA0B,IAAI,UAAU,WAAW,SAEvD,UAAU,WAAW,WACvB,MAAM,0BAA0B,IAAI,UAAU,WAAW,WAItD;EACT;;",
4
+ "sourcesContent": ["import type { Model } from \"../core/model.js\";\nimport type { Exporter, ExportOptions } from \"./types.js\";\nimport { escapeXml } from \"./types.js\";\nimport { isTelemetryEnabled, startSpan, endSpan } from \"../telemetry/index.js\";\nimport { getErrorMessage } from \"../utils/errors.js\";\n\n/**\n * ArchiMate XML Exporter for layers 1, 2, 5, 6 (Motivation, Business, Application, Technology)\n * Generates valid ArchiMate 3.2 XML format\n * Note: Product layer (layer 3) does not participate in ArchiMate export\n */\nexport class ArchiMateExporter implements Exporter {\n name = \"ArchiMate\";\n supportedLayers = [\"motivation\", \"business\", \"application\", \"technology\"];\n\n async export(model: Model, options: ExportOptions = {}): Promise<string> {\n const span = isTelemetryEnabled\n ? startSpan(\"export.format.archimate\", {\n \"export.layerCount\": options.layers?.length || this.supportedLayers.length,\n })\n : null;\n\n try {\n const lines: string[] = [];\n\n // XML declaration\n lines.push('<?xml version=\"1.0\" encoding=\"UTF-8\"?>');\n\n // Root element with namespaces\n lines.push('<model xmlns=\"http://www.opengroup.org/xsd/archimate/3.0/\"');\n lines.push(' xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"');\n lines.push(\n ' xsi:schemaLocation=\"http://www.opengroup.org/xsd/archimate/3.0/ http://www.opengroup.org/xsd/archimate/3.1/archimate3_Diagram.xsd\">'\n );\n\n // Model metadata\n lines.push(` <name>${escapeXml(model.manifest.name)}</name>`);\n if (model.manifest.description) {\n lines.push(` <documentation>${escapeXml(model.manifest.description)}</documentation>`);\n }\n\n // Export elements - load from each layer directly\n lines.push(\" <elements>\");\n\n const layersToExport = options.layers || this.supportedLayers;\n const elementsByLayer: Array<{ layer: string; element: any }> = [];\n\n // Load elements from each supported layer\n for (const layerName of layersToExport) {\n if (!this.supportedLayers.includes(layerName)) continue;\n\n const layer = await model.getLayer(layerName);\n if (!layer) continue;\n const layerElements = layer.listElements();\n for (const element of layerElements) {\n elementsByLayer.push({ layer: layerName, element });\n }\n }\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"export.elementCount\", elementsByLayer.length);\n }\n\n for (const { layer, element } of elementsByLayer) {\n const archiType = this.mapToArchiMateType(element.type, layer);\n lines.push(` <element identifier=\"${element.path}\" xsi:type=\"${archiType}\">`);\n lines.push(` <name>${escapeXml(element.name)}</name>`);\n\n if (element.description) {\n lines.push(` <documentation>${escapeXml(element.description)}</documentation>`);\n }\n\n // Add properties section\n lines.push(\" <properties>\");\n\n // Handle source_reference from element (if present)\n if (element.source_reference) {\n const flattenedProps = this.flattenSourceReference(element.source_reference);\n for (const [flatKey, flatValue] of Object.entries(flattenedProps)) {\n lines.push(\n ` <property key=\"${escapeXml(flatKey)}\" value=\"${escapeXml(String(flatValue))}\" />`\n );\n }\n }\n\n // Add element attributes as properties\n const attrKeys = Object.keys(element.attributes || {});\n if (attrKeys.length > 0) {\n for (const key of attrKeys) {\n const val = element.attributes?.[key];\n const strValue = this.valueToString(val);\n lines.push(\n ` <property key=\"${escapeXml(key)}\" value=\"${escapeXml(strValue)}\" />`\n );\n }\n }\n\n lines.push(\" </properties>\");\n lines.push(\" </element>\");\n }\n\n lines.push(\" </elements>\");\n\n // Export relationships\n lines.push(\" <relationships>\");\n\n let relationshipCount = 0;\n const elementIds = new Set(elementsByLayer.map((e) => e.element.path));\n\n // Filter relationships to those between exported elements\n for (const rel of model.relationships.getAll()) {\n if (!elementIds.has(rel.source) || !elementIds.has(rel.target)) {\n continue;\n }\n\n const relId = this.escapeId(`${rel.source}-${rel.predicate}-${rel.target}`);\n lines.push(` <relationship identifier=\"${relId}\" `);\n lines.push(` source=\"${rel.source}\" target=\"${rel.target}\" `);\n lines.push(` xsi:type=\"Association\">`);\n lines.push(` <name>${rel.predicate}</name>`);\n lines.push(` </relationship>`);\n relationshipCount++;\n }\n\n lines.push(\" </relationships>\");\n lines.push(\"</model>\");\n\n const result = lines.join(\"\\n\");\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"export.relationshipCount\", relationshipCount);\n (span as any).setAttribute(\"export.size\", result.length);\n (span as any).setStatus({ code: 0 });\n }\n\n return result;\n } catch (error) {\n if (isTelemetryEnabled && span) {\n (span as any).recordException(error as Error);\n (span as any).setStatus({\n code: 2,\n message: getErrorMessage(error),\n });\n }\n throw error;\n } finally {\n endSpan(span);\n }\n }\n\n /**\n * Map element type and layer to ArchiMate type\n */\n private mapToArchiMateType(type: string, layer: string): string {\n const mapping: Record<string, Record<string, string>> = {\n motivation: {\n stakeholder: \"Stakeholder\",\n driver: \"Driver\",\n assessment: \"Assessment\",\n goal: \"Goal\",\n outcome: \"Outcome\",\n principle: \"Principle\",\n requirement: \"Requirement\",\n constraint: \"Constraint\",\n meaning: \"Meaning\",\n value: \"Value\",\n },\n business: {\n businessactor: \"BusinessActor\",\n businessrole: \"BusinessRole\",\n businesscollaboration: \"BusinessCollaboration\",\n businessinterface: \"BusinessInterface\",\n businessprocess: \"BusinessProcess\",\n businessfunction: \"BusinessFunction\",\n businessinteraction: \"BusinessInteraction\",\n businessevent: \"BusinessEvent\",\n businessservice: \"BusinessService\",\n businessobject: \"BusinessObject\",\n businesscapability: \"Capability\",\n contract: \"Contract\",\n product: \"Product\",\n representation: \"Representation\",\n },\n application: {\n applicationcomponent: \"ApplicationComponent\",\n applicationcollaboration: \"ApplicationCollaboration\",\n applicationinterface: \"ApplicationInterface\",\n applicationfunction: \"ApplicationFunction\",\n applicationinteraction: \"ApplicationInteraction\",\n applicationprocess: \"ApplicationProcess\",\n applicationevent: \"ApplicationEvent\",\n applicationservice: \"ApplicationService\",\n dataobject: \"DataObject\",\n },\n technology: {\n node: \"Node\",\n device: \"Device\",\n systemsoftware: \"SystemSoftware\",\n technologycollaboration: \"TechnologyCollaboration\",\n technologyinterface: \"TechnologyInterface\",\n path: \"Path\",\n communicationnetwork: \"CommunicationNetwork\",\n technologyfunction: \"TechnologyFunction\",\n technologyprocess: \"TechnologyProcess\",\n technologyinteraction: \"TechnologyInteraction\",\n technologyevent: \"TechnologyEvent\",\n technologyservice: \"TechnologyService\",\n artifact: \"Artifact\",\n },\n };\n\n return mapping[layer]?.[type] || \"Element\";\n }\n\n /**\n * Escape ID characters for use in identifiers\n */\n private escapeId(str: string): string {\n return str.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n }\n\n /**\n * Convert value to string representation\n */\n private valueToString(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\") return String(value);\n if (typeof value === \"boolean\") return String(value);\n if (Array.isArray(value)) return `[${value.map((v) => this.valueToString(v)).join(\", \")}]`;\n if (value && typeof value === \"object\") {\n return JSON.stringify(value);\n }\n return String(value);\n }\n\n /**\n * Flatten source reference structure into ArchiMate properties\n * Converts nested structure like { provenance: \"extracted\", locations: [...] }\n * into flat properties like \"source.provenance\", \"source.file.0\", etc.\n */\n private flattenSourceReference(sourceRef: any): Record<string, string> {\n const props: Record<string, string> = {};\n\n if (!sourceRef || typeof sourceRef !== \"object\") {\n return props;\n }\n\n // Add provenance\n if (sourceRef.provenance) {\n props[\"source.provenance\"] = sourceRef.provenance;\n }\n\n // Add locations\n if (Array.isArray(sourceRef.locations)) {\n sourceRef.locations.forEach((location: any, index: number) => {\n if (location.file) {\n props[`source.file.${index}`] = location.file;\n }\n if (location.symbol) {\n props[`source.symbol.${index}`] = location.symbol;\n }\n if (location.line !== undefined) {\n props[`source.line.${index}`] = String(location.line);\n }\n if (location.column !== undefined) {\n props[`source.column.${index}`] = String(location.column);\n }\n });\n }\n\n // Add repository info\n if (sourceRef.repository) {\n if (sourceRef.repository.url) {\n props[\"source.repository.url\"] = sourceRef.repository.url;\n }\n if (sourceRef.repository.commit) {\n props[\"source.repository.commit\"] = sourceRef.repository.commit;\n }\n if (sourceRef.repository.branch) {\n props[\"source.repository.branch\"] = sourceRef.repository.branch;\n }\n }\n\n return props;\n }\n}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WAAI,OAAO,SAAU,WAAiB,QAClC,OAAO,SAAU,YACjB,OAAO,SAAU,YAAkB,OAAO,KAAK,IAC/C,MAAM,QAAQ,KAAK,IAAU,IAAI,MAAM,IAAI,CAAC,MAAM,KAAK,cAAc,CAAC,CAAC,EAAE,KAAK,IAAI,CAAC,MACnF,SAAS,OAAO,SAAU,WACrB,KAAK,UAAU,KAAK,IAEtB,OAAO,KAAK;EACrB;;;;;;EAOQ,uBAAuB,WAAc;AAC3C,UAAM,QAAgC,CAAA;AAEtC,WAAI,CAAC,aAAa,OAAO,aAAc,aAKnC,UAAU,eACZ,MAAM,mBAAmB,IAAI,UAAU,aAIrC,MAAM,QAAQ,UAAU,SAAS,KACnC,UAAU,UAAU,QAAQ,CAAC,UAAe,UAAiB;AAC3D,MAAI,SAAS,SACX,MAAM,eAAe,KAAK,EAAE,IAAI,SAAS,OAEvC,SAAS,WACX,MAAM,iBAAiB,KAAK,EAAE,IAAI,SAAS,SAEzC,SAAS,SAAS,WACpB,MAAM,eAAe,KAAK,EAAE,IAAI,OAAO,SAAS,IAAI,IAElD,SAAS,WAAW,WACtB,MAAM,iBAAiB,KAAK,EAAE,IAAI,OAAO,SAAS,MAAM;IAE5D,CAAC,GAIC,UAAU,eACR,UAAU,WAAW,QACvB,MAAM,uBAAuB,IAAI,UAAU,WAAW,MAEpD,UAAU,WAAW,WACvB,MAAM,0BAA0B,IAAI,UAAU,WAAW,SAEvD,UAAU,WAAW,WACvB,MAAM,0BAA0B,IAAI,UAAU,WAAW,WAItD;EACT;;",
6
6
  "names": []
7
7
  }
@@ -6,8 +6,8 @@ const sharedAjv = (() => {
6
6
  strict: !1,
7
7
  validateFormats: !0
8
8
  });
9
- return addFormats(ajv), ajv.addSchema({ $schema: "http://json-schema.org/draft-07/schema#", title: "SpecNode", description: "Base schema for all spec node types. Each node type schema extends this with type-specific attribute constraints via allOf.", type: "object", required: ["id", "path", "spec_node_id", "type", "name"], additionalProperties: !1, properties: { id: { type: "string", format: "uuid", description: "Unique node instance identifier (UUIDv4). Globally unique across the entire model.", examples: ["550e8400-e29b-41d4-a716-446655440000"] }, path: { type: "string", pattern: "^[a-z][a-z0-9-]*\\.[a-z][a-z0-9-]*\\.[a-z][a-z0-9-]*$", description: "Human-readable element path in format {layer}.{type}.{name} (e.g., 'motivation.goal.increase-revenue')" }, spec_node_id: { type: "string", pattern: "^[a-z-]+\\.[a-z][a-z0-9-]*$", description: "Reference to the spec node type that this node conforms to (e.g., 'motivation.goal')" }, type: { type: "string", description: "Denormalized node type for efficient filtering and queries. Extracted from spec_node_id (the part after the dot).", examples: ["goal", "requirement", "endpoint", "table"] }, layer_id: { type: "string", pattern: "^[a-z][a-z0-9-]*$", description: "Denormalized layer ID for efficient layer-scoped queries. Extracted from spec_node_id (the part before the dot)." }, name: { type: "string", description: "Human-readable instance name", examples: ["Improve Customer Satisfaction", "User Login API", "Customer Table"] }, description: { type: "string", description: "Optional detailed description of this specific node instance" }, attributes: { type: "object", description: "Attribute values for this node instance. Keys must correspond to attributes defined in the per-type schema, and values must conform to the type constraints." }, source_reference: { $ref: "urn:dr:spec:base:source-references#/definitions/SourceReference", description: "Optional provenance tracking linking this node to source code locations" }, metadata: { type: "object", description: "Optional metadata about the lifecycle and version of this node instance", additionalProperties: !1, properties: { created_at: { type: "string", format: "date-time", description: "ISO 8601 timestamp when this node was created" }, updated_at: { type: "string", format: "date-time", description: "ISO 8601 timestamp of the last modification" }, created_by: { type: "string", description: "User or system that created this node" }, version: { type: "integer", minimum: 1, description: "Version number of this node (incremented on updates)" } } } } }, "urn:dr:spec:base:spec-node"), ajv.addSchema({ $schema: "http://json-schema.org/draft-07/schema#", title: "SpecNodeRelationship", description: "Base type for relationship type definitions in the specification. Defines valid relationships between node types, including cardinality, strength, and semantic properties.", type: "object", required: ["id", "source_spec_node_id", "destination_spec_node_id", "predicate"], additionalProperties: !1, properties: { id: { type: "string", pattern: "^[a-z-]+\\.[a-z-]+\\.[a-z-]+$", description: "Unique relationship ID in format: {source-layer}.{predicate}.{dest-layer}. All components use lowercase with hyphens.", examples: ["motivation.supports.motivation", "motivation.realizes.business", "api.exposes.data-model"] }, source_spec_node_id: { type: "string", pattern: "^[a-z-]+\\.[a-z][a-z0-9-]*$", description: "SpecNode ID that can serve as the source of this relationship type" }, source_layer: { type: "string", pattern: "^[a-z][a-z0-9-]*$", description: "Denormalized layer ID extracted from source_spec_node_id for efficient queries" }, destination_spec_node_id: { type: "string", pattern: "^[a-z-]+\\.[a-z][a-z0-9-]*$", description: "SpecNode ID that can serve as the destination of this relationship type" }, destination_layer: { type: "string", pattern: "^[a-z][a-z0-9-]*$", description: "Denormalized layer ID extracted from destination_spec_node_id for efficient queries" }, predicate: { type: "string", description: "Semantic predicate from PredicateCatalog describing the relationship type. Must be a valid predicate name.", examples: ["supports", "realizes", "fulfills", "implements", "uses", "consumes"] }, cardinality: { type: "string", enum: ["one-to-one", "one-to-many", "many-to-one", "many-to-many"], description: "Multiplicity constraint on this relationship type. Defines how many source nodes can relate to how many destination nodes.", default: "many-to-many" }, strength: { type: "string", enum: ["critical", "high", "medium", "low"], description: "Typical importance or strength of this relationship type", default: "medium" }, required: { type: "boolean", description: "Whether instances of the source node type must have at least one relationship of this type", default: !1 }, attributes: { type: "object", description: "Optional schema defining attributes that can appear on relationship instances of this type", additionalProperties: { $ref: "urn:dr:spec:base:attribute-spec#/definitions/AttributeSpec" }, minProperties: 0, examples: [{ reason: { type: "string", description: "Explanation for why this relationship exists" }, strength_override: { type: "enum", enum_values: ["critical", "high", "medium", "low"], description: "Instance-specific strength override" } }] } } }, "urn:dr:spec:base:spec-node-relationship"), ajv.addSchema({ $schema: "http://json-schema.org/draft-07/schema#", title: "Source Code Reference Definitions", description: "Reusable JSON Schema definitions for linking architecture elements to source code locations", version: "1.0.0", definitions: { ProvenanceType: { type: "string", enum: ["extracted", "manual", "inferred", "generated"], description: "How this reference was created: extracted (automated ingestion), manual (human added), inferred (pattern matching), generated (code generated from model)" }, SourceLocation: { type: "object", description: "A specific location in source code, identified by file path and optional symbol", required: ["file"], properties: { file: { type: "string", minLength: 1, description: "File path relative to repository root" }, symbol: { type: "string", description: "Named code element (e.g., ClassName.methodName, function_name)" } } }, RepositoryContext: { type: "object", description: "Repository context for the source reference", properties: { url: { type: "string", format: "uri", description: "Git remote URL (HTTPS or SSH format)" }, commit: { type: "string", pattern: "^[0-9a-f]{40}$", description: "Full 40-character Git commit SHA" } } }, SourceReference: { type: "object", description: "Links entity to source code location(s) with provenance tracking. For inferred or generated elements, locations may be omitted when no source file exists yet.", required: ["provenance"], properties: { provenance: { $ref: "#/definitions/ProvenanceType" }, locations: { type: "array", minItems: 1, items: { $ref: "#/definitions/SourceLocation" }, description: "One or more source code locations. Required for extracted and manual provenance; optional for inferred and generated." }, repository: { $ref: "#/definitions/RepositoryContext" } } } } }, "urn:dr:spec:base:source-references"), ajv.addSchema({ $schema: "http://json-schema.org/draft-07/schema#", title: "AttributeSpec Definitions", description: "Reusable definition for attribute specifications used in spec-level schemas (e.g., spec-node-relationship attributes)", definitions: { AttributeSpec: { type: "object", title: "AttributeSpec", description: "Specification for a single attribute that can appear on node or relationship instances", required: ["type", "description"], additionalProperties: !1, properties: { type: { type: "string", enum: ["string", "integer", "number", "boolean", "array", "object", "enum"], description: "The JSON type of this attribute" }, description: { type: "string", description: "Human-readable description of this attribute's purpose" }, enum_values: { type: "array", items: { type: "string" }, description: "Required when type is 'enum'. Lists the valid string values for this attribute.", examples: [["high", "medium", "low"], ["active", "inactive", "archived"]] }, format: { type: "string", description: "Optional format constraint for string types (e.g., 'email', 'uri', 'date-time')", examples: ["email", "uri", "date-time", "uuid"] }, default: { description: "Default value for this attribute when not provided on a node instance. Can be any JSON value." } }, if: { properties: { type: { const: "enum" } }, required: ["type"] }, then: { required: ["type", "description", "enum_values"] } } } }, "urn:dr:spec:base:attribute-spec"), ajv;
10
- })(), validateSpecNode = sharedAjv.compile({ $schema: "http://json-schema.org/draft-07/schema#", title: "SpecNode", description: "Base schema for all spec node types. Each node type schema extends this with type-specific attribute constraints via allOf.", type: "object", required: ["id", "path", "spec_node_id", "type", "name"], additionalProperties: !1, properties: { id: { type: "string", format: "uuid", description: "Unique node instance identifier (UUIDv4). Globally unique across the entire model.", examples: ["550e8400-e29b-41d4-a716-446655440000"] }, path: { type: "string", pattern: "^[a-z][a-z0-9-]*\\.[a-z][a-z0-9-]*\\.[a-z][a-z0-9-]*$", description: "Human-readable element path in format {layer}.{type}.{name} (e.g., 'motivation.goal.increase-revenue')" }, spec_node_id: { type: "string", pattern: "^[a-z-]+\\.[a-z][a-z0-9-]*$", description: "Reference to the spec node type that this node conforms to (e.g., 'motivation.goal')" }, type: { type: "string", description: "Denormalized node type for efficient filtering and queries. Extracted from spec_node_id (the part after the dot).", examples: ["goal", "requirement", "endpoint", "table"] }, layer_id: { type: "string", pattern: "^[a-z][a-z0-9-]*$", description: "Denormalized layer ID for efficient layer-scoped queries. Extracted from spec_node_id (the part before the dot)." }, name: { type: "string", description: "Human-readable instance name", examples: ["Improve Customer Satisfaction", "User Login API", "Customer Table"] }, description: { type: "string", description: "Optional detailed description of this specific node instance" }, attributes: { type: "object", description: "Attribute values for this node instance. Keys must correspond to attributes defined in the per-type schema, and values must conform to the type constraints." }, source_reference: { $ref: "urn:dr:spec:base:source-references#/definitions/SourceReference", description: "Optional provenance tracking linking this node to source code locations" }, metadata: { type: "object", description: "Optional metadata about the lifecycle and version of this node instance", additionalProperties: !1, properties: { created_at: { type: "string", format: "date-time", description: "ISO 8601 timestamp when this node was created" }, updated_at: { type: "string", format: "date-time", description: "ISO 8601 timestamp of the last modification" }, created_by: { type: "string", description: "User or system that created this node" }, version: { type: "integer", minimum: 1, description: "Version number of this node (incremented on updates)" } } } } }), validateSpecNodeRelationship = sharedAjv.compile({ $schema: "http://json-schema.org/draft-07/schema#", title: "SpecNodeRelationship", description: "Base type for relationship type definitions in the specification. Defines valid relationships between node types, including cardinality, strength, and semantic properties.", type: "object", required: ["id", "source_spec_node_id", "destination_spec_node_id", "predicate"], additionalProperties: !1, properties: { id: { type: "string", pattern: "^[a-z-]+\\.[a-z-]+\\.[a-z-]+$", description: "Unique relationship ID in format: {source-layer}.{predicate}.{dest-layer}. All components use lowercase with hyphens.", examples: ["motivation.supports.motivation", "motivation.realizes.business", "api.exposes.data-model"] }, source_spec_node_id: { type: "string", pattern: "^[a-z-]+\\.[a-z][a-z0-9-]*$", description: "SpecNode ID that can serve as the source of this relationship type" }, source_layer: { type: "string", pattern: "^[a-z][a-z0-9-]*$", description: "Denormalized layer ID extracted from source_spec_node_id for efficient queries" }, destination_spec_node_id: { type: "string", pattern: "^[a-z-]+\\.[a-z][a-z0-9-]*$", description: "SpecNode ID that can serve as the destination of this relationship type" }, destination_layer: { type: "string", pattern: "^[a-z][a-z0-9-]*$", description: "Denormalized layer ID extracted from destination_spec_node_id for efficient queries" }, predicate: { type: "string", description: "Semantic predicate from PredicateCatalog describing the relationship type. Must be a valid predicate name.", examples: ["supports", "realizes", "fulfills", "implements", "uses", "consumes"] }, cardinality: { type: "string", enum: ["one-to-one", "one-to-many", "many-to-one", "many-to-many"], description: "Multiplicity constraint on this relationship type. Defines how many source nodes can relate to how many destination nodes.", default: "many-to-many" }, strength: { type: "string", enum: ["critical", "high", "medium", "low"], description: "Typical importance or strength of this relationship type", default: "medium" }, required: { type: "boolean", description: "Whether instances of the source node type must have at least one relationship of this type", default: !1 }, attributes: { type: "object", description: "Optional schema defining attributes that can appear on relationship instances of this type", additionalProperties: { $ref: "urn:dr:spec:base:attribute-spec#/definitions/AttributeSpec" }, minProperties: 0, examples: [{ reason: { type: "string", description: "Explanation for why this relationship exists" }, strength_override: { type: "enum", enum_values: ["critical", "high", "medium", "low"], description: "Instance-specific strength override" } }] } } }), validateSourceReference = sharedAjv.compile({ $schema: "http://json-schema.org/draft-07/schema#", title: "Source Code Reference Definitions", description: "Reusable JSON Schema definitions for linking architecture elements to source code locations", version: "1.0.0", definitions: { ProvenanceType: { type: "string", enum: ["extracted", "manual", "inferred", "generated"], description: "How this reference was created: extracted (automated ingestion), manual (human added), inferred (pattern matching), generated (code generated from model)" }, SourceLocation: { type: "object", description: "A specific location in source code, identified by file path and optional symbol", required: ["file"], properties: { file: { type: "string", minLength: 1, description: "File path relative to repository root" }, symbol: { type: "string", description: "Named code element (e.g., ClassName.methodName, function_name)" } } }, RepositoryContext: { type: "object", description: "Repository context for the source reference", properties: { url: { type: "string", format: "uri", description: "Git remote URL (HTTPS or SSH format)" }, commit: { type: "string", pattern: "^[0-9a-f]{40}$", description: "Full 40-character Git commit SHA" } } }, SourceReference: { type: "object", description: "Links entity to source code location(s) with provenance tracking. For inferred or generated elements, locations may be omitted when no source file exists yet.", required: ["provenance"], properties: { provenance: { $ref: "#/definitions/ProvenanceType" }, locations: { type: "array", minItems: 1, items: { $ref: "#/definitions/SourceLocation" }, description: "One or more source code locations. Required for extracted and manual provenance; optional for inferred and generated." }, repository: { $ref: "#/definitions/RepositoryContext" } } } } }), validateAttributeSpec = sharedAjv.compile({ $schema: "http://json-schema.org/draft-07/schema#", title: "AttributeSpec Definitions", description: "Reusable definition for attribute specifications used in spec-level schemas (e.g., spec-node-relationship attributes)", definitions: { AttributeSpec: { type: "object", title: "AttributeSpec", description: "Specification for a single attribute that can appear on node or relationship instances", required: ["type", "description"], additionalProperties: !1, properties: { type: { type: "string", enum: ["string", "integer", "number", "boolean", "array", "object", "enum"], description: "The JSON type of this attribute" }, description: { type: "string", description: "Human-readable description of this attribute's purpose" }, enum_values: { type: "array", items: { type: "string" }, description: "Required when type is 'enum'. Lists the valid string values for this attribute.", examples: [["high", "medium", "low"], ["active", "inactive", "archived"]] }, format: { type: "string", description: "Optional format constraint for string types (e.g., 'email', 'uri', 'date-time')", examples: ["email", "uri", "date-time", "uuid"] }, default: { description: "Default value for this attribute when not provided on a node instance. Can be any JSON value." } }, if: { properties: { type: { const: "enum" } }, required: ["type"] }, then: { required: ["type", "description", "enum_values"] } } } });
9
+ return addFormats(ajv), ajv.addSchema({ $schema: "http://json-schema.org/draft-07/schema#", title: "SpecNode", description: "Base schema for all spec node types. Each node type schema extends this with type-specific attribute constraints via allOf.", type: "object", required: ["id", "path", "spec_node_id", "type", "name"], additionalProperties: !1, properties: { id: { type: "string", format: "uuid", description: "Unique node instance identifier (UUIDv4). Globally unique across the entire model.", examples: ["550e8400-e29b-41d4-a716-446655440000"] }, path: { type: "string", pattern: "^[a-z][a-z0-9-]*\\.[a-z][a-z0-9-]*\\.[a-z][a-z0-9-]*$", description: "Human-readable element path in format {layer}.{type}.{name} (e.g., 'motivation.goal.increase-revenue')" }, spec_node_id: { type: "string", pattern: "^[a-z-]+\\.[a-z][a-z0-9-]*$", description: "Reference to the spec node type that this node conforms to (e.g., 'motivation.goal')" }, type: { type: "string", description: "Denormalized node type for efficient filtering and queries. Extracted from spec_node_id (the part after the dot).", examples: ["goal", "requirement", "endpoint", "table"] }, layer_id: { type: "string", pattern: "^[a-z][a-z0-9-]*$", description: "Denormalized layer ID for efficient layer-scoped queries. Extracted from spec_node_id (the part before the dot)." }, name: { type: "string", description: "Human-readable instance name", examples: ["Improve Customer Satisfaction", "User Login API", "Customer Table"] }, description: { type: "string", description: "Optional detailed description of this specific node instance" }, attributes: { type: "object", description: "Attribute values for this node instance. Keys must correspond to attributes defined in the per-type schema, and values must conform to the type constraints." }, source_reference: { $ref: "urn:dr:spec:base:source-references#/definitions/SourceReference", description: "Optional provenance tracking linking this node to source code locations" }, metadata: { type: "object", description: "Optional metadata about the lifecycle and version of this node instance", additionalProperties: !1, properties: { created_at: { type: "string", format: "date-time", description: "ISO 8601 timestamp when this node was created" }, updated_at: { type: "string", format: "date-time", description: "ISO 8601 timestamp of the last modification" }, created_by: { type: "string", description: "User or system that created this node" }, version: { type: "integer", minimum: 1, description: "Version number of this node (incremented on updates)" } } } } }, "urn:dr:spec:base:spec-node"), ajv.addSchema({ $schema: "http://json-schema.org/draft-07/schema#", title: "SpecNodeRelationship", description: "Base type for relationship type definitions in the specification. Defines valid relationships between node types, including cardinality, strength, and semantic properties.", type: "object", required: ["id", "source_spec_node_id", "destination_spec_node_id", "predicate"], additionalProperties: !1, properties: { id: { type: "string", pattern: "^[a-z-]+\\.[a-z-]+\\.[a-z-]+$", description: "Unique relationship ID in format: {source-layer}.{predicate}.{dest-layer}. All components use lowercase with hyphens.", examples: ["motivation.supports.motivation", "motivation.realizes.business", "api.exposes.data-model"] }, source_spec_node_id: { type: "string", pattern: "^[a-z-]+\\.[a-z][a-z0-9-]*$", description: "SpecNode ID that can serve as the source of this relationship type" }, source_layer: { type: "string", pattern: "^[a-z][a-z0-9-]*$", description: "Denormalized layer ID extracted from source_spec_node_id for efficient queries" }, destination_spec_node_id: { type: "string", pattern: "^[a-z-]+\\.[a-z][a-z0-9-]*$", description: "SpecNode ID that can serve as the destination of this relationship type" }, destination_layer: { type: "string", pattern: "^[a-z][a-z0-9-]*$", description: "Denormalized layer ID extracted from destination_spec_node_id for efficient queries" }, predicate: { type: "string", description: "Semantic predicate from PredicateCatalog describing the relationship type. Must be a valid predicate name.", examples: ["supports", "realizes", "fulfills", "uses", "consumes"] }, cardinality: { type: "string", enum: ["one-to-one", "one-to-many", "many-to-one", "many-to-many"], description: "Multiplicity constraint on this relationship type. Defines how many source nodes can relate to how many destination nodes.", default: "many-to-many" }, strength: { type: "string", enum: ["critical", "high", "medium", "low"], description: "Typical importance or strength of this relationship type", default: "medium" }, required: { type: "boolean", description: "Whether instances of the source node type must have at least one relationship of this type", default: !1 }, attributes: { type: "object", description: "Optional schema defining attributes that can appear on relationship instances of this type", additionalProperties: { $ref: "urn:dr:spec:base:attribute-spec#/definitions/AttributeSpec" }, minProperties: 0, examples: [{ reason: { type: "string", description: "Explanation for why this relationship exists" }, strength_override: { type: "enum", enum_values: ["critical", "high", "medium", "low"], description: "Instance-specific strength override" } }] } } }, "urn:dr:spec:base:spec-node-relationship"), ajv.addSchema({ $schema: "http://json-schema.org/draft-07/schema#", title: "Source Code Reference Definitions", description: "Reusable JSON Schema definitions for linking architecture elements to source code locations", version: "1.0.0", definitions: { ProvenanceType: { type: "string", enum: ["extracted", "manual", "inferred", "generated"], description: "How this reference was created: extracted (automated ingestion), manual (human added), inferred (pattern matching), generated (code generated from model)" }, SourceLocation: { type: "object", description: "A specific location in source code, identified by file path and optional symbol", required: ["file"], properties: { file: { type: "string", minLength: 1, description: "File path relative to repository root" }, symbol: { type: "string", description: "Named code element (e.g., ClassName.methodName, function_name)" } } }, RepositoryContext: { type: "object", description: "Repository context for the source reference", properties: { url: { type: "string", format: "uri", description: "Git remote URL (HTTPS or SSH format)" }, commit: { type: "string", pattern: "^[0-9a-f]{40}$", description: "Full 40-character Git commit SHA" } } }, SourceReference: { type: "object", description: "Links entity to source code location(s) with provenance tracking. For inferred or generated elements, locations may be omitted when no source file exists yet.", required: ["provenance"], properties: { provenance: { $ref: "#/definitions/ProvenanceType" }, locations: { type: "array", minItems: 1, items: { $ref: "#/definitions/SourceLocation" }, description: "One or more source code locations. Required for extracted and manual provenance; optional for inferred and generated." }, repository: { $ref: "#/definitions/RepositoryContext" } } } } }, "urn:dr:spec:base:source-references"), ajv.addSchema({ $schema: "http://json-schema.org/draft-07/schema#", title: "AttributeSpec Definitions", description: "Reusable definition for attribute specifications used in spec-level schemas (e.g., spec-node-relationship attributes)", definitions: { AttributeSpec: { type: "object", title: "AttributeSpec", description: "Specification for a single attribute that can appear on node or relationship instances", required: ["type", "description"], additionalProperties: !1, properties: { type: { type: "string", enum: ["string", "integer", "number", "boolean", "array", "object", "enum"], description: "The JSON type of this attribute" }, description: { type: "string", description: "Human-readable description of this attribute's purpose" }, enum_values: { type: "array", items: { type: "string" }, description: "Required when type is 'enum'. Lists the valid string values for this attribute.", examples: [["high", "medium", "low"], ["active", "inactive", "archived"]] }, format: { type: "string", description: "Optional format constraint for string types (e.g., 'email', 'uri', 'date-time')", examples: ["email", "uri", "date-time", "uuid"] }, default: { description: "Default value for this attribute when not provided on a node instance. Can be any JSON value." } }, if: { properties: { type: { const: "enum" } }, required: ["type"] }, then: { required: ["type", "description", "enum_values"] } } } }, "urn:dr:spec:base:attribute-spec"), ajv;
10
+ })(), validateSpecNode = sharedAjv.compile({ $schema: "http://json-schema.org/draft-07/schema#", title: "SpecNode", description: "Base schema for all spec node types. Each node type schema extends this with type-specific attribute constraints via allOf.", type: "object", required: ["id", "path", "spec_node_id", "type", "name"], additionalProperties: !1, properties: { id: { type: "string", format: "uuid", description: "Unique node instance identifier (UUIDv4). Globally unique across the entire model.", examples: ["550e8400-e29b-41d4-a716-446655440000"] }, path: { type: "string", pattern: "^[a-z][a-z0-9-]*\\.[a-z][a-z0-9-]*\\.[a-z][a-z0-9-]*$", description: "Human-readable element path in format {layer}.{type}.{name} (e.g., 'motivation.goal.increase-revenue')" }, spec_node_id: { type: "string", pattern: "^[a-z-]+\\.[a-z][a-z0-9-]*$", description: "Reference to the spec node type that this node conforms to (e.g., 'motivation.goal')" }, type: { type: "string", description: "Denormalized node type for efficient filtering and queries. Extracted from spec_node_id (the part after the dot).", examples: ["goal", "requirement", "endpoint", "table"] }, layer_id: { type: "string", pattern: "^[a-z][a-z0-9-]*$", description: "Denormalized layer ID for efficient layer-scoped queries. Extracted from spec_node_id (the part before the dot)." }, name: { type: "string", description: "Human-readable instance name", examples: ["Improve Customer Satisfaction", "User Login API", "Customer Table"] }, description: { type: "string", description: "Optional detailed description of this specific node instance" }, attributes: { type: "object", description: "Attribute values for this node instance. Keys must correspond to attributes defined in the per-type schema, and values must conform to the type constraints." }, source_reference: { $ref: "urn:dr:spec:base:source-references#/definitions/SourceReference", description: "Optional provenance tracking linking this node to source code locations" }, metadata: { type: "object", description: "Optional metadata about the lifecycle and version of this node instance", additionalProperties: !1, properties: { created_at: { type: "string", format: "date-time", description: "ISO 8601 timestamp when this node was created" }, updated_at: { type: "string", format: "date-time", description: "ISO 8601 timestamp of the last modification" }, created_by: { type: "string", description: "User or system that created this node" }, version: { type: "integer", minimum: 1, description: "Version number of this node (incremented on updates)" } } } } }), validateSpecNodeRelationship = sharedAjv.compile({ $schema: "http://json-schema.org/draft-07/schema#", title: "SpecNodeRelationship", description: "Base type for relationship type definitions in the specification. Defines valid relationships between node types, including cardinality, strength, and semantic properties.", type: "object", required: ["id", "source_spec_node_id", "destination_spec_node_id", "predicate"], additionalProperties: !1, properties: { id: { type: "string", pattern: "^[a-z-]+\\.[a-z-]+\\.[a-z-]+$", description: "Unique relationship ID in format: {source-layer}.{predicate}.{dest-layer}. All components use lowercase with hyphens.", examples: ["motivation.supports.motivation", "motivation.realizes.business", "api.exposes.data-model"] }, source_spec_node_id: { type: "string", pattern: "^[a-z-]+\\.[a-z][a-z0-9-]*$", description: "SpecNode ID that can serve as the source of this relationship type" }, source_layer: { type: "string", pattern: "^[a-z][a-z0-9-]*$", description: "Denormalized layer ID extracted from source_spec_node_id for efficient queries" }, destination_spec_node_id: { type: "string", pattern: "^[a-z-]+\\.[a-z][a-z0-9-]*$", description: "SpecNode ID that can serve as the destination of this relationship type" }, destination_layer: { type: "string", pattern: "^[a-z][a-z0-9-]*$", description: "Denormalized layer ID extracted from destination_spec_node_id for efficient queries" }, predicate: { type: "string", description: "Semantic predicate from PredicateCatalog describing the relationship type. Must be a valid predicate name.", examples: ["supports", "realizes", "fulfills", "uses", "consumes"] }, cardinality: { type: "string", enum: ["one-to-one", "one-to-many", "many-to-one", "many-to-many"], description: "Multiplicity constraint on this relationship type. Defines how many source nodes can relate to how many destination nodes.", default: "many-to-many" }, strength: { type: "string", enum: ["critical", "high", "medium", "low"], description: "Typical importance or strength of this relationship type", default: "medium" }, required: { type: "boolean", description: "Whether instances of the source node type must have at least one relationship of this type", default: !1 }, attributes: { type: "object", description: "Optional schema defining attributes that can appear on relationship instances of this type", additionalProperties: { $ref: "urn:dr:spec:base:attribute-spec#/definitions/AttributeSpec" }, minProperties: 0, examples: [{ reason: { type: "string", description: "Explanation for why this relationship exists" }, strength_override: { type: "enum", enum_values: ["critical", "high", "medium", "low"], description: "Instance-specific strength override" } }] } } }), validateSourceReference = sharedAjv.compile({ $schema: "http://json-schema.org/draft-07/schema#", title: "Source Code Reference Definitions", description: "Reusable JSON Schema definitions for linking architecture elements to source code locations", version: "1.0.0", definitions: { ProvenanceType: { type: "string", enum: ["extracted", "manual", "inferred", "generated"], description: "How this reference was created: extracted (automated ingestion), manual (human added), inferred (pattern matching), generated (code generated from model)" }, SourceLocation: { type: "object", description: "A specific location in source code, identified by file path and optional symbol", required: ["file"], properties: { file: { type: "string", minLength: 1, description: "File path relative to repository root" }, symbol: { type: "string", description: "Named code element (e.g., ClassName.methodName, function_name)" } } }, RepositoryContext: { type: "object", description: "Repository context for the source reference", properties: { url: { type: "string", format: "uri", description: "Git remote URL (HTTPS or SSH format)" }, commit: { type: "string", pattern: "^[0-9a-f]{40}$", description: "Full 40-character Git commit SHA" } } }, SourceReference: { type: "object", description: "Links entity to source code location(s) with provenance tracking. For inferred or generated elements, locations may be omitted when no source file exists yet.", required: ["provenance"], properties: { provenance: { $ref: "#/definitions/ProvenanceType" }, locations: { type: "array", minItems: 1, items: { $ref: "#/definitions/SourceLocation" }, description: "One or more source code locations. Required for extracted and manual provenance; optional for inferred and generated." }, repository: { $ref: "#/definitions/RepositoryContext" } } } } }), validateAttributeSpec = sharedAjv.compile({ $schema: "http://json-schema.org/draft-07/schema#", title: "AttributeSpec Definitions", description: "Reusable definition for attribute specifications used in spec-level schemas (e.g., spec-node-relationship attributes)", definitions: { AttributeSpec: { type: "object", title: "AttributeSpec", description: "Specification for a single attribute that can appear on node or relationship instances", required: ["type", "description"], additionalProperties: !1, properties: { type: { type: "string", enum: ["string", "integer", "number", "boolean", "array", "object", "enum"], description: "The JSON type of this attribute" }, description: { type: "string", description: "Human-readable description of this attribute's purpose" }, enum_values: { type: "array", items: { type: "string" }, description: "Required when type is 'enum'. Lists the valid string values for this attribute.", examples: [["high", "medium", "low"], ["active", "inactive", "archived"]] }, format: { type: "string", description: "Optional format constraint for string types (e.g., 'email', 'uri', 'date-time')", examples: ["email", "uri", "date-time", "uuid"] }, default: { description: "Default value for this attribute when not provided on a node instance. Can be any JSON value." } }, if: { properties: { type: { const: "enum" } }, required: ["type"] }, then: { required: ["type", "description", "enum_values"] } } } });
11
11
  export {
12
12
  validateAttributeSpec,
13
13
  validateSourceReference,