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,40 @@
1
+ import type { GitRepository } from "../repository/types.js";
2
+ import type { RepositorySnapshot } from "../snapshots/types.js";
3
+ import type { CurrentWorldSnapshot, SemanticGraphChangeOptions, SemanticGraphChanges, StructuralEvidenceResolver, WorldPublicationMetadata, WorldSnapshotState } from "./types.js";
4
+ interface ReconciliationResult {
5
+ readonly staleAssertions: readonly string[];
6
+ }
7
+ export declare class WorldSnapshotStore implements Disposable {
8
+ #private;
9
+ constructor(repository: GitRepository);
10
+ readState(): WorldSnapshotState;
11
+ begin(targetSnapshotId: string): void;
12
+ publish(snapshot: RepositorySnapshot, backendVersion: string, extractionVersion: number | null, resolver: StructuralEvidenceResolver, changes: Omit<WorldPublicationMetadata, "staleAssertions">): ReconciliationResult;
13
+ fail(targetSnapshotId: string, error: unknown): void;
14
+ requireCurrentSnapshot(): RepositorySnapshot;
15
+ requireCurrentWorld(): CurrentWorldSnapshot;
16
+ readSemanticChanges(options?: SemanticGraphChangeOptions): SemanticGraphChanges | undefined;
17
+ private readCurrentPublication;
18
+ private readPublication;
19
+ private requirePublication;
20
+ private readPreviousPublication;
21
+ private findPublication;
22
+ private readSnapshot;
23
+ close(): void;
24
+ [Symbol.dispose](): void;
25
+ private get connection();
26
+ private transaction;
27
+ private requireBuildingSnapshot;
28
+ private saveSnapshot;
29
+ private rebindEvidence;
30
+ private assertionIdentity;
31
+ private rebindEvidenceTable;
32
+ private rebindStructuralRelationTargets;
33
+ private resolveEvidence;
34
+ private resolveStructuralLocator;
35
+ private refreshValidity;
36
+ private refreshValidityTable;
37
+ private saveWorldPublication;
38
+ }
39
+ export {};
40
+ //# sourceMappingURL=world-snapshot-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"world-snapshot-store.d.ts","sourceRoot":"","sources":["../../src/world/world-snapshot-store.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAEhE,OAAO,KAAK,EACV,oBAAoB,EAEpB,0BAA0B,EAC1B,oBAAoB,EACpB,0BAA0B,EAE1B,wBAAwB,EACxB,kBAAkB,EACnB,MAAM,YAAY,CAAC;AAmBpB,UAAU,oBAAoB;IAC5B,QAAQ,CAAC,eAAe,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7C;AAwBD,qBAAa,kBAAmB,YAAW,UAAU;;gBAIvC,UAAU,EAAE,aAAa;IAKrC,SAAS,IAAI,kBAAkB;IAsC/B,KAAK,CAAC,gBAAgB,EAAE,MAAM,GAAG,IAAI;IAmBrC,OAAO,CACL,QAAQ,EAAE,kBAAkB,EAC5B,cAAc,EAAE,MAAM,EACtB,iBAAiB,EAAE,MAAM,GAAG,IAAI,EAChC,QAAQ,EAAE,0BAA0B,EACpC,OAAO,EAAE,IAAI,CAAC,wBAAwB,EAAE,iBAAiB,CAAC,GACzD,oBAAoB;IAgEvB,IAAI,CAAC,gBAAgB,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;IAmBpD,sBAAsB,IAAI,kBAAkB;IAI5C,mBAAmB,IAAI,oBAAoB;IAuB3C,mBAAmB,CAAC,OAAO,GAAE,0BAA+B,GAAG,oBAAoB,GAAG,SAAS;IAgD/F,OAAO,CAAC,sBAAsB;IAW9B,OAAO,CAAC,eAAe;IAYvB,OAAO,CAAC,kBAAkB;IAQ1B,OAAO,CAAC,uBAAuB;IAe/B,OAAO,CAAC,eAAe;IAqBvB,OAAO,CAAC,YAAY;IAYpB,KAAK,IAAI,IAAI;IAIb,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,IAAI;IAIxB,OAAO,KAAK,UAAU,GAErB;IAED,OAAO,CAAC,WAAW;IAWnB,OAAO,CAAC,uBAAuB;IAO/B,OAAO,CAAC,YAAY;IAmBpB,OAAO,CAAC,cAAc;IA8BtB,OAAO,CAAC,iBAAiB;IAsBzB,OAAO,CAAC,mBAAmB;IAoE3B,OAAO,CAAC,+BAA+B;IAuEvC,OAAO,CAAC,eAAe;IAOvB,OAAO,CAAC,wBAAwB;IAehC,OAAO,CAAC,eAAe;IAiBvB,OAAO,CAAC,oBAAoB;IA+C5B,OAAO,CAAC,oBAAoB;CA4B7B"}
@@ -0,0 +1,555 @@
1
+ import { contentIdentifierSchema } from "../contracts/identifiers.js";
2
+ import { isSupportedSource } from "../repository/repository-inspector.js";
3
+ import { AtlasDatabase } from "../storage/atlas-database.js";
4
+ export class WorldSnapshotStore {
5
+ #database;
6
+ #repositoryId;
7
+ constructor(repository) {
8
+ this.#database = new AtlasDatabase(repository);
9
+ this.#repositoryId = repository.repositoryId;
10
+ }
11
+ readState() {
12
+ const row = this.connection.prepare(`
13
+ SELECT
14
+ status,
15
+ current_snapshot_id,
16
+ target_snapshot_id,
17
+ backend_version,
18
+ extraction_version,
19
+ failure_message,
20
+ started_at,
21
+ published_at,
22
+ updated_at
23
+ FROM atlas_world_state
24
+ WHERE repository_id = ?
25
+ `).get(this.#repositoryId);
26
+ return {
27
+ status: row.status,
28
+ currentSnapshotId: row.current_snapshot_id,
29
+ targetSnapshotId: row.target_snapshot_id,
30
+ backendVersion: row.backend_version,
31
+ extractionVersion: row.extraction_version,
32
+ failureMessage: row.failure_message,
33
+ startedAt: row.started_at,
34
+ publishedAt: row.published_at,
35
+ updatedAt: row.updated_at,
36
+ };
37
+ }
38
+ begin(targetSnapshotId) {
39
+ const timestamp = new Date().toISOString();
40
+ const state = this.readState();
41
+ if (state.status === "building" && state.targetSnapshotId === targetSnapshotId) {
42
+ return;
43
+ }
44
+ this.connection.prepare(`
45
+ UPDATE atlas_world_state
46
+ SET
47
+ status = 'building',
48
+ target_snapshot_id = ?,
49
+ failure_message = NULL,
50
+ started_at = ?,
51
+ published_at = NULL,
52
+ updated_at = ?
53
+ WHERE repository_id = ?
54
+ `).run(targetSnapshotId, timestamp, timestamp, this.#repositoryId);
55
+ }
56
+ publish(snapshot, backendVersion, extractionVersion, resolver, changes) {
57
+ let result;
58
+ this.transaction(() => {
59
+ this.requireBuildingSnapshot(snapshot.snapshotId);
60
+ const previousPublication = this.readCurrentPublication();
61
+ const previousSnapshotId = previousPublication?.snapshot_id ?? null;
62
+ if (changes.fromSnapshotId !== previousSnapshotId) {
63
+ throw new Error(`World publication starts at ${changes.fromSnapshotId ?? "no snapshot"}, ` +
64
+ `but the current publication is ${previousSnapshotId ?? "missing"}`);
65
+ }
66
+ if (changes.toSnapshotId !== snapshot.snapshotId) {
67
+ throw new Error(`World publication target ${changes.toSnapshotId} does not match ` +
68
+ `the active snapshot ${snapshot.snapshotId}`);
69
+ }
70
+ this.saveSnapshot(snapshot);
71
+ const staleAssertions = this.rebindEvidence(snapshot, backendVersion, resolver);
72
+ staleAssertions.push(...this.rebindStructuralRelationTargets(snapshot, backendVersion, resolver));
73
+ const uniqueStaleAssertions = [...new Set(staleAssertions)].sort();
74
+ this.refreshValidity(snapshot.snapshotId);
75
+ const timestamp = new Date().toISOString();
76
+ const publicationId = this.saveWorldPublication(previousPublication?.publication_id ?? null, { ...changes, staleAssertions: uniqueStaleAssertions }, timestamp);
77
+ this.connection.prepare(`
78
+ UPDATE atlas_world_state
79
+ SET
80
+ status = 'current',
81
+ current_snapshot_id = ?,
82
+ current_publication_id = ?,
83
+ target_snapshot_id = NULL,
84
+ backend_version = ?,
85
+ extraction_version = ?,
86
+ failure_message = NULL,
87
+ published_at = ?,
88
+ updated_at = ?
89
+ WHERE repository_id = ?
90
+ `).run(snapshot.snapshotId, publicationId, backendVersion, extractionVersion, timestamp, timestamp, this.#repositoryId);
91
+ result = { staleAssertions: uniqueStaleAssertions };
92
+ });
93
+ return result;
94
+ }
95
+ fail(targetSnapshotId, error) {
96
+ const timestamp = new Date().toISOString();
97
+ this.connection.prepare(`
98
+ UPDATE atlas_world_state
99
+ SET
100
+ status = 'failed',
101
+ target_snapshot_id = ?,
102
+ failure_message = ?,
103
+ published_at = NULL,
104
+ updated_at = ?
105
+ WHERE repository_id = ?
106
+ `).run(targetSnapshotId, error instanceof Error ? error.message : String(error), timestamp, this.#repositoryId);
107
+ }
108
+ requireCurrentSnapshot() {
109
+ return this.requireCurrentWorld().snapshot;
110
+ }
111
+ requireCurrentWorld() {
112
+ const state = this.readState();
113
+ if (state.status !== "current" || state.currentSnapshotId === null) {
114
+ throw new Error(`World snapshot is ${state.status} and cannot serve map queries`);
115
+ }
116
+ const publication = this.readCurrentPublication();
117
+ if (publication === undefined || publication.snapshot_id !== state.currentSnapshotId) {
118
+ throw new Error("The current world publication is inconsistent with its snapshot");
119
+ }
120
+ const row = this.connection.prepare(`
121
+ SELECT payload
122
+ FROM atlas_repository_snapshots
123
+ WHERE repository_id = ? AND snapshot_id = ?
124
+ `).get(this.#repositoryId, state.currentSnapshotId);
125
+ if (row === undefined) {
126
+ throw new Error("The current world snapshot record is missing");
127
+ }
128
+ return {
129
+ publicationId: publication.publication_id,
130
+ snapshot: JSON.parse(row.payload),
131
+ };
132
+ }
133
+ readSemanticChanges(options = {}) {
134
+ const requestedStart = options.fromSnapshotId === undefined
135
+ ? undefined
136
+ : contentIdentifierSchema.parse(options.fromSnapshotId);
137
+ const requestedTarget = options.toSnapshotId === undefined
138
+ ? undefined
139
+ : contentIdentifierSchema.parse(options.toSnapshotId);
140
+ const currentPublication = this.readCurrentPublication();
141
+ if (currentPublication === undefined) {
142
+ return undefined;
143
+ }
144
+ const targetPublication = requestedTarget === undefined
145
+ ? currentPublication
146
+ : this.findPublication(currentPublication, requestedTarget);
147
+ if (targetPublication === undefined) {
148
+ return undefined;
149
+ }
150
+ const target = targetPublication.snapshot_id;
151
+ const previousPublication = this.readPreviousPublication(targetPublication);
152
+ const startPublication = requestedStart === undefined
153
+ ? previousPublication
154
+ : requestedStart === target
155
+ ? targetPublication
156
+ : previousPublication === undefined
157
+ ? undefined
158
+ : this.findPublication(previousPublication, requestedStart);
159
+ if (startPublication === undefined) {
160
+ if (requestedStart !== undefined) {
161
+ throw new Error(`No persisted semantic transition connects ${requestedStart} to ${target}`);
162
+ }
163
+ return undefined;
164
+ }
165
+ const start = startPublication.snapshot_id;
166
+ const nodes = compareSnapshotContents(this.readSnapshot(start), this.readSnapshot(target));
167
+ return {
168
+ fromSnapshotId: start,
169
+ toSnapshotId: target,
170
+ nodes,
171
+ relations: { added: [], changed: [], removed: [] },
172
+ staleAssertions: parseStringArray(targetPublication.stale_assertions),
173
+ };
174
+ }
175
+ readCurrentPublication() {
176
+ const row = this.connection.prepare(`
177
+ SELECT current_publication_id
178
+ FROM atlas_world_state
179
+ WHERE repository_id = ?
180
+ `).get(this.#repositoryId);
181
+ return row.current_publication_id === null
182
+ ? undefined
183
+ : this.requirePublication(row.current_publication_id);
184
+ }
185
+ readPublication(publicationId) {
186
+ return this.connection.prepare(`
187
+ SELECT
188
+ publication_id,
189
+ previous_publication_id,
190
+ snapshot_id,
191
+ stale_assertions
192
+ FROM atlas_world_publications
193
+ WHERE repository_id = ? AND publication_id = ?
194
+ `).get(this.#repositoryId, publicationId);
195
+ }
196
+ requirePublication(publicationId) {
197
+ const publication = this.readPublication(publicationId);
198
+ if (publication === undefined) {
199
+ throw new Error(`World publication ${publicationId} is not stored`);
200
+ }
201
+ return publication;
202
+ }
203
+ readPreviousPublication(publication) {
204
+ const previousPublicationId = publication.previous_publication_id;
205
+ if (previousPublicationId === null) {
206
+ return undefined;
207
+ }
208
+ if (previousPublicationId === publication.publication_id) {
209
+ throw new Error(`Persisted world publication chain contains a cycle at ${publication.publication_id}`);
210
+ }
211
+ return this.requirePublication(previousPublicationId);
212
+ }
213
+ findPublication(target, snapshotId) {
214
+ const visitedPublications = new Set();
215
+ let publication = target;
216
+ while (publication !== undefined) {
217
+ if (visitedPublications.has(publication.publication_id)) {
218
+ throw new Error(`Persisted world publication chain contains a cycle at ${publication.publication_id}`);
219
+ }
220
+ visitedPublications.add(publication.publication_id);
221
+ if (publication.snapshot_id === snapshotId) {
222
+ return publication;
223
+ }
224
+ publication = this.readPreviousPublication(publication);
225
+ }
226
+ return undefined;
227
+ }
228
+ readSnapshot(snapshotId) {
229
+ const row = this.connection.prepare(`
230
+ SELECT payload
231
+ FROM atlas_repository_snapshots
232
+ WHERE repository_id = ? AND snapshot_id = ?
233
+ `).get(this.#repositoryId, snapshotId);
234
+ if (row === undefined) {
235
+ throw new Error(`Repository snapshot ${snapshotId} is not stored`);
236
+ }
237
+ return JSON.parse(row.payload);
238
+ }
239
+ close() {
240
+ this.#database.close();
241
+ }
242
+ [Symbol.dispose]() {
243
+ this.close();
244
+ }
245
+ get connection() {
246
+ return this.#database.connection;
247
+ }
248
+ transaction(operation) {
249
+ this.connection.exec("BEGIN IMMEDIATE");
250
+ try {
251
+ operation();
252
+ this.connection.exec("COMMIT");
253
+ }
254
+ catch (error) {
255
+ this.connection.exec("ROLLBACK");
256
+ throw error;
257
+ }
258
+ }
259
+ requireBuildingSnapshot(snapshotId) {
260
+ const state = this.readState();
261
+ if (state.status !== "building" || state.targetSnapshotId !== snapshotId) {
262
+ throw new Error(`World snapshot ${snapshotId} is not the active build target`);
263
+ }
264
+ }
265
+ saveSnapshot(snapshot) {
266
+ const timestamp = new Date().toISOString();
267
+ this.connection.prepare(`
268
+ INSERT INTO atlas_repository_snapshots (
269
+ repository_id,
270
+ snapshot_id,
271
+ payload,
272
+ created_at
273
+ ) VALUES (?, ?, ?, ?)
274
+ ON CONFLICT (repository_id, snapshot_id) DO UPDATE SET
275
+ payload = excluded.payload
276
+ `).run(this.#repositoryId, snapshot.snapshotId, JSON.stringify(snapshot), timestamp);
277
+ this.connection.prepare(`
278
+ UPDATE atlas_repositories
279
+ SET latest_snapshot_id = ?, updated_at = ?
280
+ WHERE repository_id = ?
281
+ `).run(snapshot.snapshotId, timestamp, this.#repositoryId);
282
+ }
283
+ rebindEvidence(snapshot, backendVersion, resolver) {
284
+ const staleAssertions = [];
285
+ const bindings = [
286
+ ...this.rebindEvidenceTable("atlas_business_node_evidence", "node_id", snapshot, backendVersion, resolver),
287
+ ...this.rebindEvidenceTable("atlas_business_relation_evidence", "relation_id", snapshot, backendVersion, resolver),
288
+ ];
289
+ for (const binding of bindings) {
290
+ if (binding.status !== "bound") {
291
+ staleAssertions.push(this.assertionIdentity(binding.ownerType, binding.ownerId));
292
+ }
293
+ }
294
+ return [...new Set(staleAssertions)].sort();
295
+ }
296
+ assertionIdentity(ownerType, ownerId) {
297
+ if (ownerType === "node") {
298
+ const row = this.connection.prepare(`
299
+ SELECT node_key
300
+ FROM atlas_business_nodes
301
+ WHERE node_id = ?
302
+ `).get(ownerId);
303
+ return row.node_key;
304
+ }
305
+ const row = this.connection.prepare(`
306
+ SELECT from_key, relation_type, to_domain, to_key
307
+ FROM atlas_business_relations
308
+ WHERE relation_id = ?
309
+ `).get(ownerId);
310
+ return `${row.from_key}:${row.relation_type}:${row.to_domain}:${row.to_key}`;
311
+ }
312
+ rebindEvidenceTable(table, ownerColumn, snapshot, backendVersion, resolver) {
313
+ const rows = this.connection.prepare(`
314
+ SELECT
315
+ ${ownerColumn} AS owner_id,
316
+ position,
317
+ structural_reference,
318
+ file,
319
+ qualified_symbol,
320
+ structural_kind,
321
+ start_line,
322
+ start_column,
323
+ end_line,
324
+ end_column,
325
+ content_hash,
326
+ backend_locator
327
+ FROM ${table}
328
+ ORDER BY ${ownerColumn}, position
329
+ `).all();
330
+ const ownerType = ownerColumn === "node_id" ? "node" : "relation";
331
+ return rows.map((row) => {
332
+ const locator = locatorFromRow(row);
333
+ const match = this.resolveEvidence(locator, resolver);
334
+ const source = snapshot.files.find((file) => file.path === row.file)?.worktree;
335
+ const hashMatches = source !== null && source !== undefined && source.contentHash === row.content_hash;
336
+ const status = match.status === "bound" && hashMatches
337
+ ? "bound"
338
+ : match.status === "bound"
339
+ ? "missing"
340
+ : match.status;
341
+ this.connection.prepare(`
342
+ UPDATE ${table}
343
+ SET
344
+ structural_reference = ?,
345
+ qualified_symbol = ?,
346
+ structural_kind = ?,
347
+ atlas_snapshot_id = ?,
348
+ backend_version = ?,
349
+ backend_locator = ?,
350
+ binding_status = ?
351
+ WHERE ${ownerColumn} = ? AND position = ?
352
+ `).run(match.node?.reference.id ?? row.structural_reference, match.node?.qualifiedName ?? row.qualified_symbol, match.node?.kind ?? row.structural_kind, snapshot.snapshotId, backendVersion, match.node === undefined
353
+ ? row.backend_locator
354
+ : resolver.backendLocator(match.node) ?? null, status, row.owner_id, row.position);
355
+ return { ownerType, ownerId: row.owner_id, status };
356
+ });
357
+ }
358
+ rebindStructuralRelationTargets(snapshot, backendVersion, resolver) {
359
+ const rows = this.connection.prepare(`
360
+ SELECT
361
+ relation_id,
362
+ from_key,
363
+ relation_type,
364
+ to_key,
365
+ target_file,
366
+ target_qualified_symbol,
367
+ target_structural_kind,
368
+ target_start_line,
369
+ target_start_column,
370
+ target_end_line,
371
+ target_end_column,
372
+ target_backend_locator
373
+ FROM atlas_business_relations
374
+ WHERE repository_id = ? AND to_domain = 'structural'
375
+ ORDER BY relation_id
376
+ `).all(this.#repositoryId);
377
+ const staleAssertions = [];
378
+ for (const row of rows) {
379
+ const locator = structuralTargetLocatorFromRow(row);
380
+ const match = locator === undefined
381
+ ? { status: "unresolved" }
382
+ : this.resolveStructuralLocator(locator, resolver);
383
+ const identity = `${row.from_key}:${row.relation_type}:structural:${row.to_key}`;
384
+ if (match.status !== "bound") {
385
+ staleAssertions.push(identity);
386
+ }
387
+ this.connection.prepare(`
388
+ UPDATE atlas_business_relations
389
+ SET
390
+ to_key = ?,
391
+ target_file = ?,
392
+ target_qualified_symbol = ?,
393
+ target_structural_kind = ?,
394
+ target_start_line = ?,
395
+ target_start_column = ?,
396
+ target_end_line = ?,
397
+ target_end_column = ?,
398
+ target_atlas_snapshot_id = ?,
399
+ target_backend_version = ?,
400
+ target_backend_locator = ?,
401
+ target_binding_status = ?
402
+ WHERE relation_id = ?
403
+ `).run(match.node?.reference.id ?? row.to_key, match.node?.path ?? row.target_file, match.node?.qualifiedName ?? row.target_qualified_symbol, match.node?.kind ?? row.target_structural_kind, match.node?.range.start.line ?? row.target_start_line, match.node?.range.start.column ?? row.target_start_column, match.node?.range.end.line ?? row.target_end_line, match.node?.range.end.column ?? row.target_end_column, snapshot.snapshotId, backendVersion, match.node === undefined
404
+ ? row.target_backend_locator
405
+ : resolver.backendLocator(match.node) ?? null, match.status, row.relation_id);
406
+ }
407
+ return staleAssertions;
408
+ }
409
+ resolveEvidence(locator, resolver) {
410
+ return this.resolveStructuralLocator(locator, resolver);
411
+ }
412
+ resolveStructuralLocator(locator, resolver) {
413
+ const directlyLocated = resolver.getNode(locator.structuralReference);
414
+ if (directlyLocated !== undefined && nodeMatchesLocator(directlyLocated, locator)) {
415
+ return { status: "bound", node: directlyLocated };
416
+ }
417
+ const candidates = resolver.findCandidates(locator).filter((node) => nodeMatchesLocator(node, locator));
418
+ if (candidates.length === 1) {
419
+ return { status: "bound", node: candidates[0] };
420
+ }
421
+ return { status: candidates.length === 0 ? "missing" : "ambiguous" };
422
+ }
423
+ refreshValidity(snapshotId) {
424
+ this.refreshValidityTable("atlas_business_nodes", "atlas_business_node_evidence", "atlas_business_node_validity", "node_id", snapshotId);
425
+ this.refreshValidityTable("atlas_business_relations", "atlas_business_relation_evidence", "atlas_business_relation_validity", "relation_id", snapshotId);
426
+ }
427
+ refreshValidityTable(ownerTable, evidenceTable, validityTable, ownerColumn, snapshotId) {
428
+ const owners = this.connection.prepare(`
429
+ SELECT ${ownerColumn} AS owner_id
430
+ FROM ${ownerTable}
431
+ WHERE repository_id = ?
432
+ `).all(this.#repositoryId);
433
+ for (const { owner_id } of owners) {
434
+ const row = this.connection.prepare(`
435
+ SELECT
436
+ COUNT(*) AS evidence_count,
437
+ SUM(CASE WHEN binding_status = 'bound' THEN 1 ELSE 0 END) AS bound_count
438
+ FROM ${evidenceTable}
439
+ WHERE ${ownerColumn} = ?
440
+ `).get(owner_id);
441
+ const validity = row.evidence_count > 0 && row.evidence_count === row.bound_count
442
+ ? "valid"
443
+ : "stale";
444
+ const targetBindingStatus = ownerColumn === "relation_id"
445
+ ? this.connection.prepare(`
446
+ SELECT to_domain, target_binding_status
447
+ FROM atlas_business_relations
448
+ WHERE relation_id = ?
449
+ `).get(owner_id)
450
+ : undefined;
451
+ const targetIsBound = targetBindingStatus === undefined
452
+ || targetBindingStatus.to_domain === "business"
453
+ || targetBindingStatus.target_binding_status === "bound";
454
+ const derivedValidity = targetIsBound
455
+ ? validity
456
+ : "stale";
457
+ this.connection.prepare(`
458
+ INSERT INTO ${validityTable} (${ownerColumn}, repository_id, snapshot_id, validity)
459
+ VALUES (?, ?, ?, ?)
460
+ ON CONFLICT (${ownerColumn}, snapshot_id) DO UPDATE SET validity = excluded.validity
461
+ `).run(owner_id, this.#repositoryId, snapshotId, derivedValidity);
462
+ }
463
+ }
464
+ saveWorldPublication(previousPublicationId, changes, timestamp) {
465
+ const result = this.connection.prepare(`
466
+ INSERT INTO atlas_world_publications (
467
+ repository_id,
468
+ previous_publication_id,
469
+ snapshot_id,
470
+ added_paths,
471
+ modified_paths,
472
+ removed_paths,
473
+ stale_assertions,
474
+ published_at
475
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
476
+ `).run(this.#repositoryId, previousPublicationId, changes.toSnapshotId, JSON.stringify(changes.structural.added), JSON.stringify(changes.structural.modified), JSON.stringify(changes.structural.removed), JSON.stringify(changes.staleAssertions), timestamp);
477
+ return Number(result.lastInsertRowid);
478
+ }
479
+ }
480
+ function locatorFromRow(row) {
481
+ return {
482
+ structuralReference: row.structural_reference,
483
+ file: row.file,
484
+ qualifiedSymbol: row.qualified_symbol,
485
+ structuralKind: row.structural_kind,
486
+ range: {
487
+ start: { line: row.start_line, column: row.start_column },
488
+ end: { line: row.end_line, column: row.end_column },
489
+ },
490
+ contentHash: row.content_hash,
491
+ ...(row.backend_locator === null ? {} : { backendLocator: row.backend_locator }),
492
+ };
493
+ }
494
+ function compareSnapshotContents(from, to) {
495
+ const fromFiles = snapshotContents(from);
496
+ const toFiles = snapshotContents(to);
497
+ const added = [];
498
+ const changed = [];
499
+ const removed = [];
500
+ const paths = new Set([...fromFiles.keys(), ...toFiles.keys()]);
501
+ for (const path of [...paths].sort()) {
502
+ const before = fromFiles.get(path);
503
+ const after = toFiles.get(path);
504
+ const reference = `file:${path}`;
505
+ if (before === undefined && after !== undefined) {
506
+ added.push(reference);
507
+ }
508
+ else if (before !== undefined && after === undefined) {
509
+ removed.push(reference);
510
+ }
511
+ else if (before !== undefined && after !== undefined && before !== after) {
512
+ changed.push(reference);
513
+ }
514
+ }
515
+ return { added, changed, removed };
516
+ }
517
+ function snapshotContents(snapshot) {
518
+ return new Map(snapshot.files.flatMap((file) => (file.worktree === null || !isSupportedSource(file.path)
519
+ ? []
520
+ : [[file.path, file.worktree.contentHash]])));
521
+ }
522
+ function parseStringArray(value) {
523
+ return JSON.parse(value);
524
+ }
525
+ function structuralTargetLocatorFromRow(row) {
526
+ if (row.target_file === null
527
+ || row.target_start_line === null
528
+ || row.target_start_column === null
529
+ || row.target_end_line === null
530
+ || row.target_end_column === null) {
531
+ return undefined;
532
+ }
533
+ return {
534
+ structuralReference: row.to_key,
535
+ file: row.target_file,
536
+ qualifiedSymbol: row.target_qualified_symbol,
537
+ structuralKind: row.target_structural_kind,
538
+ range: {
539
+ start: { line: row.target_start_line, column: row.target_start_column },
540
+ end: { line: row.target_end_line, column: row.target_end_column },
541
+ },
542
+ ...(row.target_backend_locator === null
543
+ ? {}
544
+ : { backendLocator: row.target_backend_locator }),
545
+ };
546
+ }
547
+ function nodeMatchesLocator(node, locator) {
548
+ return node.path === locator.file
549
+ && (locator.qualifiedSymbol === null || node.qualifiedName === locator.qualifiedSymbol)
550
+ && (locator.structuralKind === null || node.kind === locator.structuralKind)
551
+ && node.range.start.line === locator.range.start.line
552
+ && node.range.start.column === locator.range.start.column
553
+ && node.range.end.line === locator.range.end.line
554
+ && node.range.end.column === locator.range.end.column;
555
+ }