brainbank 0.1.0-beta.1

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 (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +155 -0
  3. package/assets/architecture.png +0 -0
  4. package/bin/brainbank +18 -0
  5. package/bin/brainbank-mcp +19 -0
  6. package/dist/chunk-3YBCD6DI.js +117 -0
  7. package/dist/chunk-3YBCD6DI.js.map +1 -0
  8. package/dist/chunk-63GBCDS5.js +3249 -0
  9. package/dist/chunk-63GBCDS5.js.map +1 -0
  10. package/dist/chunk-DMFMTOHF.js +123 -0
  11. package/dist/chunk-DMFMTOHF.js.map +1 -0
  12. package/dist/chunk-FQYKWB2Q.js +136 -0
  13. package/dist/chunk-FQYKWB2Q.js.map +1 -0
  14. package/dist/chunk-IMJJ2VEM.js +74 -0
  15. package/dist/chunk-IMJJ2VEM.js.map +1 -0
  16. package/dist/chunk-M744PCJQ.js +43 -0
  17. package/dist/chunk-M744PCJQ.js.map +1 -0
  18. package/dist/chunk-O3J6ZIXK.js +82 -0
  19. package/dist/chunk-O3J6ZIXK.js.map +1 -0
  20. package/dist/chunk-OPH7GZ7U.js +124 -0
  21. package/dist/chunk-OPH7GZ7U.js.map +1 -0
  22. package/dist/chunk-PXEWQMN7.js +89 -0
  23. package/dist/chunk-PXEWQMN7.js.map +1 -0
  24. package/dist/chunk-RDQYDLYZ.js +69 -0
  25. package/dist/chunk-RDQYDLYZ.js.map +1 -0
  26. package/dist/chunk-VIIHPCC4.js +254 -0
  27. package/dist/chunk-VIIHPCC4.js.map +1 -0
  28. package/dist/chunk-WCQVDF3K.js +14 -0
  29. package/dist/chunk-WCQVDF3K.js.map +1 -0
  30. package/dist/cli.d.ts +1 -0
  31. package/dist/cli.js +3076 -0
  32. package/dist/cli.js.map +1 -0
  33. package/dist/haiku-expander-YRSIPGKP.js +8 -0
  34. package/dist/haiku-expander-YRSIPGKP.js.map +1 -0
  35. package/dist/haiku-pruner-SHAXUPY6.js +8 -0
  36. package/dist/haiku-pruner-SHAXUPY6.js.map +1 -0
  37. package/dist/http-server-QUXHLWUM.js +9 -0
  38. package/dist/http-server-QUXHLWUM.js.map +1 -0
  39. package/dist/index.d.ts +2161 -0
  40. package/dist/index.js +357 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/local-embedding-NZQTILGV.js +8 -0
  43. package/dist/local-embedding-NZQTILGV.js.map +1 -0
  44. package/dist/mcp.d.ts +2 -0
  45. package/dist/mcp.js +334 -0
  46. package/dist/mcp.js.map +1 -0
  47. package/dist/openai-embedding-ZP5TSUJG.js +8 -0
  48. package/dist/openai-embedding-ZP5TSUJG.js.map +1 -0
  49. package/dist/perplexity-context-embedding-GI5PHE6X.js +9 -0
  50. package/dist/perplexity-context-embedding-GI5PHE6X.js.map +1 -0
  51. package/dist/perplexity-embedding-KZRYGJRC.js +10 -0
  52. package/dist/perplexity-embedding-KZRYGJRC.js.map +1 -0
  53. package/dist/plugin-IKQ6IRSJ.js +32 -0
  54. package/dist/plugin-IKQ6IRSJ.js.map +1 -0
  55. package/dist/resolve-ASGLBNUC.js +10 -0
  56. package/dist/resolve-ASGLBNUC.js.map +1 -0
  57. package/dist/stats-tui-ZY2NQSEA.js +1904 -0
  58. package/dist/stats-tui-ZY2NQSEA.js.map +1 -0
  59. package/package.json +96 -0
  60. package/src/brainbank.ts +617 -0
  61. package/src/cli/commands/collection.ts +77 -0
  62. package/src/cli/commands/context.ts +179 -0
  63. package/src/cli/commands/daemon.ts +100 -0
  64. package/src/cli/commands/docs.ts +71 -0
  65. package/src/cli/commands/files.ts +69 -0
  66. package/src/cli/commands/help.ts +77 -0
  67. package/src/cli/commands/index.ts +482 -0
  68. package/src/cli/commands/kv.ts +140 -0
  69. package/src/cli/commands/mcp-export.ts +273 -0
  70. package/src/cli/commands/mcp.ts +6 -0
  71. package/src/cli/commands/reembed.ts +30 -0
  72. package/src/cli/commands/scan.ts +336 -0
  73. package/src/cli/commands/search.ts +203 -0
  74. package/src/cli/commands/stats.ts +68 -0
  75. package/src/cli/commands/status.ts +47 -0
  76. package/src/cli/commands/watch.ts +47 -0
  77. package/src/cli/factory/brain-context.ts +43 -0
  78. package/src/cli/factory/builtin-registration.ts +87 -0
  79. package/src/cli/factory/config-loader.ts +77 -0
  80. package/src/cli/factory/index.ts +69 -0
  81. package/src/cli/factory/plugin-loader.ts +325 -0
  82. package/src/cli/index.ts +71 -0
  83. package/src/cli/server-client.ts +178 -0
  84. package/src/cli/tui/index-tui.tsx +667 -0
  85. package/src/cli/tui/stats-data.ts +523 -0
  86. package/src/cli/tui/stats-search.ts +262 -0
  87. package/src/cli/tui/stats-tui.tsx +1465 -0
  88. package/src/cli/tui/tree-scanner.ts +650 -0
  89. package/src/cli/utils.ts +137 -0
  90. package/src/config.ts +49 -0
  91. package/src/constants.ts +21 -0
  92. package/src/db/adapter.ts +112 -0
  93. package/src/db/metadata.ts +130 -0
  94. package/src/db/migrations.ts +66 -0
  95. package/src/db/sqlite-adapter.ts +218 -0
  96. package/src/db/tracker.ts +91 -0
  97. package/src/engine/index-api.ts +81 -0
  98. package/src/engine/reembed.ts +206 -0
  99. package/src/engine/search-api.ts +218 -0
  100. package/src/index.ts +154 -0
  101. package/src/lib/fts.ts +57 -0
  102. package/src/lib/languages.ts +180 -0
  103. package/src/lib/logger.ts +126 -0
  104. package/src/lib/math.ts +87 -0
  105. package/src/lib/provider-key.ts +20 -0
  106. package/src/lib/prune.ts +71 -0
  107. package/src/lib/rrf.ts +133 -0
  108. package/src/lib/write-lock.ts +108 -0
  109. package/src/mcp/mcp-server.ts +195 -0
  110. package/src/mcp/workspace-factory.ts +68 -0
  111. package/src/mcp/workspace-pool.ts +224 -0
  112. package/src/plugin.ts +381 -0
  113. package/src/providers/embeddings/embedding-worker-thread.ts +95 -0
  114. package/src/providers/embeddings/embedding-worker.ts +141 -0
  115. package/src/providers/embeddings/local-embedding.ts +115 -0
  116. package/src/providers/embeddings/openai-embedding.ts +167 -0
  117. package/src/providers/embeddings/perplexity-context-embedding.ts +195 -0
  118. package/src/providers/embeddings/perplexity-embedding.ts +165 -0
  119. package/src/providers/embeddings/resolve.ts +34 -0
  120. package/src/providers/pruners/haiku-expander.ts +166 -0
  121. package/src/providers/pruners/haiku-pruner.ts +112 -0
  122. package/src/providers/vector/hnsw-index.ts +174 -0
  123. package/src/providers/vector/hnsw-loader.ts +129 -0
  124. package/src/search/bm25-boost.ts +69 -0
  125. package/src/search/context-builder.ts +251 -0
  126. package/src/search/keyword/composite-bm25-search.ts +47 -0
  127. package/src/search/types.ts +37 -0
  128. package/src/search/vector/composite-vector-search.ts +61 -0
  129. package/src/search/vector/mmr.ts +64 -0
  130. package/src/services/collection.ts +384 -0
  131. package/src/services/daemon.ts +87 -0
  132. package/src/services/http-server.ts +336 -0
  133. package/src/services/kv-service.ts +64 -0
  134. package/src/services/plugin-registry.ts +77 -0
  135. package/src/services/watch.ts +340 -0
  136. package/src/services/webhook-server.ts +100 -0
  137. package/src/types.ts +493 -0
@@ -0,0 +1,195 @@
1
+ /**
2
+ * BrainBank — MCP Server
3
+ *
4
+ * Exposes BrainBank as an MCP server via stdio transport.
5
+ * Works with Google Antigravity, Claude Desktop, and any MCP-compatible client.
6
+ *
7
+ * Usage in mcp_config.json:
8
+ * {
9
+ * "mcpServers": {
10
+ * "brainbank": {
11
+ * "command": "brainbank-mcp"
12
+ * }
13
+ * }
14
+ * }
15
+ *
16
+ * Tools:
17
+ * brainbank_context — Workflow Trace: search + call tree + called-by annotations
18
+ * brainbank_search — Hybrid search (vector + BM25 → RRF), returns structured results
19
+ *
20
+ * Indexing is handled by the CLI (`brainbank index`) — not exposed as an MCP tool.
21
+ */
22
+
23
+ import type { SearchResult } from '@/types.ts';
24
+ import type { SearchOptions } from '@/search/types.ts';
25
+
26
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
27
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
28
+ import { z } from 'zod/v3';
29
+
30
+ import { WorkspacePool } from './workspace-pool.ts';
31
+ import { createWorkspaceBrain, resolveRepoPath } from './workspace-factory.ts';
32
+
33
+
34
+
35
+ // ── Multi-Workspace BrainBank Pool ─────────────────────
36
+
37
+ const pool = new WorkspacePool({
38
+ factory: createWorkspaceBrain,
39
+ maxMemoryMB: parseInt(process.env.BRAINBANK_MAX_MEMORY_MB ?? '2048', 10),
40
+ ttlMinutes: parseInt(process.env.BRAINBANK_TTL_MINUTES ?? '30', 10),
41
+ onError: (repo, err) => {
42
+ const msg = err instanceof Error ? err.message : String(err);
43
+ console.error(`BrainBank pool error [${repo}]: ${msg}`);
44
+ },
45
+ });
46
+
47
+ /** Resolve repo and get a BrainBank from the pool. */
48
+ async function getBrainBank(targetRepo?: string) {
49
+ return pool.get(resolveRepoPath(targetRepo));
50
+ }
51
+
52
+ // ── MCP Server Setup ────────────────────────────────
53
+
54
+ const server = new McpServer({
55
+ name: 'brainbank',
56
+ version: '0.9.7',
57
+ });
58
+
59
+ // ── Tool: brainbank_context ─────────────────────────
60
+
61
+ server.registerTool(
62
+ 'brainbank_context',
63
+ {
64
+ title: 'BrainBank Context',
65
+ description:
66
+ 'Get a formatted knowledge context block for a task. Returns a Workflow Trace: ' +
67
+ 'search hits + full call tree with `called by` annotations, topologically ordered. ' +
68
+ 'All source code included — no trimming, no truncation.',
69
+ inputSchema: z.object({
70
+ task: z.string().describe('Description of the task you need context for'),
71
+ affectedFiles: z.array(z.string()).optional().default([]).describe('Files you plan to modify (improves co-edit suggestions)'),
72
+ codeResults: z.number().optional().default(20).describe('Max code results'),
73
+ gitResults: z.number().optional().default(5).describe('Max git commit results'),
74
+ docsResults: z.number().optional().describe('Max document results (omit to skip docs)'),
75
+ sources: z.record(z.number()).optional().describe('Per-source result limits, overrides codeResults/gitResults/docsResults (e.g. { code: 10, git: 0, docs: 5 })'),
76
+ 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/"])'),
77
+ ignore: z.array(z.string()).optional().describe('Exclude results whose filePath starts with any of these prefixes (e.g. ["src/tests/", "src/mocks/"])'),
78
+ repo: z.string().describe('Repository path (default: BRAINBANK_REPO)'),
79
+ // BrainBankQL context fields
80
+ lines: z.boolean().optional().describe('Prefix each code line with its source line number (e.g. 127| code)'),
81
+ symbols: z.boolean().optional().describe('Append symbol index (all functions, classes, interfaces) for matched files'),
82
+ compact: z.boolean().optional().describe('Show only function/class signatures, skip bodies'),
83
+ callTree: z.union([z.boolean(), z.object({ depth: z.number() })]).optional().describe('Include call tree expansion. Pass { depth: N } to control depth'),
84
+ imports: z.boolean().optional().describe('Include dependency/import summary section'),
85
+ expander: z.boolean().optional().describe('Enable LLM-powered context expansion to discover related chunks not found by search'),
86
+ }),
87
+ },
88
+ async ({ task, affectedFiles, codeResults, gitResults, docsResults, sources, path, ignore, repo, lines, symbols, compact, callTree, imports, expander }) => {
89
+ const repoPath = resolveRepoPath(repo);
90
+ const brainbank = await getBrainBank(repo);
91
+
92
+ // Build sources from explicit params, then let `sources` override
93
+ const base: Record<string, number> = { code: codeResults, git: gitResults };
94
+ if (docsResults !== undefined) base.docs = docsResults;
95
+ const resolvedSources = sources ? { ...base, ...sources } : base;
96
+
97
+ // Build fields from explicit params (only include defined values)
98
+ const fields: Record<string, unknown> = {};
99
+ if (lines !== undefined) fields.lines = lines;
100
+ if (symbols !== undefined) fields.symbols = symbols;
101
+ if (compact !== undefined) fields.compact = compact;
102
+ if (callTree !== undefined) fields.callTree = callTree;
103
+ if (imports !== undefined) fields.imports = imports;
104
+ if (expander !== undefined) fields.expander = expander;
105
+
106
+ const context = await brainbank.getContext(task, {
107
+ affectedFiles,
108
+ sources: resolvedSources,
109
+ pathPrefix: path,
110
+ ignorePaths: ignore,
111
+ source: 'mcp',
112
+ fields: Object.keys(fields).length > 0 ? fields : undefined,
113
+ });
114
+
115
+ return { content: [{ type: 'text' as const, text: context }] };
116
+ },
117
+ );
118
+
119
+ // ── Tool: brainbank_search ──────────────────────────
120
+
121
+ /** Format SearchResult[] into readable text blocks for the agent. */
122
+ function formatSearchResults(results: SearchResult[]): string {
123
+ if (results.length === 0) return 'No results found.';
124
+
125
+ const lines: string[] = [];
126
+ for (const r of results) {
127
+ const score = Math.round(r.score * 100);
128
+ if (r.type === 'code') {
129
+ const m = r.metadata;
130
+ lines.push(`[CODE ${score}%] ${r.filePath} — ${m.name || m.chunkType} L${m.startLine}-${m.endLine}`);
131
+ lines.push(r.content);
132
+ lines.push('');
133
+ } else if (r.type === 'commit') {
134
+ const m = r.metadata;
135
+ lines.push(`[COMMIT ${score}%] ${m.shortHash} ${r.content} (${m.author})`);
136
+ if (m.files?.length) lines.push(` Files: ${m.files.slice(0, 6).join(', ')}`);
137
+ lines.push('');
138
+ } else if (r.type === 'document') {
139
+ const ctx = r.context ? ` — ${r.context}` : '';
140
+ lines.push(`[DOC ${score}%] ${r.filePath} [${r.metadata.collection}]${ctx}`);
141
+ lines.push(r.content);
142
+ lines.push('');
143
+ } else if (r.type === 'collection') {
144
+ lines.push(`[COLLECTION ${score}%] ${r.metadata.collection ?? 'kv'}`);
145
+ lines.push(r.content);
146
+ lines.push('');
147
+ }
148
+ }
149
+ return lines.join('\n');
150
+ }
151
+
152
+ server.registerTool(
153
+ 'brainbank_search',
154
+ {
155
+ title: 'BrainBank Search',
156
+ description:
157
+ 'Hybrid search across the codebase: combines vector similarity + BM25 keyword matching ' +
158
+ 'via Reciprocal Rank Fusion. Returns code chunks, git commits, and documents ranked by relevance. ' +
159
+ 'Use for finding code, understanding systems, and locating files by meaning.',
160
+ inputSchema: z.object({
161
+ query: z.string().describe('Natural language search query (e.g. "authentication middleware", "WebSocket reconnection")'),
162
+ repo: z.string().describe('Repository path (default: BRAINBANK_REPO)'),
163
+ sources: z.record(z.number()).optional().describe('Per-source result limits (e.g. { code: 10, git: 0, docs: 5 }). Set source to 0 to skip it'),
164
+ path: z.union([z.string(), z.array(z.string())]).optional().describe('Filter results to files under these path prefixes (e.g. "src/services" or ["src/", "lib/"])'),
165
+ maxResults: z.number().optional().default(20).describe('Maximum total results to return'),
166
+ }),
167
+ },
168
+ async ({ query, repo, sources, path, maxResults }) => {
169
+ const brainbank = await getBrainBank(repo);
170
+
171
+ const opts: Record<string, unknown> = { source: 'mcp' as const };
172
+ if (sources) opts.sources = sources;
173
+ if (path) opts.pathPrefix = path;
174
+
175
+ const results = await brainbank.hybridSearch(query, opts as SearchOptions);
176
+ const limited = results.slice(0, maxResults);
177
+ const text = formatSearchResults(limited);
178
+
179
+ return { content: [{ type: 'text' as const, text }] };
180
+ },
181
+ );
182
+
183
+
184
+ // ── Start Server ────────────────────────────────────
185
+
186
+ async function main() {
187
+ const transport = new StdioServerTransport();
188
+ await server.connect(transport);
189
+ }
190
+
191
+ main().catch(err => {
192
+ const message = err instanceof Error ? err.message : String(err);
193
+ console.error(`BrainBank MCP Server Error: ${message}`);
194
+ process.exit(1);
195
+ });
@@ -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
+ }