semantic-atlas 0.4.0 → 2.0.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 (346) hide show
  1. package/.agents/skills/semantic-atlas/SKILL.md +134 -166
  2. package/.agents/skills/semantic-atlas/agents/openai.yaml +4 -0
  3. package/.agents/skills/semantic-atlas/references/observations.md +130 -0
  4. package/.agents/skills/semantic-atlas/scripts/query-context.mjs +110 -0
  5. package/.agents/skills/semantic-atlas-maintenance/SKILL.md +93 -0
  6. package/.agents/skills/semantic-atlas-maintenance/agents/openai.yaml +4 -0
  7. package/.agents/skills/semantic-atlas-maintenance/references/reconciliation.md +56 -0
  8. package/README.md +133 -265
  9. package/dist/application/map-application.d.ts +24 -0
  10. package/dist/application/map-application.d.ts.map +1 -0
  11. package/dist/application/map-application.js +134 -0
  12. package/dist/application/map-application.js.map +1 -0
  13. package/dist/cli/bin.js +6 -42
  14. package/dist/cli/bin.js.map +1 -0
  15. package/dist/cli/observation-commands.d.ts +16 -0
  16. package/dist/cli/observation-commands.d.ts.map +1 -0
  17. package/dist/cli/observation-commands.js +118 -0
  18. package/dist/cli/observation-commands.js.map +1 -0
  19. package/dist/cli/projection-writer.d.ts +2 -0
  20. package/dist/cli/projection-writer.d.ts.map +1 -0
  21. package/dist/cli/projection-writer.js +9 -0
  22. package/dist/cli/projection-writer.js.map +1 -0
  23. package/dist/cli/reconciliation-command.d.ts +7 -0
  24. package/dist/cli/reconciliation-command.d.ts.map +1 -0
  25. package/dist/cli/reconciliation-command.js +33 -0
  26. package/dist/cli/reconciliation-command.js.map +1 -0
  27. package/dist/cli/run-cli.d.ts +21 -0
  28. package/dist/cli/run-cli.d.ts.map +1 -0
  29. package/dist/cli/run-cli.js +299 -0
  30. package/dist/cli/run-cli.js.map +1 -0
  31. package/dist/contracts/cli.d.ts +166 -1211
  32. package/dist/contracts/cli.d.ts.map +1 -1
  33. package/dist/contracts/cli.js +2 -232
  34. package/dist/contracts/cli.js.map +1 -0
  35. package/dist/contracts/insights.d.ts +39 -1
  36. package/dist/contracts/insights.d.ts.map +1 -1
  37. package/dist/contracts/insights.js +2 -1
  38. package/dist/contracts/insights.js.map +1 -0
  39. package/dist/contracts/map.d.ts +154 -0
  40. package/dist/contracts/map.d.ts.map +1 -0
  41. package/dist/contracts/map.js +60 -0
  42. package/dist/contracts/map.js.map +1 -0
  43. package/dist/contracts/observation.d.ts +414 -0
  44. package/dist/contracts/observation.d.ts.map +1 -0
  45. package/dist/contracts/observation.js +125 -0
  46. package/dist/contracts/observation.js.map +1 -0
  47. package/dist/contracts/projection.d.ts +7 -0
  48. package/dist/contracts/projection.d.ts.map +1 -0
  49. package/dist/contracts/projection.js +2 -0
  50. package/dist/contracts/projection.js.map +1 -0
  51. package/dist/contracts/reconciliation.d.ts +40 -0
  52. package/dist/contracts/reconciliation.d.ts.map +1 -0
  53. package/dist/contracts/reconciliation.js +2 -0
  54. package/dist/contracts/reconciliation.js.map +1 -0
  55. package/dist/index.d.ts +7 -17
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +3 -9
  58. package/dist/index.js.map +1 -0
  59. package/dist/insights/insight-service.d.ts +14 -0
  60. package/dist/insights/insight-service.d.ts.map +1 -0
  61. package/dist/insights/insight-service.js +129 -0
  62. package/dist/insights/insight-service.js.map +1 -0
  63. package/dist/map/business-graph.d.ts +32 -0
  64. package/dist/map/business-graph.d.ts.map +1 -0
  65. package/dist/map/business-graph.js +122 -0
  66. package/dist/map/business-graph.js.map +1 -0
  67. package/dist/map/map-document-loader.d.ts +13 -0
  68. package/dist/map/map-document-loader.d.ts.map +1 -0
  69. package/dist/map/map-document-loader.js +86 -0
  70. package/dist/map/map-document-loader.js.map +1 -0
  71. package/dist/map/map-validator.d.ts +12 -0
  72. package/dist/map/map-validator.d.ts.map +1 -0
  73. package/dist/map/map-validator.js +322 -0
  74. package/dist/map/map-validator.js.map +1 -0
  75. package/dist/observations/observation-application.d.ts +23 -0
  76. package/dist/observations/observation-application.d.ts.map +1 -0
  77. package/dist/observations/observation-application.js +62 -0
  78. package/dist/observations/observation-application.js.map +1 -0
  79. package/dist/observations/observation-claim-manager.d.ts +17 -0
  80. package/dist/observations/observation-claim-manager.d.ts.map +1 -0
  81. package/dist/observations/observation-claim-manager.js +198 -0
  82. package/dist/observations/observation-claim-manager.js.map +1 -0
  83. package/dist/observations/observation-store.d.ts +43 -0
  84. package/dist/observations/observation-store.d.ts.map +1 -0
  85. package/dist/observations/observation-store.js +213 -0
  86. package/dist/observations/observation-store.js.map +1 -0
  87. package/dist/observations/repository-identity.d.ts +12 -0
  88. package/dist/observations/repository-identity.d.ts.map +1 -0
  89. package/dist/observations/repository-identity.js +108 -0
  90. package/dist/observations/repository-identity.js.map +1 -0
  91. package/dist/query/context-query-service.d.ts +15 -0
  92. package/dist/query/context-query-service.d.ts.map +1 -0
  93. package/dist/query/context-query-service.js +36 -0
  94. package/dist/query/context-query-service.js.map +1 -0
  95. package/dist/reconciliation/reconciliation-service.d.ts +10 -0
  96. package/dist/reconciliation/reconciliation-service.d.ts.map +1 -0
  97. package/dist/reconciliation/reconciliation-service.js +114 -0
  98. package/dist/reconciliation/reconciliation-service.js.map +1 -0
  99. package/dist/rendering/map-projector.d.ts +8 -0
  100. package/dist/rendering/map-projector.d.ts.map +1 -0
  101. package/dist/rendering/map-projector.js +386 -0
  102. package/dist/rendering/map-projector.js.map +1 -0
  103. package/dist/setup/managed-skill-installer.d.ts +60 -0
  104. package/dist/setup/managed-skill-installer.d.ts.map +1 -0
  105. package/dist/setup/managed-skill-installer.js +293 -0
  106. package/dist/setup/managed-skill-installer.js.map +1 -0
  107. package/dist/setup/package-identity.d.ts +6 -0
  108. package/dist/setup/package-identity.d.ts.map +1 -0
  109. package/dist/setup/package-identity.js +16 -0
  110. package/dist/setup/package-identity.js.map +1 -0
  111. package/dist/setup/package-upgrader.d.ts +10 -22
  112. package/dist/setup/package-upgrader.d.ts.map +1 -1
  113. package/dist/setup/package-upgrader.js +60 -76
  114. package/dist/setup/package-upgrader.js.map +1 -0
  115. package/docs/architecture.md +426 -0
  116. package/docs/evaluation.md +220 -174
  117. package/docs/index.md +27 -45
  118. package/docs/map-format.md +225 -0
  119. package/docs/observations.md +167 -0
  120. package/docs/product-contract.md +282 -165
  121. package/examples/commerce.yaml +204 -0
  122. package/package.json +31 -32
  123. package/.agents/skills/semantic-atlas/references/graph-patch.md +0 -190
  124. package/.agents/skills/semantic-atlas/references/product-feedback.md +0 -34
  125. package/.agents/skills/semantic-atlas/references/result-routing.md +0 -104
  126. package/.agents/skills/semantic-atlas/references/snapshot-bootstrap.md +0 -42
  127. package/.agents/skills/semantic-atlas-insights/SKILL.md +0 -55
  128. package/README.zh-CN.md +0 -296
  129. package/dist/business-flow/business-flow-derivation-service.d.ts +0 -11
  130. package/dist/business-flow/business-flow-derivation-service.d.ts.map +0 -1
  131. package/dist/business-flow/business-flow-derivation-service.js +0 -151
  132. package/dist/business-flow/business-flow-draft.d.ts +0 -16
  133. package/dist/business-flow/business-flow-draft.d.ts.map +0 -1
  134. package/dist/business-flow/business-flow-draft.js +0 -150
  135. package/dist/business-flow/framework-business-strategy.d.ts +0 -7
  136. package/dist/business-flow/framework-business-strategy.d.ts.map +0 -1
  137. package/dist/business-flow/framework-business-strategy.js +0 -1
  138. package/dist/business-flow/strategies/bullmq-business-strategy.d.ts +0 -10
  139. package/dist/business-flow/strategies/bullmq-business-strategy.d.ts.map +0 -1
  140. package/dist/business-flow/strategies/bullmq-business-strategy.js +0 -79
  141. package/dist/business-flow/strategies/called-operation-derivation.d.ts +0 -13
  142. package/dist/business-flow/strategies/called-operation-derivation.d.ts.map +0 -1
  143. package/dist/business-flow/strategies/called-operation-derivation.js +0 -32
  144. package/dist/business-flow/strategies/graphql-business-strategy.d.ts +0 -8
  145. package/dist/business-flow/strategies/graphql-business-strategy.d.ts.map +0 -1
  146. package/dist/business-flow/strategies/graphql-business-strategy.js +0 -65
  147. package/dist/business-flow/strategies/nestjs-business-strategy.d.ts +0 -8
  148. package/dist/business-flow/strategies/nestjs-business-strategy.d.ts.map +0 -1
  149. package/dist/business-flow/strategies/nestjs-business-strategy.js +0 -72
  150. package/dist/business-flow/strategies/strategy-helpers.d.ts +0 -32
  151. package/dist/business-flow/strategies/strategy-helpers.d.ts.map +0 -1
  152. package/dist/business-flow/strategies/strategy-helpers.js +0 -49
  153. package/dist/business-flow/strategies/typeorm-business-strategy.d.ts +0 -10
  154. package/dist/business-flow/strategies/typeorm-business-strategy.d.ts.map +0 -1
  155. package/dist/business-flow/strategies/typeorm-business-strategy.js +0 -136
  156. package/dist/business-flow/strategies/verified-invariant-strategy.d.ts +0 -5
  157. package/dist/business-flow/strategies/verified-invariant-strategy.d.ts.map +0 -1
  158. package/dist/business-flow/strategies/verified-invariant-strategy.js +0 -38
  159. package/dist/business-flow/strategies/verified-test-strategy.d.ts +0 -5
  160. package/dist/business-flow/strategies/verified-test-strategy.d.ts.map +0 -1
  161. package/dist/business-flow/strategies/verified-test-strategy.js +0 -26
  162. package/dist/business-flow/structural-flow-catalog.d.ts +0 -21
  163. package/dist/business-flow/structural-flow-catalog.d.ts.map +0 -1
  164. package/dist/business-flow/structural-flow-catalog.js +0 -125
  165. package/dist/business-flow/types.d.ts +0 -51
  166. package/dist/business-flow/types.d.ts.map +0 -1
  167. package/dist/business-flow/types.js +0 -1
  168. package/dist/cli/argument-parser.d.ts +0 -3
  169. package/dist/cli/argument-parser.d.ts.map +0 -1
  170. package/dist/cli/argument-parser.js +0 -200
  171. package/dist/cli/cli-application.d.ts +0 -39
  172. package/dist/cli/cli-application.d.ts.map +0 -1
  173. package/dist/cli/cli-application.js +0 -571
  174. package/dist/cli/cli-error.d.ts +0 -12
  175. package/dist/cli/cli-error.d.ts.map +0 -1
  176. package/dist/cli/cli-error.js +0 -44
  177. package/dist/cli/cli-presenter.d.ts +0 -14
  178. package/dist/cli/cli-presenter.d.ts.map +0 -1
  179. package/dist/cli/cli-presenter.js +0 -36
  180. package/dist/cli/insights-cli.d.ts +0 -6
  181. package/dist/cli/insights-cli.d.ts.map +0 -1
  182. package/dist/cli/insights-cli.js +0 -236
  183. package/dist/cli/main.d.ts +0 -3
  184. package/dist/cli/main.d.ts.map +0 -1
  185. package/dist/cli/main.js +0 -137
  186. package/dist/cli/standalone-cli.d.ts +0 -3
  187. package/dist/cli/standalone-cli.d.ts.map +0 -1
  188. package/dist/cli/standalone-cli.js +0 -104
  189. package/dist/cli/types.d.ts +0 -49
  190. package/dist/cli/types.d.ts.map +0 -1
  191. package/dist/cli/types.js +0 -1
  192. package/dist/cli/web-cli.d.ts +0 -9
  193. package/dist/cli/web-cli.d.ts.map +0 -1
  194. package/dist/cli/web-cli.js +0 -134
  195. package/dist/contracts/graph.d.ts +0 -266
  196. package/dist/contracts/graph.d.ts.map +0 -1
  197. package/dist/contracts/graph.js +0 -182
  198. package/dist/contracts/identifiers.d.ts +0 -4
  199. package/dist/contracts/identifiers.d.ts.map +0 -1
  200. package/dist/contracts/identifiers.js +0 -7
  201. package/dist/contracts/public-contracts.d.ts +0 -5
  202. package/dist/contracts/public-contracts.d.ts.map +0 -1
  203. package/dist/contracts/public-contracts.js +0 -4
  204. package/dist/evaluation/comparison.d.ts +0 -30
  205. package/dist/evaluation/comparison.d.ts.map +0 -1
  206. package/dist/evaluation/comparison.js +0 -108
  207. package/dist/evaluation/contracts.d.ts +0 -301
  208. package/dist/evaluation/contracts.d.ts.map +0 -1
  209. package/dist/evaluation/contracts.js +0 -413
  210. package/dist/graph/graph-store.d.ts +0 -55
  211. package/dist/graph/graph-store.d.ts.map +0 -1
  212. package/dist/graph/graph-store.js +0 -912
  213. package/dist/graph/types.d.ts +0 -189
  214. package/dist/graph/types.d.ts.map +0 -1
  215. package/dist/graph/types.js +0 -1
  216. package/dist/insights/contracts.d.ts +0 -266
  217. package/dist/insights/contracts.d.ts.map +0 -1
  218. package/dist/insights/contracts.js +0 -124
  219. package/dist/insights/insights-store.d.ts +0 -73
  220. package/dist/insights/insights-store.d.ts.map +0 -1
  221. package/dist/insights/insights-store.js +0 -246
  222. package/dist/knowledge/business-knowledge-service.d.ts +0 -24
  223. package/dist/knowledge/business-knowledge-service.d.ts.map +0 -1
  224. package/dist/knowledge/business-knowledge-service.js +0 -200
  225. package/dist/knowledge/graph-patch-conflict-error.d.ts +0 -8
  226. package/dist/knowledge/graph-patch-conflict-error.d.ts.map +0 -1
  227. package/dist/knowledge/graph-patch-conflict-error.js +0 -12
  228. package/dist/knowledge/structural-target-binding.d.ts +0 -14
  229. package/dist/knowledge/structural-target-binding.d.ts.map +0 -1
  230. package/dist/knowledge/structural-target-binding.js +0 -11
  231. package/dist/package-metadata.d.ts +0 -2
  232. package/dist/package-metadata.d.ts.map +0 -1
  233. package/dist/package-metadata.js +0 -9
  234. package/dist/repository/git-command.d.ts +0 -3
  235. package/dist/repository/git-command.d.ts.map +0 -1
  236. package/dist/repository/git-command.js +0 -25
  237. package/dist/repository/repository-inspector.d.ts +0 -8
  238. package/dist/repository/repository-inspector.d.ts.map +0 -1
  239. package/dist/repository/repository-inspector.js +0 -97
  240. package/dist/repository/repository-language-support.d.ts +0 -14
  241. package/dist/repository/repository-language-support.d.ts.map +0 -1
  242. package/dist/repository/repository-language-support.js +0 -64
  243. package/dist/repository/types.d.ts +0 -9
  244. package/dist/repository/types.d.ts.map +0 -1
  245. package/dist/repository/types.js +0 -1
  246. package/dist/runtime/sqlite-compatibility-process.d.ts +0 -8
  247. package/dist/runtime/sqlite-compatibility-process.d.ts.map +0 -1
  248. package/dist/runtime/sqlite-compatibility-process.js +0 -20
  249. package/dist/setup/skill-installer.d.ts +0 -20
  250. package/dist/setup/skill-installer.d.ts.map +0 -1
  251. package/dist/setup/skill-installer.js +0 -187
  252. package/dist/snapshots/repository-snapshot.d.ts +0 -4
  253. package/dist/snapshots/repository-snapshot.d.ts.map +0 -1
  254. package/dist/snapshots/repository-snapshot.js +0 -119
  255. package/dist/snapshots/types.d.ts +0 -30
  256. package/dist/snapshots/types.d.ts.map +0 -1
  257. package/dist/snapshots/types.js +0 -1
  258. package/dist/storage/atlas-database.d.ts +0 -25
  259. package/dist/storage/atlas-database.d.ts.map +0 -1
  260. package/dist/storage/atlas-database.js +0 -483
  261. package/dist/storage/snapshot-store.d.ts +0 -19
  262. package/dist/storage/snapshot-store.d.ts.map +0 -1
  263. package/dist/storage/snapshot-store.js +0 -74
  264. package/dist/structural-backend/codegraph-backend.d.ts +0 -57
  265. package/dist/structural-backend/codegraph-backend.d.ts.map +0 -1
  266. package/dist/structural-backend/codegraph-backend.js +0 -1230
  267. package/dist/structural-backend/codegraph-worker-client.d.ts +0 -5
  268. package/dist/structural-backend/codegraph-worker-client.d.ts.map +0 -1
  269. package/dist/structural-backend/codegraph-worker-client.js +0 -118
  270. package/dist/structural-backend/codegraph-worker-protocol.d.ts +0 -35
  271. package/dist/structural-backend/codegraph-worker-protocol.d.ts.map +0 -1
  272. package/dist/structural-backend/codegraph-worker-protocol.js +0 -1
  273. package/dist/structural-backend/codegraph-worker.d.ts +0 -2
  274. package/dist/structural-backend/codegraph-worker.d.ts.map +0 -1
  275. package/dist/structural-backend/codegraph-worker.js +0 -131
  276. package/dist/structural-backend/process-instance.d.ts +0 -18
  277. package/dist/structural-backend/process-instance.d.ts.map +0 -1
  278. package/dist/structural-backend/process-instance.js +0 -207
  279. package/dist/structural-backend/structural-fact-changes.d.ts +0 -7
  280. package/dist/structural-backend/structural-fact-changes.d.ts.map +0 -1
  281. package/dist/structural-backend/structural-fact-changes.js +0 -78
  282. package/dist/structural-backend/structural-projection-bootstrapper.d.ts +0 -10
  283. package/dist/structural-backend/structural-projection-bootstrapper.d.ts.map +0 -1
  284. package/dist/structural-backend/structural-projection-bootstrapper.js +0 -295
  285. package/dist/structural-backend/structural-publication.d.ts +0 -13
  286. package/dist/structural-backend/structural-publication.d.ts.map +0 -1
  287. package/dist/structural-backend/structural-publication.js +0 -255
  288. package/dist/structural-backend/structural-write-lock.d.ts +0 -8
  289. package/dist/structural-backend/structural-write-lock.d.ts.map +0 -1
  290. package/dist/structural-backend/structural-write-lock.js +0 -415
  291. package/dist/structural-backend/types.d.ts +0 -144
  292. package/dist/structural-backend/types.d.ts.map +0 -1
  293. package/dist/structural-backend/types.js +0 -11
  294. package/dist/web/application/atlas-read-service.d.ts +0 -27
  295. package/dist/web/application/atlas-read-service.d.ts.map +0 -1
  296. package/dist/web/application/atlas-read-service.js +0 -216
  297. package/dist/web/application/primary-repository-catalog.d.ts +0 -15
  298. package/dist/web/application/primary-repository-catalog.d.ts.map +0 -1
  299. package/dist/web/application/primary-repository-catalog.js +0 -202
  300. package/dist/web/application/types.d.ts +0 -41
  301. package/dist/web/application/types.d.ts.map +0 -1
  302. package/dist/web/application/types.js +0 -1
  303. package/dist/web/server/api-router.d.ts +0 -4
  304. package/dist/web/server/api-router.d.ts.map +0 -1
  305. package/dist/web/server/api-router.js +0 -151
  306. package/dist/web/server/local-web-server.d.ts +0 -12
  307. package/dist/web/server/local-web-server.d.ts.map +0 -1
  308. package/dist/web/server/local-web-server.js +0 -100
  309. package/dist/web-client/assets/index-DneaErDj.css +0 -1
  310. package/dist/web-client/assets/index-cze_4vtt.js +0 -2
  311. package/dist/web-client/assets/index-cze_4vtt.js.map +0 -1
  312. package/dist/web-client/index.html +0 -61
  313. package/dist/world/business-map-projector.d.ts +0 -14
  314. package/dist/world/business-map-projector.d.ts.map +0 -1
  315. package/dist/world/business-map-projector.js +0 -178
  316. package/dist/world/types.d.ts +0 -77
  317. package/dist/world/types.d.ts.map +0 -1
  318. package/dist/world/types.js +0 -1
  319. package/dist/world/world-graph-query.d.ts +0 -30
  320. package/dist/world/world-graph-query.d.ts.map +0 -1
  321. package/dist/world/world-graph-query.js +0 -252
  322. package/dist/world/world-model-service.d.ts +0 -21
  323. package/dist/world/world-model-service.d.ts.map +0 -1
  324. package/dist/world/world-model-service.js +0 -219
  325. package/dist/world/world-snapshot-store.d.ts +0 -41
  326. package/dist/world/world-snapshot-store.d.ts.map +0 -1
  327. package/dist/world/world-snapshot-store.js +0 -581
  328. package/docs/README.md +0 -30
  329. package/docs/architecture/codegraph-backend.md +0 -190
  330. package/docs/architecture/continuous-business-learning.md +0 -240
  331. package/docs/architecture/web-viewer.md +0 -225
  332. package/docs/contracts/cli-v1.md +0 -179
  333. package/docs/contracts/graph-model.md +0 -106
  334. package/docs/contracts/graph-patch-v1.md +0 -105
  335. package/docs/contracts/http-api-v1.md +0 -155
  336. package/docs/contracts/insights-v1.md +0 -84
  337. package/docs/log.md +0 -159
  338. package/docs/mindmaps/semantic-atlas-overview.drawio +0 -255
  339. package/docs/mindmaps/semantic-atlas-overview.png +0 -0
  340. package/docs/mindmaps/semantic-atlas-overview.zh-CN.drawio +0 -255
  341. package/docs/mindmaps/semantic-atlas-overview.zh-CN.png +0 -0
  342. package/schemas/cli-envelope-v1.schema.json +0 -1244
  343. package/schemas/evaluation-plan-v1.schema.json +0 -211
  344. package/schemas/evaluation-run-v1.schema.json +0 -659
  345. package/schemas/graph-patch-v1.schema.json +0 -392
  346. package/schemas/insights-envelope-v1.schema.json +0 -428
@@ -1,1230 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { constants as fileSystemConstants } from "node:fs";
3
- import { lstat, mkdir, open, realpath } from "node:fs/promises";
4
- import { createRequire } from "node:module";
5
- import { join, resolve } from "node:path";
6
- import { runGit } from "../repository/git-command.js";
7
- import { requiresBundledCodeGraphRuntime, runCodeGraphWorker, } from "./codegraph-worker-client.js";
8
- import { StructuralPublication } from "./structural-publication.js";
9
- import { captureStructuralFacts, compareStructuralFacts, } from "./structural-fact-changes.js";
10
- import { StructuralWriteLock } from "./structural-write-lock.js";
11
- import { STRUCTURAL_BACKEND_VERSION, StructuralBackendError, } from "./types.js";
12
- const ATLAS_DIRECTORY = ".atlas";
13
- const ATLAS_IGNORE_CONTENT = "*\n";
14
- const ATLAS_WRITE_LOCK = "semantic-atlas.lock";
15
- const CODEGRAPH_WRITE_LOCK = "codegraph.lock";
16
- const require = createRequire(import.meta.url);
17
- let operationQueue = Promise.resolve();
18
- const supportedRelationTypes = new Map([
19
- ["contains", "contains"],
20
- ["calls", "calls"],
21
- ["imports", "imports"],
22
- ["exports", "exports"],
23
- ["extends", "extends"],
24
- ["implements", "implements"],
25
- ["references", "references"],
26
- ["instantiates", "instantiates"],
27
- ["decorates", "decorated_by"],
28
- ]);
29
- const backendRelationTypes = new Map([
30
- ["contains", "contains"],
31
- ["declares", "contains"],
32
- ["calls", "calls"],
33
- ["imports", "imports"],
34
- ["exports", "exports"],
35
- ["extends", "extends"],
36
- ["implements", "implements"],
37
- ["references", "references"],
38
- ["instantiates", "instantiates"],
39
- ["decorated_by", "decorates"],
40
- ]);
41
- export class CodeGraphStructuralBackend {
42
- #repository;
43
- #databasePath;
44
- constructor(repository) {
45
- this.#repository = repository;
46
- this.#databasePath = join(repository.worktreeRoot, ATLAS_DIRECTORY, "codegraph.db");
47
- }
48
- async prepareStorageForBootstrap() {
49
- await this.prepareAtlasDirectory();
50
- }
51
- async inspect() {
52
- if (requiresBundledCodeGraphRuntime()) {
53
- try {
54
- return await runCodeGraphWorker({ operation: "inspect", repository: this.#repository });
55
- }
56
- catch (error) {
57
- return this.incompleteState(failureDiagnostic(error));
58
- }
59
- }
60
- try {
61
- return await withCodeGraphSdk((sdk) => this.inspectWithSdk(sdk));
62
- }
63
- catch (error) {
64
- return this.incompleteState(failureDiagnostic(error));
65
- }
66
- }
67
- async build() {
68
- if (requiresBundledCodeGraphRuntime()) {
69
- try {
70
- return await runCodeGraphWorker({ operation: "build", repository: this.#repository });
71
- }
72
- catch (error) {
73
- return this.failedBuildResult("full", error);
74
- }
75
- }
76
- try {
77
- return await this.runBuild("full");
78
- }
79
- catch (error) {
80
- return this.failedBuildResult("full", error);
81
- }
82
- }
83
- async sync() {
84
- if (requiresBundledCodeGraphRuntime()) {
85
- try {
86
- return await runCodeGraphWorker({ operation: "sync", repository: this.#repository });
87
- }
88
- catch (error) {
89
- return this.failedBuildResult("incremental", error);
90
- }
91
- }
92
- try {
93
- return await this.runBuild("incremental");
94
- }
95
- catch (error) {
96
- return this.failedBuildResult("incremental", error);
97
- }
98
- }
99
- async listUnknownBoundaries() {
100
- if (requiresBundledCodeGraphRuntime()) {
101
- return runCodeGraphWorker({
102
- operation: "listUnknownBoundaries",
103
- repository: this.#repository,
104
- });
105
- }
106
- return this.withCurrentGraph((graph, queries) => (normalizeUnresolvedReferences(graph, queries)));
107
- }
108
- async publishWorld(requestedMode, hooks) {
109
- if (requiresBundledCodeGraphRuntime()) {
110
- throw new Error("World publication must run inside the bundled CodeGraph worker");
111
- }
112
- try {
113
- return await this.runBuild(requestedMode, hooks);
114
- }
115
- catch (error) {
116
- hooks.fail(error);
117
- return this.failedBuildResult(requestedMode, error);
118
- }
119
- }
120
- async withWorldWriteLock(operation) {
121
- if (requiresBundledCodeGraphRuntime()) {
122
- throw new Error("Atlas writes must run inside the bundled CodeGraph worker");
123
- }
124
- return withCodeGraphSdk((sdk) => this.withPublishedGraph(sdk, (graph) => {
125
- const state = this.readState(graph);
126
- if (state.completeness !== "complete") {
127
- throw new StructuralBackendError("STRUCTURAL_INDEX_INCOMPLETE", "The structural index is incomplete and cannot accept Atlas writes");
128
- }
129
- return operation(state, structuralEvidenceResolver(graph));
130
- }));
131
- }
132
- async listRoots() {
133
- if (requiresBundledCodeGraphRuntime()) {
134
- return runCodeGraphWorker({ operation: "listRoots", repository: this.#repository });
135
- }
136
- return this.withCurrentGraph((graph) => structuralModuleRoots(graph));
137
- }
138
- async readProjectGraph(query) {
139
- if (requiresBundledCodeGraphRuntime()) {
140
- return runCodeGraphWorker({
141
- operation: "readProjectGraph",
142
- repository: this.#repository,
143
- input: query,
144
- });
145
- }
146
- return this.withCurrentGraph((graph, queries) => normalizeProjectGraph(graph, queries, query));
147
- }
148
- async search(query) {
149
- if (requiresBundledCodeGraphRuntime()) {
150
- return runCodeGraphWorker({
151
- operation: "search",
152
- repository: this.#repository,
153
- input: query,
154
- });
155
- }
156
- if (query.query.trim().length === 0) {
157
- return [];
158
- }
159
- return this.withCurrentGraph((graph) => graph.searchNodes(query.query, {
160
- ...(query.limit === undefined ? {} : { limit: query.limit }),
161
- }).map((result) => ({
162
- score: result.score,
163
- node: normalizeNode(result.node),
164
- })));
165
- }
166
- async getNode(reference) {
167
- if (requiresBundledCodeGraphRuntime()) {
168
- return runCodeGraphWorker({
169
- operation: "getNode",
170
- repository: this.#repository,
171
- input: reference,
172
- });
173
- }
174
- return this.withCurrentGraph((graph) => {
175
- const node = findNodeByReference(graph, reference);
176
- return node === undefined
177
- ? findVirtualModuleRoot(graph, reference)
178
- : normalizeNode(node);
179
- });
180
- }
181
- async traverse(query) {
182
- if (requiresBundledCodeGraphRuntime()) {
183
- return runCodeGraphWorker({
184
- operation: "traverse",
185
- repository: this.#repository,
186
- input: query,
187
- });
188
- }
189
- return this.withCurrentGraph((graph, queries) => {
190
- const virtualModule = findVirtualModuleRoot(graph, query.reference);
191
- if (virtualModule !== undefined) {
192
- return traverseVirtualModuleRoot(graph, virtualModule, query);
193
- }
194
- const start = requireNodeByReference(graph, query.reference);
195
- const requestedRelations = query.relationTypes?.map((type) => backendRelationTypes.get(type));
196
- const subgraph = graph.traverse(start.id, {
197
- includeStart: true,
198
- ...(query.maxDepth === undefined ? {} : { maxDepth: query.maxDepth }),
199
- ...(query.direction === undefined ? {} : { direction: query.direction }),
200
- ...(requestedRelations === undefined
201
- ? {}
202
- : { edgeKinds: [...new Set(requestedRelations.filter(isDefined))] }),
203
- });
204
- const nodesByBackendId = subgraph.nodes;
205
- const normalizedNodes = [...nodesByBackendId.values()].map(normalizeNode);
206
- const relations = [];
207
- const boundaries = [];
208
- for (const edge of subgraph.edges) {
209
- const source = nodesByBackendId.get(edge.source) ?? graph.getNode(edge.source) ?? undefined;
210
- const target = nodesByBackendId.get(edge.target) ?? graph.getNode(edge.target) ?? undefined;
211
- if (source === undefined) {
212
- continue;
213
- }
214
- const relation = normalizeRelation(edge, source, target);
215
- if (relation === undefined) {
216
- boundaries.push(unsupportedRelationBoundary(edge, source, target));
217
- }
218
- else if (query.relationTypes === undefined || query.relationTypes.includes(relation.type)) {
219
- relations.push(relation);
220
- }
221
- }
222
- boundaries.push(...normalizeUnresolvedReferences(graph, queries, new Set(nodesByBackendId.keys())));
223
- return {
224
- roots: subgraph.roots
225
- .map((backendId) => nodesByBackendId.get(backendId) ?? graph.getNode(backendId) ?? undefined)
226
- .filter(isDefined)
227
- .map((node) => normalizeNode(node).reference),
228
- nodes: uniqueBy(normalizedNodes, (node) => node.reference.id),
229
- relations: uniqueBy(relations, relationIdentity),
230
- boundaries: uniqueBy(boundaries, (boundary) => boundary.reference.id),
231
- };
232
- });
233
- }
234
- async getCallers(reference) {
235
- if (requiresBundledCodeGraphRuntime()) {
236
- return runCodeGraphWorker({
237
- operation: "getCallers",
238
- repository: this.#repository,
239
- input: reference,
240
- });
241
- }
242
- return this.withCurrentGraph((graph) => {
243
- const node = requireNodeByReference(graph, reference);
244
- return graph.getCallers(node.id, 1)
245
- .filter(({ edge }) => edge.kind === "calls" && edge.target === node.id)
246
- .map(({ edge, node: caller }) => ({
247
- node: normalizeNode(caller),
248
- relation: requireNormalizedRelation(edge, caller, node),
249
- }));
250
- });
251
- }
252
- async getCallees(reference) {
253
- if (requiresBundledCodeGraphRuntime()) {
254
- return runCodeGraphWorker({
255
- operation: "getCallees",
256
- repository: this.#repository,
257
- input: reference,
258
- });
259
- }
260
- return this.withCurrentGraph((graph) => {
261
- const node = requireNodeByReference(graph, reference);
262
- return graph.getCallees(node.id, 1)
263
- .filter(({ edge }) => edge.kind === "calls" && edge.source === node.id)
264
- .map(({ edge, node: callee }) => ({
265
- node: normalizeNode(callee),
266
- relation: requireNormalizedRelation(edge, node, callee),
267
- }));
268
- });
269
- }
270
- async getFileDependencies(path) {
271
- if (requiresBundledCodeGraphRuntime()) {
272
- return runCodeGraphWorker({
273
- operation: "getFileDependencies",
274
- repository: this.#repository,
275
- input: path,
276
- });
277
- }
278
- const normalizedPath = normalizeRepositoryPath(path);
279
- return this.withCurrentGraph((graph) => {
280
- const sourceFile = graph.getNode(`file:${normalizedPath}`) ?? undefined;
281
- const outgoingImports = sourceFile === undefined
282
- ? []
283
- : graph.getOutgoingEdges(sourceFile.id).filter((edge) => edge.kind === "imports");
284
- return graph.getFileDependencies(normalizedPath)
285
- .map((dependency) => {
286
- const dependencyPath = normalizeRepositoryPath(dependency);
287
- const supportingEdges = outgoingImports.filter((edge) => graph.getNode(edge.target)?.filePath === dependencyPath);
288
- return {
289
- path: dependencyPath,
290
- support: dependencySupport(supportingEdges),
291
- };
292
- })
293
- .sort((left, right) => left.path.localeCompare(right.path));
294
- });
295
- }
296
- async runBuild(requestedMode, worldHooks) {
297
- return withCodeGraphSdk(async (sdk) => {
298
- this.verifyDatabasePath(sdk.getDatabasePath(this.#repository.worktreeRoot));
299
- await this.prepareAtlasDirectory();
300
- const atlasWriteLock = StructuralWriteLock.acquire(join(this.#repository.worktreeRoot, ATLAS_DIRECTORY, ATLAS_WRITE_LOCK));
301
- if (atlasWriteLock === undefined) {
302
- return await this.createLockUnavailableBuildResult(sdk, requestedMode);
303
- }
304
- try {
305
- const writeLock = this.createCodeGraphWriteLock(sdk);
306
- try {
307
- writeLock.acquire();
308
- }
309
- catch {
310
- return await this.createLockUnavailableBuildResult(sdk, requestedMode);
311
- }
312
- try {
313
- await StructuralPublication.recoverAbandoned(this.#databasePath);
314
- await worldHooks?.onBuilding();
315
- await worldHooks?.prepareProjection();
316
- return await this.runLockedBuild(sdk, requestedMode, worldHooks);
317
- }
318
- finally {
319
- writeLock.release();
320
- }
321
- }
322
- finally {
323
- atlasWriteLock.release();
324
- }
325
- });
326
- }
327
- async runLockedBuild(sdk, requestedMode, worldHooks) {
328
- const initialized = sdk.CodeGraph.isInitialized(this.#repository.worktreeRoot);
329
- const mode = initialized ? requestedMode : "initial";
330
- let graph;
331
- let publication;
332
- try {
333
- if (!initialized && worldHooks !== undefined) {
334
- graph = await sdk.CodeGraph.init(this.#repository.worktreeRoot, { index: false });
335
- publication = await StructuralPublication.begin(this.#databasePath, false);
336
- }
337
- else {
338
- publication = await StructuralPublication.begin(this.#databasePath, initialized);
339
- graph = initialized
340
- ? await sdk.CodeGraph.open(this.#repository.worktreeRoot, { sync: false })
341
- : await sdk.CodeGraph.init(this.#repository.worktreeRoot, { index: false });
342
- }
343
- useHeldCodeGraphWriteLock(graph);
344
- const previousFacts = captureStructuralFacts(graph);
345
- const buildResult = mode === "incremental"
346
- ? await this.synchronizeGraph(sdk, graph)
347
- : await this.rebuildGraph(sdk, graph, mode);
348
- if (buildResult.completeness === "incomplete") {
349
- graph.close();
350
- graph = undefined;
351
- const restored = await this.restorePublishedGraph(publication, buildResult);
352
- await this.persistWorldFailure(sdk, initialized, worldHooks, restored.diagnostics[0]?.message);
353
- return restored;
354
- }
355
- const publishedResult = {
356
- ...buildResult,
357
- factChanges: compareStructuralFacts(previousFacts, captureStructuralFacts(graph)),
358
- };
359
- const indexedSources = graph.getFiles().map((file) => ({
360
- path: normalizeRepositoryPath(file.path),
361
- contentHash: file.contentHash,
362
- }));
363
- await worldHooks?.validate(publishedResult, indexedSources);
364
- await publication.commit();
365
- publication = undefined;
366
- await worldHooks?.publish(publishedResult, structuralEvidenceResolver(graph));
367
- return publishedResult;
368
- }
369
- catch (error) {
370
- const failedResult = this.failedBuildResult(mode, error);
371
- if (publication !== undefined) {
372
- graph?.close();
373
- graph = undefined;
374
- const restored = await this.restorePublishedGraph(publication, failedResult);
375
- await this.persistWorldFailure(sdk, initialized, worldHooks, error);
376
- return restored;
377
- }
378
- worldHooks?.fail(error);
379
- return failedResult;
380
- }
381
- finally {
382
- graph?.close();
383
- }
384
- }
385
- async persistWorldFailure(sdk, hadPublishedDatabase, hooks, error) {
386
- if (hooks === undefined) {
387
- return;
388
- }
389
- if (!hadPublishedDatabase) {
390
- const emptyGraph = await sdk.CodeGraph.init(this.#repository.worktreeRoot, { index: false });
391
- emptyGraph.close();
392
- }
393
- hooks.fail(error);
394
- }
395
- async synchronizeGraph(sdk, graph) {
396
- const changes = normalizeChangedFiles(graph.getChangedFiles());
397
- const result = await graph.sync();
398
- if (isLockUnavailableSync(result)) {
399
- return this.createLockUnavailableSyncResult(graph, result, changes);
400
- }
401
- const connection = sdk.DatabaseConnection.open(this.#databasePath);
402
- try {
403
- const boundaries = normalizeUnresolvedReferences(graph, new sdk.QueryBuilder(connection.getDb()));
404
- return this.createSyncResult(graph, result, changes, boundaries);
405
- }
406
- finally {
407
- connection.close();
408
- }
409
- }
410
- async rebuildGraph(sdk, graph, mode) {
411
- let fullRebuildStarted = false;
412
- const result = await graph.indexAll({
413
- ...(mode === "full"
414
- ? {
415
- onProgress: () => {
416
- if (!fullRebuildStarted) {
417
- fullRebuildStarted = true;
418
- graph.clear();
419
- }
420
- },
421
- }
422
- : {}),
423
- });
424
- const connection = sdk.DatabaseConnection.open(this.#databasePath);
425
- try {
426
- const queries = new sdk.QueryBuilder(connection.getDb());
427
- const boundaries = normalizeUnresolvedReferences(graph, queries);
428
- return this.createFullBuildResult(graph, result, mode, boundaries);
429
- }
430
- finally {
431
- connection.close();
432
- }
433
- }
434
- async restorePublishedGraph(publication, failedResult) {
435
- try {
436
- await publication.rollback();
437
- return failedResult;
438
- }
439
- catch (error) {
440
- return {
441
- ...failedResult,
442
- diagnostics: [
443
- ...failedResult.diagnostics,
444
- structuralRestoreFailureDiagnostic(error, publication.backupPath),
445
- ],
446
- };
447
- }
448
- }
449
- createFullBuildResult(graph, result, mode, boundaries) {
450
- const filesDiscovered = result.filesDiscovered ??
451
- result.filesIndexed + result.filesSkipped + result.filesErrored;
452
- const complete = result.success &&
453
- graph.getIndexState() === "complete" &&
454
- graph.getPendingReferenceCount() === 0 &&
455
- result.filesErrored === 0 &&
456
- !hasStructuralFileErrors(graph) &&
457
- filesDiscovered === result.filesIndexed + result.filesSkipped + result.filesErrored;
458
- const diagnostics = result.errors
459
- .filter((error) => error.severity === "error")
460
- .map((error) => ({
461
- code: "STRUCTURAL_INDEX_INCOMPLETE",
462
- message: diagnosticMessage(error.message),
463
- }));
464
- if (!complete && diagnostics.length === 0) {
465
- diagnostics.push(incompleteDiagnostic(graph.getIndexState()));
466
- }
467
- return {
468
- ...this.stateFromGraph(graph, complete ? "complete" : "incomplete", diagnostics),
469
- mode,
470
- counts: {
471
- filesDiscovered,
472
- filesIndexed: result.filesIndexed,
473
- filesSkipped: result.filesSkipped,
474
- filesErrored: result.filesErrored,
475
- nodes: graph.getStats().nodeCount,
476
- relations: graph.getStats().edgeCount,
477
- },
478
- changes: emptyChanges(),
479
- factChanges: emptyFactChanges(),
480
- boundaries,
481
- };
482
- }
483
- createSyncResult(graph, result, changes, boundaries) {
484
- const complete = graph.getIndexState() === "complete" &&
485
- graph.getPendingReferenceCount() === 0 &&
486
- !hasStructuralFileErrors(graph);
487
- const diagnostics = complete ? [] : [incompleteDiagnostic(graph.getIndexState())];
488
- const stats = graph.getStats();
489
- return {
490
- ...this.stateFromGraph(graph, complete ? "complete" : "incomplete", diagnostics),
491
- mode: "incremental",
492
- counts: {
493
- filesDiscovered: result.filesChecked,
494
- filesIndexed: result.filesAdded + result.filesModified,
495
- filesSkipped: result.filesChecked - result.filesAdded - result.filesModified - result.filesRemoved,
496
- filesErrored: 0,
497
- nodes: stats.nodeCount,
498
- relations: stats.edgeCount,
499
- },
500
- changes,
501
- factChanges: emptyFactChanges(),
502
- boundaries,
503
- };
504
- }
505
- createLockUnavailableSyncResult(graph, result, changes) {
506
- const stats = graph.getStats();
507
- return {
508
- ...this.stateFromGraph(graph, "incomplete", [lockUnavailableDiagnostic()]),
509
- mode: "incremental",
510
- counts: {
511
- filesDiscovered: result.filesChecked,
512
- filesIndexed: 0,
513
- filesSkipped: 0,
514
- filesErrored: 0,
515
- nodes: stats.nodeCount,
516
- relations: stats.edgeCount,
517
- },
518
- changes,
519
- factChanges: emptyFactChanges(),
520
- boundaries: [],
521
- };
522
- }
523
- async createLockUnavailableBuildResult(sdk, requestedMode) {
524
- const initialized = sdk.CodeGraph.isInitialized(this.#repository.worktreeRoot);
525
- const mode = initialized ? requestedMode : "initial";
526
- return {
527
- ...this.incompleteState(lockUnavailableDiagnostic()),
528
- mode,
529
- counts: emptyCounts(),
530
- changes: emptyChanges(),
531
- factChanges: emptyFactChanges(),
532
- boundaries: [],
533
- };
534
- }
535
- failedBuildResult(mode, error) {
536
- return {
537
- ...this.incompleteState(failureDiagnostic(error)),
538
- mode,
539
- counts: emptyCounts(),
540
- changes: emptyChanges(),
541
- factChanges: emptyFactChanges(),
542
- boundaries: [],
543
- };
544
- }
545
- async withCurrentGraph(operation) {
546
- try {
547
- return await withCodeGraphSdk((sdk) => this.withPublishedGraph(sdk, async (graph) => {
548
- let connection;
549
- try {
550
- const state = this.readState(graph);
551
- if (state.completeness !== "complete") {
552
- throw new StructuralBackendError("STRUCTURAL_INDEX_INCOMPLETE", "The structural index is incomplete and cannot serve queries");
553
- }
554
- connection = sdk.DatabaseConnection.open(this.#databasePath);
555
- const queries = new sdk.QueryBuilder(connection.getDb());
556
- return await operation(graph, queries);
557
- }
558
- finally {
559
- connection?.close();
560
- }
561
- }));
562
- }
563
- catch (error) {
564
- if (error instanceof StructuralBackendError) {
565
- throw error;
566
- }
567
- throw new StructuralBackendError("STRUCTURAL_QUERY_FAILED", "The structural backend could not complete the query", error);
568
- }
569
- }
570
- readState(graph) {
571
- const indexState = graph.getIndexState();
572
- const complete = indexState === "complete" &&
573
- graph.getPendingReferenceCount() === 0 &&
574
- !hasStructuralFileErrors(graph);
575
- return this.stateFromGraph(graph, complete ? "complete" : "incomplete", complete ? [] : [incompleteDiagnostic(indexState)]);
576
- }
577
- stateFromGraph(graph, completeness, diagnostics) {
578
- const buildInfo = graph.getIndexBuildInfo();
579
- const indexedAt = graph.getLastIndexedAt();
580
- return {
581
- completeness,
582
- databasePath: this.#databasePath,
583
- backendVersion: buildInfo.version ?? STRUCTURAL_BACKEND_VERSION,
584
- extractionVersion: buildInfo.extractionVersion,
585
- indexedAt: indexedAt === null ? null : new Date(indexedAt).toISOString(),
586
- diagnostics,
587
- };
588
- }
589
- missingState() {
590
- return {
591
- completeness: "missing",
592
- databasePath: this.#databasePath,
593
- backendVersion: STRUCTURAL_BACKEND_VERSION,
594
- extractionVersion: null,
595
- indexedAt: null,
596
- diagnostics: [],
597
- };
598
- }
599
- incompleteState(diagnostic) {
600
- return {
601
- completeness: "incomplete",
602
- databasePath: this.#databasePath,
603
- backendVersion: STRUCTURAL_BACKEND_VERSION,
604
- extractionVersion: null,
605
- indexedAt: null,
606
- diagnostics: [diagnostic],
607
- };
608
- }
609
- async prepareAtlasDirectory() {
610
- const directory = join(this.#repository.worktreeRoot, ATLAS_DIRECTORY);
611
- await this.verifyAtlasIgnoreIsUntracked();
612
- await mkdir(directory, { recursive: true });
613
- await this.verifyAtlasDirectory();
614
- await this.prepareAtlasIgnoreFile(directory);
615
- }
616
- async inspectWithSdk(sdk) {
617
- try {
618
- return await this.withPublishedGraph(sdk, (graph) => this.readState(graph));
619
- }
620
- catch (error) {
621
- if (error instanceof StructuralBackendError) {
622
- if (error.code === "STRUCTURAL_INDEX_MISSING") {
623
- return this.missingState();
624
- }
625
- if (error.code === "STRUCTURAL_INDEX_INCOMPLETE") {
626
- return this.incompleteState(activePublicationDiagnostic());
627
- }
628
- }
629
- return this.incompleteState(failureDiagnostic(error));
630
- }
631
- }
632
- async withPublishedGraph(sdk, operation) {
633
- this.verifyDatabasePath(sdk.getDatabasePath(this.#repository.worktreeRoot));
634
- if (!await this.atlasDirectoryExists()) {
635
- throw missingStructuralIndexError();
636
- }
637
- await this.verifyAtlasDirectory();
638
- const atlasWriteLock = this.acquireAtlasWriteLock();
639
- if (atlasWriteLock === undefined) {
640
- throw activePublicationError();
641
- }
642
- let writeLock;
643
- let graph;
644
- try {
645
- writeLock = this.createCodeGraphWriteLock(sdk);
646
- try {
647
- writeLock.acquire();
648
- }
649
- catch {
650
- throw activePublicationError();
651
- }
652
- await StructuralPublication.recoverAbandoned(this.#databasePath);
653
- await this.verifyAtlasDirectory();
654
- if (!sdk.CodeGraph.isInitialized(this.#repository.worktreeRoot)) {
655
- throw missingStructuralIndexError();
656
- }
657
- graph = await sdk.CodeGraph.open(this.#repository.worktreeRoot, { sync: false });
658
- useHeldCodeGraphWriteLock(graph);
659
- return await operation(graph);
660
- }
661
- finally {
662
- graph?.close();
663
- writeLock?.release();
664
- atlasWriteLock.release();
665
- }
666
- }
667
- acquireAtlasWriteLock() {
668
- return StructuralWriteLock.acquire(join(this.#repository.worktreeRoot, ATLAS_DIRECTORY, ATLAS_WRITE_LOCK));
669
- }
670
- createCodeGraphWriteLock(sdk) {
671
- return new sdk.FileLock(join(this.#repository.worktreeRoot, ATLAS_DIRECTORY, CODEGRAPH_WRITE_LOCK));
672
- }
673
- async atlasDirectoryExists() {
674
- try {
675
- await lstat(join(this.#repository.worktreeRoot, ATLAS_DIRECTORY));
676
- return true;
677
- }
678
- catch (error) {
679
- if (isFileSystemError(error, "ENOENT")) {
680
- return false;
681
- }
682
- throw error;
683
- }
684
- }
685
- async prepareAtlasIgnoreFile(directory) {
686
- const ignorePath = join(directory, ".gitignore");
687
- await this.verifyAtlasIgnoreIsUntracked();
688
- try {
689
- await this.verifyExistingAtlasIgnoreFile(ignorePath);
690
- return;
691
- }
692
- catch (error) {
693
- if (!isFileSystemError(error, "ENOENT")) {
694
- throw error;
695
- }
696
- }
697
- const noFollow = fileSystemConstants.O_NOFOLLOW ?? 0;
698
- let ignoreFile;
699
- try {
700
- ignoreFile = await open(ignorePath, fileSystemConstants.O_WRONLY |
701
- fileSystemConstants.O_CREAT |
702
- fileSystemConstants.O_EXCL |
703
- noFollow, 0o600);
704
- }
705
- catch (error) {
706
- if (isFileSystemError(error, "EEXIST")) {
707
- await this.verifyExistingAtlasIgnoreFile(ignorePath);
708
- return;
709
- }
710
- throw error;
711
- }
712
- try {
713
- await ignoreFile.writeFile(ATLAS_IGNORE_CONTENT, { encoding: "utf8" });
714
- }
715
- finally {
716
- await ignoreFile.close();
717
- }
718
- await this.verifyExistingAtlasIgnoreFile(ignorePath);
719
- }
720
- async verifyAtlasIgnoreIsUntracked() {
721
- const tracked = (await runGit(this.#repository.worktreeRoot, [
722
- "ls-files",
723
- "-z",
724
- "--",
725
- `${ATLAS_DIRECTORY}/.gitignore`,
726
- ])).length > 0;
727
- if (tracked) {
728
- throw new Error("The Atlas ignore file is repository-owned and cannot be modified");
729
- }
730
- }
731
- async verifyExistingAtlasIgnoreFile(ignorePath) {
732
- const metadata = await lstat(ignorePath);
733
- if (!metadata.isFile() || metadata.isSymbolicLink()) {
734
- throw new Error("The Atlas ignore file must be an Atlas-owned regular file");
735
- }
736
- const noFollow = fileSystemConstants.O_NOFOLLOW ?? 0;
737
- const ignoreFile = await open(ignorePath, fileSystemConstants.O_RDONLY | noFollow);
738
- try {
739
- const openedMetadata = await ignoreFile.stat();
740
- if (!openedMetadata.isFile() ||
741
- openedMetadata.dev !== metadata.dev ||
742
- openedMetadata.ino !== metadata.ino) {
743
- throw new Error("The Atlas ignore file must be an Atlas-owned regular file");
744
- }
745
- if (await ignoreFile.readFile({ encoding: "utf8" }) !== ATLAS_IGNORE_CONTENT) {
746
- throw new Error("The existing Atlas ignore file is not owned by Semantic Atlas");
747
- }
748
- }
749
- finally {
750
- await ignoreFile.close();
751
- }
752
- }
753
- async verifyAtlasDirectory() {
754
- const expectedDirectory = resolve(this.#repository.worktreeRoot, ATLAS_DIRECTORY);
755
- const directoryMetadata = await lstat(expectedDirectory);
756
- if (!directoryMetadata.isDirectory() || directoryMetadata.isSymbolicLink()) {
757
- throw new Error("The Atlas store must be a real directory inside the target worktree");
758
- }
759
- if (resolve(await realpath(expectedDirectory)) !== expectedDirectory) {
760
- throw new Error("The Atlas store resolves outside the target worktree");
761
- }
762
- try {
763
- const databaseMetadata = await lstat(this.#databasePath);
764
- if (!databaseMetadata.isFile() || databaseMetadata.isSymbolicLink()) {
765
- throw new Error("The structural database must be a regular file inside the Atlas store");
766
- }
767
- }
768
- catch (error) {
769
- if (!isFileSystemError(error, "ENOENT")) {
770
- throw error;
771
- }
772
- }
773
- }
774
- verifyDatabasePath(candidate) {
775
- if (resolve(candidate) !== resolve(this.#databasePath)) {
776
- throw new Error("The structural backend resolved outside the Atlas worktree store");
777
- }
778
- }
779
- }
780
- function normalizeNode(node) {
781
- const path = normalizeRepositoryPath(node.filePath);
782
- return {
783
- reference: referenceForNode(node),
784
- kind: normalizeNodeKind(node),
785
- declarationKind: node.kind,
786
- decorators: [...(node.decorators ?? [])],
787
- name: node.name,
788
- qualifiedName: node.qualifiedName,
789
- path,
790
- language: node.language,
791
- range: {
792
- start: { line: positiveLine(node.startLine), column: node.startColumn + 1 },
793
- end: { line: positiveLine(node.endLine), column: node.endColumn + 1 },
794
- },
795
- support: exactBackendSupport(),
796
- };
797
- }
798
- function normalizeProjectGraph(graph, queries, query) {
799
- const requestedKinds = new Set(query.declarationKinds);
800
- const backendNodes = projectNodes(graph, requestedKinds).filter((node) => (requestedKinds.has(node.kind)));
801
- const nodesById = new Map(backendNodes.map((node) => [node.id, node]));
802
- const relations = [];
803
- const boundaries = [];
804
- for (const source of backendNodes) {
805
- for (const edge of graph.getOutgoingEdges(source.id)) {
806
- const target = nodesById.get(edge.target);
807
- if (target === undefined) {
808
- continue;
809
- }
810
- const relation = normalizeRelation(edge, source, target);
811
- if (relation === undefined) {
812
- boundaries.push(unsupportedRelationBoundary(edge, source, target));
813
- }
814
- else {
815
- relations.push(relation);
816
- }
817
- }
818
- }
819
- const requestedBackendIds = new Set(backendNodes.map((node) => node.id));
820
- boundaries.push(...normalizeUnresolvedReferences(graph, queries, requestedBackendIds));
821
- return {
822
- roots: structuralModuleRoots(graph).map((node) => node.reference),
823
- nodes: uniqueBy(backendNodes.map(normalizeNode), (node) => node.reference.id)
824
- .sort(compareStructuralNodes),
825
- relations: uniqueBy(relations, relationIdentity),
826
- boundaries: uniqueBy(boundaries, (boundary) => boundary.reference.id),
827
- };
828
- }
829
- function projectNodes(graph, requestedKinds) {
830
- const nodes = [...requestedKinds]
831
- .filter((kind) => kind !== "test" && kind !== "virtual_module")
832
- .flatMap((kind) => graph.getNodesByKind(kind));
833
- return uniqueBy(nodes, (node) => node.id);
834
- }
835
- function structuralModuleRoots(graph) {
836
- const modules = [
837
- ...graph.getNodesByKind("module"),
838
- ...graph.getNodesByKind("namespace"),
839
- ];
840
- if (modules.length > 0) {
841
- const moduleIds = new Set(modules.map((node) => node.id));
842
- const roots = modules.filter((node) => !graph.getIncomingEdges(node.id).some((edge) => (edge.kind === "contains" && moduleIds.has(edge.source))));
843
- return uniqueBy((roots.length === 0 ? modules : roots).map(normalizeNode), (node) => node.reference.id)
844
- .sort(compareStructuralNodes);
845
- }
846
- const rootDirectories = new Map();
847
- for (const file of graph.getFiles()) {
848
- const path = normalizeRepositoryPath(file.path);
849
- const separator = path.indexOf("/");
850
- const root = separator === -1 ? "." : path.slice(0, separator);
851
- if (!rootDirectories.has(root)) {
852
- rootDirectories.set(root, path);
853
- }
854
- }
855
- return [...rootDirectories.entries()].sort(([left], [right]) => left.localeCompare(right))
856
- .map(([root, representativePath]) => virtualModuleRoot(root, representativePath));
857
- }
858
- function findVirtualModuleRoot(graph, reference) {
859
- return structuralModuleRoots(graph).find((root) => (root.virtual === true && root.reference.id === reference.id));
860
- }
861
- function traverseVirtualModuleRoot(graph, module, query) {
862
- const includesOutgoing = query.direction !== "incoming";
863
- const includesContains = query.relationTypes === undefined || query.relationTypes.includes("contains");
864
- if (!includesOutgoing || !includesContains || query.maxDepth === 0) {
865
- return { roots: [module.reference], nodes: [module], relations: [], boundaries: [] };
866
- }
867
- const root = decodeURIComponent(module.reference.id.slice("module:".length));
868
- const files = graph.getNodesByKind("file")
869
- .filter((node) => topLevelDirectory(normalizeRepositoryPath(node.filePath)) === root)
870
- .map(normalizeNode)
871
- .sort(compareStructuralNodes);
872
- return {
873
- roots: [module.reference],
874
- nodes: [module, ...files],
875
- relations: files.map((file) => ({
876
- from: module.reference,
877
- type: "contains",
878
- to: file.reference,
879
- support: exactBackendSupport(),
880
- })),
881
- boundaries: [],
882
- };
883
- }
884
- function virtualModuleRoot(root, representativePath) {
885
- return {
886
- reference: { id: `module:${encodeURIComponent(root)}` },
887
- kind: "Module",
888
- declarationKind: "virtual_module",
889
- decorators: [],
890
- name: root,
891
- qualifiedName: root,
892
- path: representativePath,
893
- language: "unknown",
894
- range: {
895
- start: { line: 1, column: 1 },
896
- end: { line: 1, column: 1 },
897
- },
898
- support: exactBackendSupport(),
899
- virtual: true,
900
- };
901
- }
902
- function topLevelDirectory(path) {
903
- const separator = path.indexOf("/");
904
- return separator === -1 ? "." : path.slice(0, separator);
905
- }
906
- function compareStructuralNodes(left, right) {
907
- return left.path.localeCompare(right.path)
908
- || left.qualifiedName.localeCompare(right.qualifiedName)
909
- || left.reference.id.localeCompare(right.reference.id);
910
- }
911
- function normalizeNodeKind(node) {
912
- if (node.kind === "file") {
913
- return "File";
914
- }
915
- if (node.kind === "module" || node.kind === "namespace") {
916
- return "Module";
917
- }
918
- return "Symbol";
919
- }
920
- function referenceForNode(node) {
921
- const path = normalizeRepositoryPath(node.filePath);
922
- if (node.kind === "file") {
923
- return { id: `file:${path}` };
924
- }
925
- const prefix = node.kind === "module" || node.kind === "namespace"
926
- ? "module"
927
- : "symbol";
928
- return {
929
- id: `${prefix}:${encodeURIComponent(path)}#${digest([
930
- node.id,
931
- node.kind,
932
- node.qualifiedName,
933
- ].join("\0"))}`,
934
- };
935
- }
936
- function findNodeByReference(graph, reference) {
937
- if (reference.id.startsWith("file:")) {
938
- return graph.getNode(reference.id) ?? undefined;
939
- }
940
- const path = pathFromStructuralReference(reference);
941
- if (path === undefined) {
942
- return undefined;
943
- }
944
- return graph.getNodesInFile(path).find((node) => referenceForNode(node).id === reference.id);
945
- }
946
- function structuralEvidenceResolver(graph) {
947
- return {
948
- getNode(reference) {
949
- const node = findNodeByReference(graph, { id: reference });
950
- return node === undefined ? undefined : normalizeNode(node);
951
- },
952
- findCandidates(locator) {
953
- return graph.getNodesInFile(locator.file)
954
- .map(normalizeNode)
955
- .filter((node) => candidateMatchesLocator(node, locator));
956
- },
957
- backendLocator(node) {
958
- return findNodeByReference(graph, node.reference)?.id;
959
- },
960
- };
961
- }
962
- function candidateMatchesLocator(node, locator) {
963
- return (locator.qualifiedSymbol === null || node.qualifiedName === locator.qualifiedSymbol)
964
- && (locator.structuralKind === null || node.kind === locator.structuralKind);
965
- }
966
- function pathFromStructuralReference(reference) {
967
- const separatorIndex = reference.id.indexOf(":");
968
- const hashIndex = reference.id.indexOf("#", separatorIndex + 1);
969
- if (separatorIndex < 0 || hashIndex < 0) {
970
- return undefined;
971
- }
972
- try {
973
- return normalizeRepositoryPath(decodeURIComponent(reference.id.slice(separatorIndex + 1, hashIndex)));
974
- }
975
- catch {
976
- return undefined;
977
- }
978
- }
979
- function requireNodeByReference(graph, reference) {
980
- const node = findNodeByReference(graph, reference);
981
- if (node === undefined) {
982
- throw new StructuralBackendError("STRUCTURAL_QUERY_FAILED", `Structural reference ${reference.id} does not resolve in the current index`);
983
- }
984
- return node;
985
- }
986
- function normalizeRelation(edge, source, target) {
987
- const relationType = supportedRelationTypes.get(edge.kind);
988
- if (relationType === undefined || target === undefined) {
989
- return undefined;
990
- }
991
- const normalizedType = relationType === "contains" && source.kind === "file" && target.kind !== "file"
992
- ? "declares"
993
- : relationType;
994
- return {
995
- from: referenceForNode(source),
996
- type: normalizedType,
997
- to: referenceForNode(target),
998
- support: supportForEdge(edge),
999
- ...(edge.line === undefined || edge.line === null
1000
- ? {}
1001
- : {
1002
- location: {
1003
- path: normalizeRepositoryPath(source.filePath),
1004
- position: { line: positiveLine(edge.line), column: (edge.column ?? 0) + 1 },
1005
- },
1006
- }),
1007
- };
1008
- }
1009
- function requireNormalizedRelation(edge, source, target) {
1010
- const relation = normalizeRelation(edge, source, target);
1011
- if (relation === undefined) {
1012
- throw new StructuralBackendError("STRUCTURAL_QUERY_FAILED", "The structural backend returned an unsupported call relation");
1013
- }
1014
- return relation;
1015
- }
1016
- function supportForEdge(edge) {
1017
- const provenance = normalizeProvenance(edge.provenance);
1018
- return {
1019
- status: provenance === "heuristic" ? "inferred" : "exact",
1020
- provenance,
1021
- };
1022
- }
1023
- function normalizeProvenance(provenance) {
1024
- return provenance === "tree-sitter" || provenance === "scip" || provenance === "heuristic"
1025
- ? provenance
1026
- : "backend";
1027
- }
1028
- function exactBackendSupport() {
1029
- return { status: "exact", provenance: "backend" };
1030
- }
1031
- function dependencySupport(edges) {
1032
- const exactEdge = edges.find((edge) => edge.provenance !== "heuristic");
1033
- if (exactEdge !== undefined) {
1034
- return supportForEdge(exactEdge);
1035
- }
1036
- return edges.length === 0
1037
- ? { status: "inferred", provenance: "backend" }
1038
- : supportForEdge(edges[0]);
1039
- }
1040
- function normalizeUnresolvedReferences(graph, queries, ownerBackendIds) {
1041
- return queries.getUnresolvedReferences()
1042
- .filter((reference) => ownerBackendIds?.has(reference.fromNodeId) ?? true)
1043
- .map((reference) => {
1044
- const owner = graph.getNode(reference.fromNodeId) ?? undefined;
1045
- return unresolvedReferenceBoundary(reference, owner);
1046
- });
1047
- }
1048
- function unresolvedReferenceBoundary(reference, owner) {
1049
- const ownerReference = owner === undefined
1050
- ? { id: `symbol:unresolved-owner-${digest(reference.fromNodeId)}` }
1051
- : referenceForNode(owner);
1052
- const path = reference.filePath === undefined
1053
- ? owner?.filePath
1054
- : reference.filePath;
1055
- const operation = reference.referenceKind === "function_ref" ? "references" : reference.referenceKind;
1056
- return {
1057
- reference: {
1058
- id: `unknown:${digest([
1059
- ownerReference.id,
1060
- operation,
1061
- reference.referenceName,
1062
- path ?? "",
1063
- reference.line,
1064
- reference.column,
1065
- ].join("\0"))}`,
1066
- },
1067
- kind: "UnknownBoundary",
1068
- owner: ownerReference,
1069
- operation,
1070
- target: reference.referenceName,
1071
- reason: `The structural backend could not resolve ${reference.referenceName}.`,
1072
- ...(path === undefined ? {} : { path: normalizeRepositoryPath(path) }),
1073
- position: { line: positiveLine(reference.line), column: reference.column + 1 },
1074
- candidates: [...(reference.candidates ?? [])].sort(),
1075
- support: { status: "unresolved", provenance: "backend" },
1076
- };
1077
- }
1078
- function unsupportedRelationBoundary(edge, source, target) {
1079
- const owner = referenceForNode(source);
1080
- return {
1081
- reference: { id: `unknown:${digest([owner.id, edge.kind, edge.target].join("\0"))}` },
1082
- kind: "UnknownBoundary",
1083
- owner,
1084
- operation: "relation",
1085
- reason: `The structural backend relation ${edge.kind} is outside the Atlas v0.1 relation contract.`,
1086
- path: normalizeRepositoryPath(source.filePath),
1087
- ...(edge.line === undefined || edge.line === null
1088
- ? {}
1089
- : { position: { line: positiveLine(edge.line), column: (edge.column ?? 0) + 1 } }),
1090
- candidates: target === undefined ? [] : [referenceForNode(target).id],
1091
- support: {
1092
- status: "unsupported",
1093
- provenance: normalizeProvenance(edge.provenance) === "backend"
1094
- ? "heuristic"
1095
- : normalizeProvenance(edge.provenance),
1096
- },
1097
- };
1098
- }
1099
- function normalizeChangedFiles(changes) {
1100
- return {
1101
- added: changes.added.map(normalizeRepositoryPath).sort(),
1102
- modified: changes.modified.map(normalizeRepositoryPath).sort(),
1103
- removed: changes.removed.map(normalizeRepositoryPath).sort(),
1104
- };
1105
- }
1106
- function hasStructuralFileErrors(graph) {
1107
- return graph.getFiles().some((file) => file.errors?.some((error) => error.severity === "error") === true);
1108
- }
1109
- function normalizeRepositoryPath(path) {
1110
- const normalized = path.replaceAll("\\", "/").replace(/^\.\//u, "");
1111
- if (normalized.length === 0 || normalized.startsWith("/") || normalized.split("/").includes("..")) {
1112
- throw new StructuralBackendError("STRUCTURAL_QUERY_FAILED", `Structural path must be repository-relative: ${path}`);
1113
- }
1114
- return normalized;
1115
- }
1116
- function positiveLine(line) {
1117
- return Math.max(1, line);
1118
- }
1119
- function emptyCounts() {
1120
- return {
1121
- filesDiscovered: 0,
1122
- filesIndexed: 0,
1123
- filesSkipped: 0,
1124
- filesErrored: 0,
1125
- nodes: 0,
1126
- relations: 0,
1127
- };
1128
- }
1129
- function emptyChanges() {
1130
- return { added: [], modified: [], removed: [] };
1131
- }
1132
- function emptyFactChanges() {
1133
- return { added: 0, changed: 0, reused: 0, removed: 0 };
1134
- }
1135
- function failureDiagnostic(error) {
1136
- return {
1137
- code: "STRUCTURAL_BACKEND_FAILURE",
1138
- message: diagnosticMessage(error instanceof Error ? error.message : String(error)),
1139
- };
1140
- }
1141
- function structuralRestoreFailureDiagnostic(error, backupPath) {
1142
- const message = error instanceof Error ? error.message : String(error);
1143
- return {
1144
- code: "STRUCTURAL_BACKEND_FAILURE",
1145
- message: `${diagnosticMessage(message)} The published database backup remains at ${backupPath}.`,
1146
- };
1147
- }
1148
- function incompleteDiagnostic(indexState) {
1149
- return {
1150
- code: "STRUCTURAL_INDEX_INCOMPLETE",
1151
- message: `The structural index is ${indexState ?? "not marked complete"}.`,
1152
- };
1153
- }
1154
- function lockUnavailableDiagnostic() {
1155
- return {
1156
- code: "STRUCTURAL_INDEX_INCOMPLETE",
1157
- message: "The structural index operation did not run because another process holds the structural write lock.",
1158
- };
1159
- }
1160
- function activePublicationDiagnostic() {
1161
- return {
1162
- code: "STRUCTURAL_INDEX_INCOMPLETE",
1163
- message: "The structural index cannot serve reads while another process is publishing it.",
1164
- };
1165
- }
1166
- function activePublicationError() {
1167
- return new StructuralBackendError("STRUCTURAL_INDEX_INCOMPLETE", "The structural index cannot serve queries while another process is publishing it");
1168
- }
1169
- function missingStructuralIndexError() {
1170
- return new StructuralBackendError("STRUCTURAL_INDEX_MISSING", "The structural index has not been built for this worktree");
1171
- }
1172
- function isLockUnavailableSync(result) {
1173
- return result.filesChecked === 0 && result.durationMs === 0;
1174
- }
1175
- function diagnosticMessage(message) {
1176
- return message.trim().length === 0
1177
- ? "The structural backend operation did not complete."
1178
- : `The structural backend operation did not complete: ${message.trim()}`;
1179
- }
1180
- function digest(value) {
1181
- return createHash("sha256").update("semantic-atlas:structural:v1\0").update(value).digest("hex");
1182
- }
1183
- function relationIdentity(relation) {
1184
- return `${relation.from.id}\0${relation.type}\0${relation.to.id}`;
1185
- }
1186
- function uniqueBy(values, identity) {
1187
- return [...new Map(values.map((value) => [identity(value), value])).values()];
1188
- }
1189
- function isDefined(value) {
1190
- return value !== undefined;
1191
- }
1192
- function isFileSystemError(error, code) {
1193
- return error instanceof Error && "code" in error && error.code === code;
1194
- }
1195
- function loadCodeGraphSdk() {
1196
- // CodeGraph 1.5.0 publishes ESM declarations through a CommonJS SDK shim.
1197
- return require("@colbymchenry/codegraph");
1198
- }
1199
- function useHeldCodeGraphWriteLock(graph) {
1200
- const graphWithLock = graph;
1201
- if (graphWithLock.fileLock === undefined ||
1202
- typeof graphWithLock.fileLock.acquire !== "function" ||
1203
- typeof graphWithLock.fileLock.release !== "function") {
1204
- throw new Error("CodeGraph 1.5.0 does not expose the expected internal write lock");
1205
- }
1206
- // Atlas already owns the same on-disk lock for the complete publication lifecycle.
1207
- graphWithLock.fileLock = {
1208
- acquire: () => undefined,
1209
- release: () => undefined,
1210
- };
1211
- }
1212
- async function withCodeGraphSdk(operation) {
1213
- const scheduled = operationQueue.then(async () => {
1214
- const originalDirectory = process.env.CODEGRAPH_DIR;
1215
- process.env.CODEGRAPH_DIR = ATLAS_DIRECTORY;
1216
- try {
1217
- return await operation(loadCodeGraphSdk());
1218
- }
1219
- finally {
1220
- if (originalDirectory === undefined) {
1221
- delete process.env.CODEGRAPH_DIR;
1222
- }
1223
- else {
1224
- process.env.CODEGRAPH_DIR = originalDirectory;
1225
- }
1226
- }
1227
- });
1228
- operationQueue = scheduled.then(() => undefined, () => undefined);
1229
- return scheduled;
1230
- }