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