semantic-atlas 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/.agents/skills/semantic-atlas/SKILL.md +172 -0
  2. package/.agents/skills/semantic-atlas/references/graph-patch.md +109 -0
  3. package/.agents/skills/semantic-atlas/references/result-routing.md +91 -0
  4. package/LICENSE +21 -0
  5. package/README.md +118 -0
  6. package/dist/business-flow/business-flow-derivation-service.d.ts +11 -0
  7. package/dist/business-flow/business-flow-derivation-service.d.ts.map +1 -0
  8. package/dist/business-flow/business-flow-derivation-service.js +151 -0
  9. package/dist/business-flow/business-flow-draft.d.ts +16 -0
  10. package/dist/business-flow/business-flow-draft.d.ts.map +1 -0
  11. package/dist/business-flow/business-flow-draft.js +150 -0
  12. package/dist/business-flow/framework-business-strategy.d.ts +7 -0
  13. package/dist/business-flow/framework-business-strategy.d.ts.map +1 -0
  14. package/dist/business-flow/framework-business-strategy.js +1 -0
  15. package/dist/business-flow/strategies/bullmq-business-strategy.d.ts +10 -0
  16. package/dist/business-flow/strategies/bullmq-business-strategy.d.ts.map +1 -0
  17. package/dist/business-flow/strategies/bullmq-business-strategy.js +79 -0
  18. package/dist/business-flow/strategies/called-operation-derivation.d.ts +13 -0
  19. package/dist/business-flow/strategies/called-operation-derivation.d.ts.map +1 -0
  20. package/dist/business-flow/strategies/called-operation-derivation.js +32 -0
  21. package/dist/business-flow/strategies/graphql-business-strategy.d.ts +8 -0
  22. package/dist/business-flow/strategies/graphql-business-strategy.d.ts.map +1 -0
  23. package/dist/business-flow/strategies/graphql-business-strategy.js +65 -0
  24. package/dist/business-flow/strategies/nestjs-business-strategy.d.ts +8 -0
  25. package/dist/business-flow/strategies/nestjs-business-strategy.d.ts.map +1 -0
  26. package/dist/business-flow/strategies/nestjs-business-strategy.js +72 -0
  27. package/dist/business-flow/strategies/strategy-helpers.d.ts +32 -0
  28. package/dist/business-flow/strategies/strategy-helpers.d.ts.map +1 -0
  29. package/dist/business-flow/strategies/strategy-helpers.js +49 -0
  30. package/dist/business-flow/strategies/typeorm-business-strategy.d.ts +10 -0
  31. package/dist/business-flow/strategies/typeorm-business-strategy.d.ts.map +1 -0
  32. package/dist/business-flow/strategies/typeorm-business-strategy.js +136 -0
  33. package/dist/business-flow/strategies/verified-invariant-strategy.d.ts +5 -0
  34. package/dist/business-flow/strategies/verified-invariant-strategy.d.ts.map +1 -0
  35. package/dist/business-flow/strategies/verified-invariant-strategy.js +38 -0
  36. package/dist/business-flow/strategies/verified-test-strategy.d.ts +5 -0
  37. package/dist/business-flow/strategies/verified-test-strategy.d.ts.map +1 -0
  38. package/dist/business-flow/strategies/verified-test-strategy.js +26 -0
  39. package/dist/business-flow/structural-flow-catalog.d.ts +21 -0
  40. package/dist/business-flow/structural-flow-catalog.d.ts.map +1 -0
  41. package/dist/business-flow/structural-flow-catalog.js +125 -0
  42. package/dist/business-flow/types.d.ts +51 -0
  43. package/dist/business-flow/types.d.ts.map +1 -0
  44. package/dist/business-flow/types.js +1 -0
  45. package/dist/cli/argument-parser.d.ts +3 -0
  46. package/dist/cli/argument-parser.d.ts.map +1 -0
  47. package/dist/cli/argument-parser.js +174 -0
  48. package/dist/cli/bin.d.ts +3 -0
  49. package/dist/cli/bin.d.ts.map +1 -0
  50. package/dist/cli/bin.js +23 -0
  51. package/dist/cli/cli-application.d.ts +38 -0
  52. package/dist/cli/cli-application.d.ts.map +1 -0
  53. package/dist/cli/cli-application.js +515 -0
  54. package/dist/cli/cli-error.d.ts +12 -0
  55. package/dist/cli/cli-error.d.ts.map +1 -0
  56. package/dist/cli/cli-error.js +44 -0
  57. package/dist/cli/cli-presenter.d.ts +14 -0
  58. package/dist/cli/cli-presenter.d.ts.map +1 -0
  59. package/dist/cli/cli-presenter.js +36 -0
  60. package/dist/cli/main.d.ts +3 -0
  61. package/dist/cli/main.d.ts.map +1 -0
  62. package/dist/cli/main.js +45 -0
  63. package/dist/cli/types.d.ts +46 -0
  64. package/dist/cli/types.d.ts.map +1 -0
  65. package/dist/cli/types.js +1 -0
  66. package/dist/contracts/cli.d.ts +2139 -0
  67. package/dist/contracts/cli.d.ts.map +1 -0
  68. package/dist/contracts/cli.js +232 -0
  69. package/dist/contracts/graph.d.ts +262 -0
  70. package/dist/contracts/graph.d.ts.map +1 -0
  71. package/dist/contracts/graph.js +182 -0
  72. package/dist/contracts/identifiers.d.ts +4 -0
  73. package/dist/contracts/identifiers.d.ts.map +1 -0
  74. package/dist/contracts/identifiers.js +7 -0
  75. package/dist/contracts/public-contracts.d.ts +4 -0
  76. package/dist/contracts/public-contracts.d.ts.map +1 -0
  77. package/dist/contracts/public-contracts.js +3 -0
  78. package/dist/evaluation/comparison.d.ts +30 -0
  79. package/dist/evaluation/comparison.d.ts.map +1 -0
  80. package/dist/evaluation/comparison.js +108 -0
  81. package/dist/evaluation/contracts.d.ts +204 -0
  82. package/dist/evaluation/contracts.d.ts.map +1 -0
  83. package/dist/evaluation/contracts.js +269 -0
  84. package/dist/graph/graph-store.d.ts +47 -0
  85. package/dist/graph/graph-store.d.ts.map +1 -0
  86. package/dist/graph/graph-store.js +719 -0
  87. package/dist/graph/types.d.ts +168 -0
  88. package/dist/graph/types.d.ts.map +1 -0
  89. package/dist/graph/types.js +1 -0
  90. package/dist/index.d.ts +19 -0
  91. package/dist/index.d.ts.map +1 -0
  92. package/dist/index.js +9 -0
  93. package/dist/knowledge/business-knowledge-service.d.ts +24 -0
  94. package/dist/knowledge/business-knowledge-service.d.ts.map +1 -0
  95. package/dist/knowledge/business-knowledge-service.js +200 -0
  96. package/dist/knowledge/graph-patch-conflict-error.d.ts +8 -0
  97. package/dist/knowledge/graph-patch-conflict-error.d.ts.map +1 -0
  98. package/dist/knowledge/graph-patch-conflict-error.js +12 -0
  99. package/dist/knowledge/structural-target-binding.d.ts +14 -0
  100. package/dist/knowledge/structural-target-binding.d.ts.map +1 -0
  101. package/dist/knowledge/structural-target-binding.js +11 -0
  102. package/dist/repository/git-command.d.ts +3 -0
  103. package/dist/repository/git-command.d.ts.map +1 -0
  104. package/dist/repository/git-command.js +25 -0
  105. package/dist/repository/repository-inspector.d.ts +7 -0
  106. package/dist/repository/repository-inspector.d.ts.map +1 -0
  107. package/dist/repository/repository-inspector.js +84 -0
  108. package/dist/repository/repository-language-support.d.ts +14 -0
  109. package/dist/repository/repository-language-support.d.ts.map +1 -0
  110. package/dist/repository/repository-language-support.js +64 -0
  111. package/dist/repository/types.d.ts +9 -0
  112. package/dist/repository/types.d.ts.map +1 -0
  113. package/dist/repository/types.js +1 -0
  114. package/dist/snapshots/repository-snapshot.d.ts +4 -0
  115. package/dist/snapshots/repository-snapshot.d.ts.map +1 -0
  116. package/dist/snapshots/repository-snapshot.js +119 -0
  117. package/dist/snapshots/types.d.ts +30 -0
  118. package/dist/snapshots/types.d.ts.map +1 -0
  119. package/dist/snapshots/types.js +1 -0
  120. package/dist/storage/atlas-database.d.ts +14 -0
  121. package/dist/storage/atlas-database.d.ts.map +1 -0
  122. package/dist/storage/atlas-database.js +552 -0
  123. package/dist/storage/snapshot-store.d.ts +19 -0
  124. package/dist/storage/snapshot-store.d.ts.map +1 -0
  125. package/dist/storage/snapshot-store.js +77 -0
  126. package/dist/structural-backend/codegraph-backend.d.ts +54 -0
  127. package/dist/structural-backend/codegraph-backend.d.ts.map +1 -0
  128. package/dist/structural-backend/codegraph-backend.js +1224 -0
  129. package/dist/structural-backend/codegraph-worker-client.d.ts +5 -0
  130. package/dist/structural-backend/codegraph-worker-client.d.ts.map +1 -0
  131. package/dist/structural-backend/codegraph-worker-client.js +118 -0
  132. package/dist/structural-backend/codegraph-worker-protocol.d.ts +35 -0
  133. package/dist/structural-backend/codegraph-worker-protocol.d.ts.map +1 -0
  134. package/dist/structural-backend/codegraph-worker-protocol.js +1 -0
  135. package/dist/structural-backend/codegraph-worker.d.ts +2 -0
  136. package/dist/structural-backend/codegraph-worker.d.ts.map +1 -0
  137. package/dist/structural-backend/codegraph-worker.js +131 -0
  138. package/dist/structural-backend/process-instance.d.ts +18 -0
  139. package/dist/structural-backend/process-instance.d.ts.map +1 -0
  140. package/dist/structural-backend/process-instance.js +207 -0
  141. package/dist/structural-backend/structural-fact-changes.d.ts +7 -0
  142. package/dist/structural-backend/structural-fact-changes.d.ts.map +1 -0
  143. package/dist/structural-backend/structural-fact-changes.js +78 -0
  144. package/dist/structural-backend/structural-publication.d.ts +12 -0
  145. package/dist/structural-backend/structural-publication.d.ts.map +1 -0
  146. package/dist/structural-backend/structural-publication.js +252 -0
  147. package/dist/structural-backend/structural-write-lock.d.ts +8 -0
  148. package/dist/structural-backend/structural-write-lock.d.ts.map +1 -0
  149. package/dist/structural-backend/structural-write-lock.js +415 -0
  150. package/dist/structural-backend/types.d.ts +144 -0
  151. package/dist/structural-backend/types.d.ts.map +1 -0
  152. package/dist/structural-backend/types.js +11 -0
  153. package/dist/world/types.d.ts +77 -0
  154. package/dist/world/types.d.ts.map +1 -0
  155. package/dist/world/types.js +1 -0
  156. package/dist/world/world-graph-query.d.ts +31 -0
  157. package/dist/world/world-graph-query.d.ts.map +1 -0
  158. package/dist/world/world-graph-query.js +453 -0
  159. package/dist/world/world-model-service.d.ts +21 -0
  160. package/dist/world/world-model-service.d.ts.map +1 -0
  161. package/dist/world/world-model-service.js +211 -0
  162. package/dist/world/world-snapshot-store.d.ts +40 -0
  163. package/dist/world/world-snapshot-store.d.ts.map +1 -0
  164. package/dist/world/world-snapshot-store.js +555 -0
  165. package/docs/architecture/codegraph-backend.md +193 -0
  166. package/docs/contracts/cli-v1.md +119 -0
  167. package/docs/contracts/graph-model.md +102 -0
  168. package/docs/contracts/graph-patch-v1.md +98 -0
  169. package/docs/evaluation.md +128 -0
  170. package/docs/product-contract.md +148 -0
  171. package/package.json +78 -0
  172. package/schemas/cli-envelope-v1.schema.json +1359 -0
  173. package/schemas/evaluation-plan-v1.schema.json +211 -0
  174. package/schemas/evaluation-run-v1.schema.json +365 -0
  175. package/schemas/graph-patch-v1.schema.json +392 -0
@@ -0,0 +1,719 @@
1
+ import { assertionCertaintySchema, businessKeySchema, businessNodeKindSchema, businessRelationTypeSchema, evidenceSchema, relativeSourcePathSchema, sourceRangeSchema, structuralNodeIdSchema, } from "../contracts/graph.js";
2
+ import { contentIdentifierSchema } from "../contracts/identifiers.js";
3
+ import { AtlasDatabase, CURRENT_ATLAS_SCHEMA_VERSION, } from "../storage/atlas-database.js";
4
+ import { readStructuralTargetBinding, } from "../knowledge/structural-target-binding.js";
5
+ export class GraphStore {
6
+ databasePath;
7
+ #atlasDatabase;
8
+ #repositoryId;
9
+ constructor(repository) {
10
+ this.#atlasDatabase = new AtlasDatabase(repository);
11
+ this.databasePath = this.#atlasDatabase.databasePath;
12
+ this.#repositoryId = repository.repositoryId;
13
+ }
14
+ get schemaVersion() {
15
+ return this.#atlasDatabase.schemaVersion;
16
+ }
17
+ reconcileSnapshot(snapshotId) {
18
+ contentIdentifierSchema.parse(snapshotId);
19
+ this.transaction(() => {
20
+ const snapshot = this.requireSnapshot(snapshotId);
21
+ this.refreshBusinessValidity(snapshot);
22
+ });
23
+ }
24
+ mutateBusinessGraph(mutation) {
25
+ this.validateBusinessMutation(mutation);
26
+ this.transaction(() => {
27
+ this.requireSnapshot(mutation.baseSnapshotId);
28
+ for (const selector of mutation.removeRelations) {
29
+ this.removeBusinessRelation(selector);
30
+ }
31
+ for (const key of mutation.removeNodeKeys) {
32
+ this.removeBusinessNode(key);
33
+ }
34
+ for (const node of mutation.upsertNodes) {
35
+ this.upsertBusinessNode(mutation.baseSnapshotId, node);
36
+ }
37
+ for (const relation of mutation.upsertRelations) {
38
+ this.upsertBusinessRelation(mutation.baseSnapshotId, relation);
39
+ }
40
+ this.refreshAllBusinessValidity();
41
+ });
42
+ }
43
+ getNode(reference, snapshotId) {
44
+ contentIdentifierSchema.parse(snapshotId);
45
+ return reference.domain === "business"
46
+ ? this.readBusinessNode(reference.key, snapshotId)
47
+ : undefined;
48
+ }
49
+ getEvidence(owner) {
50
+ if (owner.type === "node") {
51
+ const nodeId = this.findBusinessNodeId(owner.node.key);
52
+ return nodeId === undefined ? [] : this.readNodeEvidence(nodeId);
53
+ }
54
+ const relation = this.findBusinessRelation(owner.relation);
55
+ return relation === undefined ? [] : this.readRelationEvidence(relation.relation_id);
56
+ }
57
+ listBusinessRelations(snapshotId) {
58
+ contentIdentifierSchema.parse(snapshotId);
59
+ return this.readBusinessRelations(snapshotId).map((row) => this.relationFromRow(row));
60
+ }
61
+ listCapabilityRoots(snapshotId) {
62
+ contentIdentifierSchema.parse(snapshotId);
63
+ const rows = this.database.prepare(`
64
+ SELECT node.node_key
65
+ FROM atlas_business_nodes AS node
66
+ WHERE node.repository_id = ?
67
+ AND node.kind = 'Capability'
68
+ AND NOT EXISTS (
69
+ SELECT 1
70
+ FROM atlas_business_relations AS parent
71
+ WHERE parent.repository_id = node.repository_id
72
+ AND parent.from_key = node.node_key
73
+ AND parent.relation_type = 'part_of'
74
+ AND parent.to_domain = 'business'
75
+ )
76
+ ORDER BY node.node_key ASC
77
+ `).all(this.#repositoryId);
78
+ return rows.map(({ node_key }) => this.readBusinessNode(node_key, snapshotId))
79
+ .filter((node) => node !== undefined);
80
+ }
81
+ traverse(start, options) {
82
+ const maxDepth = options.maxDepth ?? 1;
83
+ if (!Number.isInteger(maxDepth) || maxDepth < 1 || maxDepth > 3) {
84
+ throw new Error("Graph traversal depth must be an integer from 1 through 3");
85
+ }
86
+ if (start.domain === "structural" || this.getNode(start, options.snapshotId) === undefined) {
87
+ return [];
88
+ }
89
+ const direction = options.direction ?? "both";
90
+ const relationTypes = options.relationTypes === undefined
91
+ ? undefined
92
+ : new Set(options.relationTypes);
93
+ const queue = [
94
+ { reference: start, depth: 0 },
95
+ ];
96
+ const queuedNodes = new Set([start.key]);
97
+ const emittedRelations = new Set();
98
+ const result = [];
99
+ for (let index = 0; index < queue.length; index += 1) {
100
+ const current = queue[index];
101
+ if (current.depth >= maxDepth) {
102
+ continue;
103
+ }
104
+ for (const adjacent of this.readBusinessAdjacency(current.reference, options.snapshotId, direction)) {
105
+ if (emittedRelations.has(adjacent.relationKey)
106
+ || (relationTypes !== undefined && !relationTypes.has(adjacent.relation.type))) {
107
+ continue;
108
+ }
109
+ emittedRelations.add(adjacent.relationKey);
110
+ const depth = current.depth + 1;
111
+ result.push({
112
+ depth,
113
+ direction: adjacent.direction,
114
+ relation: adjacent.relation,
115
+ node: adjacent.node,
116
+ });
117
+ if (!queuedNodes.has(adjacent.node.key)) {
118
+ queuedNodes.add(adjacent.node.key);
119
+ queue.push({
120
+ reference: { domain: "business", key: adjacent.node.key },
121
+ depth,
122
+ });
123
+ }
124
+ }
125
+ }
126
+ return result;
127
+ }
128
+ search(query, options) {
129
+ contentIdentifierSchema.parse(options.snapshotId);
130
+ const limit = options.limit ?? 20;
131
+ if (!Number.isInteger(limit) || limit < 1) {
132
+ throw new Error("Graph search limit must be a positive integer");
133
+ }
134
+ const terms = query.toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? [];
135
+ if (terms.length === 0) {
136
+ return [];
137
+ }
138
+ const rows = this.database.prepare(`
139
+ SELECT node_key, label, aliases, summary, symbols, paths
140
+ FROM atlas_graph_search
141
+ WHERE repository_id = ?
142
+ ORDER BY node_key ASC
143
+ `).all(this.#repositoryId);
144
+ return rows.flatMap((row) => {
145
+ const fields = [row.label, row.aliases, row.summary, row.symbols, row.paths]
146
+ .map((value) => value.toLowerCase());
147
+ if (!terms.every((term) => fields.some((field) => field.includes(term)))) {
148
+ return [];
149
+ }
150
+ const node = this.readBusinessNode(row.node_key, options.snapshotId);
151
+ if (node === undefined) {
152
+ return [];
153
+ }
154
+ return [{ score: lexicalScore(terms, fields), node }];
155
+ }).sort((left, right) => (right.score - left.score
156
+ || businessKeyOf(left.node).localeCompare(businessKeyOf(right.node)))).slice(0, limit);
157
+ }
158
+ close() {
159
+ this.#atlasDatabase.close();
160
+ }
161
+ [Symbol.dispose]() {
162
+ this.close();
163
+ }
164
+ get database() {
165
+ return this.#atlasDatabase.connection;
166
+ }
167
+ transaction(operation) {
168
+ this.database.exec("BEGIN IMMEDIATE");
169
+ try {
170
+ operation();
171
+ this.database.exec("COMMIT");
172
+ }
173
+ catch (error) {
174
+ this.database.exec("ROLLBACK");
175
+ throw error;
176
+ }
177
+ }
178
+ validateBusinessMutation(mutation) {
179
+ contentIdentifierSchema.parse(mutation.baseSnapshotId);
180
+ const upsertedKeys = new Set();
181
+ for (const node of mutation.upsertNodes) {
182
+ businessKeySchema.parse(node.key);
183
+ businessNodeKindSchema.parse(node.kind);
184
+ assertionCertaintySchema.parse(node.certainty);
185
+ if (node.label.length === 0 || node.summary.length === 0 || node.evidence.length === 0) {
186
+ throw new Error(`Business node ${node.key} requires a label, summary, and evidence`);
187
+ }
188
+ node.aliases.forEach((alias) => {
189
+ if (alias.length === 0) {
190
+ throw new Error(`Business node ${node.key} has an empty alias`);
191
+ }
192
+ });
193
+ node.evidence.forEach((evidence) => evidenceSchema.parse(publicEvidence(evidence)));
194
+ if (upsertedKeys.has(node.key)) {
195
+ throw new Error(`Duplicate business node upsert ${node.key}`);
196
+ }
197
+ upsertedKeys.add(node.key);
198
+ }
199
+ const removedKeys = new Set(mutation.removeNodeKeys);
200
+ mutation.removeNodeKeys.forEach((key) => businessKeySchema.parse(key));
201
+ for (const key of upsertedKeys) {
202
+ if (removedKeys.has(key)) {
203
+ throw new Error(`Business node ${key} cannot be removed and upserted together`);
204
+ }
205
+ }
206
+ mutation.removeRelations.forEach((relation) => this.validateBusinessRelation(relation));
207
+ mutation.upsertRelations.forEach((relation) => {
208
+ this.validateBusinessRelation(relation);
209
+ assertionCertaintySchema.parse(relation.certainty);
210
+ if (relation.evidence.length === 0) {
211
+ throw new Error("Business relations require evidence");
212
+ }
213
+ relation.evidence.forEach((evidence) => evidenceSchema.parse(publicEvidence(evidence)));
214
+ });
215
+ }
216
+ validateBusinessRelation(relation) {
217
+ businessKeySchema.parse(relation.from.key);
218
+ businessRelationTypeSchema.parse(relation.type);
219
+ if (relation.to.domain === "business") {
220
+ businessKeySchema.parse(relation.to.key);
221
+ }
222
+ else {
223
+ structuralNodeIdSchema.parse(relation.to.id);
224
+ }
225
+ const requiresStructuralTarget = relation.type === "realized_by" || relation.type === "verified_by";
226
+ const expectedDomain = requiresStructuralTarget ? "structural" : "business";
227
+ if (relation.to.domain !== expectedDomain) {
228
+ throw new Error(`${relation.type} relations require a ${expectedDomain} target`);
229
+ }
230
+ }
231
+ validateLocation(location) {
232
+ relativeSourcePathSchema.parse(location.file);
233
+ sourceRangeSchema.parse(location.range);
234
+ contentIdentifierSchema.parse(location.contentHash);
235
+ }
236
+ requireSnapshot(snapshotId) {
237
+ const row = this.database.prepare(`
238
+ SELECT payload
239
+ FROM atlas_repository_snapshots
240
+ WHERE repository_id = ? AND snapshot_id = ?
241
+ `).get(this.#repositoryId, snapshotId);
242
+ if (row === undefined) {
243
+ throw new Error(`Repository snapshot ${snapshotId} is not stored`);
244
+ }
245
+ return JSON.parse(row.payload);
246
+ }
247
+ upsertBusinessNode(baseSnapshotId, node) {
248
+ const snapshot = this.requireSnapshot(baseSnapshotId);
249
+ node.evidence.forEach((evidence) => this.requireEvidence(snapshot, evidence));
250
+ this.database.prepare(`
251
+ INSERT INTO atlas_business_nodes (
252
+ repository_id,
253
+ node_key,
254
+ base_snapshot_id,
255
+ kind,
256
+ label,
257
+ summary,
258
+ certainty
259
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
260
+ ON CONFLICT (repository_id, node_key) DO UPDATE SET
261
+ base_snapshot_id = excluded.base_snapshot_id,
262
+ kind = excluded.kind,
263
+ label = excluded.label,
264
+ summary = excluded.summary,
265
+ certainty = excluded.certainty
266
+ `).run(this.#repositoryId, node.key, baseSnapshotId, node.kind, node.label, node.summary, node.certainty);
267
+ const nodeId = this.requireBusinessNodeId(node.key);
268
+ this.database.prepare("DELETE FROM atlas_business_node_aliases WHERE node_id = ?").run(nodeId);
269
+ this.database.prepare("DELETE FROM atlas_business_node_evidence WHERE node_id = ?").run(nodeId);
270
+ node.aliases.forEach((alias, position) => {
271
+ this.database.prepare(`
272
+ INSERT INTO atlas_business_node_aliases (node_id, position, alias)
273
+ VALUES (?, ?, ?)
274
+ `).run(nodeId, position, alias);
275
+ });
276
+ node.evidence.forEach((evidence, position) => {
277
+ this.insertNodeEvidence(nodeId, position, evidence);
278
+ });
279
+ this.database.prepare(`
280
+ INSERT INTO atlas_graph_search (
281
+ repository_id,
282
+ node_key,
283
+ label,
284
+ aliases,
285
+ summary,
286
+ symbols,
287
+ paths
288
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
289
+ ON CONFLICT (repository_id, node_key) DO UPDATE SET
290
+ label = excluded.label,
291
+ aliases = excluded.aliases,
292
+ summary = excluded.summary,
293
+ symbols = excluded.symbols,
294
+ paths = excluded.paths
295
+ `).run(this.#repositoryId, node.key, node.label, node.aliases.join(" "), node.summary, node.evidence.map((evidence) => evidence.symbolId).join(" "), node.evidence.map((evidence) => evidence.file).join(" "));
296
+ }
297
+ upsertBusinessRelation(baseSnapshotId, relation) {
298
+ const snapshot = this.requireSnapshot(baseSnapshotId);
299
+ relation.evidence.forEach((evidence) => this.requireEvidence(snapshot, evidence));
300
+ this.requireBusinessNodeId(relation.from.key);
301
+ if (relation.to.domain === "business") {
302
+ this.requireBusinessNodeId(relation.to.key);
303
+ }
304
+ const targetKey = relation.to.domain === "business" ? relation.to.key : relation.to.id;
305
+ const target = relation.to.domain === "structural"
306
+ ? readStructuralTargetBinding(relation) ?? inferredStructuralTarget(relation, baseSnapshotId)
307
+ : undefined;
308
+ this.database.prepare(`
309
+ INSERT INTO atlas_business_relations (
310
+ repository_id,
311
+ base_snapshot_id,
312
+ from_key,
313
+ relation_type,
314
+ to_domain,
315
+ to_key,
316
+ certainty,
317
+ target_file,
318
+ target_qualified_symbol,
319
+ target_structural_kind,
320
+ target_start_line,
321
+ target_start_column,
322
+ target_end_line,
323
+ target_end_column,
324
+ target_atlas_snapshot_id,
325
+ target_backend_version,
326
+ target_backend_locator,
327
+ target_binding_status
328
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
329
+ ON CONFLICT (repository_id, from_key, relation_type, to_domain, to_key)
330
+ DO UPDATE SET
331
+ base_snapshot_id = excluded.base_snapshot_id,
332
+ certainty = excluded.certainty,
333
+ target_file = excluded.target_file,
334
+ target_qualified_symbol = excluded.target_qualified_symbol,
335
+ target_structural_kind = excluded.target_structural_kind,
336
+ target_start_line = excluded.target_start_line,
337
+ target_start_column = excluded.target_start_column,
338
+ target_end_line = excluded.target_end_line,
339
+ target_end_column = excluded.target_end_column,
340
+ target_atlas_snapshot_id = excluded.target_atlas_snapshot_id,
341
+ target_backend_version = excluded.target_backend_version,
342
+ target_backend_locator = excluded.target_backend_locator,
343
+ target_binding_status = excluded.target_binding_status
344
+ `).run(this.#repositoryId, baseSnapshotId, relation.from.key, relation.type, relation.to.domain, targetKey, relation.certainty, target?.file ?? null, target?.qualifiedSymbol ?? null, target?.structuralKind ?? null, target?.range.start.line ?? null, target?.range.start.column ?? null, target?.range.end.line ?? null, target?.range.end.column ?? null, target?.atlasSnapshotId ?? null, target?.backendVersion ?? null, target?.backendLocator ?? null, target === undefined ? "unresolved" : "bound");
345
+ const stored = this.findBusinessRelation(relation);
346
+ if (stored === undefined) {
347
+ throw new Error("Business relation was not stored");
348
+ }
349
+ this.database.prepare(`
350
+ DELETE FROM atlas_business_relation_evidence
351
+ WHERE relation_id = ?
352
+ `).run(stored.relation_id);
353
+ relation.evidence.forEach((evidence, position) => {
354
+ this.insertRelationEvidence(stored.relation_id, position, evidence);
355
+ });
356
+ }
357
+ removeBusinessNode(key) {
358
+ this.requireBusinessNodeId(key);
359
+ const relation = this.database.prepare(`
360
+ SELECT relation_id
361
+ FROM atlas_business_relations
362
+ WHERE repository_id = ?
363
+ AND (from_key = ? OR (to_domain = 'business' AND to_key = ?))
364
+ LIMIT 1
365
+ `).get(this.#repositoryId, key, key);
366
+ if (relation !== undefined) {
367
+ throw new Error(`Business node ${key} is still referenced by a relation`);
368
+ }
369
+ this.database.prepare(`
370
+ DELETE FROM atlas_business_nodes
371
+ WHERE repository_id = ? AND node_key = ?
372
+ `).run(this.#repositoryId, key);
373
+ }
374
+ removeBusinessRelation(selector) {
375
+ this.requireBusinessNodeId(selector.from.key);
376
+ if (selector.to.domain === "business") {
377
+ this.requireBusinessNodeId(selector.to.key);
378
+ }
379
+ const relation = this.findBusinessRelation(selector);
380
+ if (relation !== undefined) {
381
+ this.database.prepare("DELETE FROM atlas_business_relations WHERE relation_id = ?")
382
+ .run(relation.relation_id);
383
+ }
384
+ }
385
+ insertNodeEvidence(nodeId, position, evidence) {
386
+ this.database.prepare(`
387
+ INSERT INTO atlas_business_node_evidence (
388
+ node_id,
389
+ position,
390
+ structural_reference,
391
+ file,
392
+ start_line,
393
+ start_column,
394
+ end_line,
395
+ end_column,
396
+ content_hash,
397
+ qualified_symbol,
398
+ structural_kind,
399
+ atlas_snapshot_id,
400
+ backend_version,
401
+ backend_locator,
402
+ binding_status
403
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'bound')
404
+ `).run(nodeId, position, evidence.symbolId, evidence.file, evidence.range.start.line, evidence.range.start.column, evidence.range.end.line, evidence.range.end.column, evidence.contentHash, evidence.qualifiedSymbol ?? null, evidence.structuralKind ?? null, evidence.atlasSnapshotId ?? null, evidence.backendVersion ?? null, evidence.backendLocator ?? null);
405
+ }
406
+ insertRelationEvidence(relationId, position, evidence) {
407
+ this.database.prepare(`
408
+ INSERT INTO atlas_business_relation_evidence (
409
+ relation_id,
410
+ position,
411
+ structural_reference,
412
+ file,
413
+ start_line,
414
+ start_column,
415
+ end_line,
416
+ end_column,
417
+ content_hash,
418
+ qualified_symbol,
419
+ structural_kind,
420
+ atlas_snapshot_id,
421
+ backend_version,
422
+ backend_locator,
423
+ binding_status
424
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'bound')
425
+ `).run(relationId, position, evidence.symbolId, evidence.file, evidence.range.start.line, evidence.range.start.column, evidence.range.end.line, evidence.range.end.column, evidence.contentHash, evidence.qualifiedSymbol ?? null, evidence.structuralKind ?? null, evidence.atlasSnapshotId ?? null, evidence.backendVersion ?? null, evidence.backendLocator ?? null);
426
+ }
427
+ requireEvidence(snapshot, evidence) {
428
+ this.validateLocation(evidence);
429
+ if (!evidenceMatchesSnapshot(evidence, snapshot)) {
430
+ throw new Error(`Evidence ${evidence.symbolId} at ${evidence.file} does not match snapshot ${snapshot.snapshotId}`);
431
+ }
432
+ }
433
+ refreshAllBusinessValidity() {
434
+ const snapshots = this.database.prepare(`
435
+ SELECT payload
436
+ FROM atlas_repository_snapshots
437
+ WHERE repository_id = ?
438
+ ORDER BY snapshot_id ASC
439
+ `).all(this.#repositoryId);
440
+ for (const { payload } of snapshots) {
441
+ this.refreshBusinessValidity(JSON.parse(payload));
442
+ }
443
+ }
444
+ refreshBusinessValidity(snapshot) {
445
+ const nodeRows = this.database.prepare(`
446
+ SELECT node_id
447
+ FROM atlas_business_nodes
448
+ WHERE repository_id = ?
449
+ `).all(this.#repositoryId);
450
+ for (const { node_id } of nodeRows) {
451
+ const validity = allEvidenceMatches(this.readNodeEvidenceRows(node_id), snapshot)
452
+ ? "valid"
453
+ : "stale";
454
+ this.database.prepare(`
455
+ INSERT INTO atlas_business_node_validity (
456
+ node_id,
457
+ repository_id,
458
+ snapshot_id,
459
+ validity
460
+ ) VALUES (?, ?, ?, ?)
461
+ ON CONFLICT (node_id, snapshot_id) DO UPDATE SET
462
+ validity = excluded.validity
463
+ `).run(node_id, this.#repositoryId, snapshot.snapshotId, validity);
464
+ }
465
+ const relationRows = this.database.prepare(`
466
+ SELECT relation_id, to_domain, target_binding_status
467
+ FROM atlas_business_relations
468
+ WHERE repository_id = ?
469
+ `).all(this.#repositoryId);
470
+ for (const relation of relationRows) {
471
+ const targetIsBound = relation.to_domain === "business"
472
+ || relation.target_binding_status === "bound";
473
+ const validity = targetIsBound
474
+ && allEvidenceMatches(this.readRelationEvidenceRows(relation.relation_id), snapshot)
475
+ ? "valid"
476
+ : "stale";
477
+ this.database.prepare(`
478
+ INSERT INTO atlas_business_relation_validity (
479
+ relation_id,
480
+ repository_id,
481
+ snapshot_id,
482
+ validity
483
+ ) VALUES (?, ?, ?, ?)
484
+ ON CONFLICT (relation_id, snapshot_id) DO UPDATE SET
485
+ validity = excluded.validity
486
+ `).run(relation.relation_id, this.#repositoryId, snapshot.snapshotId, validity);
487
+ }
488
+ }
489
+ readBusinessNode(key, snapshotId) {
490
+ const row = this.database.prepare(`
491
+ SELECT
492
+ node.node_id,
493
+ node.base_snapshot_id,
494
+ node.kind,
495
+ node.label,
496
+ node.summary,
497
+ node.certainty,
498
+ COALESCE(validity.validity, 'stale') AS validity
499
+ FROM atlas_business_nodes AS node
500
+ LEFT JOIN atlas_business_node_validity AS validity
501
+ ON validity.node_id = node.node_id
502
+ AND validity.snapshot_id = ?
503
+ WHERE node.repository_id = ? AND node.node_key = ?
504
+ `).get(snapshotId, this.#repositoryId, key);
505
+ if (row === undefined) {
506
+ return undefined;
507
+ }
508
+ const aliases = this.database.prepare(`
509
+ SELECT alias
510
+ FROM atlas_business_node_aliases
511
+ WHERE node_id = ?
512
+ ORDER BY position ASC
513
+ `).all(row.node_id);
514
+ return {
515
+ domain: "business",
516
+ key,
517
+ kind: row.kind,
518
+ label: row.label,
519
+ summary: row.summary,
520
+ aliases: aliases.map(({ alias }) => alias),
521
+ certainty: row.certainty,
522
+ validity: row.validity,
523
+ evidence: this.readNodeEvidence(row.node_id),
524
+ baseSnapshotId: row.base_snapshot_id,
525
+ };
526
+ }
527
+ readNodeEvidence(nodeId) {
528
+ return this.readNodeEvidenceRows(nodeId).map(evidenceFromRow);
529
+ }
530
+ readNodeEvidenceRows(nodeId) {
531
+ return this.database.prepare(`
532
+ SELECT
533
+ structural_reference,
534
+ file,
535
+ start_line,
536
+ start_column,
537
+ end_line,
538
+ end_column,
539
+ content_hash,
540
+ qualified_symbol,
541
+ structural_kind,
542
+ atlas_snapshot_id,
543
+ backend_version,
544
+ backend_locator,
545
+ binding_status
546
+ FROM atlas_business_node_evidence
547
+ WHERE node_id = ?
548
+ ORDER BY position ASC
549
+ `).all(nodeId);
550
+ }
551
+ readRelationEvidence(relationId) {
552
+ return this.readRelationEvidenceRows(relationId).map(evidenceFromRow);
553
+ }
554
+ readRelationEvidenceRows(relationId) {
555
+ return this.database.prepare(`
556
+ SELECT
557
+ structural_reference,
558
+ file,
559
+ start_line,
560
+ start_column,
561
+ end_line,
562
+ end_column,
563
+ content_hash,
564
+ qualified_symbol,
565
+ structural_kind,
566
+ atlas_snapshot_id,
567
+ backend_version,
568
+ backend_locator,
569
+ binding_status
570
+ FROM atlas_business_relation_evidence
571
+ WHERE relation_id = ?
572
+ ORDER BY position ASC
573
+ `).all(relationId);
574
+ }
575
+ readBusinessRelations(snapshotId) {
576
+ return this.database.prepare(`
577
+ SELECT
578
+ relation.relation_id,
579
+ relation.base_snapshot_id,
580
+ relation.from_key,
581
+ relation.relation_type,
582
+ relation.to_domain,
583
+ relation.to_key,
584
+ relation.certainty,
585
+ COALESCE(validity.validity, 'stale') AS validity
586
+ FROM atlas_business_relations AS relation
587
+ LEFT JOIN atlas_business_relation_validity AS validity
588
+ ON validity.relation_id = relation.relation_id
589
+ AND validity.snapshot_id = ?
590
+ WHERE relation.repository_id = ?
591
+ ORDER BY relation.from_key, relation.relation_type, relation.to_domain, relation.to_key
592
+ `).all(snapshotId, this.#repositoryId);
593
+ }
594
+ relationFromRow(row) {
595
+ return {
596
+ domain: "business",
597
+ from: { domain: "business", key: row.from_key },
598
+ type: row.relation_type,
599
+ to: row.to_domain === "business"
600
+ ? { domain: "business", key: row.to_key }
601
+ : { domain: "structural", id: row.to_key },
602
+ baseSnapshotId: row.base_snapshot_id,
603
+ certainty: row.certainty,
604
+ validity: row.validity,
605
+ evidence: this.readRelationEvidence(row.relation_id),
606
+ };
607
+ }
608
+ readBusinessAdjacency(reference, snapshotId, direction) {
609
+ const directions = direction === "both" ? ["outgoing", "incoming"] : [direction];
610
+ const adjacency = [];
611
+ for (const currentDirection of directions) {
612
+ for (const row of this.readBusinessRelations(snapshotId)) {
613
+ const isAdjacent = currentDirection === "outgoing"
614
+ ? row.from_key === reference.key && row.to_domain === "business"
615
+ : row.to_domain === "business" && row.to_key === reference.key;
616
+ if (!isAdjacent) {
617
+ continue;
618
+ }
619
+ const otherKey = currentDirection === "outgoing" ? row.to_key : row.from_key;
620
+ const node = this.readBusinessNode(otherKey, snapshotId);
621
+ if (node === undefined) {
622
+ continue;
623
+ }
624
+ adjacency.push({
625
+ relationKey: `business:${row.relation_id}`,
626
+ direction: currentDirection,
627
+ relation: this.relationFromRow(row),
628
+ node,
629
+ });
630
+ }
631
+ }
632
+ return adjacency.sort((left, right) => (left.relation.type.localeCompare(right.relation.type)
633
+ || left.node.key.localeCompare(right.node.key)));
634
+ }
635
+ findBusinessRelation(selector) {
636
+ const targetKey = selector.to.domain === "business" ? selector.to.key : selector.to.id;
637
+ return this.database.prepare(`
638
+ SELECT relation_id
639
+ FROM atlas_business_relations
640
+ WHERE repository_id = ?
641
+ AND from_key = ?
642
+ AND relation_type = ?
643
+ AND to_domain = ?
644
+ AND to_key = ?
645
+ `).get(this.#repositoryId, selector.from.key, selector.type, selector.to.domain, targetKey);
646
+ }
647
+ findBusinessNodeId(key) {
648
+ const row = this.database.prepare(`
649
+ SELECT node_id
650
+ FROM atlas_business_nodes
651
+ WHERE repository_id = ? AND node_key = ?
652
+ `).get(this.#repositoryId, key);
653
+ return row?.node_id;
654
+ }
655
+ requireBusinessNodeId(key) {
656
+ const nodeId = this.findBusinessNodeId(key);
657
+ if (nodeId === undefined) {
658
+ throw new Error(`Business relation endpoint ${key} is missing`);
659
+ }
660
+ return nodeId;
661
+ }
662
+ }
663
+ function evidenceFromRow(row) {
664
+ return {
665
+ symbolId: row.structural_reference,
666
+ file: row.file,
667
+ range: {
668
+ start: { line: row.start_line, column: row.start_column },
669
+ end: { line: row.end_line, column: row.end_column },
670
+ },
671
+ contentHash: row.content_hash,
672
+ };
673
+ }
674
+ function publicEvidence(evidence) {
675
+ return {
676
+ symbolId: evidence.symbolId,
677
+ file: evidence.file,
678
+ range: evidence.range,
679
+ contentHash: evidence.contentHash,
680
+ };
681
+ }
682
+ function evidenceMatchesSnapshot(evidence, snapshot) {
683
+ return snapshot.files.some((file) => (file.path === evidence.file
684
+ && file.worktree?.contentHash === evidence.contentHash));
685
+ }
686
+ function allEvidenceMatches(rows, snapshot) {
687
+ return rows.length > 0 && rows.every((row) => (row.binding_status === "bound"
688
+ && evidenceMatchesSnapshot(evidenceFromRow(row), snapshot)));
689
+ }
690
+ function inferredStructuralTarget(relation, snapshotId) {
691
+ if (relation.to.domain !== "structural") {
692
+ return undefined;
693
+ }
694
+ const targetReference = relation.to.id;
695
+ const matchingEvidence = relation.evidence.find((item) => item.symbolId === targetReference);
696
+ if (matchingEvidence === undefined) {
697
+ return undefined;
698
+ }
699
+ const storedEvidence = matchingEvidence;
700
+ return {
701
+ structuralReference: targetReference,
702
+ file: matchingEvidence.file,
703
+ qualifiedSymbol: storedEvidence.qualifiedSymbol ?? null,
704
+ structuralKind: storedEvidence.structuralKind ?? null,
705
+ range: matchingEvidence.range,
706
+ atlasSnapshotId: storedEvidence.atlasSnapshotId ?? snapshotId,
707
+ backendVersion: storedEvidence.backendVersion ?? null,
708
+ backendLocator: storedEvidence.backendLocator ?? null,
709
+ };
710
+ }
711
+ function lexicalScore(terms, fields) {
712
+ const weights = [10, 8, 4, 6, 5];
713
+ const score = terms.reduce((total, term) => total + fields.reduce((fieldTotal, field, index) => fieldTotal + (field.includes(term) ? weights[index] : 0), 0), 0);
714
+ return score / (score + 1);
715
+ }
716
+ function businessKeyOf(node) {
717
+ return node.domain === "business" ? node.key : node.id;
718
+ }
719
+ export { CURRENT_ATLAS_SCHEMA_VERSION };