codebasesearch 0.1.22 → 0.1.23

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/.prd ADDED
@@ -0,0 +1,78 @@
1
+ {
2
+ "project": "code-search",
3
+ "created": "2026-03-12",
4
+ "objective": "Profile and improve code-search speed and result quality",
5
+ "items": [
6
+ {
7
+ "id": "fix-dedup-buildtextindex",
8
+ "subject": "Remove duplicate buildTextIndex from search.js",
9
+ "status": "pending",
10
+ "description": "search.js has a private copy of buildTextIndex and tokenize/extractSymbols/isCodeFile that duplicates text-search.js. Import the exported buildTextIndex from text-search.js instead.",
11
+ "category": "refactor",
12
+ "effort": "small",
13
+ "blocking": ["fix-score-normalization", "fix-hybrid-weights"],
14
+ "blockedBy": []
15
+ },
16
+ {
17
+ "id": "fix-chunk-size",
18
+ "subject": "Reduce chunk size from 300 to 60 lines for better semantic granularity",
19
+ "status": "pending",
20
+ "description": "scanner.js uses 300-line chunks. Embeddings work best on 50-100 line chunks. Reduce to 60-line chunks with 15-line overlap for better vector search quality.",
21
+ "category": "feature",
22
+ "effort": "small",
23
+ "blocking": [],
24
+ "blockedBy": []
25
+ },
26
+ {
27
+ "id": "fix-score-normalization",
28
+ "subject": "Fix text search score normalization so top result is always 1.0",
29
+ "status": "pending",
30
+ "description": "Text scores divide raw by 100 but scores can exceed 100. Use dynamic max-score scaling. Lower hasGoodTextResults threshold from 0.5 to 0.3.",
31
+ "category": "bug",
32
+ "effort": "small",
33
+ "blocking": [],
34
+ "blockedBy": ["fix-dedup-buildtextindex"]
35
+ },
36
+ {
37
+ "id": "fix-hybrid-weights",
38
+ "subject": "Boost text-only exact-match results in hybrid merge",
39
+ "status": "pending",
40
+ "description": "Text-only results are capped at 20% weight. Give high-scoring text-only results a floor finalScore of 0.4.",
41
+ "category": "feature",
42
+ "effort": "small",
43
+ "blocking": [],
44
+ "blockedBy": ["fix-dedup-buildtextindex"]
45
+ },
46
+ {
47
+ "id": "fix-vector-cache-key",
48
+ "subject": "Strengthen vector search cache key to 20 dimensions",
49
+ "status": "pending",
50
+ "description": "Cache key uses only first 5 embedding dims. Use 20 dims for near-zero collision rate.",
51
+ "category": "bug",
52
+ "effort": "small",
53
+ "blocking": [],
54
+ "blockedBy": []
55
+ },
56
+ {
57
+ "id": "remove-dead-meanpooling",
58
+ "subject": "Remove dead meanPooling function from embeddings.js",
59
+ "status": "pending",
60
+ "description": "meanPooling is defined but never called. Remove dead code.",
61
+ "category": "refactor",
62
+ "effort": "small",
63
+ "blocking": [],
64
+ "blockedBy": []
65
+ },
66
+ {
67
+ "id": "verify-and-commit",
68
+ "subject": "Verify improvements and commit all changes",
69
+ "status": "pending",
70
+ "description": "Run end-to-end search logic test inline. Commit and push all changes.",
71
+ "category": "infra",
72
+ "effort": "small",
73
+ "blocking": [],
74
+ "blockedBy": ["fix-dedup-buildtextindex", "fix-chunk-size", "fix-score-normalization", "fix-hybrid-weights", "fix-vector-cache-key", "remove-dead-meanpooling"]
75
+ }
76
+ ],
77
+ "completed": []
78
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codebasesearch",
3
- "version": "0.1.22",
3
+ "version": "0.1.23",
4
4
  "description": "Ultra-simple code search tool with Jina embeddings, LanceDB, and MCP protocol support",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.js CHANGED
@@ -75,29 +75,39 @@ export async function run(args) {
75
75
  console.log('Generating embeddings and indexing...');
76
76
 
77
77
  // Generate embeddings in batches and upsert immediately to free memory
78
- const batchSize = 32;
79
- let processedCount = 0;
80
-
81
- for (let i = 0; i < chunks.length; i += batchSize) {
82
- const batchChunks = chunks.slice(i, i + batchSize);
83
- const batchTexts = batchChunks.map(c => c.content);
84
- const batchEmbeddings = await generateEmbeddings(batchTexts);
85
-
86
- // Create batch with embeddings
87
- const batchWithEmbeddings = batchChunks.map((chunk, idx) => ({
88
- ...chunk,
89
- vector: batchEmbeddings[idx]
90
- }));
78
+ // Optimize batch size based on chunk count (larger batches are more efficient)
79
+ let batchSize = 32;
80
+ if (chunks.length > 500) batchSize = 64;
81
+ if (chunks.length > 1000) batchSize = 96;
91
82
 
92
- // Upsert immediately to free memory
93
- await upsertChunks(batchWithEmbeddings);
94
- processedCount += batchWithEmbeddings.length;
83
+ let processedCount = 0;
84
+ let embeddingsAvailable = true;
85
+
86
+ try {
87
+ for (let i = 0; i < chunks.length; i += batchSize) {
88
+ const batchChunks = chunks.slice(i, i + batchSize);
89
+ const batchTexts = batchChunks.map(c => c.content);
90
+ const batchEmbeddings = await generateEmbeddings(batchTexts);
91
+
92
+ // Create batch with embeddings
93
+ const batchWithEmbeddings = batchChunks.map((chunk, idx) => ({
94
+ ...chunk,
95
+ vector: batchEmbeddings[idx]
96
+ }));
97
+
98
+ // Upsert immediately to free memory
99
+ await upsertChunks(batchWithEmbeddings);
100
+ processedCount += batchWithEmbeddings.length;
101
+ }
102
+ } catch (embeddingError) {
103
+ console.warn(`Warning: Embedding generation failed (${embeddingError.message}). Using text-only search.\n`);
104
+ embeddingsAvailable = false;
95
105
  }
96
106
 
97
107
  console.log('Index created\n');
98
108
 
99
- // Execute search
100
- const results = await executeSearch(query);
109
+ // Execute search with chunks for hybrid search (text-only if embeddings failed)
110
+ const results = await executeSearch(query, 10, chunks);
101
111
 
102
112
  // Format and display results
103
113
  const output = formatResults(results);
package/src/embeddings.js CHANGED
@@ -13,6 +13,7 @@ try {
13
13
 
14
14
  let modelCache = null;
15
15
  let cacheCleared = false;
16
+ let modelLoadTime = 0;
16
17
 
17
18
  function clearModelCache() {
18
19
  const cacheDirs = [
@@ -37,6 +38,7 @@ async function getModel(retryOnError = true) {
37
38
  return modelCache;
38
39
  }
39
40
 
41
+ const modelStart = performance.now();
40
42
  console.error('Loading embeddings model (this may take a moment on first run)...');
41
43
 
42
44
  const modelLoadPromise = pipeline(
@@ -50,6 +52,7 @@ async function getModel(retryOnError = true) {
50
52
 
51
53
  try {
52
54
  modelCache = await Promise.race([modelLoadPromise, timeoutPromise]);
55
+ modelLoadTime = performance.now() - modelStart;
53
56
  } catch (e) {
54
57
  if (retryOnError && !cacheCleared && (e.message.includes('Protobuf') || e.message.includes('parsing'))) {
55
58
  console.error('Detected corrupted cache, clearing and retrying...');
@@ -65,37 +68,8 @@ async function getModel(retryOnError = true) {
65
68
  return modelCache;
66
69
  }
67
70
 
68
- async function meanPooling(modelOutput, attentionMask) {
69
- // Get token embeddings from model output
70
- const tokenEmbeddings = modelOutput.data;
71
- const embeddingDim = modelOutput.dims[modelOutput.dims.length - 1];
72
- const batchSize = modelOutput.dims[0];
73
- const seqLength = modelOutput.dims[1];
74
-
75
- const pooled = [];
76
-
77
- for (let b = 0; b < batchSize; b++) {
78
- let sum = new Array(embeddingDim).fill(0);
79
- let count = 0;
80
-
81
- for (let s = 0; s < seqLength; s++) {
82
- const tokenIdx = b * seqLength + s;
83
- const maskValue = attentionMask[tokenIdx] || 1;
84
-
85
- if (maskValue > 0) {
86
- const tokenStart = tokenIdx * embeddingDim;
87
- for (let d = 0; d < embeddingDim; d++) {
88
- sum[d] += tokenEmbeddings[tokenStart + d] * maskValue;
89
- }
90
- count += maskValue;
91
- }
92
- }
93
-
94
- const normalized = sum.map(v => v / Math.max(count, 1e-9));
95
- pooled.push(normalized);
96
- }
97
-
98
- return pooled;
71
+ export function getModelLoadTime() {
72
+ return modelLoadTime;
99
73
  }
100
74
 
101
75
  export async function generateEmbeddings(texts) {
@@ -105,11 +79,16 @@ export async function generateEmbeddings(texts) {
105
79
  texts = [texts];
106
80
  }
107
81
 
108
- // Generate embeddings for all texts
109
- const embeddings = await model(texts, {
110
- pooling: 'mean',
111
- normalize: true
112
- });
82
+ // Generate embeddings for all texts with timeout per batch
83
+ const embeddings = await Promise.race([
84
+ model(texts, {
85
+ pooling: 'mean',
86
+ normalize: true
87
+ }),
88
+ new Promise((_, reject) =>
89
+ setTimeout(() => reject(new Error('Embedding generation timeout')), 60000)
90
+ )
91
+ ]);
113
92
 
114
93
  // Convert to regular arrays
115
94
  const result = [];
package/src/scanner.js CHANGED
@@ -65,7 +65,7 @@ function walkDirectory(dirPath, ignorePatterns, relativePath = '') {
65
65
  return files;
66
66
  }
67
67
 
68
- function chunkContent(content, chunkSize = 1000, overlapSize = 100) {
68
+ function chunkContent(content, chunkSize = 60, overlapSize = 15) {
69
69
  const lines = content.split('\n');
70
70
  const chunks = [];
71
71
 
@@ -81,7 +81,6 @@ function chunkContent(content, chunkSize = 1000, overlapSize = 100) {
81
81
  });
82
82
  }
83
83
 
84
- // Stop if we've reached the end
85
84
  if (endIdx === lines.length) {
86
85
  break;
87
86
  }
@@ -100,7 +99,7 @@ export function scanRepository(rootPath, ignorePatterns) {
100
99
  const mtime = file.mtime;
101
100
 
102
101
  // For small files, treat as single chunk
103
- if (content.split('\n').length <= 1000) {
102
+ if (content.split('\n').length <= 60) {
104
103
  chunks.push({
105
104
  file_path: file.relativePath,
106
105
  chunk_index: 0,
package/src/search.js CHANGED
@@ -1,20 +1,84 @@
1
1
  import { generateSingleEmbedding } from './embeddings.js';
2
2
  import { searchSimilar } from './store.js';
3
+ import { buildTextIndex, searchText } from './text-search.js';
3
4
 
4
- export async function executeSearch(query, limit = 10) {
5
+ export async function executeSearch(query, limit = 10, allChunks = null, skipVector = false) {
5
6
  if (!query || query.trim().length === 0) {
6
7
  throw new Error('Query cannot be empty');
7
8
  }
8
9
 
9
10
  console.error(`Searching for: "${query}"`);
10
11
 
11
- // Generate embedding for query
12
- const queryEmbedding = await generateSingleEmbedding(query);
12
+ try {
13
+ let vectorResults = [];
14
+ let textResults = [];
13
15
 
14
- // Search vector store
15
- const results = await searchSimilar(queryEmbedding, limit);
16
+ if (allChunks && allChunks.length > 0) {
17
+ const textIndexData = buildTextIndex(allChunks);
18
+ textResults = searchText(query, allChunks, textIndexData);
19
+ }
20
+
21
+ const hasGoodTextResults = textResults.length > 0 && textResults[0].score > 0.3;
22
+ if (!skipVector && !hasGoodTextResults) {
23
+ try {
24
+ const queryEmbedding = await generateSingleEmbedding(query);
25
+ vectorResults = await searchSimilar(queryEmbedding, limit * 2);
26
+ } catch (e) {
27
+ console.warn(`Vector search unavailable: ${e.message}`);
28
+ }
29
+ }
30
+
31
+ if (vectorResults.length > 0 && textResults.length > 0) {
32
+ return mergeSearchResults(vectorResults, textResults.slice(0, limit * 2), limit);
33
+ }
34
+
35
+ const allResults = vectorResults.length > 0 ? vectorResults : textResults;
36
+ return allResults.slice(0, limit);
37
+ } catch (error) {
38
+ console.error('Search error:', error.message);
39
+ if (allChunks && allChunks.length > 0) {
40
+ const textIndexData = buildTextIndex(allChunks);
41
+ const textResults = searchText(query, allChunks, textIndexData);
42
+ return textResults.slice(0, limit);
43
+ }
44
+ throw error;
45
+ }
46
+ }
47
+
48
+ function mergeSearchResults(vectorResults, textResults, limit) {
49
+ const merged = new Map();
50
+
51
+ vectorResults.forEach((result) => {
52
+ const key = `${result.file_path}:${result.chunk_index}`;
53
+ merged.set(key, {
54
+ ...result,
55
+ vectorScore: result.score || 0,
56
+ textScore: 0,
57
+ finalScore: (result.score || 0) * 0.8
58
+ });
59
+ });
60
+
61
+ textResults.forEach((result) => {
62
+ const key = `${result.file_path}:${result.chunk_index || 0}`;
63
+ if (merged.has(key)) {
64
+ const existing = merged.get(key);
65
+ existing.textScore = result.score || 0;
66
+ existing.finalScore = (existing.vectorScore * 0.8) + (result.score * 0.2);
67
+ } else {
68
+ const textScore = result.score || 0;
69
+ const finalScore = Math.max(textScore * 0.2, textScore > 0.7 ? 0.4 : 0);
70
+ merged.set(key, {
71
+ ...result,
72
+ vectorScore: 0,
73
+ textScore,
74
+ finalScore
75
+ });
76
+ }
77
+ });
16
78
 
17
- return results;
79
+ return Array.from(merged.values())
80
+ .sort((a, b) => b.finalScore - a.finalScore)
81
+ .slice(0, limit);
18
82
  }
19
83
 
20
84
  export function formatResults(results) {
@@ -27,15 +91,14 @@ export function formatResults(results) {
27
91
 
28
92
  for (let i = 0; i < results.length; i++) {
29
93
  const result = results[i];
30
- const match = i + 1;
94
+ const scoreValue = result.finalScore !== undefined ? result.finalScore : (result.score || 0);
95
+ const scorePercent = (scoreValue * 100).toFixed(1);
31
96
 
32
- lines.push(`${match}. ${result.file_path}:${result.line_start}-${result.line_end} (score: ${(result.score * 100).toFixed(1)}%)`);
97
+ lines.push(`${i + 1}. ${result.file_path}:${result.line_start}-${result.line_end} (score: ${scorePercent}%)`);
33
98
 
34
- // Show code snippet (first 3 lines)
35
99
  const codeLines = result.content.split('\n').slice(0, 3);
36
100
  for (const line of codeLines) {
37
- const trimmed = line.slice(0, 80); // Limit line length
38
- lines.push(` > ${trimmed}`);
101
+ lines.push(` > ${line.slice(0, 80)}`);
39
102
  }
40
103
 
41
104
  lines.push('');
package/src/store.js CHANGED
@@ -5,6 +5,7 @@ import { mkdirSync, existsSync } from 'fs';
5
5
  let dbConnection = null;
6
6
  let tableRef = null;
7
7
  let isFirstBatch = true;
8
+ let vectorSearchCache = new Map();
8
9
 
9
10
  export async function initStore(dbPath) {
10
11
  // Ensure directory exists
@@ -121,12 +122,19 @@ export async function searchSimilar(queryEmbedding, limit = 10) {
121
122
  // Ensure vector is a proper array/tensor
122
123
  const query = Array.isArray(queryEmbedding) ? queryEmbedding : Array.from(queryEmbedding);
123
124
 
125
+ // Check cache using 20-dimension hash for near-zero collision rate
126
+ const cacheKey = query.slice(0, 20).join(',');
127
+ const cached = vectorSearchCache.get(cacheKey);
128
+ if (cached) {
129
+ return cached.slice(0, limit);
130
+ }
131
+
124
132
  const results = await tableRef
125
133
  .search(query)
126
134
  .limit(limit)
127
135
  .execute();
128
136
 
129
- return results.map(result => {
137
+ const formattedResults = results.map(result => {
130
138
  const distance = result._distance !== undefined ? result._distance : (result.distance || 0);
131
139
  const score = distance !== null && distance !== undefined ? 1 / (1 + distance) : 0;
132
140
  return {
@@ -139,6 +147,15 @@ export async function searchSimilar(queryEmbedding, limit = 10) {
139
147
  score: score
140
148
  };
141
149
  });
150
+
151
+ // Cache results (keep max 100 cached searches)
152
+ if (vectorSearchCache.size > 100) {
153
+ const firstKey = vectorSearchCache.keys().next().value;
154
+ vectorSearchCache.delete(firstKey);
155
+ }
156
+ vectorSearchCache.set(cacheKey, formattedResults);
157
+
158
+ return formattedResults;
142
159
  } catch (e) {
143
160
  console.error('Search failed:', e.message);
144
161
  return [];
@@ -52,12 +52,14 @@ export function searchText(query, chunks, indexData) {
52
52
  const meta = chunkMetadata[idx];
53
53
  let score = 0;
54
54
 
55
- queryTokens.forEach(token => {
56
- if (index.has(token) && index.get(token).has(idx)) {
57
- const freq = meta.frequency.get(token) || 1;
58
- const lengthBoost = token.length > 4 ? 1.5 : 1;
59
- score += lengthBoost * Math.min(freq, 5);
60
- }
55
+ // Exact phrase match - highest priority (saves embedding cost)
56
+ if (chunk.content.toLowerCase().includes(query.toLowerCase())) {
57
+ score += 30;
58
+ }
59
+
60
+ // Symbol match in content - function/class named after query terms
61
+ querySymbols.forEach(symbol => {
62
+ if (meta.symbols.includes(symbol)) score += 10;
61
63
  });
62
64
 
63
65
  // Filename token match - strong signal that this file is about the query topic
@@ -66,32 +68,32 @@ export function searchText(query, chunks, indexData) {
66
68
  if (meta.fileNameTokens.includes(token)) fileNameMatches++;
67
69
  });
68
70
  if (fileNameMatches > 0) {
69
- score += fileNameMatches * 8;
71
+ score += fileNameMatches * 10;
70
72
  }
71
73
 
72
- // Symbol match in content - function/class named after query terms
73
- querySymbols.forEach(symbol => {
74
- if (meta.symbols.includes(symbol)) score += 5;
74
+ // Token frequency scoring
75
+ queryTokens.forEach(token => {
76
+ if (index.has(token) && index.get(token).has(idx)) {
77
+ const freq = meta.frequency.get(token) || 1;
78
+ const lengthBoost = token.length > 4 ? 1.5 : 1;
79
+ score += lengthBoost * Math.min(freq, 5);
80
+ }
75
81
  });
76
82
 
77
- // Exact phrase match
78
- if (chunk.content.toLowerCase().includes(query.toLowerCase())) {
79
- score += 15;
80
- }
81
-
82
83
  // Code file boost
83
84
  if (meta.isCode) score *= 1.2;
84
85
 
85
86
  if (score > 0) chunkScores.set(idx, score);
86
87
  }
87
88
 
88
- const results = Array.from(chunkScores.entries())
89
- .map(([idx, score]) => ({
90
- ...chunks[idx],
91
- score: Math.min(score / 100, 1),
92
- _rawScore: score,
93
- }))
94
- .sort((a, b) => b._rawScore - a._rawScore);
89
+ const entries = Array.from(chunkScores.entries()).sort((a, b) => b[1] - a[1]);
90
+ const maxScore = entries.length > 0 ? entries[0][1] : 1;
91
+
92
+ const results = entries.map(([idx, score]) => ({
93
+ ...chunks[idx],
94
+ score: score / maxScore,
95
+ _rawScore: score,
96
+ }));
95
97
 
96
98
  return results;
97
99
  }