@daogee/mdgraph 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/LICENSE +21 -0
- package/README-ZH.md +203 -0
- package/README.md +203 -0
- package/agent-pack/README.md +26 -0
- package/agent-pack/host-examples.md +71 -0
- package/agent-pack/mcp-config.example.json +14 -0
- package/agent-pack/mdgraph-agent-instructions.md +21 -0
- package/agent-pack/prompts/relationship-trace.md +12 -0
- package/agent-pack/prompts/status-doctor.md +13 -0
- package/agent-pack/prompts/task-start-context.md +15 -0
- package/dist/analysis/doctor-scope.d.ts +8 -0
- package/dist/analysis/doctor-scope.js +109 -0
- package/dist/analysis/doctor.d.ts +148 -0
- package/dist/analysis/doctor.js +919 -0
- package/dist/analysis/status-freshness.d.ts +13 -0
- package/dist/analysis/status-freshness.js +55 -0
- package/dist/benchmark/benchmark.d.ts +118 -0
- package/dist/benchmark/benchmark.js +357 -0
- package/dist/bin/mdgraph.d.ts +2 -0
- package/dist/bin/mdgraph.js +877 -0
- package/dist/bundle/bundle.d.ts +66 -0
- package/dist/bundle/bundle.js +320 -0
- package/dist/config/limits.d.ts +24 -0
- package/dist/config/limits.js +24 -0
- package/dist/config/load-config.d.ts +14 -0
- package/dist/config/load-config.js +177 -0
- package/dist/db/connection.d.ts +15 -0
- package/dist/db/connection.js +145 -0
- package/dist/db/repositories.d.ts +159 -0
- package/dist/db/repositories.js +929 -0
- package/dist/db/schema.sql +110 -0
- package/dist/db/sqlite-adapter.d.ts +18 -0
- package/dist/db/sqlite-adapter.js +60 -0
- package/dist/diff/graph-diff.d.ts +41 -0
- package/dist/diff/graph-diff.js +334 -0
- package/dist/evaluation/retrieval-eval.d.ts +115 -0
- package/dist/evaluation/retrieval-eval.js +399 -0
- package/dist/export/diagram.d.ts +11 -0
- package/dist/export/diagram.js +41 -0
- package/dist/export/graphjson.d.ts +89 -0
- package/dist/export/graphjson.js +299 -0
- package/dist/export/markdown-index.d.ts +21 -0
- package/dist/export/markdown-index.js +89 -0
- package/dist/export/source-bridge.d.ts +22 -0
- package/dist/export/source-bridge.js +83 -0
- package/dist/extraction/entity-extractor.d.ts +12 -0
- package/dist/extraction/entity-extractor.js +153 -0
- package/dist/extraction/graph-builder.d.ts +2 -0
- package/dist/extraction/graph-builder.js +168 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.js +28 -0
- package/dist/indexer.d.ts +19 -0
- package/dist/indexer.js +100 -0
- package/dist/mcp/debug.d.ts +7 -0
- package/dist/mcp/debug.js +41 -0
- package/dist/mcp/server-instructions.d.ts +2 -0
- package/dist/mcp/server-instructions.js +40 -0
- package/dist/mcp/server.d.ts +28 -0
- package/dist/mcp/server.js +232 -0
- package/dist/mcp/tools.d.ts +31 -0
- package/dist/mcp/tools.js +506 -0
- package/dist/mcp/transport.d.ts +50 -0
- package/dist/mcp/transport.js +88 -0
- package/dist/parser/frontmatter.d.ts +10 -0
- package/dist/parser/frontmatter.js +191 -0
- package/dist/parser/links.d.ts +6 -0
- package/dist/parser/links.js +9 -0
- package/dist/parser/markdown-parser.d.ts +2 -0
- package/dist/parser/markdown-parser.js +267 -0
- package/dist/query/context-builder.d.ts +85 -0
- package/dist/query/context-builder.js +413 -0
- package/dist/query/search.d.ts +32 -0
- package/dist/query/search.js +237 -0
- package/dist/query/trace.d.ts +10 -0
- package/dist/query/trace.js +55 -0
- package/dist/reporting/report.d.ts +49 -0
- package/dist/reporting/report.js +143 -0
- package/dist/resolution/link-resolver.d.ts +17 -0
- package/dist/resolution/link-resolver.js +113 -0
- package/dist/scanner/file-scanner.d.ts +4 -0
- package/dist/scanner/file-scanner.js +144 -0
- package/dist/semantic/local-embedding.d.ts +4 -0
- package/dist/semantic/local-embedding.js +30 -0
- package/dist/semantic/status.d.ts +19 -0
- package/dist/semantic/status.js +70 -0
- package/dist/semantic/vector-codec.d.ts +3 -0
- package/dist/semantic/vector-codec.js +35 -0
- package/dist/types.d.ts +198 -0
- package/dist/types.js +15 -0
- package/dist/utils/bounded-json.d.ts +9 -0
- package/dist/utils/bounded-json.js +57 -0
- package/dist/utils/content-risk.d.ts +5 -0
- package/dist/utils/content-risk.js +20 -0
- package/dist/utils/fts.d.ts +3 -0
- package/dist/utils/fts.js +52 -0
- package/dist/utils/id.d.ts +2 -0
- package/dist/utils/id.js +8 -0
- package/dist/utils/path-safety.d.ts +4 -0
- package/dist/utils/path-safety.js +25 -0
- package/dist/utils/text.d.ts +7 -0
- package/dist/utils/text.js +36 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +11 -0
- package/dist/watcher/file-watcher.d.ts +11 -0
- package/dist/watcher/file-watcher.js +127 -0
- package/docs/EN/Agent_Integration.md +129 -0
- package/docs/EN/Architecture.md +135 -0
- package/docs/EN/Evaluation_Questions.md +68 -0
- package/docs/EN/Output_Contracts.md +274 -0
- package/docs/EN/Public_Contracts.md +88 -0
- package/docs/EN/Public_Contracts_1.0.md +234 -0
- package/docs/EN/Release_Checklist.md +82 -0
- package/docs/ZH/Agent_Integration.md +105 -0
- package/docs/ZH/Architecture.md +124 -0
- package/docs/ZH/Evaluation_Questions.md +66 -0
- package/docs/ZH/Output_Contracts.md +269 -0
- package/docs/ZH/Public_Contracts.md +81 -0
- package/docs/ZH/Public_Contracts_1.0.md +202 -0
- package/docs/ZH/Release_Checklist.md +83 -0
- package/package.json +94 -0
|
@@ -0,0 +1,929 @@
|
|
|
1
|
+
import { readSchemaMetadata } from "./connection.js";
|
|
2
|
+
import { decodeFloat32Vector, encodeFloat32Vector } from "../semantic/vector-codec.js";
|
|
3
|
+
import { ftsIndexContent } from "../utils/fts.js";
|
|
4
|
+
import { normalizePath, slugifyHeading } from "../utils/text.js";
|
|
5
|
+
export class GraphRepository {
|
|
6
|
+
db;
|
|
7
|
+
constructor(db) {
|
|
8
|
+
this.db = db;
|
|
9
|
+
}
|
|
10
|
+
close() {
|
|
11
|
+
this.db.close();
|
|
12
|
+
}
|
|
13
|
+
replaceAll(records) {
|
|
14
|
+
const write = this.db.transaction(() => {
|
|
15
|
+
this.db.exec("DELETE FROM chunks_fts; DELETE FROM chunk_vectors; DELETE FROM edges; DELETE FROM chunks; DELETE FROM source_refs; DELETE FROM entities; DELETE FROM sections; DELETE FROM documents;");
|
|
16
|
+
this.insertRecords(records, "strict");
|
|
17
|
+
});
|
|
18
|
+
write();
|
|
19
|
+
this.compactStorage({ vacuum: true });
|
|
20
|
+
}
|
|
21
|
+
replaceDocuments(records, changedDocumentIds, deletedDocumentIds) {
|
|
22
|
+
const write = this.db.transaction(() => {
|
|
23
|
+
for (const documentId of [...changedDocumentIds, ...deletedDocumentIds]) {
|
|
24
|
+
this.deleteDocumentDerivedRecords(documentId);
|
|
25
|
+
}
|
|
26
|
+
this.insertRecords(records, "incremental");
|
|
27
|
+
this.pruneUnreferencedEntitiesAndSources();
|
|
28
|
+
});
|
|
29
|
+
write();
|
|
30
|
+
this.compactStorage({ vacuum: false });
|
|
31
|
+
}
|
|
32
|
+
counts() {
|
|
33
|
+
return {
|
|
34
|
+
documents: tableCount(this.db, "documents"),
|
|
35
|
+
sections: tableCount(this.db, "sections"),
|
|
36
|
+
entities: tableCount(this.db, "entities"),
|
|
37
|
+
sourceRefs: tableCount(this.db, "source_refs"),
|
|
38
|
+
edges: tableCount(this.db, "edges"),
|
|
39
|
+
chunks: tableCount(this.db, "chunks"),
|
|
40
|
+
vectors: tableCount(this.db, "chunk_vectors")
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
latestIndexedAt() {
|
|
44
|
+
const row = this.db.prepare("SELECT MAX(indexed_at) AS indexed_at FROM documents").get();
|
|
45
|
+
return typeof row?.indexed_at === "string" && row.indexed_at ? row.indexed_at : undefined;
|
|
46
|
+
}
|
|
47
|
+
schemaMetadata() {
|
|
48
|
+
return readSchemaMetadata(this.db);
|
|
49
|
+
}
|
|
50
|
+
storageDiagnostics() {
|
|
51
|
+
const pageSize = pragmaNumber(this.db, "page_size");
|
|
52
|
+
const pageCount = pragmaNumber(this.db, "page_count");
|
|
53
|
+
const freelistCount = pragmaNumber(this.db, "freelist_count");
|
|
54
|
+
const objectSizes = objectStorageStats(this.db);
|
|
55
|
+
const providers = vectorStorageStats(this.db);
|
|
56
|
+
return {
|
|
57
|
+
database: {
|
|
58
|
+
pageSize,
|
|
59
|
+
pageCount,
|
|
60
|
+
freelistCount,
|
|
61
|
+
estimatedBytes: pageSize * pageCount,
|
|
62
|
+
journalMode: pragmaString(this.db, "journal_mode"),
|
|
63
|
+
walCheckpoint: walCheckpointStats(this.db)
|
|
64
|
+
},
|
|
65
|
+
objects: objectSizes,
|
|
66
|
+
pathGroups: pathStorageContributions(this.db),
|
|
67
|
+
edgeKinds: edgeKindStorageStats(this.db),
|
|
68
|
+
highDegreeNodes: highDegreeNodeStats(this.db, (id) => this.getNode(id)),
|
|
69
|
+
vectors: {
|
|
70
|
+
total: tableCount(this.db, "chunk_vectors"),
|
|
71
|
+
format: vectorStorageFormat(this.db),
|
|
72
|
+
providers
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
checkpointStorage() {
|
|
77
|
+
this.db.exec("PRAGMA wal_checkpoint(TRUNCATE);");
|
|
78
|
+
}
|
|
79
|
+
documentHashes() {
|
|
80
|
+
const rows = this.db.prepare("SELECT id, path, hash FROM documents").all();
|
|
81
|
+
return new Map(rows.map((row) => [stringValue(row.path), { id: stringValue(row.id), hash: stringValue(row.hash) }]));
|
|
82
|
+
}
|
|
83
|
+
searchChunks(ftsQuery, limit) {
|
|
84
|
+
const rows = this.db.prepare(`
|
|
85
|
+
SELECT
|
|
86
|
+
d.id AS d_id, d.path AS d_path, d.title AS d_title, d.type AS d_type, d.status AS d_status,
|
|
87
|
+
d.hash AS d_hash, d.trust_tier AS d_trust_tier, d.updated_at AS d_updated_at,
|
|
88
|
+
d.indexed_at AS d_indexed_at, d.metadata_json AS d_metadata_json,
|
|
89
|
+
s.id AS s_id, s.document_id AS s_document_id, s.anchor AS s_anchor, s.heading AS s_heading,
|
|
90
|
+
s.level AS s_level, s.start_line AS s_start_line, s.end_line AS s_end_line, s.content AS s_content,
|
|
91
|
+
c.id AS c_id, c.document_id AS c_document_id, c.section_id AS c_section_id, c.content AS c_content,
|
|
92
|
+
c.token_estimate AS c_token_estimate, c.metadata_json AS c_metadata_json,
|
|
93
|
+
bm25(chunks_fts) AS rank
|
|
94
|
+
FROM chunks_fts
|
|
95
|
+
JOIN chunks c ON c.rowid = chunks_fts.rowid
|
|
96
|
+
JOIN documents d ON d.id = c.document_id
|
|
97
|
+
LEFT JOIN sections s ON s.id = c.section_id
|
|
98
|
+
WHERE chunks_fts MATCH ?
|
|
99
|
+
ORDER BY rank ASC
|
|
100
|
+
LIMIT ?
|
|
101
|
+
`).all(ftsQuery, limit);
|
|
102
|
+
return rows.map((row) => ({
|
|
103
|
+
document: rowToDocument(row, "d_"),
|
|
104
|
+
section: row.s_id ? rowToSection(row, "s_") : undefined,
|
|
105
|
+
chunk: rowToChunk(row, "c_"),
|
|
106
|
+
rank: numberValue(row.rank)
|
|
107
|
+
}));
|
|
108
|
+
}
|
|
109
|
+
findEntitiesByNormalizedNames(names) {
|
|
110
|
+
if (!names.length) {
|
|
111
|
+
return [];
|
|
112
|
+
}
|
|
113
|
+
const statement = this.db.prepare("SELECT * FROM entities WHERE normalized_name = ?");
|
|
114
|
+
return names.flatMap((name) => statement.all(name).map(rowToEntity));
|
|
115
|
+
}
|
|
116
|
+
entityDocumentFrequencies(entityIds) {
|
|
117
|
+
const frequencies = new Map();
|
|
118
|
+
if (!entityIds.length) {
|
|
119
|
+
return frequencies;
|
|
120
|
+
}
|
|
121
|
+
const statement = this.db.prepare(`
|
|
122
|
+
WITH related_documents(document_id) AS (
|
|
123
|
+
SELECT document.id
|
|
124
|
+
FROM edges edge
|
|
125
|
+
JOIN documents document ON document.id = edge.from_id
|
|
126
|
+
WHERE edge.to_id = ? AND edge.kind <> 'CONTAINS'
|
|
127
|
+
UNION
|
|
128
|
+
SELECT section.document_id
|
|
129
|
+
FROM edges edge
|
|
130
|
+
JOIN sections section ON section.id = edge.from_id
|
|
131
|
+
WHERE edge.to_id = ? AND edge.kind <> 'CONTAINS'
|
|
132
|
+
UNION
|
|
133
|
+
SELECT chunk.document_id
|
|
134
|
+
FROM edges edge
|
|
135
|
+
JOIN chunks chunk ON chunk.id = edge.from_id
|
|
136
|
+
WHERE edge.to_id = ? AND edge.kind <> 'CONTAINS'
|
|
137
|
+
UNION
|
|
138
|
+
SELECT document.id
|
|
139
|
+
FROM edges edge
|
|
140
|
+
JOIN documents document ON document.id = edge.to_id
|
|
141
|
+
WHERE edge.from_id = ? AND edge.kind <> 'CONTAINS'
|
|
142
|
+
UNION
|
|
143
|
+
SELECT section.document_id
|
|
144
|
+
FROM edges edge
|
|
145
|
+
JOIN sections section ON section.id = edge.to_id
|
|
146
|
+
WHERE edge.from_id = ? AND edge.kind <> 'CONTAINS'
|
|
147
|
+
UNION
|
|
148
|
+
SELECT chunk.document_id
|
|
149
|
+
FROM edges edge
|
|
150
|
+
JOIN chunks chunk ON chunk.id = edge.to_id
|
|
151
|
+
WHERE edge.from_id = ? AND edge.kind <> 'CONTAINS'
|
|
152
|
+
)
|
|
153
|
+
SELECT count(DISTINCT document_id) AS count FROM related_documents
|
|
154
|
+
`);
|
|
155
|
+
for (const entityId of entityIds) {
|
|
156
|
+
const row = statement.get(entityId, entityId, entityId, entityId, entityId, entityId);
|
|
157
|
+
frequencies.set(entityId, row.count);
|
|
158
|
+
}
|
|
159
|
+
return frequencies;
|
|
160
|
+
}
|
|
161
|
+
findEntityDefinitions(entityIds) {
|
|
162
|
+
if (!entityIds.length) {
|
|
163
|
+
return [];
|
|
164
|
+
}
|
|
165
|
+
const statement = this.db.prepare(`
|
|
166
|
+
SELECT
|
|
167
|
+
d.id AS d_id, d.path AS d_path, d.title AS d_title, d.type AS d_type, d.status AS d_status,
|
|
168
|
+
d.hash AS d_hash, d.trust_tier AS d_trust_tier, d.updated_at AS d_updated_at,
|
|
169
|
+
d.indexed_at AS d_indexed_at, d.metadata_json AS d_metadata_json,
|
|
170
|
+
s.id AS s_id, s.document_id AS s_document_id, s.anchor AS s_anchor, s.heading AS s_heading,
|
|
171
|
+
s.level AS s_level, s.start_line AS s_start_line, s.end_line AS s_end_line, s.content AS s_content,
|
|
172
|
+
e.weight AS rank
|
|
173
|
+
FROM edges e
|
|
174
|
+
LEFT JOIN sections s ON s.id = e.from_id
|
|
175
|
+
JOIN documents d ON d.id = COALESCE(s.document_id, e.from_id)
|
|
176
|
+
WHERE e.kind = 'DEFINES' AND e.to_id = ?
|
|
177
|
+
ORDER BY e.weight DESC, d.path ASC, s.start_line ASC, e.id ASC
|
|
178
|
+
LIMIT 3
|
|
179
|
+
`);
|
|
180
|
+
const sectionChunk = this.db.prepare("SELECT * FROM chunks WHERE section_id = ? ORDER BY id LIMIT 1");
|
|
181
|
+
const documentChunk = this.db.prepare("SELECT * FROM chunks WHERE document_id = ? ORDER BY id LIMIT 1");
|
|
182
|
+
return entityIds.flatMap((entityId) => statement.all(entityId).map((row) => ({
|
|
183
|
+
document: rowToDocument(row, "d_"),
|
|
184
|
+
section: row.s_id ? rowToSection(row, "s_") : undefined,
|
|
185
|
+
chunk: definitionChunk(row, sectionChunk, documentChunk),
|
|
186
|
+
rank: numberValue(row.rank)
|
|
187
|
+
})));
|
|
188
|
+
}
|
|
189
|
+
searchSemanticChunks(queryVector, provider, model, limit) {
|
|
190
|
+
const rows = this.db.prepare(`
|
|
191
|
+
SELECT
|
|
192
|
+
d.id AS d_id, d.path AS d_path, d.title AS d_title, d.type AS d_type, d.status AS d_status,
|
|
193
|
+
d.hash AS d_hash, d.trust_tier AS d_trust_tier, d.updated_at AS d_updated_at,
|
|
194
|
+
d.indexed_at AS d_indexed_at, d.metadata_json AS d_metadata_json,
|
|
195
|
+
s.id AS s_id, s.document_id AS s_document_id, s.anchor AS s_anchor, s.heading AS s_heading,
|
|
196
|
+
s.level AS s_level, s.start_line AS s_start_line, s.end_line AS s_end_line, s.content AS s_content,
|
|
197
|
+
c.id AS c_id, c.document_id AS c_document_id, c.section_id AS c_section_id, c.content AS c_content,
|
|
198
|
+
c.token_estimate AS c_token_estimate, c.metadata_json AS c_metadata_json,
|
|
199
|
+
v.vector_blob AS vector_blob
|
|
200
|
+
FROM chunk_vectors v
|
|
201
|
+
JOIN chunks c ON c.id = v.chunk_id
|
|
202
|
+
JOIN documents d ON d.id = c.document_id
|
|
203
|
+
LEFT JOIN sections s ON s.id = c.section_id
|
|
204
|
+
WHERE v.provider = ? AND v.model = ?
|
|
205
|
+
`).all(provider, model);
|
|
206
|
+
return rows
|
|
207
|
+
.map((row) => ({
|
|
208
|
+
document: rowToDocument(row, "d_"),
|
|
209
|
+
section: row.s_id ? rowToSection(row, "s_") : undefined,
|
|
210
|
+
chunk: rowToChunk(row, "c_"),
|
|
211
|
+
rank: 0,
|
|
212
|
+
similarity: cosine(queryVector, decodeFloat32Vector(row.vector_blob))
|
|
213
|
+
}))
|
|
214
|
+
.filter((row) => row.similarity > 0)
|
|
215
|
+
.sort((a, b) => b.similarity - a.similarity)
|
|
216
|
+
.slice(0, limit);
|
|
217
|
+
}
|
|
218
|
+
contextChunkForNode(id) {
|
|
219
|
+
const chunkRow = this.db.prepare(`
|
|
220
|
+
SELECT
|
|
221
|
+
d.id AS d_id, d.path AS d_path, d.title AS d_title, d.type AS d_type, d.status AS d_status,
|
|
222
|
+
d.hash AS d_hash, d.trust_tier AS d_trust_tier, d.updated_at AS d_updated_at,
|
|
223
|
+
d.indexed_at AS d_indexed_at, d.metadata_json AS d_metadata_json,
|
|
224
|
+
s.id AS s_id, s.document_id AS s_document_id, s.anchor AS s_anchor, s.heading AS s_heading,
|
|
225
|
+
s.level AS s_level, s.start_line AS s_start_line, s.end_line AS s_end_line, s.content AS s_content,
|
|
226
|
+
c.id AS c_id, c.document_id AS c_document_id, c.section_id AS c_section_id, c.content AS c_content,
|
|
227
|
+
c.token_estimate AS c_token_estimate, c.metadata_json AS c_metadata_json,
|
|
228
|
+
0 AS rank
|
|
229
|
+
FROM chunks c
|
|
230
|
+
JOIN documents d ON d.id = c.document_id
|
|
231
|
+
LEFT JOIN sections s ON s.id = c.section_id
|
|
232
|
+
WHERE c.id = ?
|
|
233
|
+
LIMIT 1
|
|
234
|
+
`).get(id);
|
|
235
|
+
if (chunkRow) {
|
|
236
|
+
return rowToChunkSearchRow(chunkRow);
|
|
237
|
+
}
|
|
238
|
+
const sectionRow = this.db.prepare(`
|
|
239
|
+
SELECT
|
|
240
|
+
d.id AS d_id, d.path AS d_path, d.title AS d_title, d.type AS d_type, d.status AS d_status,
|
|
241
|
+
d.hash AS d_hash, d.trust_tier AS d_trust_tier, d.updated_at AS d_updated_at,
|
|
242
|
+
d.indexed_at AS d_indexed_at, d.metadata_json AS d_metadata_json,
|
|
243
|
+
s.id AS s_id, s.document_id AS s_document_id, s.anchor AS s_anchor, s.heading AS s_heading,
|
|
244
|
+
s.level AS s_level, s.start_line AS s_start_line, s.end_line AS s_end_line, s.content AS s_content,
|
|
245
|
+
c.id AS c_id, c.document_id AS c_document_id, c.section_id AS c_section_id, c.content AS c_content,
|
|
246
|
+
c.token_estimate AS c_token_estimate, c.metadata_json AS c_metadata_json,
|
|
247
|
+
0 AS rank
|
|
248
|
+
FROM sections s
|
|
249
|
+
JOIN documents d ON d.id = s.document_id
|
|
250
|
+
JOIN chunks c ON c.section_id = s.id
|
|
251
|
+
WHERE s.id = ?
|
|
252
|
+
ORDER BY c.id
|
|
253
|
+
LIMIT 1
|
|
254
|
+
`).get(id);
|
|
255
|
+
if (sectionRow) {
|
|
256
|
+
return rowToChunkSearchRow(sectionRow);
|
|
257
|
+
}
|
|
258
|
+
const documentRow = this.db.prepare(`
|
|
259
|
+
SELECT
|
|
260
|
+
d.id AS d_id, d.path AS d_path, d.title AS d_title, d.type AS d_type, d.status AS d_status,
|
|
261
|
+
d.hash AS d_hash, d.trust_tier AS d_trust_tier, d.updated_at AS d_updated_at,
|
|
262
|
+
d.indexed_at AS d_indexed_at, d.metadata_json AS d_metadata_json,
|
|
263
|
+
s.id AS s_id, s.document_id AS s_document_id, s.anchor AS s_anchor, s.heading AS s_heading,
|
|
264
|
+
s.level AS s_level, s.start_line AS s_start_line, s.end_line AS s_end_line, s.content AS s_content,
|
|
265
|
+
c.id AS c_id, c.document_id AS c_document_id, c.section_id AS c_section_id, c.content AS c_content,
|
|
266
|
+
c.token_estimate AS c_token_estimate, c.metadata_json AS c_metadata_json,
|
|
267
|
+
0 AS rank
|
|
268
|
+
FROM documents d
|
|
269
|
+
JOIN chunks c ON c.document_id = d.id
|
|
270
|
+
LEFT JOIN sections s ON s.id = c.section_id
|
|
271
|
+
WHERE d.id = ?
|
|
272
|
+
ORDER BY s.start_line ASC, c.id ASC
|
|
273
|
+
LIMIT 1
|
|
274
|
+
`).get(id);
|
|
275
|
+
return documentRow ? rowToChunkSearchRow(documentRow) : undefined;
|
|
276
|
+
}
|
|
277
|
+
resolveNode(query) {
|
|
278
|
+
const resolution = this.resolveNodeDetailed(query);
|
|
279
|
+
return resolution.status === "found" ? resolution.node : undefined;
|
|
280
|
+
}
|
|
281
|
+
resolveNodeDetailed(query) {
|
|
282
|
+
const trimmed = query.trim();
|
|
283
|
+
if (!trimmed) {
|
|
284
|
+
return { status: "not_found", query, error: "not_found" };
|
|
285
|
+
}
|
|
286
|
+
const direct = this.getNode(trimmed);
|
|
287
|
+
if (direct) {
|
|
288
|
+
return { status: "found", node: direct };
|
|
289
|
+
}
|
|
290
|
+
const pathAnchor = this.resolveSectionByPathAnchor(trimmed);
|
|
291
|
+
if (pathAnchor) {
|
|
292
|
+
return { status: "found", node: pathAnchor };
|
|
293
|
+
}
|
|
294
|
+
const normalized = trimmed.toLowerCase();
|
|
295
|
+
const document = this.db.prepare("SELECT * FROM documents WHERE lower(path) = ? OR lower(title) = ? OR id = ? ORDER BY path, id LIMIT 1").get(normalized, normalized, query);
|
|
296
|
+
if (document) {
|
|
297
|
+
const data = rowToDocument(document);
|
|
298
|
+
return { status: "found", node: { id: data.id, label: data.title, kind: "document", data } };
|
|
299
|
+
}
|
|
300
|
+
const sourceRef = this.db.prepare("SELECT * FROM source_refs WHERE normalized_path = ? OR id = ? ORDER BY path, id LIMIT 1").get(normalized, query);
|
|
301
|
+
if (sourceRef) {
|
|
302
|
+
const data = rowToSourceRef(sourceRef);
|
|
303
|
+
return { status: "found", node: { id: data.id, label: data.path, kind: "source_ref", data } };
|
|
304
|
+
}
|
|
305
|
+
const section = this.resolveSectionByHeading(trimmed);
|
|
306
|
+
if (section.status !== "not_found") {
|
|
307
|
+
return section;
|
|
308
|
+
}
|
|
309
|
+
const entity = this.db.prepare("SELECT * FROM entities WHERE normalized_name = ? OR id = ? ORDER BY kind, id LIMIT 1").get(normalized, query);
|
|
310
|
+
if (entity) {
|
|
311
|
+
const data = rowToEntity(entity);
|
|
312
|
+
return { status: "found", node: { id: data.id, label: data.name, kind: "entity", data } };
|
|
313
|
+
}
|
|
314
|
+
return section;
|
|
315
|
+
}
|
|
316
|
+
getNode(id) {
|
|
317
|
+
const probes = [
|
|
318
|
+
["document", "SELECT * FROM documents WHERE id = ?", (row) => {
|
|
319
|
+
const data = rowToDocument(row);
|
|
320
|
+
return { id: data.id, label: data.title, kind: "document", data };
|
|
321
|
+
}],
|
|
322
|
+
["section", "SELECT * FROM sections WHERE id = ?", (row) => {
|
|
323
|
+
const data = rowToSection(row);
|
|
324
|
+
return { id: data.id, label: data.heading, kind: "section", data };
|
|
325
|
+
}],
|
|
326
|
+
["entity", "SELECT * FROM entities WHERE id = ?", (row) => {
|
|
327
|
+
const data = rowToEntity(row);
|
|
328
|
+
return { id: data.id, label: data.name, kind: "entity", data };
|
|
329
|
+
}],
|
|
330
|
+
["source_ref", "SELECT * FROM source_refs WHERE id = ?", (row) => {
|
|
331
|
+
const data = rowToSourceRef(row);
|
|
332
|
+
return { id: data.id, label: data.path, kind: "source_ref", data };
|
|
333
|
+
}],
|
|
334
|
+
["chunk", "SELECT * FROM chunks WHERE id = ?", (row) => {
|
|
335
|
+
const data = rowToChunk(row);
|
|
336
|
+
return { id: data.id, label: data.id, kind: "chunk", data };
|
|
337
|
+
}]
|
|
338
|
+
];
|
|
339
|
+
for (const [, sql, map] of probes) {
|
|
340
|
+
const row = this.db.prepare(sql).get(id);
|
|
341
|
+
if (row) {
|
|
342
|
+
return map(row);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return undefined;
|
|
346
|
+
}
|
|
347
|
+
edgesForNode(id) {
|
|
348
|
+
const rows = this.db.prepare("SELECT * FROM edges WHERE from_id = ? OR to_id = ? ORDER BY weight DESC, confidence DESC").all(id, id);
|
|
349
|
+
return rows.map(rowToEdge);
|
|
350
|
+
}
|
|
351
|
+
resolveSectionByPathAnchor(query) {
|
|
352
|
+
const hashIndex = query.indexOf("#");
|
|
353
|
+
if (hashIndex < 0) {
|
|
354
|
+
return undefined;
|
|
355
|
+
}
|
|
356
|
+
const rawPath = normalizePath(query.slice(0, hashIndex).trim()).replace(/^\.\//, "").toLowerCase();
|
|
357
|
+
const rawAnchor = query.slice(hashIndex + 1).trim();
|
|
358
|
+
if (!rawPath || !rawAnchor) {
|
|
359
|
+
return undefined;
|
|
360
|
+
}
|
|
361
|
+
const pathCandidates = sectionPathCandidates(rawPath);
|
|
362
|
+
const placeholders = pathCandidates.map(() => "?").join(", ");
|
|
363
|
+
const row = this.db.prepare(`
|
|
364
|
+
SELECT s.*
|
|
365
|
+
FROM sections s
|
|
366
|
+
JOIN documents d ON d.id = s.document_id
|
|
367
|
+
WHERE lower(d.path) IN (${placeholders}) AND lower(s.anchor) = ?
|
|
368
|
+
ORDER BY d.path ASC, s.start_line ASC, s.id ASC
|
|
369
|
+
LIMIT 1
|
|
370
|
+
`).get(...pathCandidates, slugifyHeading(rawAnchor));
|
|
371
|
+
if (!row) {
|
|
372
|
+
return undefined;
|
|
373
|
+
}
|
|
374
|
+
const data = rowToSection(row);
|
|
375
|
+
return { id: data.id, label: data.heading, kind: "section", data };
|
|
376
|
+
}
|
|
377
|
+
resolveSectionByHeading(query) {
|
|
378
|
+
const normalizedHeading = query.trim().toLowerCase();
|
|
379
|
+
const normalizedAnchor = slugifyHeading(query);
|
|
380
|
+
const rows = this.db.prepare(`
|
|
381
|
+
SELECT d.path AS document_path, s.*
|
|
382
|
+
FROM sections s
|
|
383
|
+
JOIN documents d ON d.id = s.document_id
|
|
384
|
+
WHERE lower(s.heading) = ? OR lower(s.anchor) = ?
|
|
385
|
+
ORDER BY d.path ASC, s.start_line ASC, s.id ASC
|
|
386
|
+
`).all(normalizedHeading, normalizedAnchor);
|
|
387
|
+
if (rows.length === 0) {
|
|
388
|
+
return { status: "not_found", query, error: "not_found" };
|
|
389
|
+
}
|
|
390
|
+
if (rows.length === 1) {
|
|
391
|
+
const data = rowToSection(rows[0]);
|
|
392
|
+
return { status: "found", node: { id: data.id, label: data.heading, kind: "section", data } };
|
|
393
|
+
}
|
|
394
|
+
return {
|
|
395
|
+
status: "ambiguous",
|
|
396
|
+
query,
|
|
397
|
+
error: "ambiguous_section",
|
|
398
|
+
candidates: rows.map((row) => {
|
|
399
|
+
const section = rowToSection(row);
|
|
400
|
+
return {
|
|
401
|
+
kind: "section",
|
|
402
|
+
id: section.id,
|
|
403
|
+
documentPath: stringValue(row.document_path),
|
|
404
|
+
anchor: section.anchor,
|
|
405
|
+
heading: section.heading,
|
|
406
|
+
line: section.startLine
|
|
407
|
+
};
|
|
408
|
+
})
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
edgesFromNode(id) {
|
|
412
|
+
const rows = this.db.prepare("SELECT * FROM edges WHERE from_id = ? ORDER BY weight DESC, confidence DESC").all(id);
|
|
413
|
+
return rows.map(rowToEdge);
|
|
414
|
+
}
|
|
415
|
+
allDocuments() {
|
|
416
|
+
const rows = this.db.prepare("SELECT * FROM documents ORDER BY path").all();
|
|
417
|
+
return rows.map((row) => rowToDocument(row));
|
|
418
|
+
}
|
|
419
|
+
allSections() {
|
|
420
|
+
const rows = this.db.prepare("SELECT * FROM sections ORDER BY document_id, start_line, id").all();
|
|
421
|
+
return rows.map((row) => rowToSection(row));
|
|
422
|
+
}
|
|
423
|
+
allEntities() {
|
|
424
|
+
const rows = this.db.prepare("SELECT * FROM entities ORDER BY kind, normalized_name, id").all();
|
|
425
|
+
return rows.map(rowToEntity);
|
|
426
|
+
}
|
|
427
|
+
allSourceRefs() {
|
|
428
|
+
const rows = this.db.prepare("SELECT * FROM source_refs ORDER BY path").all();
|
|
429
|
+
return rows.map(rowToSourceRef);
|
|
430
|
+
}
|
|
431
|
+
allEdges() {
|
|
432
|
+
const rows = this.db.prepare("SELECT * FROM edges ORDER BY from_id, to_id, kind, provenance").all();
|
|
433
|
+
return rows.map(rowToEdge);
|
|
434
|
+
}
|
|
435
|
+
documentLinkStats() {
|
|
436
|
+
const documents = this.allDocuments();
|
|
437
|
+
const statement = this.db.prepare(`
|
|
438
|
+
SELECT
|
|
439
|
+
SUM(CASE WHEN e.kind <> 'CONTAINS' THEN 1 ELSE 0 END) AS non_containment_edges,
|
|
440
|
+
SUM(CASE WHEN e.kind = 'DEFINES' THEN 1 ELSE 0 END) AS definition_edges
|
|
441
|
+
FROM documents d
|
|
442
|
+
LEFT JOIN sections s ON s.document_id = d.id
|
|
443
|
+
LEFT JOIN chunks c ON c.document_id = d.id
|
|
444
|
+
LEFT JOIN edges e ON e.from_id IN (d.id, s.id, c.id) OR e.to_id IN (d.id, s.id, c.id)
|
|
445
|
+
WHERE d.id = ?
|
|
446
|
+
`);
|
|
447
|
+
return documents.map((document) => {
|
|
448
|
+
const row = statement.get(document.id);
|
|
449
|
+
return {
|
|
450
|
+
document,
|
|
451
|
+
nonContainmentEdges: numberValue(row?.non_containment_edges),
|
|
452
|
+
definitionEdges: numberValue(row?.definition_edges)
|
|
453
|
+
};
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
definitionCollisions() {
|
|
457
|
+
const collisionRows = this.db.prepare(`
|
|
458
|
+
SELECT edge.to_id AS entity_id
|
|
459
|
+
FROM edges edge
|
|
460
|
+
JOIN entities entity ON entity.id = edge.to_id
|
|
461
|
+
LEFT JOIN sections section ON section.id = edge.from_id
|
|
462
|
+
JOIN documents document ON document.id = COALESCE(section.document_id, edge.from_id)
|
|
463
|
+
WHERE edge.kind = 'DEFINES' AND document.status = 'active'
|
|
464
|
+
GROUP BY edge.to_id
|
|
465
|
+
HAVING COUNT(DISTINCT document.id) > 1
|
|
466
|
+
`).all();
|
|
467
|
+
const entityStatement = this.db.prepare("SELECT * FROM entities WHERE id = ?");
|
|
468
|
+
const documentsStatement = this.db.prepare(`
|
|
469
|
+
SELECT DISTINCT document.*
|
|
470
|
+
FROM edges edge
|
|
471
|
+
LEFT JOIN sections section ON section.id = edge.from_id
|
|
472
|
+
JOIN documents document ON document.id = COALESCE(section.document_id, edge.from_id)
|
|
473
|
+
WHERE edge.kind = 'DEFINES' AND edge.to_id = ? AND document.status = 'active'
|
|
474
|
+
ORDER BY document.path
|
|
475
|
+
`);
|
|
476
|
+
return collisionRows.map((row) => ({
|
|
477
|
+
entity: rowToEntity(entityStatement.get(row.entity_id)),
|
|
478
|
+
documents: documentsStatement.all(row.entity_id).map((documentRow) => rowToDocument(documentRow))
|
|
479
|
+
}));
|
|
480
|
+
}
|
|
481
|
+
insertRecords(records, mode) {
|
|
482
|
+
const entityInsert = mode === "incremental" ? "INSERT OR IGNORE" : "INSERT";
|
|
483
|
+
const sourceRefInsert = mode === "incremental" ? "INSERT OR IGNORE" : "INSERT";
|
|
484
|
+
const edgeInsert = mode === "incremental" ? "INSERT OR REPLACE" : "INSERT";
|
|
485
|
+
const insertDocument = this.db.prepare(`
|
|
486
|
+
INSERT INTO documents (id, path, title, type, status, hash, trust_tier, updated_at, indexed_at, metadata_json)
|
|
487
|
+
VALUES (@id, @path, @title, @type, @status, @hash, @trustTier, @updatedAt, @indexedAt, @metadataJson)
|
|
488
|
+
`);
|
|
489
|
+
const insertSection = this.db.prepare(`
|
|
490
|
+
INSERT INTO sections (id, document_id, anchor, heading, level, start_line, end_line, content)
|
|
491
|
+
VALUES (@id, @documentId, @anchor, @heading, @level, @startLine, @endLine, @content)
|
|
492
|
+
`);
|
|
493
|
+
const insertEntity = this.db.prepare(`
|
|
494
|
+
${entityInsert} INTO entities (id, name, normalized_name, kind, namespace, created_at, metadata_json)
|
|
495
|
+
VALUES (@id, @name, @normalizedName, @kind, @namespace, @createdAt, @metadataJson)
|
|
496
|
+
`);
|
|
497
|
+
const insertSourceRef = this.db.prepare(`
|
|
498
|
+
${sourceRefInsert} INTO source_refs (id, path, normalized_path, created_at, metadata_json)
|
|
499
|
+
VALUES (@id, @path, @normalizedPath, @createdAt, @metadataJson)
|
|
500
|
+
`);
|
|
501
|
+
const insertEdge = this.db.prepare(`
|
|
502
|
+
${edgeInsert} INTO edges (id, from_id, to_id, kind, weight, confidence, provenance, metadata_json, created_at)
|
|
503
|
+
VALUES (@id, @fromId, @toId, @kind, @weight, @confidence, @provenance, @metadataJson, @createdAt)
|
|
504
|
+
`);
|
|
505
|
+
const insertChunk = this.db.prepare(`
|
|
506
|
+
INSERT INTO chunks (id, document_id, section_id, content, token_estimate, metadata_json)
|
|
507
|
+
VALUES (@id, @documentId, @sectionId, @content, @tokenEstimate, @metadataJson)
|
|
508
|
+
`);
|
|
509
|
+
const insertFts = this.db.prepare(`
|
|
510
|
+
INSERT INTO chunks_fts (rowid, content)
|
|
511
|
+
VALUES (@rowid, @content)
|
|
512
|
+
`);
|
|
513
|
+
const insertVector = this.prepareInsertVector();
|
|
514
|
+
for (const document of records.documents) {
|
|
515
|
+
insertDocument.run({
|
|
516
|
+
id: document.id,
|
|
517
|
+
path: document.path,
|
|
518
|
+
title: document.title,
|
|
519
|
+
type: document.type,
|
|
520
|
+
status: document.status,
|
|
521
|
+
hash: document.hash,
|
|
522
|
+
trustTier: document.trustTier,
|
|
523
|
+
updatedAt: document.updatedAt ?? null,
|
|
524
|
+
indexedAt: document.indexedAt,
|
|
525
|
+
metadataJson: toJson(document.metadata)
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
for (const section of records.sections) {
|
|
529
|
+
insertSection.run(section);
|
|
530
|
+
}
|
|
531
|
+
for (const entity of records.entities) {
|
|
532
|
+
insertEntity.run({
|
|
533
|
+
id: entity.id,
|
|
534
|
+
name: entity.name,
|
|
535
|
+
normalizedName: entity.normalizedName,
|
|
536
|
+
kind: entity.kind,
|
|
537
|
+
namespace: entity.namespace ?? null,
|
|
538
|
+
createdAt: entity.createdAt,
|
|
539
|
+
metadataJson: toJson(entity.metadata)
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
for (const sourceRef of records.sourceRefs) {
|
|
543
|
+
insertSourceRef.run({
|
|
544
|
+
id: sourceRef.id,
|
|
545
|
+
path: sourceRef.path,
|
|
546
|
+
normalizedPath: sourceRef.normalizedPath,
|
|
547
|
+
createdAt: sourceRef.createdAt,
|
|
548
|
+
metadataJson: toJson(sourceRef.metadata)
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
for (const edge of records.edges) {
|
|
552
|
+
insertEdge.run({
|
|
553
|
+
id: edge.id,
|
|
554
|
+
fromId: edge.fromId,
|
|
555
|
+
toId: edge.toId,
|
|
556
|
+
kind: edge.kind,
|
|
557
|
+
weight: edge.weight,
|
|
558
|
+
confidence: edge.confidence,
|
|
559
|
+
provenance: edge.provenance,
|
|
560
|
+
metadataJson: toJson(edge.metadata),
|
|
561
|
+
createdAt: edge.createdAt
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
for (const chunk of records.chunks) {
|
|
565
|
+
const result = insertChunk.run({
|
|
566
|
+
id: chunk.id,
|
|
567
|
+
documentId: chunk.documentId,
|
|
568
|
+
sectionId: chunk.sectionId ?? null,
|
|
569
|
+
content: chunk.content,
|
|
570
|
+
tokenEstimate: chunk.tokenEstimate,
|
|
571
|
+
metadataJson: toJson(chunk.metadata)
|
|
572
|
+
});
|
|
573
|
+
insertFts.run({
|
|
574
|
+
rowid: result.lastInsertRowid,
|
|
575
|
+
content: ftsIndexContent(chunk.content)
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
for (const vector of records.vectors) {
|
|
579
|
+
insertVector.run(vectorToParams(vector));
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
prepareInsertVector() {
|
|
583
|
+
return this.db.prepare(`
|
|
584
|
+
INSERT INTO chunk_vectors (chunk_id, provider, model, dimensions, vector_blob, created_at)
|
|
585
|
+
VALUES (@chunkId, @provider, @model, @dimensions, @vectorBlob, @createdAt)
|
|
586
|
+
`);
|
|
587
|
+
}
|
|
588
|
+
deleteDocumentDerivedRecords(documentId) {
|
|
589
|
+
const chunkRows = this.db.prepare("SELECT rowid, content FROM chunks WHERE document_id = ?").all(documentId);
|
|
590
|
+
const deleteFts = this.db.prepare("INSERT INTO chunks_fts(chunks_fts, rowid, content) VALUES (@operation, @rowid, @content)");
|
|
591
|
+
for (const row of chunkRows) {
|
|
592
|
+
deleteFts.run({ operation: "delete", rowid: row.rowid, content: ftsIndexContent(row.content) });
|
|
593
|
+
}
|
|
594
|
+
const nodeRows = this.db.prepare(`
|
|
595
|
+
SELECT id FROM documents WHERE id = ?
|
|
596
|
+
UNION SELECT id FROM sections WHERE document_id = ?
|
|
597
|
+
UNION SELECT id FROM chunks WHERE document_id = ?
|
|
598
|
+
`).all(documentId, documentId, documentId);
|
|
599
|
+
const deleteEdges = this.db.prepare("DELETE FROM edges WHERE from_id = ? OR to_id = ?");
|
|
600
|
+
for (const row of nodeRows) {
|
|
601
|
+
deleteEdges.run(row.id, row.id);
|
|
602
|
+
}
|
|
603
|
+
this.db.prepare("DELETE FROM documents WHERE id = ?").run(documentId);
|
|
604
|
+
}
|
|
605
|
+
pruneUnreferencedEntitiesAndSources() {
|
|
606
|
+
this.db.exec(`
|
|
607
|
+
DELETE FROM entities
|
|
608
|
+
WHERE id NOT IN (SELECT from_id FROM edges UNION SELECT to_id FROM edges);
|
|
609
|
+
DELETE FROM source_refs
|
|
610
|
+
WHERE id NOT IN (SELECT from_id FROM edges UNION SELECT to_id FROM edges);
|
|
611
|
+
`);
|
|
612
|
+
}
|
|
613
|
+
compactStorage(options) {
|
|
614
|
+
this.db.exec("INSERT INTO chunks_fts(chunks_fts) VALUES('optimize');");
|
|
615
|
+
this.db.exec("PRAGMA optimize;");
|
|
616
|
+
this.db.exec("PRAGMA wal_checkpoint(TRUNCATE);");
|
|
617
|
+
if (options.vacuum) {
|
|
618
|
+
this.db.exec("VACUUM;");
|
|
619
|
+
this.db.exec("PRAGMA wal_checkpoint(TRUNCATE);");
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
function definitionChunk(row, sectionChunk, documentChunk) {
|
|
624
|
+
const sectionChunkRow = row.s_id ? sectionChunk.get(row.s_id) : undefined;
|
|
625
|
+
const chunkRow = sectionChunkRow ?? documentChunk.get(row.d_id);
|
|
626
|
+
return chunkRow ? rowToChunk(chunkRow) : {
|
|
627
|
+
id: `${row.d_id}:document`,
|
|
628
|
+
documentId: stringValue(row.d_id),
|
|
629
|
+
content: stringValue(row.d_title),
|
|
630
|
+
tokenEstimate: 1
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
function sectionPathCandidates(rawPath) {
|
|
634
|
+
const withoutExtension = rawPath.replace(/\.(?:md|mdx)$/i, "");
|
|
635
|
+
return [...new Set([rawPath, `${withoutExtension}.md`, `${withoutExtension}.mdx`])];
|
|
636
|
+
}
|
|
637
|
+
function tableCount(db, table) {
|
|
638
|
+
const row = db.prepare(countStatements[table]).get();
|
|
639
|
+
return row.count;
|
|
640
|
+
}
|
|
641
|
+
function objectStorageStats(db) {
|
|
642
|
+
const schemaRows = db.prepare(`
|
|
643
|
+
SELECT name, type
|
|
644
|
+
FROM sqlite_schema
|
|
645
|
+
WHERE name NOT LIKE 'sqlite_%'
|
|
646
|
+
ORDER BY name
|
|
647
|
+
`).all();
|
|
648
|
+
const sizes = dbstatSizes(db);
|
|
649
|
+
const entries = schemaRows.map((row) => ({
|
|
650
|
+
name: row.name,
|
|
651
|
+
type: row.type,
|
|
652
|
+
category: objectCategory(row.name, row.type),
|
|
653
|
+
rows: row.type === "table" ? safeObjectRowCount(db, row.name) : undefined,
|
|
654
|
+
bytes: sizes.get(row.name)
|
|
655
|
+
}));
|
|
656
|
+
return {
|
|
657
|
+
dbstatAvailable: sizes.size > 0,
|
|
658
|
+
entries
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
function dbstatSizes(db) {
|
|
662
|
+
try {
|
|
663
|
+
const rows = db.prepare(`
|
|
664
|
+
SELECT name, SUM(pgsize) AS bytes
|
|
665
|
+
FROM dbstat
|
|
666
|
+
GROUP BY name
|
|
667
|
+
`).all();
|
|
668
|
+
return new Map(rows.map((row) => [row.name, Number(row.bytes)]));
|
|
669
|
+
}
|
|
670
|
+
catch {
|
|
671
|
+
return new Map();
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
function safeObjectRowCount(db, name) {
|
|
675
|
+
try {
|
|
676
|
+
const row = db.prepare(`SELECT count(*) AS count FROM ${quoteIdentifier(name)}`).get();
|
|
677
|
+
return row.count;
|
|
678
|
+
}
|
|
679
|
+
catch {
|
|
680
|
+
return undefined;
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
function pathStorageContributions(db) {
|
|
684
|
+
const rows = db.prepare(`
|
|
685
|
+
SELECT
|
|
686
|
+
d.path AS path,
|
|
687
|
+
COUNT(DISTINCT c.id) AS chunks,
|
|
688
|
+
COALESCE(SUM(LENGTH(c.content)), 0) AS content_chars
|
|
689
|
+
FROM documents d
|
|
690
|
+
LEFT JOIN chunks c ON c.document_id = d.id
|
|
691
|
+
GROUP BY d.id, d.path
|
|
692
|
+
ORDER BY d.path
|
|
693
|
+
`).all();
|
|
694
|
+
const byGroup = new Map();
|
|
695
|
+
for (const row of rows) {
|
|
696
|
+
const group = pathGroup(row.path);
|
|
697
|
+
const current = byGroup.get(group) ?? { group, documents: 0, chunks: 0, contentBytes: 0 };
|
|
698
|
+
byGroup.set(group, {
|
|
699
|
+
group,
|
|
700
|
+
documents: current.documents + 1,
|
|
701
|
+
chunks: current.chunks + Number(row.chunks),
|
|
702
|
+
contentBytes: current.contentBytes + Buffer.byteLength(row.path, "utf8") + Number(row.content_chars)
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
return [...byGroup.values()].sort((left, right) => right.contentBytes - left.contentBytes || left.group.localeCompare(right.group));
|
|
706
|
+
}
|
|
707
|
+
function edgeKindStorageStats(db) {
|
|
708
|
+
const rows = db.prepare(`
|
|
709
|
+
SELECT kind, COUNT(*) AS edges, AVG(weight) AS average_weight, AVG(confidence) AS average_confidence
|
|
710
|
+
FROM edges
|
|
711
|
+
GROUP BY kind
|
|
712
|
+
ORDER BY edges DESC, kind ASC
|
|
713
|
+
`).all();
|
|
714
|
+
return rows.map((row) => ({
|
|
715
|
+
kind: row.kind,
|
|
716
|
+
edges: Number(row.edges),
|
|
717
|
+
averageWeight: Number(row.average_weight),
|
|
718
|
+
averageConfidence: Number(row.average_confidence)
|
|
719
|
+
}));
|
|
720
|
+
}
|
|
721
|
+
function highDegreeNodeStats(db, resolveNode) {
|
|
722
|
+
const rows = db.prepare(`
|
|
723
|
+
WITH endpoints(id) AS (
|
|
724
|
+
SELECT from_id FROM edges WHERE kind <> 'CONTAINS'
|
|
725
|
+
UNION ALL
|
|
726
|
+
SELECT to_id FROM edges WHERE kind <> 'CONTAINS'
|
|
727
|
+
)
|
|
728
|
+
SELECT id, COUNT(*) AS degree
|
|
729
|
+
FROM endpoints
|
|
730
|
+
GROUP BY id
|
|
731
|
+
ORDER BY degree DESC, id ASC
|
|
732
|
+
LIMIT 10
|
|
733
|
+
`).all();
|
|
734
|
+
return rows.map((row) => {
|
|
735
|
+
const node = resolveNode(row.id);
|
|
736
|
+
return {
|
|
737
|
+
id: row.id,
|
|
738
|
+
label: node?.label ?? row.id,
|
|
739
|
+
kind: node?.kind ?? "unknown",
|
|
740
|
+
degree: Number(row.degree)
|
|
741
|
+
};
|
|
742
|
+
});
|
|
743
|
+
}
|
|
744
|
+
function vectorStorageStats(db) {
|
|
745
|
+
const rows = db.prepare(`
|
|
746
|
+
SELECT provider, model, dimensions, COUNT(*) AS vectors
|
|
747
|
+
FROM chunk_vectors
|
|
748
|
+
GROUP BY provider, model, dimensions
|
|
749
|
+
ORDER BY vectors DESC, provider ASC, model ASC, dimensions ASC
|
|
750
|
+
`).all();
|
|
751
|
+
return rows.map((row) => ({
|
|
752
|
+
provider: row.provider,
|
|
753
|
+
model: row.model,
|
|
754
|
+
dimensions: Number(row.dimensions),
|
|
755
|
+
vectors: Number(row.vectors)
|
|
756
|
+
}));
|
|
757
|
+
}
|
|
758
|
+
function vectorStorageFormat(db) {
|
|
759
|
+
const columns = new Set(db.prepare("PRAGMA table_info(chunk_vectors)").all().map((row) => row.name));
|
|
760
|
+
if (columns.has("vector_blob")) {
|
|
761
|
+
return "float32_blob";
|
|
762
|
+
}
|
|
763
|
+
if (columns.has("vector_json")) {
|
|
764
|
+
return "legacy_json";
|
|
765
|
+
}
|
|
766
|
+
return "unknown";
|
|
767
|
+
}
|
|
768
|
+
function walCheckpointStats(db) {
|
|
769
|
+
try {
|
|
770
|
+
const row = db.pragma("wal_checkpoint(PASSIVE)");
|
|
771
|
+
return {
|
|
772
|
+
available: true,
|
|
773
|
+
busy: numberValue(row?.busy),
|
|
774
|
+
log: numberValue(row?.log),
|
|
775
|
+
checkpointed: numberValue(row?.checkpointed)
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
catch (error) {
|
|
779
|
+
return {
|
|
780
|
+
available: false,
|
|
781
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
782
|
+
};
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
function pragmaNumber(db, name) {
|
|
786
|
+
return numberValue(db.pragma(name, { simple: true }));
|
|
787
|
+
}
|
|
788
|
+
function pragmaString(db, name) {
|
|
789
|
+
return stringValue(db.pragma(name, { simple: true }));
|
|
790
|
+
}
|
|
791
|
+
function objectCategory(name, type) {
|
|
792
|
+
if (name.startsWith("chunks_fts_")) {
|
|
793
|
+
return "fts_shadow";
|
|
794
|
+
}
|
|
795
|
+
if (type === "table" || type === "index") {
|
|
796
|
+
return type;
|
|
797
|
+
}
|
|
798
|
+
return "other";
|
|
799
|
+
}
|
|
800
|
+
function pathGroup(documentPath) {
|
|
801
|
+
const normalized = normalizePath(documentPath).replace(/^\.\//, "");
|
|
802
|
+
const slash = normalized.indexOf("/");
|
|
803
|
+
return slash === -1 ? "." : normalized.slice(0, slash);
|
|
804
|
+
}
|
|
805
|
+
function quoteIdentifier(name) {
|
|
806
|
+
return `"${name.replace(/"/g, "\"\"")}"`;
|
|
807
|
+
}
|
|
808
|
+
const countStatements = {
|
|
809
|
+
documents: "SELECT count(*) AS count FROM documents",
|
|
810
|
+
sections: "SELECT count(*) AS count FROM sections",
|
|
811
|
+
entities: "SELECT count(*) AS count FROM entities",
|
|
812
|
+
source_refs: "SELECT count(*) AS count FROM source_refs",
|
|
813
|
+
edges: "SELECT count(*) AS count FROM edges",
|
|
814
|
+
chunks: "SELECT count(*) AS count FROM chunks",
|
|
815
|
+
chunk_vectors: "SELECT count(*) AS count FROM chunk_vectors"
|
|
816
|
+
};
|
|
817
|
+
function rowToDocument(row, prefix = "") {
|
|
818
|
+
return {
|
|
819
|
+
id: stringValue(row[`${prefix}id`]),
|
|
820
|
+
path: stringValue(row[`${prefix}path`]),
|
|
821
|
+
title: stringValue(row[`${prefix}title`]),
|
|
822
|
+
type: stringValue(row[`${prefix}type`]),
|
|
823
|
+
status: stringValue(row[`${prefix}status`]),
|
|
824
|
+
hash: stringValue(row[`${prefix}hash`]),
|
|
825
|
+
trustTier: stringValue(row[`${prefix}trust_tier`]),
|
|
826
|
+
updatedAt: optionalString(row[`${prefix}updated_at`]),
|
|
827
|
+
indexedAt: stringValue(row[`${prefix}indexed_at`]),
|
|
828
|
+
metadata: fromJson(row[`${prefix}metadata_json`])
|
|
829
|
+
};
|
|
830
|
+
}
|
|
831
|
+
function rowToSection(row, prefix = "") {
|
|
832
|
+
return {
|
|
833
|
+
id: stringValue(row[`${prefix}id`]),
|
|
834
|
+
documentId: stringValue(row[`${prefix}document_id`]),
|
|
835
|
+
anchor: stringValue(row[`${prefix}anchor`]),
|
|
836
|
+
heading: stringValue(row[`${prefix}heading`]),
|
|
837
|
+
level: numberValue(row[`${prefix}level`]),
|
|
838
|
+
startLine: numberValue(row[`${prefix}start_line`]),
|
|
839
|
+
endLine: numberValue(row[`${prefix}end_line`]),
|
|
840
|
+
content: stringValue(row[`${prefix}content`])
|
|
841
|
+
};
|
|
842
|
+
}
|
|
843
|
+
function rowToEntity(row) {
|
|
844
|
+
return {
|
|
845
|
+
id: stringValue(row.id),
|
|
846
|
+
name: stringValue(row.name),
|
|
847
|
+
normalizedName: stringValue(row.normalized_name),
|
|
848
|
+
kind: stringValue(row.kind),
|
|
849
|
+
namespace: optionalString(row.namespace),
|
|
850
|
+
createdAt: stringValue(row.created_at),
|
|
851
|
+
metadata: fromJson(row.metadata_json)
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
function rowToSourceRef(row) {
|
|
855
|
+
return {
|
|
856
|
+
id: stringValue(row.id),
|
|
857
|
+
path: stringValue(row.path),
|
|
858
|
+
normalizedPath: stringValue(row.normalized_path),
|
|
859
|
+
createdAt: stringValue(row.created_at),
|
|
860
|
+
metadata: fromJson(row.metadata_json)
|
|
861
|
+
};
|
|
862
|
+
}
|
|
863
|
+
function rowToEdge(row) {
|
|
864
|
+
return {
|
|
865
|
+
id: stringValue(row.id),
|
|
866
|
+
fromId: stringValue(row.from_id),
|
|
867
|
+
toId: stringValue(row.to_id),
|
|
868
|
+
kind: stringValue(row.kind),
|
|
869
|
+
weight: numberValue(row.weight),
|
|
870
|
+
confidence: numberValue(row.confidence),
|
|
871
|
+
provenance: stringValue(row.provenance),
|
|
872
|
+
metadata: fromJson(row.metadata_json),
|
|
873
|
+
createdAt: stringValue(row.created_at)
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
function rowToChunk(row, prefix = "") {
|
|
877
|
+
return {
|
|
878
|
+
id: stringValue(row[`${prefix}id`]),
|
|
879
|
+
documentId: stringValue(row[`${prefix}document_id`]),
|
|
880
|
+
sectionId: optionalString(row[`${prefix}section_id`]),
|
|
881
|
+
content: stringValue(row[`${prefix}content`]),
|
|
882
|
+
tokenEstimate: numberValue(row[`${prefix}token_estimate`]),
|
|
883
|
+
metadata: fromJson(row[`${prefix}metadata_json`])
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
function rowToChunkSearchRow(row) {
|
|
887
|
+
return {
|
|
888
|
+
document: rowToDocument(row, "d_"),
|
|
889
|
+
section: row.s_id ? rowToSection(row, "s_") : undefined,
|
|
890
|
+
chunk: rowToChunk(row, "c_"),
|
|
891
|
+
rank: numberValue(row.rank)
|
|
892
|
+
};
|
|
893
|
+
}
|
|
894
|
+
function toJson(value) {
|
|
895
|
+
return value === undefined ? null : JSON.stringify(value);
|
|
896
|
+
}
|
|
897
|
+
function vectorToParams(vector) {
|
|
898
|
+
return {
|
|
899
|
+
chunkId: vector.chunkId,
|
|
900
|
+
provider: vector.provider,
|
|
901
|
+
model: vector.model,
|
|
902
|
+
dimensions: vector.dimensions,
|
|
903
|
+
vectorBlob: encodeFloat32Vector(vector.vector),
|
|
904
|
+
createdAt: vector.createdAt
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
function cosine(left, right) {
|
|
908
|
+
const length = Math.min(left.length, right.length);
|
|
909
|
+
let score = 0;
|
|
910
|
+
for (let index = 0; index < length; index += 1) {
|
|
911
|
+
score += left[index] * right[index];
|
|
912
|
+
}
|
|
913
|
+
return score;
|
|
914
|
+
}
|
|
915
|
+
function fromJson(value) {
|
|
916
|
+
if (typeof value !== "string" || !value) {
|
|
917
|
+
return undefined;
|
|
918
|
+
}
|
|
919
|
+
return JSON.parse(value);
|
|
920
|
+
}
|
|
921
|
+
function stringValue(value) {
|
|
922
|
+
return typeof value === "string" ? value : String(value ?? "");
|
|
923
|
+
}
|
|
924
|
+
function optionalString(value) {
|
|
925
|
+
return typeof value === "string" && value.length ? value : undefined;
|
|
926
|
+
}
|
|
927
|
+
function numberValue(value) {
|
|
928
|
+
return typeof value === "number" ? value : Number(value ?? 0);
|
|
929
|
+
}
|