@floydous/pi-agent-kernel 0.1.0

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 (57) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +108 -0
  3. package/config.toml +24 -0
  4. package/docs/README.md +22 -0
  5. package/docs/architecture.md +40 -0
  6. package/docs/configuration.md +43 -0
  7. package/docs/editing-and-verification.md +41 -0
  8. package/docs/lsp.md +31 -0
  9. package/docs/retrieval.md +42 -0
  10. package/docs/testing.md +32 -0
  11. package/package.json +48 -0
  12. package/src/config/index.ts +2 -0
  13. package/src/config/kernel_config.ts +218 -0
  14. package/src/config/toml.ts +237 -0
  15. package/src/context/session_repair.ts +99 -0
  16. package/src/dedup/content_store.ts +365 -0
  17. package/src/dedup/recall_tool.ts +157 -0
  18. package/src/editing/patch.ts +482 -0
  19. package/src/editing/post_edit_verification.ts +200 -0
  20. package/src/editing/syntax-verify.ts +353 -0
  21. package/src/index.ts +852 -0
  22. package/src/lsp/adapters/base.ts +42 -0
  23. package/src/lsp/adapters/index.ts +21 -0
  24. package/src/lsp/adapters/python.ts +37 -0
  25. package/src/lsp/adapters/rust.ts +35 -0
  26. package/src/lsp/adapters/typescript.ts +40 -0
  27. package/src/lsp/index.ts +13 -0
  28. package/src/lsp/lsp_client.ts +650 -0
  29. package/src/lsp/lsp_detector.ts +52 -0
  30. package/src/lsp/lsp_formatter.ts +284 -0
  31. package/src/lsp/lsp_installer.ts +604 -0
  32. package/src/lsp/lsp_manager.ts +202 -0
  33. package/src/lsp/lsp_modal.ts +675 -0
  34. package/src/lsp/lsp_registry.ts +539 -0
  35. package/src/lsp/lsp_types.ts +143 -0
  36. package/src/retrieval/ast_search.ts +926 -0
  37. package/src/retrieval/repomap.ts +779 -0
  38. package/src/retrieval/search_bm25.ts +190 -0
  39. package/src/retrieval/search_chunker.ts +251 -0
  40. package/src/retrieval/search_config.ts +162 -0
  41. package/src/retrieval/search_embedder.ts +362 -0
  42. package/src/retrieval/search_index.ts +753 -0
  43. package/src/retrieval/search_modal.ts +358 -0
  44. package/src/retrieval/symbol_reader.ts +200 -0
  45. package/src/safety/atomic_write.ts +26 -0
  46. package/src/safety/epistemic_guard.ts +733 -0
  47. package/src/safety/kernel_debug.ts +15 -0
  48. package/src/safety/output_clamper.ts +213 -0
  49. package/src/tools/ast_search_tool.ts +131 -0
  50. package/src/tools/code_search_tool.ts +147 -0
  51. package/src/tools/context.ts +20 -0
  52. package/src/tools/edit_tool.ts +288 -0
  53. package/src/tools/lsp_tool.ts +813 -0
  54. package/src/tools/read_tool.ts +348 -0
  55. package/src/tools/repo_map_tool.ts +57 -0
  56. package/src/ui/footer.ts +287 -0
  57. package/src/ui/tui_utils.ts +278 -0
@@ -0,0 +1,190 @@
1
+ import { CodeChunk } from "./search_chunker";
2
+
3
+ export interface BM25SearchResult {
4
+ chunkId: string;
5
+ score: number;
6
+ matches: string[];
7
+ }
8
+
9
+ /**
10
+ * Specialized code tokenizer handling CamelCase, snake_case, identifiers and symbols.
11
+ */
12
+ export function tokenizeCode(text: string): string[] {
13
+ if (!text) return [];
14
+
15
+ const rawTokens = text.match(/[a-zA-Z0-9_]+/g) || [];
16
+ const tokens: string[] = [];
17
+
18
+ for (const raw of rawTokens) {
19
+ const lower = raw.toLowerCase();
20
+ if (lower.length >= 2) {
21
+ tokens.push(lower);
22
+ }
23
+
24
+ // Split snake_case
25
+ if (raw.includes("_")) {
26
+ const parts = raw.split("_");
27
+ for (const p of parts) {
28
+ const pl = p.toLowerCase();
29
+ if (pl.length >= 2) tokens.push(pl);
30
+ }
31
+ }
32
+
33
+ // Split camelCase and PascalCase (e.g. "verifySignature" -> "verify", "signature")
34
+ const camelParts = raw.replace(/([a-z])([A-Z])/g, "$1 $2").split(" ");
35
+ if (camelParts.length > 1) {
36
+ for (const cp of camelParts) {
37
+ const cpl = cp.toLowerCase();
38
+ if (cpl.length >= 2) tokens.push(cpl);
39
+ }
40
+ }
41
+ }
42
+
43
+ return tokens;
44
+ }
45
+
46
+ export class BM25Engine {
47
+ private k1 = 1.2;
48
+ private b = 0.75;
49
+
50
+ // chunkId -> term frequency map: term -> count
51
+ private docTermFreqs: Map<string, Map<string, number>> = new Map();
52
+ // chunkId -> total token count in document
53
+ private docLengths: Map<string, number> = new Map();
54
+ // term -> document frequency (number of docs containing term)
55
+ private termDocFreqs: Map<string, number> = new Map();
56
+ // term -> Set of chunkIds (Inverted index for O(Σ matches) query scanning)
57
+ private postings: Map<string, Set<string>> = new Map();
58
+
59
+ private totalDocs = 0;
60
+ private avgDocLength = 0;
61
+
62
+ public clear(): void {
63
+ this.docTermFreqs.clear();
64
+ this.docLengths.clear();
65
+ this.termDocFreqs.clear();
66
+ this.postings.clear();
67
+ this.totalDocs = 0;
68
+ this.avgDocLength = 0;
69
+ }
70
+
71
+ /**
72
+ * Index a list of CodeChunks into the BM25 inverted index.
73
+ */
74
+ public indexChunks(chunks: CodeChunk[]): void {
75
+ for (const chunk of chunks) {
76
+ this.addChunk(chunk);
77
+ }
78
+ this.recalculateStats();
79
+ }
80
+
81
+ public addChunk(chunk: CodeChunk): void {
82
+ // Combine breadcrumb, signature and content with extra weight for signature/name
83
+ const weightedText = `${chunk.symbolName} ${chunk.symbolName} ${chunk.signature} ${chunk.breadcrumb}\n${chunk.content}`;
84
+ const tokens = tokenizeCode(weightedText);
85
+
86
+ const tfMap = new Map<string, number>();
87
+ for (const t of tokens) {
88
+ tfMap.set(t, (tfMap.get(t) || 0) + 1);
89
+ }
90
+
91
+ this.docTermFreqs.set(chunk.id, tfMap);
92
+ this.docLengths.set(chunk.id, tokens.length);
93
+
94
+ for (const term of tfMap.keys()) {
95
+ this.termDocFreqs.set(term, (this.termDocFreqs.get(term) || 0) + 1);
96
+ let chunkSet = this.postings.get(term);
97
+ if (!chunkSet) {
98
+ chunkSet = new Set();
99
+ this.postings.set(term, chunkSet);
100
+ }
101
+ chunkSet.add(chunk.id);
102
+ }
103
+
104
+ this.totalDocs++;
105
+ }
106
+
107
+ /**
108
+ * Remove all chunks associated with a specific relative file path.
109
+ */
110
+ public removeFile(filePath: string): void {
111
+ const prefix = `${filePath}:`;
112
+ for (const chunkId of Array.from(this.docTermFreqs.keys())) {
113
+ if (chunkId.startsWith(prefix) || chunkId.includes(filePath)) {
114
+ const tfMap = this.docTermFreqs.get(chunkId);
115
+ if (tfMap) {
116
+ for (const term of tfMap.keys()) {
117
+ const count = (this.termDocFreqs.get(term) || 1) - 1;
118
+ if (count <= 0) {
119
+ this.termDocFreqs.delete(term);
120
+ } else {
121
+ this.termDocFreqs.set(term, count);
122
+ }
123
+ const chunkSet = this.postings.get(term);
124
+ if (chunkSet) {
125
+ chunkSet.delete(chunkId);
126
+ if (chunkSet.size === 0) {
127
+ this.postings.delete(term);
128
+ }
129
+ }
130
+ }
131
+ }
132
+ this.docTermFreqs.delete(chunkId);
133
+ this.docLengths.delete(chunkId);
134
+ this.totalDocs--;
135
+ }
136
+ }
137
+ this.recalculateStats();
138
+ }
139
+
140
+ public recalculateStats(): void {
141
+ let totalLength = 0;
142
+ for (const len of this.docLengths.values()) {
143
+ totalLength += len;
144
+ }
145
+ this.totalDocs = this.docLengths.size;
146
+ this.avgDocLength = this.totalDocs > 0 ? totalLength / this.totalDocs : 0;
147
+ }
148
+
149
+ /**
150
+ * Search the BM25 index with a query string.
151
+ */
152
+ public search(query: string, limit = 50): BM25SearchResult[] {
153
+ if (this.totalDocs === 0) return [];
154
+ const queryTokens = Array.from(new Set(tokenizeCode(query)));
155
+ if (queryTokens.length === 0) return [];
156
+
157
+ const scores: Map<string, { score: number; matches: string[] }> = new Map();
158
+
159
+ for (const term of queryTokens) {
160
+ const n = this.termDocFreqs.get(term) || 0;
161
+ if (n === 0) continue;
162
+
163
+ // Okapi BM25 Inverse Document Frequency
164
+ const idf = Math.log(1 + (this.totalDocs - n + 0.5) / (n + 0.5));
165
+ const matchingChunkIds = this.postings.get(term);
166
+ if (!matchingChunkIds) continue;
167
+
168
+ for (const chunkId of matchingChunkIds) {
169
+ const tfMap = this.docTermFreqs.get(chunkId);
170
+ if (!tfMap) continue;
171
+ const tf = tfMap.get(term) || 0;
172
+ if (tf === 0) continue;
173
+
174
+ const docLen = this.docLengths.get(chunkId) || this.avgDocLength;
175
+ const tfNorm = (tf * (this.k1 + 1)) / (tf + this.k1 * (1 - this.b + this.b * (docLen / (this.avgDocLength || 1))));
176
+ const termScore = idf * tfNorm;
177
+
178
+ const current = scores.get(chunkId) || { score: 0, matches: [] };
179
+ current.score += termScore;
180
+ current.matches.push(term);
181
+ scores.set(chunkId, current);
182
+ }
183
+ }
184
+
185
+ return Array.from(scores.entries())
186
+ .map(([chunkId, data]) => ({ chunkId, score: data.score, matches: data.matches }))
187
+ .sort((a, b) => b.score - a.score)
188
+ .slice(0, limit);
189
+ }
190
+ }
@@ -0,0 +1,251 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import * as crypto from "node:crypto";
4
+ import { extractFileTags, SymbolDef } from "./repomap";
5
+
6
+ export interface CodeChunk {
7
+ id: string; // e.g. "src/auth.ts:45-90#verifyToken"
8
+ filePath: string; // Relative path
9
+ absolutePath: string;
10
+ startLine: number;
11
+ endLine: number;
12
+ symbolName: string;
13
+ kind: string; // "function" | "class" | "method" | "interface" | "type" | "block"
14
+ signature: string;
15
+ breadcrumb: string; // e.g. "// [File: src/auth.ts] > [Class: AuthManager] > [Function: verifyToken]"
16
+ content: string; // The full code block text
17
+ textForEmbedding: string;// Search-optimized representation
18
+ hash: string; // SHA-256 hash of content
19
+ }
20
+
21
+ const SUPPORTED_EXTENSIONS = new Set([
22
+ ".ts", ".tsx", ".js", ".jsx", ".py", ".rs", ".go", ".c", ".cpp", ".h", ".hpp", ".java", ".cs", ".rb", ".php", ".swift", ".sh", ".bash", ".sql", ".md"
23
+ ]);
24
+
25
+ const IGNORED_DIRS = new Set([
26
+ ".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build", "coverage", ".pi", ".hermes", ".next", ".turbo", ".cache", "target", "vendor"
27
+ ]);
28
+
29
+ /**
30
+ * Compute SHA-256 hash of a string.
31
+ */
32
+ export function computeHash(content: string): string {
33
+ return crypto.createHash("sha256").update(content, "utf8").digest("hex").slice(0, 16);
34
+ }
35
+
36
+ /**
37
+ * Chunk a single source file into logical AST-bounded chunks.
38
+ */
39
+ export function chunkFile(rootDir: string, filePath: string, content?: string): CodeChunk[] {
40
+ const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(rootDir, filePath);
41
+ const relPath = path.relative(rootDir, absPath).replace(/\\/g, "/");
42
+
43
+ let fileContent = content;
44
+ if (fileContent === undefined) {
45
+ try {
46
+ fileContent = fs.readFileSync(absPath, "utf-8");
47
+ } catch {
48
+ return [];
49
+ }
50
+ }
51
+
52
+ const lines = fileContent.split("\n");
53
+ if (lines.length === 0) return [];
54
+
55
+ const ext = path.extname(absPath).toLowerCase();
56
+ const chunks: CodeChunk[] = [];
57
+
58
+ // 1. Extract AST symbols using extractFileTags
59
+ const tags = extractFileTags(absPath, fileContent);
60
+ const defs = tags.definitions.sort((a, b) => a.line - b.line);
61
+
62
+ // If file has no AST definitions or is small (< 40 lines), chunk as single whole file
63
+ if (defs.length === 0 || lines.length <= 40) {
64
+ const wholeContent = lines.join("\n");
65
+ const breadcrumb = `// [File: ${relPath}]`;
66
+ const hash = computeHash(wholeContent);
67
+ chunks.push({
68
+ id: `${relPath}:1-${lines.length}`,
69
+ filePath: relPath,
70
+ absolutePath: absPath,
71
+ startLine: 1,
72
+ endLine: lines.length,
73
+ symbolName: path.basename(relPath),
74
+ kind: "file",
75
+ signature: `File: ${relPath}`,
76
+ breadcrumb,
77
+ content: wholeContent,
78
+ textForEmbedding: `${breadcrumb}\n${wholeContent.slice(0, 1500)}`,
79
+ hash,
80
+ });
81
+ return chunks;
82
+ }
83
+
84
+ // 2. Map symbol spans using delimiter & indentation boundaries
85
+ interface SymbolSpan {
86
+ def: SymbolDef;
87
+ startLine: number;
88
+ endLine: number;
89
+ parentClass?: string;
90
+ }
91
+
92
+ const spans: SymbolSpan[] = [];
93
+ let currentClass: string | undefined = undefined;
94
+ let currentClassEndLine = -1;
95
+
96
+ for (let i = 0; i < defs.length; i++) {
97
+ const def = defs[i];
98
+ const startIdx = Math.max(0, def.line - 1);
99
+ let endIdx = lines.length - 1;
100
+
101
+ if (def.line > currentClassEndLine) {
102
+ currentClass = undefined;
103
+ }
104
+
105
+ if (def.kind === "class") {
106
+ currentClass = def.name;
107
+ }
108
+
109
+ if (ext === ".py") {
110
+ // Python scope
111
+ const defLine = lines[startIdx];
112
+ const matchIndent = defLine.match(/^(\s*)/);
113
+ const baseIndent = matchIndent ? matchIndent[1].length : 0;
114
+
115
+ for (let j = startIdx + 1; j < lines.length; j++) {
116
+ const line = lines[j];
117
+ if (!line.trim() || line.trim().startsWith("#")) continue;
118
+ const indent = line.match(/^(\s*)/)?.[1].length || 0;
119
+ if (indent <= baseIndent) {
120
+ endIdx = j - 1;
121
+ break;
122
+ }
123
+ endIdx = j;
124
+ }
125
+ } else {
126
+ // Brace based scope
127
+ let braceCount = 0;
128
+ let foundOpenBrace = false;
129
+
130
+ for (let j = startIdx; j < lines.length; j++) {
131
+ const line = lines[j];
132
+ for (const ch of line) {
133
+ if (ch === "{") {
134
+ braceCount++;
135
+ foundOpenBrace = true;
136
+ } else if (ch === "}") {
137
+ braceCount--;
138
+ }
139
+ }
140
+ if (foundOpenBrace && braceCount <= 0) {
141
+ endIdx = j;
142
+ break;
143
+ }
144
+ }
145
+ }
146
+
147
+ // Bound endLine to before next top-level def if necessary
148
+ if (i + 1 < defs.length && endIdx >= defs[i + 1].line - 1 && def.kind !== "class") {
149
+ endIdx = Math.min(endIdx, defs[i + 1].line - 2);
150
+ }
151
+
152
+ endIdx = Math.max(startIdx, Math.min(lines.length - 1, endIdx));
153
+
154
+ if (def.kind === "class") {
155
+ currentClassEndLine = endIdx + 1;
156
+ }
157
+
158
+ spans.push({
159
+ def,
160
+ startLine: startIdx + 1,
161
+ endLine: endIdx + 1,
162
+ parentClass: def.kind !== "class" && def.line <= currentClassEndLine ? currentClass : undefined,
163
+ });
164
+ }
165
+
166
+ // 3. Construct CodeChunk objects from spans
167
+ for (const span of spans) {
168
+ const startIdx = span.startLine - 1;
169
+ const endIdx = span.endLine - 1;
170
+ const chunkLines = lines.slice(startIdx, endIdx + 1);
171
+ const chunkContent = chunkLines.join("\n");
172
+
173
+ if (!chunkContent.trim()) continue;
174
+
175
+ let breadcrumb = `// [File: ${relPath}]`;
176
+ if (span.parentClass) {
177
+ breadcrumb += ` > [Class: ${span.parentClass}]`;
178
+ }
179
+ breadcrumb += ` > [${span.def.kind.toUpperCase()}: ${span.def.name}]`;
180
+
181
+ const textForEmbedding = `${breadcrumb}\nSignature: ${span.def.signature}\n\n${chunkContent.slice(0, 1500)}`;
182
+ const hash = computeHash(chunkContent);
183
+
184
+ chunks.push({
185
+ id: `${relPath}:${span.startLine}-${span.endLine}#${span.def.name}`,
186
+ filePath: relPath,
187
+ absolutePath: absPath,
188
+ startLine: span.startLine,
189
+ endLine: span.endLine,
190
+ symbolName: span.def.name,
191
+ kind: span.def.kind,
192
+ signature: span.def.signature,
193
+ breadcrumb,
194
+ content: chunkContent,
195
+ textForEmbedding,
196
+ hash,
197
+ });
198
+ }
199
+
200
+ return chunks;
201
+ }
202
+
203
+ /**
204
+ * Find supported source files in a workspace using the same traversal policy as
205
+ * chunkWorkspace. The search index uses this to check live file freshness
206
+ * without reparsing unchanged files.
207
+ */
208
+ export function findChunkableFiles(rootDir: string, maxFiles = 500): string[] {
209
+ const files: string[] = [];
210
+
211
+ function scan(dir: string) {
212
+ if (files.length >= maxFiles) return;
213
+ let entries: fs.Dirent[];
214
+ try {
215
+ entries = fs.readdirSync(dir, { withFileTypes: true });
216
+ } catch {
217
+ return;
218
+ }
219
+
220
+ for (const entry of entries) {
221
+ if (entry.name.startsWith(".") && entry.name !== ".github") continue;
222
+ if (IGNORED_DIRS.has(entry.name)) continue;
223
+
224
+ const fullPath = path.join(dir, entry.name);
225
+ if (entry.isDirectory()) {
226
+ scan(fullPath);
227
+ } else if (entry.isFile()) {
228
+ const ext = path.extname(entry.name).toLowerCase();
229
+ if (SUPPORTED_EXTENSIONS.has(ext)) {
230
+ files.push(fullPath);
231
+ if (files.length >= maxFiles) return;
232
+ }
233
+ }
234
+ }
235
+ }
236
+
237
+ scan(rootDir);
238
+ return files;
239
+ }
240
+
241
+ /**
242
+ * Scan workspace and chunk all supported source files.
243
+ */
244
+ export function chunkWorkspace(rootDir: string, maxFiles = 500): { chunks: CodeChunk[]; fileCount: number } {
245
+ const files = findChunkableFiles(rootDir, maxFiles);
246
+ const chunks: CodeChunk[] = [];
247
+ for (const filePath of files) {
248
+ chunks.push(...chunkFile(rootDir, filePath));
249
+ }
250
+ return { chunks, fileCount: files.length };
251
+ }
@@ -0,0 +1,162 @@
1
+ import * as os from "node:os";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { getPiHomeDir, loadKernelConfig } from "../config";
5
+ import { kernelDebug } from "../safety/kernel_debug";
6
+ import { writeFileSyncAtomic } from "../safety/atomic_write";
7
+
8
+ export type SearchProfile = "lean" | "hybrid" | "full" | "off" | "auto";
9
+
10
+ export interface SearchConfig {
11
+ profile: SearchProfile;
12
+ effectiveProfile: "lean" | "hybrid" | "full" | "off";
13
+ matryoshkaDim: number;
14
+ /** Minimum cosine similarity required before vector results enter RRF. */
15
+ vectorSimilarityThreshold: number;
16
+ numThreads: number;
17
+ modelId: string;
18
+ dtype: "q8" | "fp32" | "fp16";
19
+ batchSize: number;
20
+ sleepBetweenBatchesMs: number;
21
+ cacheDir: string;
22
+ lazyLoad: boolean;
23
+ }
24
+
25
+ const SETTINGS_FILE = path.join(
26
+ getPiHomeDir(),
27
+ "agent",
28
+ "search_settings.json",
29
+ );
30
+
31
+ /**
32
+ * Auto-detect the best profile based on current hardware.
33
+ * Strictly defaults to "lean" (AST-aware BM25) for ultra-fast, zero-overhead lexical search.
34
+ */
35
+ export function detectBestProfile(): "lean" | "hybrid" | "full" {
36
+ const cpuCount = os.cpus().length;
37
+ if (cpuCount >= 8) return "full";
38
+ if (cpuCount >= 4) return "hybrid";
39
+ return "lean";
40
+ }
41
+
42
+ /**
43
+ * Load persisted search settings or default to config.toml setting.
44
+ */
45
+ export function loadPersistedProfile(): SearchProfile {
46
+ try {
47
+ if (fs.existsSync(SETTINGS_FILE)) {
48
+ const data = JSON.parse(fs.readFileSync(SETTINGS_FILE, "utf-8"));
49
+ if (
50
+ data.profile &&
51
+ ["lean", "hybrid", "full", "off", "auto"].includes(data.profile)
52
+ ) {
53
+ return data.profile as SearchProfile;
54
+ }
55
+ }
56
+ } catch (e) {
57
+ kernelDebug(e);
58
+ }
59
+ const kernelCfg = loadKernelConfig();
60
+ return (kernelCfg.retrieval.default_profile as SearchProfile) || "lean";
61
+ }
62
+
63
+ /**
64
+ * Persist search settings to disk.
65
+ */
66
+ export function savePersistedProfile(profile: SearchProfile): void {
67
+ try {
68
+ const dir = path.dirname(SETTINGS_FILE);
69
+ if (!fs.existsSync(dir)) {
70
+ fs.mkdirSync(dir, { recursive: true });
71
+ }
72
+ writeFileSyncAtomic(
73
+ SETTINGS_FILE,
74
+ JSON.stringify({ profile, updatedAt: new Date().toISOString() }, null, 2),
75
+ );
76
+ } catch (e) {
77
+ kernelDebug(e);
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Resolve effective configuration for the given profile.
83
+ * When requestedProfile is not explicitly provided, strictly resolves to BM25 lean mode.
84
+ */
85
+ export function getSearchConfig(
86
+ requestedProfile?: SearchProfile,
87
+ ): SearchConfig {
88
+ const profile = requestedProfile || loadPersistedProfile();
89
+ const effectiveProfile: "lean" | "hybrid" | "full" | "off" =
90
+ profile === "auto" ? detectBestProfile() : profile || "lean";
91
+
92
+ const globalCacheDir = path.join(os.homedir(), ".pi", "cache", "search");
93
+
94
+ if (effectiveProfile === "off") {
95
+ return {
96
+ profile,
97
+ effectiveProfile: "off",
98
+ matryoshkaDim: 0,
99
+ vectorSimilarityThreshold: 0,
100
+ numThreads: 1,
101
+ modelId: "nomic-ai/nomic-embed-text-v1.5",
102
+ dtype: "q8",
103
+ batchSize: 1,
104
+ sleepBetweenBatchesMs: 0,
105
+ cacheDir: globalCacheDir,
106
+ lazyLoad: true,
107
+ };
108
+ }
109
+
110
+ // Lean Profile: Pure AST-aware BM25. Zero ONNX loading, zero CPU overhead, <1MB RAM.
111
+ if (effectiveProfile === "lean") {
112
+ return {
113
+ profile,
114
+ effectiveProfile: "lean",
115
+ matryoshkaDim: 0,
116
+ vectorSimilarityThreshold: 0,
117
+ numThreads: 1,
118
+ modelId: "nomic-ai/nomic-embed-text-v1.5",
119
+ dtype: "q8",
120
+ batchSize: 1,
121
+ sleepBetweenBatchesMs: 0,
122
+ cacheDir: globalCacheDir,
123
+ lazyLoad: true,
124
+ };
125
+ }
126
+
127
+ // Hybrid Profile: Gentle 1-thread Nomic 256-dim embeddings with throttle sleeps.
128
+ if (effectiveProfile === "hybrid") {
129
+ return {
130
+ profile,
131
+ effectiveProfile: "hybrid",
132
+ matryoshkaDim: 256,
133
+ // Initial conservative floor from the bounded feedback fixture; larger
134
+ // labeled-corpus calibration remains planned.
135
+ vectorSimilarityThreshold: 0.6,
136
+ numThreads: 1,
137
+ modelId: "nomic-ai/nomic-embed-text-v1.5",
138
+ dtype: "q8",
139
+ batchSize: 1,
140
+ sleepBetweenBatchesMs: 80, // 80ms sleep between chunk batches to prevent CPU starvation
141
+ cacheDir: globalCacheDir,
142
+ lazyLoad: true,
143
+ };
144
+ }
145
+
146
+ // Full Profile: Controlled multi-core workstation setting.
147
+ return {
148
+ profile,
149
+ effectiveProfile: "full",
150
+ matryoshkaDim: 768,
151
+ // Use the same initial floor until a larger labeled corpus justifies
152
+ // profile-specific calibration.
153
+ vectorSimilarityThreshold: 0.6,
154
+ numThreads: Math.min(2, Math.max(1, Math.floor(os.cpus().length / 2))),
155
+ modelId: "nomic-ai/nomic-embed-text-v1.5",
156
+ dtype: "q8",
157
+ batchSize: 2,
158
+ sleepBetweenBatchesMs: 50,
159
+ cacheDir: globalCacheDir,
160
+ lazyLoad: true,
161
+ };
162
+ }