brainbank 0.1.3 → 0.1.5
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/README.md +84 -1107
- package/assets/architecture.png +0 -0
- package/bin/brainbank +8 -1
- package/bin/brainbank-mcp +19 -0
- package/dist/chunk-3UIWA32X.js +3341 -0
- package/dist/chunk-3UIWA32X.js.map +1 -0
- package/dist/chunk-3YBCD6DI.js +117 -0
- package/dist/chunk-3YBCD6DI.js.map +1 -0
- package/dist/chunk-DAGVUEXL.js +258 -0
- package/dist/chunk-DAGVUEXL.js.map +1 -0
- package/dist/chunk-DMFMTOHF.js +123 -0
- package/dist/chunk-DMFMTOHF.js.map +1 -0
- package/dist/chunk-FQYKWB2Q.js +136 -0
- package/dist/chunk-FQYKWB2Q.js.map +1 -0
- package/dist/chunk-IMJJ2VEM.js +74 -0
- package/dist/chunk-IMJJ2VEM.js.map +1 -0
- package/dist/chunk-M744PCJQ.js +43 -0
- package/dist/chunk-M744PCJQ.js.map +1 -0
- package/dist/chunk-NNDY7P2R.js +211 -0
- package/dist/chunk-NNDY7P2R.js.map +1 -0
- package/dist/chunk-O3J6ZIXK.js +82 -0
- package/dist/chunk-O3J6ZIXK.js.map +1 -0
- package/dist/chunk-RDQYDLYZ.js +69 -0
- package/dist/chunk-RDQYDLYZ.js.map +1 -0
- package/dist/chunk-WCQVDF3K.js +14 -0
- package/dist/cli.js +2713 -325
- package/dist/cli.js.map +1 -1
- package/dist/haiku-pruner-5KVT5AI2.js +8 -0
- package/dist/http-server-2ZQ6I43B.js +9 -0
- package/dist/index.d.ts +1886 -626
- package/dist/index.js +319 -46
- package/dist/index.js.map +1 -1
- package/dist/local-embedding-NZQTILGV.js +8 -0
- package/dist/mcp.d.ts +2 -0
- package/dist/mcp.js +333 -0
- package/dist/mcp.js.map +1 -0
- package/dist/openai-embedding-ZP5TSUJG.js +8 -0
- package/dist/perplexity-context-embedding-GI5PHE6X.js +9 -0
- package/dist/perplexity-context-embedding-GI5PHE6X.js.map +1 -0
- package/dist/perplexity-embedding-KZRYGJRC.js +10 -0
- package/dist/perplexity-embedding-KZRYGJRC.js.map +1 -0
- package/dist/plugin-IKQ6IRSJ.js +32 -0
- package/dist/plugin-IKQ6IRSJ.js.map +1 -0
- package/dist/resolve-ASGLBNUC.js +10 -0
- package/dist/resolve-ASGLBNUC.js.map +1 -0
- package/dist/stats-tui-AD3AMYGV.js +1904 -0
- package/dist/stats-tui-AD3AMYGV.js.map +1 -0
- package/package.json +38 -53
- package/src/brainbank.ts +617 -0
- package/src/cli/commands/collection.ts +77 -0
- package/src/cli/commands/context.ts +59 -0
- package/src/cli/commands/daemon.ts +100 -0
- package/src/cli/commands/docs.ts +71 -0
- package/src/cli/commands/files.ts +69 -0
- package/src/cli/commands/help.ts +82 -0
- package/src/cli/commands/index.ts +478 -0
- package/src/cli/commands/kv.ts +140 -0
- package/src/cli/commands/mcp-export.ts +273 -0
- package/src/cli/commands/mcp.ts +6 -0
- package/src/cli/commands/query.ts +167 -0
- package/src/cli/commands/reembed.ts +30 -0
- package/src/cli/commands/reindex.ts +40 -0
- package/src/cli/commands/scan.ts +336 -0
- package/src/cli/commands/search.ts +203 -0
- package/src/cli/commands/stats.ts +68 -0
- package/src/cli/commands/status.ts +47 -0
- package/src/cli/commands/watch.ts +47 -0
- package/src/cli/factory/brain-context.ts +43 -0
- package/src/cli/factory/builtin-registration.ts +87 -0
- package/src/cli/factory/config-loader.ts +77 -0
- package/src/cli/factory/index.ts +69 -0
- package/src/cli/factory/plugin-loader.ts +324 -0
- package/src/cli/index.ts +76 -0
- package/src/cli/server-client.ts +186 -0
- package/src/cli/tui/index-tui.tsx +667 -0
- package/src/cli/tui/stats-data.ts +523 -0
- package/src/cli/tui/stats-search.ts +262 -0
- package/src/cli/tui/stats-tui.tsx +1465 -0
- package/src/cli/tui/tree-scanner.ts +650 -0
- package/src/cli/utils.ts +137 -0
- package/src/config.ts +48 -0
- package/src/constants.ts +21 -0
- package/src/db/adapter.ts +112 -0
- package/src/db/metadata.ts +130 -0
- package/src/db/migrations.ts +66 -0
- package/src/db/sqlite-adapter.ts +218 -0
- package/src/db/tracker.ts +91 -0
- package/src/engine/index-api.ts +81 -0
- package/src/engine/reembed.ts +206 -0
- package/src/engine/search-api.ts +218 -0
- package/src/index.ts +150 -0
- package/src/lib/fts.ts +57 -0
- package/src/lib/languages.ts +179 -0
- package/src/lib/logger.ts +126 -0
- package/src/lib/math.ts +87 -0
- package/src/lib/provider-key.ts +20 -0
- package/src/lib/prune.ts +72 -0
- package/src/lib/rrf.ts +133 -0
- package/src/lib/write-lock.ts +108 -0
- package/src/mcp/mcp-server.ts +192 -0
- package/src/mcp/workspace-factory.ts +68 -0
- package/src/mcp/workspace-pool.ts +224 -0
- package/src/plugin.ts +381 -0
- package/src/providers/embeddings/embedding-worker-thread.ts +95 -0
- package/src/providers/embeddings/embedding-worker.ts +141 -0
- package/src/providers/embeddings/local-embedding.ts +115 -0
- package/src/providers/embeddings/openai-embedding.ts +167 -0
- package/src/providers/embeddings/perplexity-context-embedding.ts +195 -0
- package/src/providers/embeddings/perplexity-embedding.ts +165 -0
- package/src/providers/embeddings/resolve.ts +34 -0
- package/src/providers/pruners/haiku-expander.ts +178 -0
- package/src/providers/pruners/haiku-pruner.ts +263 -0
- package/src/providers/vector/hnsw-index.ts +174 -0
- package/src/providers/vector/hnsw-loader.ts +129 -0
- package/src/search/bm25-boost.ts +76 -0
- package/src/search/context-builder.ts +209 -0
- package/src/search/keyword/composite-bm25-search.ts +47 -0
- package/src/search/query-decomposer.ts +124 -0
- package/src/search/types.ts +37 -0
- package/src/search/vector/composite-vector-search.ts +105 -0
- package/src/search/vector/mmr.ts +64 -0
- package/src/services/collection.ts +384 -0
- package/src/services/daemon.ts +87 -0
- package/src/services/http-server.ts +344 -0
- package/src/services/kv-service.ts +64 -0
- package/src/services/plugin-registry.ts +77 -0
- package/src/services/watch.ts +340 -0
- package/src/services/webhook-server.ts +100 -0
- package/src/types.ts +509 -0
- package/dist/chunk-2P3EGY6S.js +0 -37
- package/dist/chunk-2P3EGY6S.js.map +0 -1
- package/dist/chunk-3GAIDXRW.js +0 -105
- package/dist/chunk-3GAIDXRW.js.map +0 -1
- package/dist/chunk-4ZKBQ33J.js +0 -56
- package/dist/chunk-4ZKBQ33J.js.map +0 -1
- package/dist/chunk-7QVYU63E.js +0 -7
- package/dist/chunk-GOUBW7UA.js +0 -373
- package/dist/chunk-GOUBW7UA.js.map +0 -1
- package/dist/chunk-MJ3Y24H6.js +0 -185
- package/dist/chunk-MJ3Y24H6.js.map +0 -1
- package/dist/chunk-N6ZMBFDE.js +0 -224
- package/dist/chunk-N6ZMBFDE.js.map +0 -1
- package/dist/chunk-RAEBYV75.js +0 -709
- package/dist/chunk-RAEBYV75.js.map +0 -1
- package/dist/chunk-TW5NTYYZ.js +0 -2066
- package/dist/chunk-TW5NTYYZ.js.map +0 -1
- package/dist/chunk-Z5SU54HP.js +0 -171
- package/dist/chunk-Z5SU54HP.js.map +0 -1
- package/dist/code.d.ts +0 -31
- package/dist/code.js +0 -8
- package/dist/docs.d.ts +0 -19
- package/dist/docs.js +0 -8
- package/dist/git.d.ts +0 -31
- package/dist/git.js +0 -8
- package/dist/memory.d.ts +0 -19
- package/dist/memory.js +0 -146
- package/dist/memory.js.map +0 -1
- package/dist/notes.d.ts +0 -19
- package/dist/notes.js +0 -57
- package/dist/notes.js.map +0 -1
- package/dist/openai-PCTYLOWI.js +0 -8
- package/dist/types-Da_zLLOl.d.ts +0 -474
- /package/dist/{chunk-7QVYU63E.js.map → chunk-WCQVDF3K.js.map} +0 -0
- /package/dist/{code.js.map → haiku-pruner-5KVT5AI2.js.map} +0 -0
- /package/dist/{docs.js.map → http-server-2ZQ6I43B.js.map} +0 -0
- /package/dist/{git.js.map → local-embedding-NZQTILGV.js.map} +0 -0
- /package/dist/{openai-PCTYLOWI.js.map → openai-embedding-ZP5TSUJG.js.map} +0 -0
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* BrainBank — MCP Server
|
|
3
|
+
*
|
|
4
|
+
* Exposes BrainBank as an MCP server via stdio transport.
|
|
5
|
+
* Works with Google Antigravity, Claude Code, and any MCP-compatible client.
|
|
6
|
+
*
|
|
7
|
+
* Tools:
|
|
8
|
+
* brainbank_query — AI-pruned semantic context for a task
|
|
9
|
+
* brainbank_index — Index/re-index a repository
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
14
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
15
|
+
import { z } from 'zod/v3';
|
|
16
|
+
|
|
17
|
+
import { WorkspacePool } from './workspace-pool.ts';
|
|
18
|
+
import { createWorkspaceBrain, resolveRepoPath } from './workspace-factory.ts';
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
// ── Multi-Workspace BrainBank Pool ─────────────────────
|
|
23
|
+
|
|
24
|
+
const pool = new WorkspacePool({
|
|
25
|
+
factory: createWorkspaceBrain,
|
|
26
|
+
maxMemoryMB: parseInt(process.env.BRAINBANK_MAX_MEMORY_MB ?? '2048', 10),
|
|
27
|
+
ttlMinutes: parseInt(process.env.BRAINBANK_TTL_MINUTES ?? '30', 10),
|
|
28
|
+
onError: (repo, err) => {
|
|
29
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
30
|
+
console.error(`BrainBank pool error [${repo}]: ${msg}`);
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
/** Resolve repo and get a BrainBank from the pool. */
|
|
35
|
+
async function getBrainBank(targetRepo?: string) {
|
|
36
|
+
return pool.get(resolveRepoPath(targetRepo));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// ── MCP Server Setup ────────────────────────────────
|
|
40
|
+
|
|
41
|
+
const server = new McpServer({
|
|
42
|
+
name: 'brainbank',
|
|
43
|
+
version: '0.1.5',
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
// ── Tool: brainbank_query ───────────────────────────
|
|
47
|
+
|
|
48
|
+
server.registerTool(
|
|
49
|
+
'brainbank_query',
|
|
50
|
+
{
|
|
51
|
+
title: 'BrainBank Context',
|
|
52
|
+
description:
|
|
53
|
+
'Get AI-pruned semantic context for a task. Returns search hits + full call tree ' +
|
|
54
|
+
'with `called by` annotations, topologically ordered. Pass `context` for general ' +
|
|
55
|
+
'background and `pruner` for specific filtering instructions.',
|
|
56
|
+
inputSchema: z.object({
|
|
57
|
+
task: z.string().describe('Description of the task you need context for'),
|
|
58
|
+
affectedFiles: z.array(z.string()).optional().default([]).describe('Files you plan to modify (improves co-edit suggestions)'),
|
|
59
|
+
codeResults: z.number().optional().default(20).describe('Max code results'),
|
|
60
|
+
gitResults: z.number().optional().default(5).describe('Max git commit results'),
|
|
61
|
+
docsResults: z.number().optional().describe('Max document results (omit to skip docs)'),
|
|
62
|
+
sources: z.record(z.number()).optional().describe('Per-source result limits, overrides codeResults/gitResults/docsResults (e.g. { code: 10, git: 0, docs: 5 })'),
|
|
63
|
+
path: z.union([z.string(), z.array(z.string())]).optional().describe('Filter results to files under these path prefixes. Pass a single string or array (e.g. ["src/services/", "lib/"])'),
|
|
64
|
+
ignore: z.array(z.string()).optional().describe('Exclude results whose filePath starts with any of these prefixes (e.g. ["src/tests/", "src/mocks/"])'),
|
|
65
|
+
repo: z.string().describe('Repository path (default: BRAINBANK_REPO)'),
|
|
66
|
+
// BrainBankQL context fields
|
|
67
|
+
lines: z.boolean().optional().describe('Prefix each code line with its source line number (e.g. 127| code)'),
|
|
68
|
+
symbols: z.boolean().optional().describe('Append symbol index (all functions, classes, interfaces) for matched files'),
|
|
69
|
+
compact: z.boolean().optional().describe('Show only function/class signatures, skip bodies'),
|
|
70
|
+
callTree: z.union([z.boolean(), z.object({ depth: z.number() })]).optional().describe('Include call tree expansion. Pass { depth: N } to control depth'),
|
|
71
|
+
imports: z.boolean().optional().describe('Include dependency/import summary section'),
|
|
72
|
+
context: z.string().optional().describe('General task context for the pruner — e.g. GitHub issue body, requirements doc, conversation context. Helps the AI pruner understand the broader task'),
|
|
73
|
+
pruner: z.string().optional().describe('Specific pruning instructions — tells the pruner exactly what to focus on (e.g. "only keep files related to WebSocket JWT refresh")'),
|
|
74
|
+
}),
|
|
75
|
+
},
|
|
76
|
+
async ({ task, affectedFiles, codeResults, gitResults, docsResults, sources, path, ignore, repo, lines, symbols, compact, callTree, imports, context: ctx, pruner: prunerCtx }) => {
|
|
77
|
+
const repoPath = resolveRepoPath(repo);
|
|
78
|
+
const brainbank = await getBrainBank(repo);
|
|
79
|
+
|
|
80
|
+
// Build sources from explicit params, then let `sources` override
|
|
81
|
+
const base: Record<string, number> = { code: codeResults, git: gitResults };
|
|
82
|
+
if (docsResults !== undefined) base.docs = docsResults;
|
|
83
|
+
const resolvedSources = sources ? { ...base, ...sources } : base;
|
|
84
|
+
|
|
85
|
+
// Build fields from explicit params (only include defined values)
|
|
86
|
+
const fields: Record<string, unknown> = {};
|
|
87
|
+
if (lines !== undefined) fields.lines = lines;
|
|
88
|
+
if (symbols !== undefined) fields.symbols = symbols;
|
|
89
|
+
if (compact !== undefined) fields.compact = compact;
|
|
90
|
+
if (callTree !== undefined) fields.callTree = callTree;
|
|
91
|
+
if (imports !== undefined) fields.imports = imports;
|
|
92
|
+
|
|
93
|
+
const context = await brainbank.getContext(task, {
|
|
94
|
+
affectedFiles,
|
|
95
|
+
sources: resolvedSources,
|
|
96
|
+
pathPrefix: path,
|
|
97
|
+
ignorePaths: ignore,
|
|
98
|
+
source: 'mcp',
|
|
99
|
+
fields: Object.keys(fields).length > 0 ? fields : undefined,
|
|
100
|
+
context: ctx,
|
|
101
|
+
prunerContext: prunerCtx,
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
return { content: [{ type: 'text' as const, text: context }] };
|
|
105
|
+
},
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
// ── Tool: brainbank_index ───────────────────────────
|
|
111
|
+
|
|
112
|
+
server.registerTool(
|
|
113
|
+
'brainbank_index',
|
|
114
|
+
{
|
|
115
|
+
title: 'BrainBank Index',
|
|
116
|
+
description:
|
|
117
|
+
'Index (or re-index) a repository. Scans code files, git history, and documents, ' +
|
|
118
|
+
'then builds vector embeddings and FTS5 indices. Run this after significant code changes ' +
|
|
119
|
+
'or when search results feel stale. Returns a summary of what changed.',
|
|
120
|
+
inputSchema: z.object({
|
|
121
|
+
repo: z.string().describe('Repository path to index'),
|
|
122
|
+
forceReindex: z.boolean().optional().default(false).describe('Force re-index all files (ignore cache). Use when embeddings changed or index is corrupted'),
|
|
123
|
+
modules: z.array(z.string()).optional().describe('Which plugins to index (e.g. ["code", "git", "docs"]). Omit to use config defaults'),
|
|
124
|
+
}),
|
|
125
|
+
},
|
|
126
|
+
async ({ repo, forceReindex, modules }) => {
|
|
127
|
+
const brainbank = await getBrainBank(repo);
|
|
128
|
+
|
|
129
|
+
const result = await brainbank.index({
|
|
130
|
+
forceReindex,
|
|
131
|
+
modules: modules && modules.length > 0 ? modules : undefined,
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
// Format results summary
|
|
135
|
+
const lines: string[] = ['# Index Results\n'];
|
|
136
|
+
let hasChanges = false;
|
|
137
|
+
|
|
138
|
+
for (const [name, value] of Object.entries(result)) {
|
|
139
|
+
if (!value) continue;
|
|
140
|
+
const v = value as Record<string, unknown>;
|
|
141
|
+
if (typeof v.indexed !== 'number') {
|
|
142
|
+
lines.push(`✓ ${name}: done`);
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const indexed = v.indexed as number;
|
|
147
|
+
const skipped = (v.skipped ?? 0) as number;
|
|
148
|
+
const removed = (v.removed ?? 0) as number;
|
|
149
|
+
const chunks = (v.chunks ?? 0) as number;
|
|
150
|
+
|
|
151
|
+
if (indexed > 0 || removed > 0) hasChanges = true;
|
|
152
|
+
|
|
153
|
+
const parts: string[] = [];
|
|
154
|
+
if (indexed > 0) parts.push(`+${indexed} files (${chunks} chunks)`);
|
|
155
|
+
if (removed > 0) parts.push(`−${removed} files`);
|
|
156
|
+
if (skipped > 0) parts.push(`${skipped} unchanged`);
|
|
157
|
+
|
|
158
|
+
lines.push(`${name}: ${parts.join(' ')}`);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (!hasChanges) {
|
|
162
|
+
lines.push('No changes — everything up to date');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Stats
|
|
166
|
+
const stats = brainbank.stats();
|
|
167
|
+
lines.push('\n## Totals\n');
|
|
168
|
+
for (const [name, s] of Object.entries(stats)) {
|
|
169
|
+
if (!s || typeof s !== 'object') continue;
|
|
170
|
+
const entries = Object.entries(s as Record<string, unknown>)
|
|
171
|
+
.map(([k, v]) => `${k}: ${v}`)
|
|
172
|
+
.join(', ');
|
|
173
|
+
lines.push(`${name}: ${entries}`);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
return { content: [{ type: 'text' as const, text: lines.join('\n') }] };
|
|
177
|
+
},
|
|
178
|
+
);
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
// ── Start Server ────────────────────────────────────
|
|
182
|
+
|
|
183
|
+
async function main() {
|
|
184
|
+
const transport = new StdioServerTransport();
|
|
185
|
+
await server.connect(transport);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
main().catch(err => {
|
|
189
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
190
|
+
console.error(`BrainBank MCP Server Error: ${message}`);
|
|
191
|
+
process.exit(1);
|
|
192
|
+
});
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WorkspaceFactory — creates BrainBank instances via the core factory.
|
|
3
|
+
*
|
|
4
|
+
* Delegates to `createBrain()` from the core factory, passing
|
|
5
|
+
* a portable `BrainContext`. No plugin hardcoding — the factory handles
|
|
6
|
+
* plugin discovery from config and installed packages.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { BrainBank } from '@/brainbank.ts';
|
|
10
|
+
import type { BrainContext } from '@/cli/factory/brain-context.ts';
|
|
11
|
+
|
|
12
|
+
import { createBrain, resetFactoryCache } from '@/cli/factory/index.ts';
|
|
13
|
+
|
|
14
|
+
import * as fs from 'node:fs';
|
|
15
|
+
import * as path from 'node:path';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Detect repo root by walking up from startDir until we find `.git/`.
|
|
19
|
+
* Returns startDir itself if no `.git/` is found.
|
|
20
|
+
*/
|
|
21
|
+
export function findRepoRoot(startDir: string): string {
|
|
22
|
+
let dir = path.resolve(startDir);
|
|
23
|
+
while (true) {
|
|
24
|
+
if (fs.existsSync(path.join(dir, '.git'))) return dir;
|
|
25
|
+
const parent = path.dirname(dir);
|
|
26
|
+
if (parent === dir) break;
|
|
27
|
+
dir = parent;
|
|
28
|
+
}
|
|
29
|
+
return path.resolve(startDir);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Resolve the effective repo path from an optional target, env, or cwd. */
|
|
33
|
+
export function resolveRepoPath(targetRepo?: string): string {
|
|
34
|
+
const rp = targetRepo
|
|
35
|
+
?? process.env.BRAINBANK_REPO
|
|
36
|
+
?? findRepoRoot(process.cwd());
|
|
37
|
+
return rp.replace(/\/+$/, '');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Create a BrainBank instance for a workspace.
|
|
42
|
+
* Uses the core factory which handles:
|
|
43
|
+
* - Config loading from .brainbank/config.json
|
|
44
|
+
* - Dynamic plugin discovery and registration
|
|
45
|
+
* - Embedding/pruner/expander provider setup
|
|
46
|
+
* - Folder plugin auto-discovery
|
|
47
|
+
*/
|
|
48
|
+
export async function createWorkspaceBrain(repoPath: string): Promise<BrainBank> {
|
|
49
|
+
resetFactoryCache();
|
|
50
|
+
|
|
51
|
+
const context: BrainContext = {
|
|
52
|
+
repoPath,
|
|
53
|
+
env: process.env as Record<string, string | undefined>,
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
// Silence stdout during initialization — the core factory emits ANSI-colored
|
|
57
|
+
// console.log messages (plugin loading) that corrupt
|
|
58
|
+
// the MCP JSON-RPC stdio transport. Redirect console.log → stderr temporarily.
|
|
59
|
+
const origLog = console.log;
|
|
60
|
+
console.log = (...args: unknown[]) => console.error(...args);
|
|
61
|
+
try {
|
|
62
|
+
const brain = await createBrain(context);
|
|
63
|
+
await brain.initialize();
|
|
64
|
+
return brain;
|
|
65
|
+
} finally {
|
|
66
|
+
console.log = origLog;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WorkspacePool — BrainBank instance lifecycle manager.
|
|
3
|
+
*
|
|
4
|
+
* Manages cached BrainBank instances per workspace with:
|
|
5
|
+
* - Memory-pressure eviction (oldest idle first)
|
|
6
|
+
* - TTL eviction for inactive workspaces
|
|
7
|
+
* - Active-operation tracking (prevents mid-query eviction)
|
|
8
|
+
* - Hot-reload of stale HNSW indices
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { BrainBank } from '@/brainbank.ts';
|
|
12
|
+
|
|
13
|
+
/** Pool configuration. */
|
|
14
|
+
export interface PoolOptions {
|
|
15
|
+
/** Max total estimated memory in MB. Default: 2048. */
|
|
16
|
+
maxMemoryMB?: number;
|
|
17
|
+
/** Minutes of inactivity before eviction. Default: 30. */
|
|
18
|
+
ttlMinutes?: number;
|
|
19
|
+
/** Factory function to create a BrainBank for a repo path. */
|
|
20
|
+
factory: (repoPath: string) => Promise<BrainBank>;
|
|
21
|
+
/** Called when a workspace is evicted. */
|
|
22
|
+
onEvict?: (repoPath: string) => void;
|
|
23
|
+
/** Called when an error occurs during pool operations. */
|
|
24
|
+
onError?: (repoPath: string, err: unknown) => void;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Internal pool entry. */
|
|
28
|
+
interface PoolEntry {
|
|
29
|
+
brain: BrainBank;
|
|
30
|
+
repoPath: string;
|
|
31
|
+
lastAccess: number;
|
|
32
|
+
createdAt: number;
|
|
33
|
+
activeOps: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Public pool statistics. */
|
|
37
|
+
export interface PoolStats {
|
|
38
|
+
size: number;
|
|
39
|
+
totalMemoryMB: number;
|
|
40
|
+
entries: PoolEntryStats[];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Per-entry statistics. */
|
|
44
|
+
export interface PoolEntryStats {
|
|
45
|
+
repoPath: string;
|
|
46
|
+
lastAccessAgo: string;
|
|
47
|
+
memoryMB: number;
|
|
48
|
+
activeOps: number;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const DEFAULT_MAX_MEMORY_MB = 2048;
|
|
52
|
+
const DEFAULT_TTL_MINUTES = 30;
|
|
53
|
+
const EVICTION_INTERVAL_MS = 60_000;
|
|
54
|
+
|
|
55
|
+
/** Format milliseconds as a human-readable "ago" string. */
|
|
56
|
+
function formatAgo(ms: number): string {
|
|
57
|
+
if (ms < 60_000) return `${Math.round(ms / 1000)}s ago`;
|
|
58
|
+
if (ms < 3_600_000) return `${Math.round(ms / 60_000)}m ago`;
|
|
59
|
+
return `${Math.round(ms / 3_600_000)}h ago`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export class WorkspacePool {
|
|
63
|
+
private _pool = new Map<string, PoolEntry>();
|
|
64
|
+
private _timer: ReturnType<typeof setInterval> | null = null;
|
|
65
|
+
private _maxMemoryBytes: number;
|
|
66
|
+
private _ttlMs: number;
|
|
67
|
+
private _factory: (repoPath: string) => Promise<BrainBank>;
|
|
68
|
+
private _onEvict?: (repoPath: string) => void;
|
|
69
|
+
private _onError?: (repoPath: string, err: unknown) => void;
|
|
70
|
+
|
|
71
|
+
constructor(options: PoolOptions) {
|
|
72
|
+
this._maxMemoryBytes = (options.maxMemoryMB ?? DEFAULT_MAX_MEMORY_MB) * 1024 * 1024;
|
|
73
|
+
this._ttlMs = (options.ttlMinutes ?? DEFAULT_TTL_MINUTES) * 60 * 1000;
|
|
74
|
+
this._factory = options.factory;
|
|
75
|
+
this._onEvict = options.onEvict;
|
|
76
|
+
this._onError = options.onError;
|
|
77
|
+
|
|
78
|
+
this._timer = setInterval(() => this._evictStale(), EVICTION_INTERVAL_MS);
|
|
79
|
+
// Don't hold the process open for the timer
|
|
80
|
+
if (this._timer.unref) this._timer.unref();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Number of cached workspaces. */
|
|
84
|
+
get size(): number {
|
|
85
|
+
return this._pool.size;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Get a BrainBank for the given repo path.
|
|
90
|
+
* Returns a cached instance (with hot-reload) or creates a new one.
|
|
91
|
+
*/
|
|
92
|
+
async get(repoPath: string): Promise<BrainBank> {
|
|
93
|
+
const key = repoPath.replace(/\/+$/, '');
|
|
94
|
+
|
|
95
|
+
const existing = this._pool.get(key);
|
|
96
|
+
if (existing) {
|
|
97
|
+
existing.lastAccess = Date.now();
|
|
98
|
+
try { await existing.brain.ensureFresh(); } catch { /* stale is better than nothing */ }
|
|
99
|
+
return existing.brain;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
this._evictByMemoryPressure();
|
|
103
|
+
|
|
104
|
+
const brain = await this._factory(key);
|
|
105
|
+
this._pool.set(key, {
|
|
106
|
+
brain,
|
|
107
|
+
repoPath: key,
|
|
108
|
+
lastAccess: Date.now(),
|
|
109
|
+
createdAt: Date.now(),
|
|
110
|
+
activeOps: 0,
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
return brain;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Execute an operation with active-op tracking.
|
|
118
|
+
* Prevents the workspace from being evicted while the operation runs.
|
|
119
|
+
*/
|
|
120
|
+
async withBrain<T>(repoPath: string, fn: (brain: BrainBank) => Promise<T>): Promise<T> {
|
|
121
|
+
const brain = await this.get(repoPath);
|
|
122
|
+
const key = repoPath.replace(/\/+$/, '');
|
|
123
|
+
const entry = this._pool.get(key);
|
|
124
|
+
if (entry) entry.activeOps++;
|
|
125
|
+
|
|
126
|
+
try {
|
|
127
|
+
return await fn(brain);
|
|
128
|
+
} finally {
|
|
129
|
+
if (entry) {
|
|
130
|
+
entry.activeOps--;
|
|
131
|
+
entry.lastAccess = Date.now();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Manually evict a specific workspace. */
|
|
137
|
+
evict(repoPath: string): void {
|
|
138
|
+
const key = repoPath.replace(/\/+$/, '');
|
|
139
|
+
this._evictEntry(key);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Get pool statistics. */
|
|
143
|
+
stats(): PoolStats {
|
|
144
|
+
const now = Date.now();
|
|
145
|
+
let totalMemory = 0;
|
|
146
|
+
const entries: PoolEntryStats[] = [];
|
|
147
|
+
|
|
148
|
+
for (const entry of this._pool.values()) {
|
|
149
|
+
const memBytes = entry.brain.memoryHint();
|
|
150
|
+
const memMB = Math.round(memBytes / 1024 / 1024 * 100) / 100;
|
|
151
|
+
totalMemory += memBytes;
|
|
152
|
+
|
|
153
|
+
entries.push({
|
|
154
|
+
repoPath: entry.repoPath,
|
|
155
|
+
lastAccessAgo: formatAgo(now - entry.lastAccess),
|
|
156
|
+
memoryMB: memMB,
|
|
157
|
+
activeOps: entry.activeOps,
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return {
|
|
162
|
+
size: this._pool.size,
|
|
163
|
+
totalMemoryMB: Math.round(totalMemory / 1024 / 1024 * 100) / 100,
|
|
164
|
+
entries,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Close all entries and stop the eviction timer. */
|
|
169
|
+
close(): void {
|
|
170
|
+
if (this._timer) {
|
|
171
|
+
clearInterval(this._timer);
|
|
172
|
+
this._timer = null;
|
|
173
|
+
}
|
|
174
|
+
for (const key of [...this._pool.keys()]) {
|
|
175
|
+
this._evictEntry(key);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Evict workspaces that haven't been accessed within the TTL. */
|
|
180
|
+
private _evictStale(): void {
|
|
181
|
+
const cutoff = Date.now() - this._ttlMs;
|
|
182
|
+
for (const [key, entry] of this._pool) {
|
|
183
|
+
if (entry.lastAccess < cutoff && entry.activeOps === 0) {
|
|
184
|
+
this._evictEntry(key);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Evict oldest idle entries until total memory is under the limit. */
|
|
190
|
+
private _evictByMemoryPressure(): void {
|
|
191
|
+
let totalMemory = 0;
|
|
192
|
+
for (const entry of this._pool.values()) {
|
|
193
|
+
totalMemory += entry.brain.memoryHint();
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (totalMemory < this._maxMemoryBytes) return;
|
|
197
|
+
|
|
198
|
+
// Sort by lastAccess ascending (oldest first), filter idle
|
|
199
|
+
const candidates = [...this._pool.entries()]
|
|
200
|
+
.filter(([, e]) => e.activeOps === 0)
|
|
201
|
+
.sort(([, a], [, b]) => a.lastAccess - b.lastAccess);
|
|
202
|
+
|
|
203
|
+
for (const [key, entry] of candidates) {
|
|
204
|
+
if (totalMemory < this._maxMemoryBytes) break;
|
|
205
|
+
totalMemory -= entry.brain.memoryHint();
|
|
206
|
+
this._evictEntry(key);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Evict a single entry by key. */
|
|
211
|
+
private _evictEntry(key: string): void {
|
|
212
|
+
const entry = this._pool.get(key);
|
|
213
|
+
if (!entry) return;
|
|
214
|
+
|
|
215
|
+
try {
|
|
216
|
+
entry.brain.close();
|
|
217
|
+
} catch (err: unknown) {
|
|
218
|
+
this._onError?.(key, err);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
this._pool.delete(key);
|
|
222
|
+
this._onEvict?.(key);
|
|
223
|
+
}
|
|
224
|
+
}
|