@andespindola/brainlink 0.1.0-beta.14 → 0.1.0-beta.15

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.
@@ -1,51 +0,0 @@
1
- import { createEmbeddingBuckets } from '../../domain/embeddings.js';
2
- const toTitleKey = (title) => title.toLowerCase();
3
- export const createIndexWriter = (database) => ({
4
- reset: () => {
5
- database.exec(`
6
- DELETE FROM embedding_buckets;
7
- DELETE FROM chunks_fts;
8
- DELETE FROM links;
9
- DELETE FROM chunks;
10
- DELETE FROM documents;
11
- `);
12
- },
13
- saveDocuments: (documents) => {
14
- const insertDocument = database.prepare(`
15
- INSERT INTO documents (id, agent_id, title, path, content, tags_json, frontmatter_json, created_at, updated_at)
16
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
17
- `);
18
- const insertChunk = database.prepare(`
19
- INSERT INTO chunks (id, document_id, ordinal, content, token_count, embedding_provider, embedding_json)
20
- VALUES (?, ?, ?, ?, ?, ?, ?)
21
- `);
22
- const insertChunkFts = database.prepare(`
23
- INSERT INTO chunks_fts (chunk_id, document_id, agent_id, title, content)
24
- VALUES (?, ?, ?, ?, ?)
25
- `);
26
- const insertEmbeddingBucket = database.prepare(`
27
- INSERT OR IGNORE INTO embedding_buckets (bucket, chunk_id)
28
- VALUES (?, ?)
29
- `);
30
- const insertLink = database.prepare(`
31
- INSERT INTO links (from_document_id, to_title, to_title_key, to_document_id, weight, priority)
32
- VALUES (?, ?, ?, ?, ?, ?)
33
- `);
34
- const transaction = database.transaction(() => {
35
- documents.forEach(({ document, chunks, links }) => {
36
- insertDocument.run(document.id, document.agentId, document.title, document.path, document.content, JSON.stringify(document.tags), JSON.stringify(document.frontmatter), document.createdAt, document.updatedAt);
37
- chunks.forEach((chunk) => {
38
- insertChunk.run(chunk.id, chunk.documentId, chunk.ordinal, chunk.content, chunk.tokenCount, chunk.embeddingProvider, JSON.stringify(chunk.embedding));
39
- insertChunkFts.run(chunk.id, chunk.documentId, document.agentId, document.title, chunk.content);
40
- createEmbeddingBuckets(chunk.embedding).forEach((bucket) => insertEmbeddingBucket.run(bucket, chunk.id));
41
- });
42
- });
43
- documents.forEach(({ links }) => {
44
- links.forEach((link) => {
45
- insertLink.run(link.fromDocumentId, link.toTitle, toTitleKey(link.toTitle), link.toDocumentId, link.weight, link.priority);
46
- });
47
- });
48
- });
49
- transaction();
50
- }
51
- });
@@ -1,267 +0,0 @@
1
- import { sanitizeAgentId } from '../../domain/agents.js';
2
- const toGraphLink = (row) => ({
3
- agentId: row.agent_id,
4
- fromTitle: row.from_title,
5
- fromPath: row.from_path,
6
- toTitle: row.to_title,
7
- toPath: row.to_path,
8
- weight: row.weight,
9
- priority: row.priority
10
- });
11
- const normalizeAgentFilter = (agentId) => agentId ? sanitizeAgentId(agentId) : undefined;
12
- const toTitleKey = (title) => title.toLowerCase();
13
- const toFtsQuery = (query) => query
14
- .toLowerCase()
15
- .match(/[\p{L}\p{N}_-]+/gu)
16
- ?.map((term) => `"${term.replaceAll('"', '""')}"*`)
17
- .join(' OR ') ?? '';
18
- export const createGraphReader = (database) => (() => {
19
- const listLinksStatement = database.prepare(`
20
- SELECT
21
- source.agent_id AS agent_id,
22
- source.title AS from_title,
23
- source.path AS from_path,
24
- COALESCE(target.title, links.to_title) AS to_title,
25
- target.path AS to_path,
26
- links.weight AS weight,
27
- links.priority AS priority
28
- FROM links
29
- JOIN documents source ON source.id = links.from_document_id
30
- LEFT JOIN documents target ON target.id = links.to_document_id
31
- ORDER BY source.title, links.weight DESC, to_title
32
- `);
33
- const listLinksByAgentStatement = database.prepare(`
34
- SELECT
35
- source.agent_id AS agent_id,
36
- source.title AS from_title,
37
- source.path AS from_path,
38
- COALESCE(target.title, links.to_title) AS to_title,
39
- target.path AS to_path,
40
- links.weight AS weight,
41
- links.priority AS priority
42
- FROM links
43
- JOIN documents source ON source.id = links.from_document_id
44
- LEFT JOIN documents target ON target.id = links.to_document_id
45
- WHERE source.agent_id = ?
46
- ORDER BY source.title, links.weight DESC, to_title
47
- `);
48
- const listBacklinksStatement = database.prepare(`
49
- SELECT
50
- source.agent_id AS agent_id,
51
- source.title AS from_title,
52
- source.path AS from_path,
53
- COALESCE(target.title, links.to_title) AS to_title,
54
- target.path AS to_path,
55
- links.weight AS weight,
56
- links.priority AS priority
57
- FROM links
58
- JOIN documents source ON source.id = links.from_document_id
59
- LEFT JOIN documents target ON target.id = links.to_document_id
60
- WHERE links.to_title_key = ?
61
- ORDER BY links.weight DESC, source.title
62
- `);
63
- const listBacklinksByAgentStatement = database.prepare(`
64
- SELECT
65
- source.agent_id AS agent_id,
66
- source.title AS from_title,
67
- source.path AS from_path,
68
- COALESCE(target.title, links.to_title) AS to_title,
69
- target.path AS to_path,
70
- links.weight AS weight,
71
- links.priority AS priority
72
- FROM links
73
- JOIN documents source ON source.id = links.from_document_id
74
- LEFT JOIN documents target ON target.id = links.to_document_id
75
- WHERE links.to_title_key = ? AND source.agent_id = ?
76
- ORDER BY links.weight DESC, source.title
77
- `);
78
- const graphNodesStatement = database.prepare(`
79
- SELECT id, agent_id, title, path, content, tags_json
80
- FROM documents
81
- ORDER BY title
82
- `);
83
- const graphNodesByAgentStatement = database.prepare(`
84
- SELECT id, agent_id, title, path, content, tags_json
85
- FROM documents
86
- WHERE agent_id = ?
87
- ORDER BY title
88
- `);
89
- const graphSummaryNodesStatement = database.prepare(`
90
- SELECT id, agent_id, title, path, '' AS content, tags_json
91
- FROM documents
92
- ORDER BY title
93
- `);
94
- const graphSummaryNodesByAgentStatement = database.prepare(`
95
- SELECT id, agent_id, title, path, '' AS content, tags_json
96
- FROM documents
97
- WHERE agent_id = ?
98
- ORDER BY title
99
- `);
100
- const graphEdgesStatement = database.prepare(`
101
- SELECT
102
- links.from_document_id AS source,
103
- links.to_document_id AS target,
104
- links.to_title AS target_title,
105
- links.weight AS weight,
106
- links.priority AS priority
107
- FROM links
108
- JOIN documents source ON source.id = links.from_document_id
109
- ORDER BY links.from_document_id, links.weight DESC, links.to_title
110
- `);
111
- const graphEdgesByAgentStatement = database.prepare(`
112
- SELECT
113
- links.from_document_id AS source,
114
- links.to_document_id AS target,
115
- links.to_title AS target_title,
116
- links.weight AS weight,
117
- links.priority AS priority
118
- FROM links
119
- JOIN documents source ON source.id = links.from_document_id
120
- WHERE source.agent_id = ?
121
- ORDER BY links.from_document_id, links.weight DESC, links.to_title
122
- `);
123
- const graphNodeByIdStatement = database.prepare(`
124
- SELECT id, agent_id, title, path, content, tags_json
125
- FROM documents
126
- WHERE id = ?
127
- `);
128
- const graphNodeByIdAndAgentStatement = database.prepare(`
129
- SELECT id, agent_id, title, path, content, tags_json
130
- FROM documents
131
- WHERE id = ? AND agent_id = ?
132
- `);
133
- const filterNodeIdsMetadataStatement = database.prepare(`
134
- SELECT id
135
- FROM documents
136
- WHERE lower(title) LIKE ?
137
- OR lower(path) LIKE ?
138
- OR lower(tags_json) LIKE ?
139
- ORDER BY title
140
- LIMIT ?
141
- `);
142
- const filterNodeIdsMetadataByAgentStatement = database.prepare(`
143
- SELECT id
144
- FROM documents
145
- WHERE agent_id = ?
146
- AND (
147
- lower(title) LIKE ?
148
- OR lower(path) LIKE ?
149
- OR lower(tags_json) LIKE ?
150
- )
151
- ORDER BY title
152
- LIMIT ?
153
- `);
154
- const filterNodeIdsContentStatement = database.prepare(`
155
- SELECT DISTINCT documents.id AS id
156
- FROM chunks_fts
157
- JOIN documents ON documents.id = chunks_fts.document_id
158
- WHERE chunks_fts MATCH ?
159
- LIMIT ?
160
- `);
161
- const filterNodeIdsContentByAgentStatement = database.prepare(`
162
- SELECT DISTINCT documents.id AS id
163
- FROM chunks_fts
164
- JOIN documents ON documents.id = chunks_fts.document_id
165
- WHERE chunks_fts MATCH ?
166
- AND documents.agent_id = ?
167
- LIMIT ?
168
- `);
169
- const listAgentsStatement = database.prepare(`
170
- SELECT agent_id AS id, count(*) AS document_count
171
- FROM documents
172
- GROUP BY agent_id
173
- ORDER BY agent_id
174
- `);
175
- return {
176
- listLinks: (agentId) => {
177
- const normalizedAgentId = normalizeAgentFilter(agentId);
178
- const rows = (normalizedAgentId
179
- ? listLinksByAgentStatement.all(normalizedAgentId)
180
- : listLinksStatement.all());
181
- return rows.map(toGraphLink);
182
- },
183
- listBacklinks: (title, agentId) => {
184
- const normalizedAgentId = normalizeAgentFilter(agentId);
185
- const titleKey = toTitleKey(title);
186
- const rows = (normalizedAgentId
187
- ? listBacklinksByAgentStatement.all(titleKey, normalizedAgentId)
188
- : listBacklinksStatement.all(titleKey));
189
- return rows.map(toGraphLink);
190
- },
191
- getGraph: (agentId) => {
192
- const normalizedAgentId = normalizeAgentFilter(agentId);
193
- const nodeRows = (normalizedAgentId
194
- ? graphNodesByAgentStatement.all(normalizedAgentId)
195
- : graphNodesStatement.all());
196
- const edgeRows = (normalizedAgentId
197
- ? graphEdgesByAgentStatement.all(normalizedAgentId)
198
- : graphEdgesStatement.all());
199
- return {
200
- nodes: nodeRows.map(toGraphNode),
201
- edges: edgeRows.map(toGraphEdge)
202
- };
203
- },
204
- getGraphSummary: (agentId) => {
205
- const normalizedAgentId = normalizeAgentFilter(agentId);
206
- const nodeRows = (normalizedAgentId
207
- ? graphSummaryNodesByAgentStatement.all(normalizedAgentId)
208
- : graphSummaryNodesStatement.all());
209
- const edgeRows = (normalizedAgentId
210
- ? graphEdgesByAgentStatement.all(normalizedAgentId)
211
- : graphEdgesStatement.all());
212
- return {
213
- nodes: nodeRows.map(toGraphNode),
214
- edges: edgeRows.map(toGraphEdge)
215
- };
216
- },
217
- getGraphNode: (id, agentId) => {
218
- const normalizedAgentId = normalizeAgentFilter(agentId);
219
- const row = (normalizedAgentId
220
- ? graphNodeByIdAndAgentStatement.get(id, normalizedAgentId)
221
- : graphNodeByIdStatement.get(id));
222
- return row ? toGraphNode(row) : undefined;
223
- },
224
- searchGraphNodeIds: (query, limit, agentId) => {
225
- const normalizedQuery = query.trim().toLowerCase();
226
- if (!normalizedQuery || limit <= 0) {
227
- return [];
228
- }
229
- const normalizedAgentId = normalizeAgentFilter(agentId);
230
- const likeQuery = `%${normalizedQuery}%`;
231
- const metadataRows = (normalizedAgentId
232
- ? filterNodeIdsMetadataByAgentStatement.all(normalizedAgentId, likeQuery, likeQuery, likeQuery, limit)
233
- : filterNodeIdsMetadataStatement.all(likeQuery, likeQuery, likeQuery, limit));
234
- const ids = new Set(metadataRows.map((row) => row.id));
235
- const remainingLimit = Math.max(limit - ids.size, 0);
236
- if (remainingLimit > 0) {
237
- const ftsQuery = toFtsQuery(normalizedQuery);
238
- if (ftsQuery) {
239
- const contentRows = (normalizedAgentId
240
- ? filterNodeIdsContentByAgentStatement.all(ftsQuery, normalizedAgentId, remainingLimit)
241
- : filterNodeIdsContentStatement.all(ftsQuery, remainingLimit));
242
- contentRows.forEach((row) => ids.add(row.id));
243
- }
244
- }
245
- return Array.from(ids).slice(0, limit);
246
- },
247
- listAgents: () => listAgentsStatement.all().map((row) => ({
248
- id: row.id,
249
- documentCount: row.document_count
250
- }))
251
- };
252
- })();
253
- const toGraphNode = (row) => ({
254
- id: row.id,
255
- agentId: row.agent_id,
256
- title: row.title,
257
- path: row.path,
258
- content: row.content,
259
- tags: JSON.parse(row.tags_json)
260
- });
261
- const toGraphEdge = (row) => ({
262
- source: row.source,
263
- target: row.target,
264
- targetTitle: row.target_title,
265
- weight: row.weight,
266
- priority: row.priority
267
- });
@@ -1,163 +0,0 @@
1
- import Database from 'better-sqlite3';
2
- import { copyFileSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
3
- import { basename, dirname, join } from 'node:path';
4
- const sqliteCorruptionHints = [
5
- 'database disk image is malformed',
6
- 'file is not a database',
7
- 'database is corrupted',
8
- 'malformed database schema',
9
- 'sqlite quick_check failed'
10
- ];
11
- const maxSnapshotFiles = 24;
12
- const normalizeMessage = (error) => error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
13
- const isSqliteCorruptionError = (error) => sqliteCorruptionHints.some((hint) => normalizeMessage(error).includes(hint));
14
- const safeUnlink = (path) => {
15
- if (!existsSync(path)) {
16
- return;
17
- }
18
- try {
19
- unlinkSync(path);
20
- }
21
- catch {
22
- // Ignore best-effort cleanup failures.
23
- }
24
- };
25
- const clearSidecars = (databasePath) => {
26
- safeUnlink(`${databasePath}-wal`);
27
- safeUnlink(`${databasePath}-shm`);
28
- };
29
- const assertQuickCheck = (database) => {
30
- const rows = database.prepare('PRAGMA quick_check').all();
31
- const first = rows[0]?.quick_check?.toLowerCase() ?? 'ok';
32
- if (first !== 'ok') {
33
- throw new Error(`sqlite quick_check failed: ${first}`);
34
- }
35
- };
36
- const archiveCorruptedDatabase = (databasePath) => {
37
- if (!existsSync(databasePath)) {
38
- return;
39
- }
40
- const archivedPath = `${databasePath}.corrupt-${Date.now()}`;
41
- renameSync(databasePath, archivedPath);
42
- };
43
- const snapshotDirectoryPath = (backupPath) => join(dirname(backupPath), `${basename(backupPath)}.snapshots`);
44
- const snapshotFileName = () => `snapshot-${new Date().toISOString().replace(/[:.]/g, '-')}.db`;
45
- const cleanupSnapshotOverflow = (backupPath) => {
46
- const directory = snapshotDirectoryPath(backupPath);
47
- if (!existsSync(directory)) {
48
- return;
49
- }
50
- const snapshots = readdirSync(directory)
51
- .filter((name) => name.endsWith('.db'))
52
- .sort((left, right) => right.localeCompare(left));
53
- snapshots.slice(maxSnapshotFiles).forEach((name) => {
54
- rmSync(join(directory, name), { force: true });
55
- });
56
- };
57
- const openCheckedDatabase = (databasePath) => {
58
- const database = new Database(databasePath);
59
- try {
60
- assertQuickCheck(database);
61
- }
62
- catch (error) {
63
- database.close();
64
- throw error;
65
- }
66
- return database;
67
- };
68
- const isValidDatabaseSnapshot = (path) => {
69
- if (!existsSync(path)) {
70
- return false;
71
- }
72
- try {
73
- const size = statSync(path).size;
74
- if (size <= 0) {
75
- return false;
76
- }
77
- }
78
- catch {
79
- return false;
80
- }
81
- try {
82
- const database = new Database(path);
83
- try {
84
- assertQuickCheck(database);
85
- return true;
86
- }
87
- finally {
88
- database.close();
89
- }
90
- }
91
- catch {
92
- return false;
93
- }
94
- };
95
- const candidateBackupFiles = (backupPath) => {
96
- const directory = snapshotDirectoryPath(backupPath);
97
- const snapshots = existsSync(directory)
98
- ? readdirSync(directory)
99
- .filter((name) => name.endsWith('.db'))
100
- .sort((left, right) => right.localeCompare(left))
101
- .map((name) => join(directory, name))
102
- : [];
103
- return [backupPath, ...snapshots];
104
- };
105
- const ensureSnapshotDirectory = (backupPath) => {
106
- mkdirSync(snapshotDirectoryPath(backupPath), { recursive: true, mode: 0o700 });
107
- };
108
- const writeRecoveryMarker = (backupPath, restoredFrom) => {
109
- const markerPath = join(dirname(backupPath), 'recovery-last-restore.json');
110
- const payload = {
111
- restoredAt: new Date().toISOString(),
112
- restoredFrom
113
- };
114
- writeFileSync(markerPath, `${JSON.stringify(payload, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
115
- };
116
- const restoreFromBackupOrReset = (databasePath, backupPath) => {
117
- clearSidecars(databasePath);
118
- archiveCorruptedDatabase(databasePath);
119
- for (const candidate of candidateBackupFiles(backupPath)) {
120
- if (!isValidDatabaseSnapshot(candidate)) {
121
- continue;
122
- }
123
- copyFileSync(candidate, databasePath);
124
- clearSidecars(databasePath);
125
- if (isValidDatabaseSnapshot(databasePath)) {
126
- writeRecoveryMarker(backupPath, candidate);
127
- return;
128
- }
129
- }
130
- rmSync(databasePath, { force: true });
131
- };
132
- export const createRecoverySnapshot = (database, backupPath) => {
133
- const backupDirectory = dirname(backupPath);
134
- const tempBackupPath = `${backupPath}.tmp`;
135
- const snapshotDirectory = snapshotDirectoryPath(backupPath);
136
- const snapshotPath = join(snapshotDirectory, snapshotFileName());
137
- mkdirSync(backupDirectory, { recursive: true });
138
- ensureSnapshotDirectory(backupPath);
139
- rmSync(tempBackupPath, { force: true });
140
- try {
141
- database.pragma('wal_checkpoint(PASSIVE)');
142
- }
143
- catch {
144
- // Checkpoint is best-effort.
145
- }
146
- database.prepare('VACUUM INTO ?').run(tempBackupPath);
147
- renameSync(tempBackupPath, backupPath);
148
- copyFileSync(backupPath, snapshotPath);
149
- cleanupSnapshotOverflow(backupPath);
150
- };
151
- export const openDatabaseWithRecovery = (databasePath, backupPath) => {
152
- mkdirSync(dirname(databasePath), { recursive: true });
153
- try {
154
- return openCheckedDatabase(databasePath);
155
- }
156
- catch (error) {
157
- if (!isSqliteCorruptionError(error)) {
158
- throw error;
159
- }
160
- restoreFromBackupOrReset(databasePath, backupPath);
161
- return openCheckedDatabase(databasePath);
162
- }
163
- };
@@ -1,114 +0,0 @@
1
- const schemaVersion = 6;
2
- const requiredTableColumns = {
3
- documents: ['id', 'agent_id', 'title', 'path', 'content', 'tags_json', 'frontmatter_json', 'created_at', 'updated_at'],
4
- chunks: ['id', 'document_id', 'ordinal', 'content', 'token_count', 'embedding_provider', 'embedding_json'],
5
- links: ['from_document_id', 'to_title', 'to_title_key', 'to_document_id', 'weight', 'priority'],
6
- chunks_fts: ['chunk_id', 'document_id', 'agent_id', 'title', 'content']
7
- };
8
- const getStoredSchemaVersion = (database) => {
9
- const hasMetadata = database
10
- .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'metadata'")
11
- .get();
12
- if (!hasMetadata) {
13
- return 0;
14
- }
15
- const row = database.prepare("SELECT value FROM metadata WHERE key = 'schema_version'").get();
16
- return Number.parseInt(row?.value ?? '0', 10);
17
- };
18
- const dropDerivedSchema = (database) => {
19
- database.exec(`
20
- DROP TABLE IF EXISTS embedding_buckets;
21
- DROP TABLE IF EXISTS chunks_fts;
22
- DROP TABLE IF EXISTS links;
23
- DROP TABLE IF EXISTS chunks;
24
- DROP TABLE IF EXISTS documents;
25
- `);
26
- };
27
- const getTableColumns = (database, tableName) => {
28
- const rows = database.prepare(`SELECT name FROM pragma_table_info(?)`).all(tableName);
29
- return rows.map((row) => row.name);
30
- };
31
- const hasCompatibleSchemaShape = (database) => Object.entries(requiredTableColumns).every(([tableName, requiredColumns]) => {
32
- const columns = getTableColumns(database, tableName);
33
- return columns.length === 0 || requiredColumns.every((column) => columns.includes(column));
34
- });
35
- export const createSchema = (database) => {
36
- const storedSchemaVersion = getStoredSchemaVersion(database);
37
- if ((storedSchemaVersion > 0 && storedSchemaVersion < schemaVersion) || !hasCompatibleSchemaShape(database)) {
38
- dropDerivedSchema(database);
39
- }
40
- database.exec(`
41
- CREATE TABLE IF NOT EXISTS metadata (
42
- key TEXT PRIMARY KEY,
43
- value TEXT NOT NULL
44
- );
45
-
46
- CREATE TABLE IF NOT EXISTS documents (
47
- id TEXT PRIMARY KEY,
48
- agent_id TEXT NOT NULL,
49
- title TEXT NOT NULL,
50
- path TEXT NOT NULL UNIQUE,
51
- content TEXT NOT NULL,
52
- tags_json TEXT NOT NULL,
53
- frontmatter_json TEXT NOT NULL,
54
- created_at TEXT NOT NULL,
55
- updated_at TEXT NOT NULL
56
- );
57
-
58
- CREATE TABLE IF NOT EXISTS chunks (
59
- id TEXT PRIMARY KEY,
60
- document_id TEXT NOT NULL,
61
- ordinal INTEGER NOT NULL,
62
- content TEXT NOT NULL,
63
- token_count INTEGER NOT NULL,
64
- embedding_provider TEXT NOT NULL,
65
- embedding_json TEXT NOT NULL,
66
- FOREIGN KEY (document_id) REFERENCES documents(id) ON DELETE CASCADE
67
- );
68
-
69
- CREATE INDEX IF NOT EXISTS idx_documents_agent_title ON documents(agent_id, title);
70
- CREATE INDEX IF NOT EXISTS idx_documents_agent_id ON documents(agent_id, id);
71
- CREATE INDEX IF NOT EXISTS idx_chunks_document_ordinal ON chunks(document_id, ordinal);
72
- CREATE INDEX IF NOT EXISTS idx_chunks_token_count ON chunks(token_count);
73
-
74
- CREATE TABLE IF NOT EXISTS embedding_buckets (
75
- bucket TEXT NOT NULL,
76
- chunk_id TEXT NOT NULL,
77
- PRIMARY KEY (bucket, chunk_id),
78
- FOREIGN KEY (chunk_id) REFERENCES chunks(id) ON DELETE CASCADE
79
- );
80
-
81
- CREATE INDEX IF NOT EXISTS idx_embedding_buckets_bucket ON embedding_buckets(bucket);
82
-
83
- CREATE TABLE IF NOT EXISTS links (
84
- from_document_id TEXT NOT NULL,
85
- to_title TEXT NOT NULL,
86
- to_title_key TEXT NOT NULL,
87
- to_document_id TEXT,
88
- weight INTEGER NOT NULL,
89
- priority TEXT NOT NULL,
90
- PRIMARY KEY (from_document_id, to_title_key),
91
- FOREIGN KEY (from_document_id) REFERENCES documents(id) ON DELETE CASCADE,
92
- FOREIGN KEY (to_document_id) REFERENCES documents(id) ON DELETE SET NULL
93
- );
94
-
95
- CREATE INDEX IF NOT EXISTS idx_links_to_document_id ON links(to_document_id);
96
- CREATE INDEX IF NOT EXISTS idx_links_to_title_key ON links(to_title_key);
97
- CREATE INDEX IF NOT EXISTS idx_links_source_weight ON links(from_document_id, weight DESC, to_title);
98
-
99
- CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
100
- chunk_id UNINDEXED,
101
- document_id UNINDEXED,
102
- agent_id UNINDEXED,
103
- title,
104
- content
105
- );
106
- `);
107
- database
108
- .prepare(`
109
- INSERT INTO metadata (key, value)
110
- VALUES ('schema_version', ?)
111
- ON CONFLICT(key) DO UPDATE SET value = excluded.value
112
- `)
113
- .run(String(schemaVersion));
114
- };