@agenthead/graph 0.0.0-stage → 0.2.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.
@@ -0,0 +1,273 @@
1
+ import { isUtf8 } from "node:buffer";
2
+ import { createHash } from "node:crypto";
3
+ import { mkdirSync } from "node:fs";
4
+ import { dirname, sep } from "node:path";
5
+ import Database from "better-sqlite3";
6
+ import { ExcludedPathError, OutsideProjectError, StoreSourceError, WorkspaceBoundary, } from "@agenthead/core";
7
+ import { migrate, schemaVersion } from "./migrations.js";
8
+ import { createGraphSignals } from "./graph-signals.js";
9
+ import { languageFor, parseFile } from "./parser.js";
10
+ import { resolveImport } from "./resolve-import.js";
11
+ // Bump when extraction or grammar versions change, even if schema is unchanged.
12
+ const parserVersion = "@vscode/tree-sitter-wasm@0.3.1/extractor-3";
13
+ const ignored = /(?:^|\/)(?:\.git|node_modules|dist|build|\.next|out|coverage|__pycache__|\.venv|venv)(?:\/|$)|\.min\.js$/i;
14
+ /** One durable, rebuildable syntactic graph per project. */
15
+ export class GraphStore {
16
+ /** The project root and exclusions every query applies, including generated directories. */
17
+ boundary;
18
+ db;
19
+ indexing = false;
20
+ constructor(project, options = {}) {
21
+ this.boundary = new WorkspaceBoundary(project, {
22
+ excludedPaths: [ignored, ...(options.excludedPaths ?? [])],
23
+ });
24
+ const database = ".agenthead/graph.db";
25
+ const path = this.boundary.resolveStorage(database);
26
+ for (const suffix of ["-journal", "-wal", "-shm"])
27
+ this.boundary.resolveStorage(database + suffix);
28
+ if (!options.readonly)
29
+ mkdirSync(dirname(path), { recursive: true });
30
+ this.db = new Database(path, options.readonly ? { readonly: true, fileMustExist: true } : {});
31
+ try {
32
+ if (options.readonly) {
33
+ const version = this.db.pragma("user_version", { simple: true });
34
+ if (version !== schemaVersion)
35
+ throw new Error(`Unsupported graph database version ${version}`);
36
+ }
37
+ else {
38
+ this.db.pragma("foreign_keys = ON");
39
+ this.db.pragma("journal_mode = WAL");
40
+ migrate(this.db);
41
+ }
42
+ }
43
+ catch (error) {
44
+ this.db.close();
45
+ throw error;
46
+ }
47
+ }
48
+ /** Hash every permitted source; parse only new, changed or version-invalid files. */
49
+ async index() {
50
+ if (this.indexing)
51
+ throw new Error("Indexing is already in progress");
52
+ this.indexing = true;
53
+ try {
54
+ const previous = new Map(this.fileRows().map((row) => [row.path, row]));
55
+ const files = this.boundary
56
+ .listSourceFiles()
57
+ .filter((file) => languageFor(file));
58
+ const present = new Set(files);
59
+ const changed = [];
60
+ const errors = [];
61
+ let reusedFiles = 0;
62
+ // Stage before entering a synchronous SQLite transaction. Failed reads or
63
+ // parser failures leave the previous graph intact, including its hashes.
64
+ for (const file of files) {
65
+ const bytes = this.boundary.readSource(file);
66
+ if (!isUtf8(bytes) || bytes.includes(0)) {
67
+ errors.push(file);
68
+ // Drop stale entries and keep imports from linking to skipped files.
69
+ present.delete(file);
70
+ continue;
71
+ }
72
+ const hash = createHash("sha256").update(bytes).digest("hex");
73
+ const old = previous.get(file);
74
+ if (old?.hash === hash && old.parser_version === parserVersion) {
75
+ reusedFiles++;
76
+ if (old.has_errors)
77
+ errors.push(file);
78
+ }
79
+ else {
80
+ const graph = await parseFile(file, bytes.toString("utf8"), languageFor(file), hash);
81
+ changed.push(graph);
82
+ if (graph.hasErrors)
83
+ errors.push(file);
84
+ }
85
+ }
86
+ const removed = [...previous.keys()].filter((file) => !present.has(file));
87
+ this.db
88
+ .transaction(() => {
89
+ const remove = this.db.prepare("DELETE FROM graph_files WHERE path = ?");
90
+ for (const file of removed)
91
+ remove.run(file);
92
+ for (const graph of changed) {
93
+ remove.run(graph.file);
94
+ this.db
95
+ .prepare("INSERT INTO graph_files VALUES (?, ?, ?, ?, ?)")
96
+ .run(graph.file, graph.hash, graph.language, parserVersion, Number(graph.hasErrors));
97
+ this.insert("symbol", graph.symbols);
98
+ this.insert("import", graph.imports);
99
+ this.insert("call", graph.calls);
100
+ this.insert("reference", graph.references);
101
+ }
102
+ // Targets can change when files are added/deleted, even if importers are
103
+ // unchanged. Relink stored imports without reparsing their source files.
104
+ const imports = this.db
105
+ .prepare(`
106
+ SELECT e.id, e.data, f.language FROM graph_entries e
107
+ JOIN graph_files f ON f.path = e.file WHERE e.kind = 'import'
108
+ `)
109
+ .all();
110
+ const update = this.db.prepare("UPDATE graph_entries SET target = ?, data = ? WHERE id = ?");
111
+ for (const row of imports) {
112
+ const entry = JSON.parse(row.data);
113
+ const target = resolveImport(entry.file, row.language, entry, present);
114
+ if (target !== entry.target)
115
+ update.run(target, JSON.stringify({ ...entry, target }), row.id);
116
+ }
117
+ })
118
+ .immediate();
119
+ return {
120
+ totalFiles: files.length,
121
+ parsedFiles: changed.length,
122
+ reusedFiles,
123
+ removedFiles: removed.length,
124
+ reusePercentage: files.length
125
+ ? (100 * reusedFiles) / files.length
126
+ : 100,
127
+ filesWithErrors: errors,
128
+ changes: {
129
+ added: changed
130
+ .filter((graph) => !previous.has(graph.file))
131
+ .map((graph) => graph.file),
132
+ changed: changed
133
+ .filter((graph) => previous.has(graph.file))
134
+ .map((graph) => graph.file),
135
+ removed,
136
+ },
137
+ };
138
+ }
139
+ finally {
140
+ this.indexing = false;
141
+ }
142
+ }
143
+ fileRows() {
144
+ return this.db
145
+ .prepare("SELECT * FROM graph_files ORDER BY path")
146
+ .all();
147
+ }
148
+ /** Compare source hashes and parser versions without updating the index. */
149
+ freshness() {
150
+ const integrity = this.db.pragma("integrity_check", { simple: true });
151
+ if (integrity !== "ok")
152
+ throw new Error("Graph integrity_check failed");
153
+ const previous = new Map(this.fileRows().map((row) => [row.path, row]));
154
+ const files = this.boundary
155
+ .listSourceFiles()
156
+ .filter((file) => languageFor(file));
157
+ const stale = new Set(previous.keys());
158
+ for (const file of files) {
159
+ const row = previous.get(file);
160
+ const hash = createHash("sha256")
161
+ .update(this.boundary.readSource(file))
162
+ .digest("hex");
163
+ if (row?.hash === hash && row.parser_version === parserVersion)
164
+ stale.delete(file);
165
+ else
166
+ stale.add(file);
167
+ }
168
+ return {
169
+ files: files.length,
170
+ stale: [...stale].sort(),
171
+ filesWithErrors: [...previous.values()]
172
+ .filter((row) => row.has_errors)
173
+ .map((row) => row.path),
174
+ };
175
+ }
176
+ insert(kind, entries) {
177
+ const insert = this.db.prepare("INSERT INTO graph_entries(file, kind, name, target, data) VALUES (?, ?, ?, ?, ?)");
178
+ for (const entry of entries)
179
+ insert.run(entry.file, kind, "source" in entry ? entry.source : entry.name, null, JSON.stringify(entry));
180
+ }
181
+ allowed(file) {
182
+ try {
183
+ this.boundary.resolveSource(file);
184
+ return true;
185
+ }
186
+ catch (error) {
187
+ if (error instanceof ExcludedPathError ||
188
+ error instanceof OutsideProjectError ||
189
+ error instanceof StoreSourceError)
190
+ return false;
191
+ throw error;
192
+ }
193
+ }
194
+ entries(kind, name, file) {
195
+ const clauses = ["kind = ?"];
196
+ const params = [kind];
197
+ if (name !== undefined) {
198
+ clauses.push("name = ?");
199
+ params.push(name);
200
+ }
201
+ if (file !== undefined) {
202
+ clauses.push("file = ?");
203
+ params.push(this.normalize(file));
204
+ }
205
+ return this.db
206
+ .prepare(`SELECT data FROM graph_entries WHERE ${clauses.join(" AND ")} ORDER BY file, id`)
207
+ .all(...params)
208
+ .map((row) => JSON.parse(row.data))
209
+ .filter((entry) => this.allowed(entry.file));
210
+ }
211
+ normalize(file) {
212
+ return this.boundary.resolveSource(file).relativePath.split(sep).join("/");
213
+ }
214
+ definitions(name, file) {
215
+ return this.entries("symbol", name, file);
216
+ }
217
+ references(name, file) {
218
+ return this.entries("reference", name, file);
219
+ }
220
+ calls(name, file) {
221
+ return this.entries("call", name, file);
222
+ }
223
+ /** The name of the definition or reference whose range holds a one-based position, end included. */
224
+ nameAt(file, line, column) {
225
+ return this.db
226
+ .prepare("SELECT data FROM graph_entries WHERE file = ? AND kind IN ('symbol', 'reference') ORDER BY id")
227
+ .all(this.normalize(file))
228
+ .map((row) => JSON.parse(row.data))
229
+ .find((entry) => entry.line === line &&
230
+ entry.column <= column &&
231
+ column <= entry.endColumn)?.name;
232
+ }
233
+ imports(file) {
234
+ return this.entries("import", undefined, file).map((entry) => ({
235
+ ...entry,
236
+ target: entry.target && this.allowed(entry.target) ? entry.target : null,
237
+ }));
238
+ }
239
+ /** Unique, sorted importer paths, including re-exports and literal require/import. */
240
+ importers(file) {
241
+ const target = this.normalize(file);
242
+ return this.db
243
+ .prepare("SELECT DISTINCT file FROM graph_entries WHERE kind = 'import' AND target = ? ORDER BY file")
244
+ .all(target)
245
+ .map((row) => row.file)
246
+ .filter((path) => this.allowed(path));
247
+ }
248
+ /** A deterministic full snapshot, useful for inspection and fixture verification. */
249
+ snapshot() {
250
+ return this.db.transaction(() => this.fileRows()
251
+ .filter((row) => this.allowed(row.path))
252
+ .map((row) => ({
253
+ file: row.path,
254
+ hash: row.hash,
255
+ language: row.language,
256
+ hasErrors: Boolean(row.has_errors),
257
+ symbols: this.entries("symbol", undefined, row.path),
258
+ imports: this.imports(row.path),
259
+ calls: this.calls(undefined, row.path),
260
+ references: this.entries("reference", undefined, row.path),
261
+ })))();
262
+ }
263
+ /** Detached ranking snapshot; usable after closing this store. */
264
+ signals() {
265
+ return createGraphSignals(this.snapshot(), (file) => this.normalize(file));
266
+ }
267
+ close() {
268
+ if (this.indexing)
269
+ throw new Error("Cannot close while indexing");
270
+ this.db.close();
271
+ }
272
+ }
273
+ //# sourceMappingURL=graph-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph-store.js","sourceRoot":"","sources":["../src/graph-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,QAAQ,MAAM,gBAAgB,CAAC;AACtC,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EAC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"./load-signals.js";
3
+ export { loadGraphSignals } from "./load-signals.js";
4
+ export type { Call, FileGraph, Import, IndexReport, Language, Location, Reference, SymbolDefinition, } from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { GraphStore } from "./graph-store.js";
2
+ export { loadGraphSignals } from "./load-signals.js";
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC"}
@@ -0,0 +1,7 @@
1
+ import { type GraphSignals, type WorkspaceBoundaryOptions } from "@agenthead/core";
2
+ export interface LoadGraphSignalsOptions extends WorkspaceBoundaryOptions {
3
+ /** Map evidence paths (for example workspace/src/a.ts) to graph paths. Must be idempotent. */
4
+ mapPath?: (path: string) => string;
5
+ }
6
+ /** Best-effort, read-only snapshot of an existing, supported graph cache. */
7
+ export declare function loadGraphSignals(project: string, options?: LoadGraphSignalsOptions): GraphSignals | undefined;
@@ -0,0 +1,35 @@
1
+ import {} from "@agenthead/core";
2
+ import { GraphStore } from "./graph-store.js";
3
+ /** Best-effort, read-only snapshot of an existing, supported graph cache. */
4
+ export function loadGraphSignals(project, options = {}) {
5
+ try {
6
+ const graph = new GraphStore(project, { ...options, readonly: true });
7
+ try {
8
+ const signals = graph.signals();
9
+ const map = options.mapPath;
10
+ if (!map)
11
+ return signals;
12
+ const mappedRoots = new WeakMap();
13
+ const roots = (files) => {
14
+ if (!mappedRoots.has(files))
15
+ mappedRoots.set(files, files.map(map));
16
+ return mappedRoots.get(files);
17
+ };
18
+ return {
19
+ resolveTaskFiles: (task) => signals.resolveTaskFiles(task.replace(/[\p{L}\p{N}_$@./\\-]+/gu, (path) => map(path))),
20
+ distance: (from, to) => signals.distance(roots(from), map(to)),
21
+ impacted: (files) => signals.impacted(roots(files)),
22
+ outline: (file, hash) => signals.outline?.(map(file), hash),
23
+ };
24
+ }
25
+ finally {
26
+ graph.close();
27
+ }
28
+ }
29
+ catch {
30
+ // The graph is a rebuildable ranking hint. Storage, schema and snapshot
31
+ // failures must not prevent packing the underlying evidence.
32
+ return undefined;
33
+ }
34
+ }
35
+ //# sourceMappingURL=load-signals.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"load-signals.js","sourceRoot":"","sources":["../src/load-signals.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAO9C,6EAA6E;AAC7E,MAAM,UAAU,gBAAgB,CAC9B,OAAe,EACf,UAAmC,EAAE;IAErC,IAAI,CAAC;QACH,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;QACtE,IAAI,CAAC;YACH,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC;YAChC,MAAM,GAAG,GAAG,OAAO,CAAC,OAAO,CAAC;YAC5B,IAAI,CAAC,GAAG;gBAAE,OAAO,OAAO,CAAC;YACzB,MAAM,WAAW,GAAG,IAAI,OAAO,EAAwC,CAAC;YACxE,MAAM,KAAK,GAAG,CAAC,KAAwB,EAAE,EAAE;gBACzC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC;oBAAE,WAAW,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;gBACpE,OAAO,WAAW,CAAC,GAAG,CAAC,KAAK,CAAE,CAAC;YACjC,CAAC,CAAC;YACF,OAAO;gBACL,gBAAgB,EAAE,CAAC,IAAI,EAAE,EAAE,CACzB,OAAO,CAAC,gBAAgB,CACtB,IAAI,CAAC,OAAO,CAAC,yBAAyB,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAC7D;gBACH,QAAQ,EAAE,CAAC,IAAI,EAAE,EAAE,EAAE,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC;gBAC9D,QAAQ,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;gBACnD,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC;aAC5D,CAAC;QACJ,CAAC;gBAAS,CAAC;YACT,KAAK,CAAC,KAAK,EAAE,CAAC;QAChB,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACP,wEAAwE;QACxE,6DAA6D;QAC7D,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC"}
@@ -0,0 +1,91 @@
1
+ import type { GraphStore } from "./graph-store.js";
2
+ import { type LspFailure as ClientFailure } from "./lsp-client.js";
3
+ import type { IndexReport, Location } from "./types.js";
4
+ /** Why the graph answered: the server was configured off, or it failed. */
5
+ export type LspFailure = ClientFailure | "disabled";
6
+ export interface LspServerConfig {
7
+ /** An absolute path, or a bare name to look up on PATH. */
8
+ command: string;
9
+ args?: readonly string[];
10
+ }
11
+ export interface LspBridgeOptions {
12
+ /** TypeScript and JavaScript files. Default: `typescript-language-server --stdio` from PATH. */
13
+ typescript?: LspServerConfig | false;
14
+ /** Python files. Default: `pyright-langserver --stdio` from PATH. */
15
+ python?: LspServerConfig | false;
16
+ /** Milliseconds allowed for a server to answer `initialize`. Default 30,000. */
17
+ startupTimeoutMs?: number;
18
+ /** Milliseconds allowed for each request. Default 30,000. */
19
+ timeoutMs?: number;
20
+ }
21
+ /** A one-based line and UTF-16 column, as in graph locations. */
22
+ export interface LspPosition {
23
+ file: string;
24
+ line: number;
25
+ column: number;
26
+ }
27
+ export type LspResult = {
28
+ source: "lsp";
29
+ locations: Location[];
30
+ } | {
31
+ source: "graph";
32
+ reason: LspFailure;
33
+ locations: Location[];
34
+ };
35
+ /**
36
+ * Bridge options from `AGENTHEAD_LSP`, the switch the CLI and the MCP server read.
37
+ * Language servers can run code from the project, so they are off unless it is
38
+ * `on`. Unset, empty or `off` turns both off; any other value throws, so a
39
+ * misspelt setting is noticed rather than read either way.
40
+ */
41
+ export declare function lspOptionsFromEnv(env?: NodeJS.ProcessEnv): LspBridgeOptions;
42
+ /**
43
+ * Definitions and references from a language server when one is available and
44
+ * healthy, otherwise from the graph's name matches. Every location a server
45
+ * returns is checked against the graph's workspace boundary.
46
+ */
47
+ export declare class LspBridge {
48
+ private readonly graph;
49
+ private readonly boundary;
50
+ private readonly configs;
51
+ private readonly startupTimeoutMs;
52
+ private readonly timeoutMs;
53
+ private readonly servers;
54
+ /** The servers' temporary directory: made for the first, removed by close(). */
55
+ private temporary;
56
+ private closed;
57
+ constructor(graph: GraphStore, options?: LspBridgeOptions);
58
+ /** Where the symbol at a position is declared. */
59
+ definitions(at: LspPosition): Promise<LspResult>;
60
+ /** Uses of the symbol at a position, without its declaration. */
61
+ references(at: LspPosition): Promise<LspResult>;
62
+ /**
63
+ * Tell the running servers which files an index run added, changed or
64
+ * removed, with `workspace/didChangeWatchedFiles`, so that they read those
65
+ * files again. Pass it the report of every `graph.index()` while the bridge
66
+ * is open. A server that has not started yet reads the files when it does.
67
+ */
68
+ filesChanged({ changes }: IndexReport): void;
69
+ /**
70
+ * Shut down every server this bridge started and remove their temporary
71
+ * directory. Later queries throw.
72
+ */
73
+ close(): Promise<void>;
74
+ private query;
75
+ /** Files where the graph records `name`, and importers of those defining it. */
76
+ private seeds;
77
+ private server;
78
+ private start;
79
+ /**
80
+ * Bring the server's copy of every file it was given up to date, then open
81
+ * those of `files` it has not seen. A server reads an open file from the
82
+ * client, never from disk, so an unsynced copy would answer from old text.
83
+ * False if `files[0]`, the queried file, cannot be read as UTF-8; other
84
+ * files that cannot be read are left out.
85
+ */
86
+ private sync;
87
+ /** A file's text, read through the boundary; undefined if gone or not UTF-8. */
88
+ private read;
89
+ /** File locations inside the boundary, canonical, deduplicated and sorted. */
90
+ private locations;
91
+ }