@andespindola/brainlink 0.1.0-beta.3 → 0.1.0-beta.30

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 (56) hide show
  1. package/AGENTS.md +5 -5
  2. package/CHANGELOG.md +37 -3
  3. package/CONTRIBUTING.md +2 -2
  4. package/COPYRIGHT.md +5 -0
  5. package/README.md +172 -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/frontend/client-css.js +214 -100
  10. package/dist/application/frontend/client-html.js +60 -45
  11. package/dist/application/frontend/client-js.js +525 -88
  12. package/dist/application/get-graph-layout.js +22 -7
  13. package/dist/application/get-graph-node.js +12 -0
  14. package/dist/application/get-graph-summary.js +12 -0
  15. package/dist/application/get-graph.js +3 -3
  16. package/dist/application/import-legacy-sqlite.js +296 -0
  17. package/dist/application/index-vault.js +11 -4
  18. package/dist/application/list-agents.js +3 -3
  19. package/dist/application/list-links.js +5 -5
  20. package/dist/application/migrate-vault.js +91 -0
  21. package/dist/application/search-graph-node-ids.js +12 -0
  22. package/dist/application/search-knowledge.js +75 -5
  23. package/dist/application/server/routes.js +27 -1
  24. package/dist/benchmarks/large-vault.js +1 -1
  25. package/dist/cli/commands/agent-commands.js +412 -0
  26. package/dist/cli/commands/config-commands.js +167 -0
  27. package/dist/cli/commands/read-commands.js +25 -8
  28. package/dist/cli/commands/write-commands.js +205 -4
  29. package/dist/cli/main.js +4 -0
  30. package/dist/cli/runtime.js +5 -2
  31. package/dist/domain/context.js +53 -11
  32. package/dist/domain/embeddings.js +2 -1
  33. package/dist/domain/graph-layout.js +20 -14
  34. package/dist/domain/markdown.js +36 -4
  35. package/dist/domain/middle-out.js +18 -0
  36. package/dist/infrastructure/config.js +94 -8
  37. package/dist/infrastructure/file-index.js +294 -0
  38. package/dist/infrastructure/file-system-vault.js +15 -0
  39. package/dist/infrastructure/paths.js +9 -1
  40. package/dist/infrastructure/private-pack-codec.js +73 -0
  41. package/dist/infrastructure/search-packs.js +348 -0
  42. package/dist/infrastructure/session-state.js +172 -0
  43. package/dist/mcp/main.js +11 -3
  44. package/dist/mcp/server.js +17 -2
  45. package/dist/mcp/startup.js +35 -0
  46. package/dist/mcp/tools.js +571 -19
  47. package/docs/AGENT_USAGE.md +112 -16
  48. package/docs/ARCHITECTURE.md +37 -26
  49. package/docs/QUICKSTART.md +111 -0
  50. package/package.json +2 -3
  51. package/dist/infrastructure/sqlite/document-writer.js +0 -51
  52. package/dist/infrastructure/sqlite/graph-reader.js +0 -120
  53. package/dist/infrastructure/sqlite/schema.js +0 -111
  54. package/dist/infrastructure/sqlite/search-reader.js +0 -156
  55. package/dist/infrastructure/sqlite/types.js +0 -1
  56. package/dist/infrastructure/sqlite-index.js +0 -25
@@ -0,0 +1,348 @@
1
+ import { gunzipSync } from 'node:zlib';
2
+ import { mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { middleOutIndices } from '../domain/middle-out.js';
5
+ import { decodePrivatePack, encodePrivatePack, isPrivatePackPayload } from './private-pack-codec.js';
6
+ const packsDirectoryName = 'search-packs';
7
+ const manifestFileName = 'manifest.json';
8
+ const rowChunkSize = 5_000;
9
+ const queryTokenPattern = /[\p{L}\p{N}_-]+/gu;
10
+ const bloomBytes = 256;
11
+ const bloomBitSize = bloomBytes * 8;
12
+ const bloomSeeds = [0x9e3779b1, 0x85ebca6b, 0xc2b2ae35];
13
+ const toPackDirectory = (vaultPath) => join(vaultPath, '.brainlink', packsDirectoryName);
14
+ const toManifestPath = (vaultPath) => join(toPackDirectory(vaultPath), manifestFileName);
15
+ const parseRowsFromPack = async (vaultPath, content) => {
16
+ const raw = isPrivatePackPayload(content) ? await decodePrivatePack(vaultPath, content) : gunzipSync(content);
17
+ return raw
18
+ .toString('utf8')
19
+ .split('\n')
20
+ .map((line) => line.trim())
21
+ .filter((line) => line.length > 0)
22
+ .map((line) => JSON.parse(line))
23
+ .flatMap((row) => {
24
+ if (typeof row.documentId !== 'string' ||
25
+ typeof row.agentId !== 'string' ||
26
+ typeof row.title !== 'string' ||
27
+ typeof row.path !== 'string' ||
28
+ typeof row.chunkId !== 'string' ||
29
+ typeof row.content !== 'string') {
30
+ return [];
31
+ }
32
+ return [
33
+ {
34
+ documentId: row.documentId,
35
+ agentId: row.agentId,
36
+ title: row.title,
37
+ path: row.path,
38
+ chunkId: row.chunkId,
39
+ chunkOrdinal: typeof row.chunkOrdinal === 'number' ? row.chunkOrdinal : 0,
40
+ content: row.content,
41
+ tags: Array.isArray(row.tags) ? row.tags.filter((item) => typeof item === 'string') : []
42
+ }
43
+ ];
44
+ });
45
+ };
46
+ const toRows = (documents) => documents.flatMap((document) => document.chunks.map((chunk) => ({
47
+ documentId: document.document.id,
48
+ agentId: document.document.agentId,
49
+ title: document.document.title,
50
+ path: document.document.path,
51
+ chunkId: chunk.id,
52
+ chunkOrdinal: chunk.ordinal,
53
+ content: chunk.content,
54
+ tags: document.document.tags
55
+ })));
56
+ const writeManifest = async (vaultPath, manifest) => {
57
+ await writeFile(toManifestPath(vaultPath), `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
58
+ };
59
+ const readManifest = async (vaultPath) => {
60
+ try {
61
+ const parsed = JSON.parse(await readFile(toManifestPath(vaultPath), 'utf8'));
62
+ if (parsed.version === 2 && parsed.format === 'private-v2') {
63
+ return {
64
+ version: 2,
65
+ createdAt: typeof parsed.createdAt === 'string' ? parsed.createdAt : new Date().toISOString(),
66
+ packCount: typeof parsed.packCount === 'number' ? parsed.packCount : 0,
67
+ recordCount: typeof parsed.recordCount === 'number' ? parsed.recordCount : 0,
68
+ format: 'private-v2'
69
+ };
70
+ }
71
+ if (parsed.version === 3 && parsed.format === 'private-v2') {
72
+ const packIndex = Array.isArray(parsed.packIndex)
73
+ ? parsed.packIndex.flatMap((entry) => {
74
+ if (!entry || typeof entry !== 'object') {
75
+ return [];
76
+ }
77
+ const candidate = entry;
78
+ if (typeof candidate.fileName !== 'string' || typeof candidate.tokenBloomB64 !== 'string') {
79
+ return [];
80
+ }
81
+ return [
82
+ {
83
+ fileName: candidate.fileName,
84
+ recordCount: typeof candidate.recordCount === 'number' ? candidate.recordCount : 0,
85
+ agents: Array.isArray(candidate.agents) ? candidate.agents.filter((item) => typeof item === 'string') : [],
86
+ tokenBloomB64: candidate.tokenBloomB64
87
+ }
88
+ ];
89
+ })
90
+ : [];
91
+ return {
92
+ version: 3,
93
+ createdAt: typeof parsed.createdAt === 'string' ? parsed.createdAt : new Date().toISOString(),
94
+ packCount: typeof parsed.packCount === 'number' ? parsed.packCount : packIndex.length,
95
+ recordCount: typeof parsed.recordCount === 'number' ? parsed.recordCount : 0,
96
+ format: 'private-v2',
97
+ packIndex
98
+ };
99
+ }
100
+ return null;
101
+ }
102
+ catch {
103
+ return null;
104
+ }
105
+ };
106
+ const chunkRows = (rows, size) => {
107
+ const chunks = [];
108
+ for (let index = 0; index < rows.length; index += size) {
109
+ chunks.push(rows.slice(index, index + size));
110
+ }
111
+ return chunks;
112
+ };
113
+ const normalizeToken = (value) => value
114
+ .normalize('NFKD')
115
+ .replace(/\p{Diacritic}/gu, '')
116
+ .toLowerCase();
117
+ const tokenize = (query) => query
118
+ .match(queryTokenPattern)
119
+ ?.map(normalizeToken)
120
+ .filter((token) => token.length > 1) ?? [];
121
+ const countOccurrences = (text, token) => {
122
+ let hits = 0;
123
+ let start = 0;
124
+ while (start < text.length) {
125
+ const index = text.indexOf(token, start);
126
+ if (index < 0) {
127
+ break;
128
+ }
129
+ hits += 1;
130
+ start = index + token.length;
131
+ }
132
+ return hits;
133
+ };
134
+ const hashToken = (token, seed) => {
135
+ let hash = seed >>> 0;
136
+ for (let index = 0; index < token.length; index += 1) {
137
+ hash ^= token.charCodeAt(index);
138
+ hash = Math.imul(hash, 16777619) >>> 0;
139
+ }
140
+ return hash >>> 0;
141
+ };
142
+ const createBloom = () => new Uint8Array(bloomBytes);
143
+ const bloomAdd = (bloom, token) => {
144
+ bloomSeeds.forEach((seed) => {
145
+ const bit = hashToken(token, seed) % bloomBitSize;
146
+ bloom[Math.floor(bit / 8)] |= 1 << (bit % 8);
147
+ });
148
+ };
149
+ const bloomMayContain = (bloom, token) => bloomSeeds.every((seed) => {
150
+ const bit = hashToken(token, seed) % bloomBitSize;
151
+ return (bloom[Math.floor(bit / 8)] & (1 << (bit % 8))) !== 0;
152
+ });
153
+ const bloomFromRows = (rows) => {
154
+ const bloom = createBloom();
155
+ rows.forEach((row) => {
156
+ tokenize([row.title, row.path, row.tags.join(' '), row.content].join(' ')).forEach((token) => bloomAdd(bloom, token));
157
+ });
158
+ return bloom;
159
+ };
160
+ const bloomToBase64 = (bloom) => Buffer.from(bloom).toString('base64url');
161
+ const bloomFromBase64 = (value) => {
162
+ try {
163
+ const decoded = Buffer.from(value, 'base64url');
164
+ if (decoded.byteLength === bloomBytes) {
165
+ return {
166
+ bloom: new Uint8Array(decoded),
167
+ valid: true
168
+ };
169
+ }
170
+ }
171
+ catch {
172
+ // fallback below
173
+ }
174
+ return {
175
+ bloom: createBloom(),
176
+ valid: false
177
+ };
178
+ };
179
+ const computeTextScore = (row, tokens) => {
180
+ if (tokens.length === 0) {
181
+ return 0;
182
+ }
183
+ const title = normalizeToken(row.title);
184
+ const path = normalizeToken(row.path);
185
+ const content = normalizeToken(row.content);
186
+ const tags = normalizeToken(row.tags.join(' '));
187
+ return tokens.reduce((score, token) => {
188
+ const titleHits = countOccurrences(title, token);
189
+ const tagHits = countOccurrences(tags, token);
190
+ const pathHits = countOccurrences(path, token);
191
+ const contentHits = countOccurrences(content, token);
192
+ return score + titleHits * 5 + tagHits * 4 + pathHits * 2 + Math.min(contentHits, 5);
193
+ }, 0);
194
+ };
195
+ const toSearchResult = (row, score) => ({
196
+ documentId: row.documentId,
197
+ agentId: row.agentId,
198
+ title: row.title,
199
+ path: row.path,
200
+ chunkId: row.chunkId,
201
+ chunkOrdinal: row.chunkOrdinal,
202
+ content: row.content,
203
+ score,
204
+ textScore: score,
205
+ semanticScore: 0,
206
+ searchMode: 'fts',
207
+ tags: row.tags
208
+ });
209
+ const sortedPackFiles = async (vaultPath) => {
210
+ try {
211
+ const files = await readdir(toPackDirectory(vaultPath));
212
+ return files
213
+ .filter((file) => file.endsWith('.blpk') || file.endsWith('.jsonl.gz'))
214
+ .sort((left, right) => left.localeCompare(right));
215
+ }
216
+ catch (error) {
217
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
218
+ return [];
219
+ }
220
+ throw error;
221
+ }
222
+ };
223
+ const writeRowsAsPrivatePacks = async (vaultPath, rows, clearExisting) => {
224
+ const directory = toPackDirectory(vaultPath);
225
+ await mkdir(directory, { recursive: true });
226
+ if (clearExisting) {
227
+ const current = await readdir(directory);
228
+ await Promise.all(current
229
+ .filter((name) => name.endsWith('.blpk') || name.endsWith('.jsonl.gz') || name === manifestFileName)
230
+ .map((name) => rm(join(directory, name), { force: true })));
231
+ }
232
+ const chunks = chunkRows(rows, rowChunkSize);
233
+ const packIndex = [];
234
+ for (let index = 0; index < chunks.length; index += 1) {
235
+ const chunk = chunks[index];
236
+ const fileName = `pack-${String(index + 1).padStart(4, '0')}.blpk`;
237
+ const serialized = `${chunk.map((row) => JSON.stringify(row)).join('\n')}\n`;
238
+ const compressed = await encodePrivatePack(vaultPath, Buffer.from(serialized, 'utf8'));
239
+ const tokenBloomB64 = bloomToBase64(bloomFromRows(chunk));
240
+ await writeFile(join(directory, fileName), compressed);
241
+ packIndex.push({
242
+ fileName,
243
+ recordCount: chunk.length,
244
+ agents: Array.from(new Set(chunk.map((row) => row.agentId))).sort((left, right) => left.localeCompare(right)),
245
+ tokenBloomB64
246
+ });
247
+ }
248
+ await writeManifest(vaultPath, {
249
+ version: 3,
250
+ createdAt: new Date().toISOString(),
251
+ packCount: chunks.length,
252
+ recordCount: rows.length,
253
+ format: 'private-v2',
254
+ packIndex
255
+ });
256
+ return {
257
+ packCount: chunks.length,
258
+ recordCount: rows.length
259
+ };
260
+ };
261
+ const selectCandidatePackFiles = async (vaultPath, tokens, agentId) => {
262
+ const allFiles = await sortedPackFiles(vaultPath);
263
+ if (allFiles.length === 0) {
264
+ return [];
265
+ }
266
+ const manifest = await readManifest(vaultPath);
267
+ if (!manifest || manifest.version !== 3 || !Array.isArray(manifest.packIndex)) {
268
+ return allFiles;
269
+ }
270
+ const normalizedAgent = agentId?.trim();
271
+ const byAgent = manifest.packIndex.filter((entry) => normalizedAgent ? entry.agents.includes(normalizedAgent) : true);
272
+ if (tokens.length === 0) {
273
+ return byAgent.map((entry) => entry.fileName);
274
+ }
275
+ let hasInvalidBloomIndex = false;
276
+ const byToken = byAgent.filter((entry) => {
277
+ const decoded = bloomFromBase64(entry.tokenBloomB64);
278
+ if (!decoded.valid) {
279
+ hasInvalidBloomIndex = true;
280
+ return true;
281
+ }
282
+ return tokens.some((token) => bloomMayContain(decoded.bloom, token));
283
+ });
284
+ // Lossless guarantee: if compressed metadata is partially invalid, do not prune packs.
285
+ if (hasInvalidBloomIndex) {
286
+ return byAgent.map((entry) => entry.fileName);
287
+ }
288
+ if (byToken.length > 0) {
289
+ return byToken.map((entry) => entry.fileName);
290
+ }
291
+ return byAgent.length > 0 ? byAgent.map((entry) => entry.fileName) : allFiles;
292
+ };
293
+ export const buildSearchPacks = async (vaultPath, documents) => {
294
+ return writeRowsAsPrivatePacks(vaultPath, toRows(documents), true);
295
+ };
296
+ export const ensurePrivatePacksFromLegacyIndex = async (vaultPath) => {
297
+ const files = await sortedPackFiles(vaultPath);
298
+ if (files.some((file) => file.endsWith('.blpk'))) {
299
+ return { imported: false };
300
+ }
301
+ const legacyPackFiles = files.filter((file) => file.endsWith('.jsonl.gz'));
302
+ if (legacyPackFiles.length > 0) {
303
+ const rows = [];
304
+ for (const file of legacyPackFiles) {
305
+ const parsed = await parseRowsFromPack(vaultPath, await readFile(join(toPackDirectory(vaultPath), file)));
306
+ rows.push(...parsed);
307
+ }
308
+ const report = await writeRowsAsPrivatePacks(vaultPath, rows, true);
309
+ return {
310
+ imported: true,
311
+ source: 'legacy-packs',
312
+ ...report
313
+ };
314
+ }
315
+ return { imported: false };
316
+ };
317
+ export const searchInPacks = async (vaultPath, query, limit, agentId) => {
318
+ const normalizedAgent = agentId?.trim();
319
+ const tokens = tokenize(query);
320
+ if (limit <= 0 || tokens.length === 0) {
321
+ return [];
322
+ }
323
+ const files = await selectCandidatePackFiles(vaultPath, tokens, normalizedAgent);
324
+ if (files.length === 0) {
325
+ return [];
326
+ }
327
+ const scored = [];
328
+ for (const file of files) {
329
+ const rows = await parseRowsFromPack(vaultPath, await readFile(join(toPackDirectory(vaultPath), file)));
330
+ const traversal = middleOutIndices(rows.length, Math.floor(rows.length / 2));
331
+ traversal.forEach((rowIndex) => {
332
+ const row = rows[rowIndex];
333
+ if (!row) {
334
+ return;
335
+ }
336
+ if (normalizedAgent && row.agentId !== normalizedAgent) {
337
+ return;
338
+ }
339
+ const score = computeTextScore(row, tokens);
340
+ if (score > 0) {
341
+ scored.push(toSearchResult(row, score));
342
+ }
343
+ });
344
+ }
345
+ return scored
346
+ .sort((left, right) => right.score - left.score || left.title.localeCompare(right.title))
347
+ .slice(0, limit);
348
+ };
@@ -0,0 +1,172 @@
1
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ import { getBrainlinkHomePath } from './paths.js';
4
+ const defaultPolicy = {
5
+ enforceBootstrap: true,
6
+ enforceContextFirst: true,
7
+ autoBootstrapOnRead: true,
8
+ autoBootstrapOnStartup: true,
9
+ staleAfterMinutes: 120
10
+ };
11
+ const defaultState = {
12
+ policy: defaultPolicy,
13
+ bootstraps: [],
14
+ contexts: []
15
+ };
16
+ const sessionStatePath = () => join(getBrainlinkHomePath(), 'session-state.json');
17
+ const normalizeAgent = (agent) => agent?.trim() ? agent.trim() : '*';
18
+ const safePositive = (value, fallback) => typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback;
19
+ const sanitizeState = (value) => {
20
+ if (typeof value !== 'object' || value === null) {
21
+ return defaultState;
22
+ }
23
+ const record = value;
24
+ const policyRecord = typeof record.policy === 'object' && record.policy !== null ? record.policy : {};
25
+ const rawBootstraps = Array.isArray(record.bootstraps) ? record.bootstraps : [];
26
+ const rawContexts = Array.isArray(record.contexts) ? record.contexts : [];
27
+ const bootstraps = rawBootstraps.flatMap((entry) => {
28
+ if (typeof entry !== 'object' || entry === null) {
29
+ return [];
30
+ }
31
+ const row = entry;
32
+ const vault = typeof row.vault === 'string' && row.vault.trim().length > 0 ? row.vault.trim() : undefined;
33
+ const agent = typeof row.agent === 'string' && row.agent.trim().length > 0 ? row.agent.trim() : undefined;
34
+ const lastBootstrappedAt = typeof row.lastBootstrappedAt === 'string' && row.lastBootstrappedAt.trim().length > 0 ? row.lastBootstrappedAt.trim() : undefined;
35
+ return vault && agent && lastBootstrappedAt ? [{ vault, agent, lastBootstrappedAt }] : [];
36
+ });
37
+ const contexts = rawContexts.flatMap((entry) => {
38
+ if (typeof entry !== 'object' || entry === null) {
39
+ return [];
40
+ }
41
+ const row = entry;
42
+ const vault = typeof row.vault === 'string' && row.vault.trim().length > 0 ? row.vault.trim() : undefined;
43
+ const agent = typeof row.agent === 'string' && row.agent.trim().length > 0 ? row.agent.trim() : undefined;
44
+ const lastContextAt = typeof row.lastContextAt === 'string' && row.lastContextAt.trim().length > 0 ? row.lastContextAt.trim() : undefined;
45
+ return vault && agent && lastContextAt ? [{ vault, agent, lastContextAt }] : [];
46
+ });
47
+ return {
48
+ policy: {
49
+ enforceBootstrap: typeof policyRecord.enforceBootstrap === 'boolean' ? policyRecord.enforceBootstrap : defaultPolicy.enforceBootstrap,
50
+ enforceContextFirst: typeof policyRecord.enforceContextFirst === 'boolean'
51
+ ? policyRecord.enforceContextFirst
52
+ : defaultPolicy.enforceContextFirst,
53
+ autoBootstrapOnRead: typeof policyRecord.autoBootstrapOnRead === 'boolean'
54
+ ? policyRecord.autoBootstrapOnRead
55
+ : defaultPolicy.autoBootstrapOnRead,
56
+ autoBootstrapOnStartup: typeof policyRecord.autoBootstrapOnStartup === 'boolean'
57
+ ? policyRecord.autoBootstrapOnStartup
58
+ : defaultPolicy.autoBootstrapOnStartup,
59
+ staleAfterMinutes: safePositive(policyRecord.staleAfterMinutes, defaultPolicy.staleAfterMinutes)
60
+ },
61
+ bootstraps,
62
+ contexts
63
+ };
64
+ };
65
+ const readState = async () => {
66
+ try {
67
+ const content = await readFile(sessionStatePath(), 'utf8');
68
+ return sanitizeState(JSON.parse(content));
69
+ }
70
+ catch (error) {
71
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
72
+ return defaultState;
73
+ }
74
+ throw error;
75
+ }
76
+ };
77
+ const writeState = async (state) => {
78
+ const path = sessionStatePath();
79
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
80
+ await writeFile(path, `${JSON.stringify(state, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
81
+ };
82
+ export const getSessionStatePath = () => sessionStatePath();
83
+ export const getBootstrapPolicy = async () => (await readState()).policy;
84
+ export const setBootstrapPolicy = async (patch) => {
85
+ const state = await readState();
86
+ const next = {
87
+ enforceBootstrap: typeof patch.enforceBootstrap === 'boolean' ? patch.enforceBootstrap : state.policy.enforceBootstrap,
88
+ enforceContextFirst: typeof patch.enforceContextFirst === 'boolean' ? patch.enforceContextFirst : state.policy.enforceContextFirst,
89
+ autoBootstrapOnRead: typeof patch.autoBootstrapOnRead === 'boolean' ? patch.autoBootstrapOnRead : state.policy.autoBootstrapOnRead,
90
+ autoBootstrapOnStartup: typeof patch.autoBootstrapOnStartup === 'boolean' ? patch.autoBootstrapOnStartup : state.policy.autoBootstrapOnStartup,
91
+ staleAfterMinutes: safePositive(patch.staleAfterMinutes, state.policy.staleAfterMinutes)
92
+ };
93
+ await writeState({
94
+ ...state,
95
+ policy: next
96
+ });
97
+ return next;
98
+ };
99
+ export const touchBootstrapSession = async (vault, agent) => {
100
+ const state = await readState();
101
+ const normalizedAgent = normalizeAgent(agent);
102
+ const entry = {
103
+ vault,
104
+ agent: normalizedAgent,
105
+ lastBootstrappedAt: new Date().toISOString()
106
+ };
107
+ const bootstraps = [
108
+ entry,
109
+ ...state.bootstraps.filter((item) => !(item.vault === entry.vault && item.agent === entry.agent))
110
+ ].slice(0, 500);
111
+ await writeState({
112
+ ...state,
113
+ bootstraps
114
+ });
115
+ return entry;
116
+ };
117
+ export const touchContextSession = async (vault, agent) => {
118
+ const state = await readState();
119
+ const normalizedAgent = normalizeAgent(agent);
120
+ const entry = {
121
+ vault,
122
+ agent: normalizedAgent,
123
+ lastContextAt: new Date().toISOString()
124
+ };
125
+ const contexts = [
126
+ entry,
127
+ ...state.contexts.filter((item) => !(item.vault === entry.vault && item.agent === entry.agent))
128
+ ].slice(0, 500);
129
+ await writeState({
130
+ ...state,
131
+ contexts
132
+ });
133
+ return entry;
134
+ };
135
+ export const getBootstrapSessionStatus = async (vault, agent) => {
136
+ const state = await readState();
137
+ const normalizedAgent = normalizeAgent(agent);
138
+ const match = state.bootstraps.find((entry) => entry.vault === vault && entry.agent === normalizedAgent);
139
+ if (!match) {
140
+ return {
141
+ ready: false,
142
+ stale: true
143
+ };
144
+ }
145
+ const ageMinutes = Math.max(0, (Date.now() - new Date(match.lastBootstrappedAt).getTime()) / 60000);
146
+ const stale = ageMinutes > state.policy.staleAfterMinutes;
147
+ return {
148
+ ready: !stale,
149
+ stale,
150
+ lastBootstrappedAt: match.lastBootstrappedAt,
151
+ ageMinutes
152
+ };
153
+ };
154
+ export const getContextSessionStatus = async (vault, agent) => {
155
+ const state = await readState();
156
+ const normalizedAgent = normalizeAgent(agent);
157
+ const match = state.contexts.find((entry) => entry.vault === vault && entry.agent === normalizedAgent);
158
+ if (!match) {
159
+ return {
160
+ ready: false,
161
+ stale: true
162
+ };
163
+ }
164
+ const ageMinutes = Math.max(0, (Date.now() - new Date(match.lastContextAt).getTime()) / 60000);
165
+ const stale = ageMinutes > state.policy.staleAfterMinutes;
166
+ return {
167
+ ready: !stale,
168
+ stale,
169
+ lastContextAt: match.lastContextAt,
170
+ ageMinutes
171
+ };
172
+ };
package/dist/mcp/main.js CHANGED
@@ -1,9 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
3
  import { createBrainlinkMcpServer } from './server.js';
4
- const server = createBrainlinkMcpServer();
5
- const transport = new StdioServerTransport();
6
- server.connect(transport).catch((error) => {
4
+ import { runStartupBootstrap } from './startup.js';
5
+ const start = async () => {
6
+ const startup = await runStartupBootstrap();
7
+ if (startup.error) {
8
+ console.error(`Brainlink MCP startup bootstrap warning: ${startup.error}`);
9
+ }
10
+ const server = createBrainlinkMcpServer();
11
+ const transport = new StdioServerTransport();
12
+ await server.connect(transport);
13
+ };
14
+ start().catch((error) => {
7
15
  const message = error instanceof Error ? error.message : String(error);
8
16
  console.error(message);
9
17
  process.exitCode = 1;
@@ -2,7 +2,7 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import { readFileSync } from 'node:fs';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
- import { addNoteInputSchema, addFileInputSchema, addFileTool, addNoteTool, brokenLinksInputSchema, brokenLinksTool, contextInputSchema, contextTool, graphInputSchema, graphTool, indexInputSchema, indexTool, orphansInputSchema, orphansTool, searchInputSchema, searchTool, statsInputSchema, statsTool, syncInputSchema, syncTool, validateInputSchema, validateTool } from './tools.js';
5
+ import { addNoteInputSchema, addFileInputSchema, addFileTool, addNoteTool, brokenLinksInputSchema, brokenLinksTool, bootstrapInputSchema, bootstrapTool, contextInputSchema, contextTool, graphInputSchema, graphTool, indexInputSchema, indexTool, orphansInputSchema, orphansTool, policyInputSchema, policyTool, recommendationsInputSchema, recommendationsTool, searchInputSchema, searchTool, statsInputSchema, statsTool, syncInputSchema, syncTool, validateInputSchema, validateTool } from './tools.js';
6
6
  const readPackageVersion = () => {
7
7
  const packagePath = join(dirname(fileURLToPath(import.meta.url)), '../../package.json');
8
8
  const metadata = JSON.parse(readFileSync(packagePath, 'utf8'));
@@ -15,9 +15,24 @@ export const createBrainlinkMcpServer = () => {
15
15
  version: readPackageVersion(),
16
16
  description: 'Local-first Markdown memory tools for AI agents.'
17
17
  });
18
+ server.registerTool('brainlink_bootstrap', {
19
+ title: 'Bootstrap Brainlink For A Task (Default Entrypoint)',
20
+ description: 'Default entrypoint for agents. Run this first to index/check memory state, then optionally retrieve context for the current task query.',
21
+ inputSchema: bootstrapInputSchema
22
+ }, bootstrapTool);
23
+ server.registerTool('brainlink_policy', {
24
+ title: 'Brainlink Bootstrap Policy',
25
+ description: 'Read or update bootstrap enforcement policy and inspect bootstrap readiness for the current vault/agent.',
26
+ inputSchema: policyInputSchema
27
+ }, policyTool);
28
+ server.registerTool('brainlink_recommendations', {
29
+ title: 'Brainlink Recommended MCP Workflow',
30
+ description: 'Return a plug-and-play action plan for this vault/agent, including policy, bootstrap, context retrieval and durable write guidance.',
31
+ inputSchema: recommendationsInputSchema
32
+ }, recommendationsTool);
18
33
  server.registerTool('brainlink_context', {
19
34
  title: 'Build Brainlink Context',
20
- description: 'Read indexed Brainlink memory for a task or question. This is read-only and does not create graph links.',
35
+ description: 'Read indexed Brainlink memory for a task or question. Usually called after brainlink_bootstrap. This is read-only and does not create graph links.',
21
36
  inputSchema: contextInputSchema
22
37
  }, contextTool);
23
38
  server.registerTool('brainlink_search', {
@@ -0,0 +1,35 @@
1
+ import { indexVault } from '../application/index-vault.js';
2
+ import { loadBrainlinkConfig } from '../infrastructure/config.js';
3
+ import { assertVaultAllowed } from '../infrastructure/file-system-vault.js';
4
+ import { getBootstrapPolicy, touchBootstrapSession } from '../infrastructure/session-state.js';
5
+ export const runStartupBootstrap = async () => {
6
+ try {
7
+ const policy = await getBootstrapPolicy();
8
+ if (!policy.autoBootstrapOnStartup) {
9
+ return {
10
+ attempted: false,
11
+ skipped: true,
12
+ reason: 'autoBootstrapOnStartup=false'
13
+ };
14
+ }
15
+ const config = await loadBrainlinkConfig();
16
+ const vault = assertVaultAllowed(config.vault, config.allowedVaults);
17
+ const agent = config.defaultAgent;
18
+ const index = await indexVault(vault);
19
+ await touchBootstrapSession(vault, agent);
20
+ return {
21
+ attempted: true,
22
+ skipped: false,
23
+ vault,
24
+ agent: agent ?? '*',
25
+ index
26
+ };
27
+ }
28
+ catch (error) {
29
+ return {
30
+ attempted: true,
31
+ skipped: false,
32
+ error: error instanceof Error ? error.message : String(error)
33
+ };
34
+ }
35
+ };