@andespindola/brainlink 0.1.0-beta.4 → 0.1.0-beta.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/AGENTS.md +5 -5
  2. package/CHANGELOG.md +43 -2
  3. package/CONTRIBUTING.md +2 -2
  4. package/COPYRIGHT.md +5 -0
  5. package/README.md +213 -20
  6. package/SECURITY.md +1 -1
  7. package/dist/application/add-note.js +62 -13
  8. package/dist/application/analyze-vault.js +95 -8
  9. package/dist/application/build-context.js +56 -1
  10. package/dist/application/dedupe-notes.js +226 -0
  11. package/dist/application/frontend/client-css.js +214 -100
  12. package/dist/application/frontend/client-html.js +60 -45
  13. package/dist/application/frontend/client-js.js +656 -94
  14. package/dist/application/get-graph-layout.js +22 -7
  15. package/dist/application/get-graph-node.js +12 -0
  16. package/dist/application/get-graph-summary.js +12 -0
  17. package/dist/application/get-graph.js +3 -3
  18. package/dist/application/import-legacy-sqlite.js +296 -0
  19. package/dist/application/index-vault.js +11 -4
  20. package/dist/application/list-agents.js +3 -3
  21. package/dist/application/list-links.js +5 -5
  22. package/dist/application/migrate-vault.js +91 -0
  23. package/dist/application/search-graph-node-ids.js +12 -0
  24. package/dist/application/search-knowledge.js +75 -5
  25. package/dist/application/server/routes.js +27 -1
  26. package/dist/benchmarks/large-vault.js +1 -1
  27. package/dist/cli/commands/agent-commands.js +412 -0
  28. package/dist/cli/commands/config-commands.js +167 -0
  29. package/dist/cli/commands/read-commands.js +25 -8
  30. package/dist/cli/commands/write-commands.js +669 -9
  31. package/dist/cli/main.js +4 -0
  32. package/dist/cli/runtime.js +5 -2
  33. package/dist/domain/context.js +53 -11
  34. package/dist/domain/embeddings.js +2 -1
  35. package/dist/domain/graph-layout.js +20 -14
  36. package/dist/domain/markdown.js +36 -4
  37. package/dist/domain/middle-out.js +18 -0
  38. package/dist/infrastructure/config.js +94 -8
  39. package/dist/infrastructure/file-index.js +328 -0
  40. package/dist/infrastructure/file-system-vault.js +15 -0
  41. package/dist/infrastructure/paths.js +9 -1
  42. package/dist/infrastructure/private-pack-codec.js +73 -0
  43. package/dist/infrastructure/search-packs.js +348 -0
  44. package/dist/infrastructure/session-state.js +172 -0
  45. package/dist/mcp/main.js +11 -3
  46. package/dist/mcp/server.js +27 -2
  47. package/dist/mcp/startup.js +35 -0
  48. package/dist/mcp/tools.js +633 -19
  49. package/docs/AGENT_USAGE.md +144 -16
  50. package/docs/ARCHITECTURE.md +37 -26
  51. package/docs/QUICKSTART.md +111 -0
  52. package/package.json +6 -4
  53. package/dist/infrastructure/sqlite/document-writer.js +0 -51
  54. package/dist/infrastructure/sqlite/graph-reader.js +0 -120
  55. package/dist/infrastructure/sqlite/schema.js +0 -111
  56. package/dist/infrastructure/sqlite/search-reader.js +0 -156
  57. package/dist/infrastructure/sqlite/types.js +0 -1
  58. package/dist/infrastructure/sqlite-index.js +0 -25
@@ -0,0 +1,328 @@
1
+ import { mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ import { cosineSimilarity } from '../domain/embeddings.js';
4
+ const queryTokenPattern = /[\p{L}\p{N}_-]+/gu;
5
+ const indexCacheMaxEntries = 16;
6
+ const indexCache = new Map();
7
+ const emptyIndex = () => ({
8
+ version: 1,
9
+ updatedAt: new Date().toISOString(),
10
+ documents: [],
11
+ chunks: [],
12
+ links: []
13
+ });
14
+ export const indexStoragePath = (vaultPath) => join(vaultPath, '.brainlink', 'index.json');
15
+ const readIndex = async (vaultPath) => {
16
+ const path = indexStoragePath(vaultPath);
17
+ let stats = null;
18
+ try {
19
+ const fileStats = await stat(path);
20
+ stats = { mtimeMs: fileStats.mtimeMs, size: fileStats.size };
21
+ }
22
+ catch (error) {
23
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
24
+ indexCache.delete(path);
25
+ return emptyIndex();
26
+ }
27
+ return emptyIndex();
28
+ }
29
+ const cached = indexCache.get(path);
30
+ if (cached && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size) {
31
+ return cached.index;
32
+ }
33
+ try {
34
+ const parsed = JSON.parse(await readFile(path, 'utf8'));
35
+ const loaded = {
36
+ version: 1,
37
+ updatedAt: typeof parsed.updatedAt === 'string' ? parsed.updatedAt : new Date().toISOString(),
38
+ documents: Array.isArray(parsed.documents) ? parsed.documents : [],
39
+ chunks: Array.isArray(parsed.chunks) ? parsed.chunks : [],
40
+ links: Array.isArray(parsed.links) ? parsed.links : []
41
+ };
42
+ indexCache.set(path, { ...stats, index: loaded });
43
+ if (indexCache.size > indexCacheMaxEntries) {
44
+ const oldest = indexCache.keys().next().value;
45
+ if (typeof oldest === 'string') {
46
+ indexCache.delete(oldest);
47
+ }
48
+ }
49
+ return loaded;
50
+ }
51
+ catch (error) {
52
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
53
+ indexCache.delete(path);
54
+ return emptyIndex();
55
+ }
56
+ return emptyIndex();
57
+ }
58
+ };
59
+ const writeIndex = async (vaultPath, index) => {
60
+ const target = indexStoragePath(vaultPath);
61
+ const temp = `${target}.tmp`;
62
+ await mkdir(dirname(target), { recursive: true, mode: 0o700 });
63
+ await writeFile(temp, `${JSON.stringify(index)}\n`, { encoding: 'utf8', mode: 0o600 });
64
+ await rename(temp, target);
65
+ const fileStats = await stat(target);
66
+ indexCache.set(target, {
67
+ mtimeMs: fileStats.mtimeMs,
68
+ size: fileStats.size,
69
+ index
70
+ });
71
+ };
72
+ const normalizeToken = (value) => value
73
+ .normalize('NFKD')
74
+ .replace(/\p{Diacritic}/gu, '')
75
+ .toLowerCase();
76
+ const tokenize = (query) => query
77
+ .match(queryTokenPattern)
78
+ ?.map(normalizeToken)
79
+ .filter((token) => token.length > 1) ?? [];
80
+ const countOccurrences = (text, token) => {
81
+ let hits = 0;
82
+ let cursor = 0;
83
+ while (cursor < text.length) {
84
+ const index = text.indexOf(token, cursor);
85
+ if (index < 0) {
86
+ break;
87
+ }
88
+ hits += 1;
89
+ cursor = index + token.length;
90
+ }
91
+ return hits;
92
+ };
93
+ const textScore = (row, tokens) => {
94
+ if (tokens.length === 0) {
95
+ return 0;
96
+ }
97
+ const title = normalizeToken(row.title);
98
+ const path = normalizeToken(row.path);
99
+ const content = normalizeToken(row.content);
100
+ const tags = normalizeToken(row.tags.join(' '));
101
+ return tokens.reduce((score, token) => {
102
+ const titleHits = countOccurrences(title, token);
103
+ const tagHits = countOccurrences(tags, token);
104
+ const pathHits = countOccurrences(path, token);
105
+ const contentHits = countOccurrences(content, token);
106
+ return score + titleHits * 5 + tagHits * 4 + pathHits * 2 + Math.min(contentHits, 6);
107
+ }, 0);
108
+ };
109
+ const semanticScore = (row, queryEmbedding) => queryEmbedding.length > 0 && row.embedding.length > 0 ? cosineSimilarity(queryEmbedding, row.embedding) : 0;
110
+ const toResult = (row, mode, text, semantic) => {
111
+ const score = mode === 'fts' ? text : mode === 'semantic' ? semantic : text + semantic * 8;
112
+ return {
113
+ documentId: row.documentId,
114
+ agentId: row.agentId,
115
+ title: row.title,
116
+ path: row.path,
117
+ chunkId: row.chunkId,
118
+ chunkOrdinal: row.chunkOrdinal,
119
+ content: row.content,
120
+ score,
121
+ textScore: text,
122
+ semanticScore: semantic,
123
+ searchMode: mode,
124
+ tags: row.tags
125
+ };
126
+ };
127
+ const toGraphLink = (link, documentsById) => {
128
+ const source = documentsById.get(link.fromDocumentId);
129
+ const target = link.toDocumentId ? documentsById.get(link.toDocumentId) : undefined;
130
+ return {
131
+ agentId: source?.agentId ?? 'shared',
132
+ fromTitle: source?.title ?? 'Unknown',
133
+ fromPath: source?.path ?? 'Unknown',
134
+ toTitle: target?.title ?? link.toTitle,
135
+ toPath: target?.path ?? null,
136
+ weight: link.weight,
137
+ priority: link.priority
138
+ };
139
+ };
140
+ export const openFileIndex = (vaultPath) => {
141
+ const load = async () => readIndex(vaultPath);
142
+ const persist = async (index) => writeIndex(vaultPath, index);
143
+ return {
144
+ reset: async () => {
145
+ await persist(emptyIndex());
146
+ },
147
+ saveDocuments: async (documents) => {
148
+ const chunks = documents.flatMap((document) => document.chunks);
149
+ const links = documents.flatMap((document) => document.links);
150
+ await persist({
151
+ version: 1,
152
+ updatedAt: new Date().toISOString(),
153
+ documents: documents.map((document) => document.document),
154
+ chunks,
155
+ links
156
+ });
157
+ },
158
+ search: async (query, limit, agentId, mode = 'hybrid', queryEmbedding = []) => {
159
+ const index = await load();
160
+ const documentsById = new Map(index.documents.map((document) => [document.id, document]));
161
+ const rows = index.chunks.flatMap((chunk) => {
162
+ const document = documentsById.get(chunk.documentId);
163
+ if (!document) {
164
+ return [];
165
+ }
166
+ if (agentId && document.agentId !== agentId) {
167
+ return [];
168
+ }
169
+ return [
170
+ {
171
+ documentId: document.id,
172
+ agentId: document.agentId,
173
+ title: document.title,
174
+ path: document.path,
175
+ chunkId: chunk.id,
176
+ chunkOrdinal: chunk.ordinal,
177
+ content: chunk.content,
178
+ tags: document.tags,
179
+ embedding: chunk.embedding
180
+ }
181
+ ];
182
+ });
183
+ const tokens = tokenize(query);
184
+ const results = rows
185
+ .map((row) => {
186
+ const text = textScore(row, tokens);
187
+ const semantic = semanticScore(row, queryEmbedding);
188
+ return toResult(row, mode, text, semantic);
189
+ })
190
+ .filter((row) => row.score > 0 || tokens.length === 0)
191
+ .sort((left, right) => right.score - left.score || left.title.localeCompare(right.title))
192
+ .slice(0, Math.max(0, limit));
193
+ return results;
194
+ },
195
+ listLinks: async (agentId) => {
196
+ const index = await load();
197
+ const documentsById = new Map(index.documents.map((document) => [document.id, document]));
198
+ return index.links
199
+ .filter((link) => {
200
+ const source = documentsById.get(link.fromDocumentId);
201
+ return agentId ? source?.agentId === agentId : true;
202
+ })
203
+ .map((link) => toGraphLink(link, documentsById))
204
+ .sort((left, right) => left.fromTitle.localeCompare(right.fromTitle));
205
+ },
206
+ listBacklinks: async (title, agentId) => {
207
+ const index = await load();
208
+ const titleKey = title.toLowerCase();
209
+ const documentsById = new Map(index.documents.map((document) => [document.id, document]));
210
+ return index.links
211
+ .filter((link) => link.toTitle.toLowerCase() === titleKey)
212
+ .filter((link) => {
213
+ const source = documentsById.get(link.fromDocumentId);
214
+ return agentId ? source?.agentId === agentId : true;
215
+ })
216
+ .map((link) => toGraphLink(link, documentsById))
217
+ .sort((left, right) => right.weight - left.weight || left.fromTitle.localeCompare(right.fromTitle));
218
+ },
219
+ getGraph: async (agentId) => {
220
+ const index = await load();
221
+ const documents = agentId ? index.documents.filter((document) => document.agentId === agentId) : index.documents;
222
+ const documentIds = new Set(documents.map((document) => document.id));
223
+ const edges = index.links
224
+ .filter((link) => documentIds.has(link.fromDocumentId))
225
+ .map((link) => ({
226
+ source: link.fromDocumentId,
227
+ target: link.toDocumentId,
228
+ targetTitle: link.toTitle,
229
+ weight: link.weight,
230
+ priority: link.priority
231
+ }));
232
+ return {
233
+ nodes: documents.map((document) => ({
234
+ id: document.id,
235
+ agentId: document.agentId,
236
+ title: document.title,
237
+ path: document.path,
238
+ content: document.content,
239
+ tags: document.tags
240
+ })),
241
+ edges
242
+ };
243
+ },
244
+ getGraphSummary: async (agentId) => {
245
+ const graph = await (async () => {
246
+ const index = await load();
247
+ const documents = agentId ? index.documents.filter((document) => document.agentId === agentId) : index.documents;
248
+ const documentIds = new Set(documents.map((document) => document.id));
249
+ const edges = index.links
250
+ .filter((link) => documentIds.has(link.fromDocumentId))
251
+ .map((link) => ({
252
+ source: link.fromDocumentId,
253
+ target: link.toDocumentId,
254
+ targetTitle: link.toTitle,
255
+ weight: link.weight,
256
+ priority: link.priority
257
+ }));
258
+ return {
259
+ nodes: documents.map((document) => ({
260
+ id: document.id,
261
+ agentId: document.agentId,
262
+ title: document.title,
263
+ path: document.path,
264
+ content: '',
265
+ tags: document.tags
266
+ })),
267
+ edges
268
+ };
269
+ })();
270
+ return graph;
271
+ },
272
+ getGraphNode: async (id, agentId) => {
273
+ const index = await load();
274
+ const document = index.documents.find((row) => row.id === id && (!agentId || row.agentId === agentId));
275
+ return document
276
+ ? {
277
+ id: document.id,
278
+ agentId: document.agentId,
279
+ title: document.title,
280
+ path: document.path,
281
+ content: document.content,
282
+ tags: document.tags
283
+ }
284
+ : undefined;
285
+ },
286
+ searchGraphNodeIds: async (query, limit, agentId) => {
287
+ const index = await load();
288
+ const normalized = normalizeToken(query);
289
+ if (normalized.length === 0 || limit <= 0) {
290
+ return [];
291
+ }
292
+ const tokens = tokenize(query);
293
+ const scored = index.documents
294
+ .filter((document) => (!agentId || document.agentId === agentId))
295
+ .map((document) => {
296
+ const score = textScore({
297
+ documentId: document.id,
298
+ agentId: document.agentId,
299
+ title: document.title,
300
+ path: document.path,
301
+ chunkId: document.id,
302
+ chunkOrdinal: 0,
303
+ content: document.content,
304
+ tags: document.tags,
305
+ embedding: []
306
+ }, tokens);
307
+ return { id: document.id, score };
308
+ })
309
+ .filter((row) => row.score > 0)
310
+ .sort((left, right) => right.score - left.score || left.id.localeCompare(right.id))
311
+ .slice(0, limit);
312
+ return scored.map((row) => row.id);
313
+ },
314
+ listAgents: async () => {
315
+ const index = await load();
316
+ const counts = index.documents.reduce((state, document) => {
317
+ state.set(document.agentId, (state.get(document.agentId) ?? 0) + 1);
318
+ return state;
319
+ }, new Map());
320
+ return Array.from(counts.entries())
321
+ .sort((left, right) => left[0].localeCompare(right[0]))
322
+ .map(([id, documentCount]) => ({ id, documentCount }));
323
+ },
324
+ close: () => {
325
+ // File-based index has no persistent connection.
326
+ }
327
+ };
328
+ };
@@ -16,6 +16,17 @@ const walkMarkdownFiles = async (directory) => {
16
16
  }));
17
17
  return nested.flat();
18
18
  };
19
+ const walkVaultFiles = async (directory) => {
20
+ const entries = await readdir(directory, { withFileTypes: true });
21
+ const nested = await Promise.all(entries.map(async (entry) => {
22
+ const absolutePath = join(directory, entry.name);
23
+ if (entry.isDirectory()) {
24
+ return excludedDirectories.has(entry.name) ? [] : walkVaultFiles(absolutePath);
25
+ }
26
+ return entry.isFile() ? [absolutePath] : [];
27
+ }));
28
+ return nested.flat();
29
+ };
19
30
  export const resolveVaultPath = (vaultPath) => isBucketVaultUri(vaultPath) ? getBucketVaultCachePath(vaultPath) : resolvePath(vaultPath);
20
31
  export const isBucketVaultPath = (vaultPath) => isBucketVaultUri(vaultPath);
21
32
  const isPathInside = (parent, child) => {
@@ -65,6 +76,10 @@ export const readMarkdownFiles = async (vaultPath) => {
65
76
  };
66
77
  }));
67
78
  };
79
+ export const listVaultFiles = async (vaultPath) => {
80
+ const absoluteVaultPath = await ensureVault(vaultPath);
81
+ return walkVaultFiles(absoluteVaultPath);
82
+ };
68
83
  export const writeMarkdownFile = async (vaultPath, filename, content) => {
69
84
  if (isBucketVaultUri(vaultPath)) {
70
85
  return writeBucketMarkdownFile(vaultPath, filename, content);
@@ -2,8 +2,16 @@ import { homedir } from 'node:os';
2
2
  import { isAbsolute, join, resolve } from 'node:path';
3
3
  const defaultHomeDirectoryName = '.brainlink';
4
4
  const defaultVaultDirectoryName = 'vault';
5
+ const resolveSafeCwd = () => {
6
+ try {
7
+ return process.cwd();
8
+ }
9
+ catch {
10
+ return homedir();
11
+ }
12
+ };
5
13
  export const expandHomePath = (path) => path === '~' || path.startsWith('~/') ? join(homedir(), path.slice(2)) : path;
6
- export const resolvePath = (path, cwd = process.cwd()) => {
14
+ export const resolvePath = (path, cwd = resolveSafeCwd()) => {
7
15
  const expandedPath = expandHomePath(path);
8
16
  return isAbsolute(expandedPath) ? expandedPath : resolve(cwd, expandedPath);
9
17
  };
@@ -0,0 +1,73 @@
1
+ import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto';
2
+ import { brotliCompressSync, brotliDecompressSync } from 'node:zlib';
3
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
4
+ import { dirname, join } from 'node:path';
5
+ import { getBrainlinkHomePath } from './paths.js';
6
+ const magic = Buffer.from('BLPK2', 'ascii');
7
+ const version = 1;
8
+ const nonceLength = 12;
9
+ const authTagLength = 16;
10
+ const algorithm = 'aes-256-gcm';
11
+ const keyFilePath = (vaultPath) => {
12
+ const vaultHash = createHash('sha256').update(vaultPath).digest('hex').slice(0, 24);
13
+ return join(getBrainlinkHomePath(), 'keys', `search-pack-${vaultHash}.key`);
14
+ };
15
+ const deriveKeyFromSecret = (secret) => createHash('sha256').update(secret, 'utf8').digest();
16
+ const readOrCreateKey = async (vaultPath) => {
17
+ const envSecret = process.env.BRAINLINK_SEARCH_PACK_KEY?.trim();
18
+ if (envSecret && envSecret.length > 0) {
19
+ return deriveKeyFromSecret(envSecret);
20
+ }
21
+ const path = keyFilePath(vaultPath);
22
+ try {
23
+ const existing = (await readFile(path, 'utf8')).trim();
24
+ if (existing.length > 0) {
25
+ return deriveKeyFromSecret(existing);
26
+ }
27
+ }
28
+ catch (error) {
29
+ if (!(error instanceof Error) || !('code' in error) || error.code !== 'ENOENT') {
30
+ throw error;
31
+ }
32
+ }
33
+ const secret = randomBytes(48).toString('base64url');
34
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
35
+ await writeFile(path, `${secret}\n`, { encoding: 'utf8', mode: 0o600 });
36
+ return deriveKeyFromSecret(secret);
37
+ };
38
+ const parseHeader = (payload) => {
39
+ if (payload.length < magic.length + 1 + nonceLength + authTagLength) {
40
+ throw new Error('Invalid private pack payload: too short.');
41
+ }
42
+ const payloadMagic = payload.subarray(0, magic.length);
43
+ const payloadVersion = payload[magic.length];
44
+ if (!payloadMagic.equals(magic) || payloadVersion !== version) {
45
+ throw new Error('Invalid private pack payload: unsupported format.');
46
+ }
47
+ const nonceStart = magic.length + 1;
48
+ const authTagStart = nonceStart + nonceLength;
49
+ const dataStart = authTagStart + authTagLength;
50
+ return {
51
+ nonce: payload.subarray(nonceStart, authTagStart),
52
+ authTag: payload.subarray(authTagStart, dataStart),
53
+ ciphertext: payload.subarray(dataStart)
54
+ };
55
+ };
56
+ export const encodePrivatePack = async (vaultPath, content) => {
57
+ const key = await readOrCreateKey(vaultPath);
58
+ const nonce = randomBytes(nonceLength);
59
+ const compressed = brotliCompressSync(content);
60
+ const cipher = createCipheriv(algorithm, key, nonce);
61
+ const ciphertext = Buffer.concat([cipher.update(compressed), cipher.final()]);
62
+ const authTag = cipher.getAuthTag();
63
+ return Buffer.concat([magic, Buffer.from([version]), nonce, authTag, ciphertext]);
64
+ };
65
+ export const decodePrivatePack = async (vaultPath, payload) => {
66
+ const key = await readOrCreateKey(vaultPath);
67
+ const { nonce, authTag, ciphertext } = parseHeader(payload);
68
+ const decipher = createDecipheriv(algorithm, key, nonce);
69
+ decipher.setAuthTag(authTag);
70
+ const compressed = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
71
+ return brotliDecompressSync(compressed);
72
+ };
73
+ export const isPrivatePackPayload = (payload) => payload.length >= magic.length + 1 && payload.subarray(0, magic.length).equals(magic);