gitnexus 1.6.9-rc.33 → 1.6.9-rc.34
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/dist/core/embeddings/embedding-pipeline.d.ts +3 -5
- package/dist/core/embeddings/embedding-pipeline.js +39 -33
- package/dist/core/embeddings/text-generator.d.ts +1 -1
- package/dist/core/embeddings/text-generator.js +51 -21
- package/dist/core/embeddings/types.d.ts +0 -7
- package/dist/core/run-analyze.js +1 -15
- package/dist/server/api.js +0 -1
- package/package.json +1 -1
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* 4. Update LadybugDB with chunk-aware embeddings
|
|
9
9
|
* 5. Create vector index for semantic search
|
|
10
10
|
*/
|
|
11
|
-
import { type EmbeddingProgress, type EmbeddingConfig, type EmbeddableNode, type SemanticSearchResult
|
|
11
|
+
import { type EmbeddingProgress, type EmbeddingConfig, type EmbeddableNode, type SemanticSearchResult } from './types.js';
|
|
12
12
|
import type { ExtensionInstallPolicy } from '../lbug/extension-loader.js';
|
|
13
13
|
/**
|
|
14
14
|
* Resolve the extension-install policy for the embedding WRITE path (analyze).
|
|
@@ -28,7 +28,7 @@ export declare const resolveEmbeddingInstallPolicy: () => ExtensionInstallPolicy
|
|
|
28
28
|
* invalidate existing vectors, such as metadata/header shape changes,
|
|
29
29
|
* structural container context changes, or preceding-context formatting rules.
|
|
30
30
|
*/
|
|
31
|
-
export declare const EMBEDDING_TEXT_VERSION = "
|
|
31
|
+
export declare const EMBEDDING_TEXT_VERSION = "v4";
|
|
32
32
|
/**
|
|
33
33
|
* Compute a stable content fingerprint for an embeddable node.
|
|
34
34
|
* Used to detect when the underlying text has changed so stale vectors
|
|
@@ -65,13 +65,11 @@ export interface EmbeddingPipelineResult {
|
|
|
65
65
|
* @param onProgress - Callback for progress updates
|
|
66
66
|
* @param config - Optional configuration override
|
|
67
67
|
* @param skipNodeIds - Optional set of node IDs that already have embeddings (incremental mode)
|
|
68
|
-
* @param context - Optional repo/server context for metadata enrichment
|
|
69
68
|
* @param existingEmbeddings - Optional map of nodeId → contentHash for incremental mode.
|
|
70
69
|
* Nodes whose hash matches are skipped; nodes with a changed hash are DELETE'd
|
|
71
70
|
* and re-embedded; nodes not in the map are embedded fresh.
|
|
72
|
-
|
|
73
71
|
*/
|
|
74
|
-
export declare const runEmbeddingPipeline: (executeQuery: (cypher: string) => Promise<any[]>, executeWithReusedStatement: (cypher: string, paramsList: Array<Record<string, any>>) => Promise<void>, onProgress: EmbeddingProgressCallback, config?: Partial<EmbeddingConfig>, skipNodeIds?: Set<string>,
|
|
72
|
+
export declare const runEmbeddingPipeline: (executeQuery: (cypher: string) => Promise<any[]>, executeWithReusedStatement: (cypher: string, paramsList: Array<Record<string, any>>) => Promise<void>, onProgress: EmbeddingProgressCallback, config?: Partial<EmbeddingConfig>, skipNodeIds?: Set<string>, existingEmbeddings?: Map<string, string>) => Promise<EmbeddingPipelineResult>;
|
|
75
73
|
/**
|
|
76
74
|
* Perform semantic search using the vector index with chunk deduplication
|
|
77
75
|
*/
|
|
@@ -51,7 +51,7 @@ const ensureVectorExtensionAvailable = async () => {
|
|
|
51
51
|
* invalidate existing vectors, such as metadata/header shape changes,
|
|
52
52
|
* structural container context changes, or preceding-context formatting rules.
|
|
53
53
|
*/
|
|
54
|
-
export const EMBEDDING_TEXT_VERSION = '
|
|
54
|
+
export const EMBEDDING_TEXT_VERSION = 'v4';
|
|
55
55
|
/**
|
|
56
56
|
* Compute a stable content fingerprint for an embeddable node.
|
|
57
57
|
* Used to detect when the underlying text has changed so stale vectors
|
|
@@ -185,6 +185,32 @@ const buildVectorIndex = async () => {
|
|
|
185
185
|
return false;
|
|
186
186
|
}
|
|
187
187
|
};
|
|
188
|
+
/**
|
|
189
|
+
* DELETE stale embedding rows for the given nodeIds so they can be re-inserted.
|
|
190
|
+
*
|
|
191
|
+
* Kuzu forbids SET on vector-indexed properties; DELETE-then-INSERT is the
|
|
192
|
+
* sanctioned pattern. A `"does not exist"` error means the rows are already gone
|
|
193
|
+
* (safe to proceed); any other error risks vector-index corruption, so it
|
|
194
|
+
* propagates and aborts the pipeline.
|
|
195
|
+
*
|
|
196
|
+
* Called per-batch (just before each batch's INSERT), not once up front — see
|
|
197
|
+
* the caller comment / KTD7: an up-front bulk delete of every stale row leaves
|
|
198
|
+
* the whole index deleted-not-reinserted if the re-embed is interrupted. Per-batch
|
|
199
|
+
* interleaving bounds that window to a single batch.
|
|
200
|
+
*/
|
|
201
|
+
const deleteStaleEmbeddingRows = async (executeWithReusedStatement, nodeIds) => {
|
|
202
|
+
if (nodeIds.length === 0)
|
|
203
|
+
return;
|
|
204
|
+
try {
|
|
205
|
+
await executeWithReusedStatement(`MATCH (e:${EMBEDDING_TABLE_NAME} {nodeId: $nodeId}) DELETE e`, nodeIds.map((nodeId) => ({ nodeId })));
|
|
206
|
+
}
|
|
207
|
+
catch (err) {
|
|
208
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
209
|
+
if (!msg.includes('does not exist')) {
|
|
210
|
+
throw new Error(`[embed] Failed to delete stale embedding rows — aborting to prevent vector-index corruption: ${msg}`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
};
|
|
188
214
|
/**
|
|
189
215
|
* Run the embedding pipeline
|
|
190
216
|
*
|
|
@@ -193,13 +219,11 @@ const buildVectorIndex = async () => {
|
|
|
193
219
|
* @param onProgress - Callback for progress updates
|
|
194
220
|
* @param config - Optional configuration override
|
|
195
221
|
* @param skipNodeIds - Optional set of node IDs that already have embeddings (incremental mode)
|
|
196
|
-
* @param context - Optional repo/server context for metadata enrichment
|
|
197
222
|
* @param existingEmbeddings - Optional map of nodeId → contentHash for incremental mode.
|
|
198
223
|
* Nodes whose hash matches are skipped; nodes with a changed hash are DELETE'd
|
|
199
224
|
* and re-embedded; nodes not in the map are embedded fresh.
|
|
200
|
-
|
|
201
225
|
*/
|
|
202
|
-
export const runEmbeddingPipeline = async (executeQuery, executeWithReusedStatement, onProgress, config = {}, skipNodeIds,
|
|
226
|
+
export const runEmbeddingPipeline = async (executeQuery, executeWithReusedStatement, onProgress, config = {}, skipNodeIds, existingEmbeddings) => {
|
|
203
227
|
const finalConfig = resolveEmbeddingConfig(config);
|
|
204
228
|
let totalChunks = 0;
|
|
205
229
|
try {
|
|
@@ -233,20 +257,16 @@ export const runEmbeddingPipeline = async (executeQuery, executeWithReusedStatem
|
|
|
233
257
|
}
|
|
234
258
|
// Phase 2: Query embeddable nodes
|
|
235
259
|
let nodes = await queryEmbeddableNodes(executeQuery);
|
|
236
|
-
// Apply context metadata
|
|
237
|
-
if (context?.repoName) {
|
|
238
|
-
for (const node of nodes) {
|
|
239
|
-
node.repoName = context.repoName;
|
|
240
|
-
node.serverName = context.serverName;
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
260
|
// Incremental mode: compare content hashes, delete stale rows, skip fresh ones.
|
|
244
261
|
// Computed hashes for stale nodes are cached so batchInsertEmbeddings can reuse them
|
|
245
262
|
// (avoids double computation).
|
|
246
263
|
const computedStaleHashes = new Map();
|
|
264
|
+
// Stale rows are DELETE'd per-batch (just before each batch's INSERT) rather
|
|
265
|
+
// than all up front — see U6 / KTD7. `staleNodeIds` is consulted inside the
|
|
266
|
+
// batch loop; it stays empty in full (non-incremental) mode so no deletes fire.
|
|
267
|
+
const staleNodeIds = new Set();
|
|
247
268
|
if (existingEmbeddings && existingEmbeddings.size > 0) {
|
|
248
269
|
const beforeCount = nodes.length;
|
|
249
|
-
const staleNodeIds = [];
|
|
250
270
|
nodes = nodes.filter((n) => {
|
|
251
271
|
const existingHash = existingEmbeddings.get(n.id);
|
|
252
272
|
if (existingHash === undefined) {
|
|
@@ -257,33 +277,14 @@ export const runEmbeddingPipeline = async (executeQuery, executeWithReusedStatem
|
|
|
257
277
|
if (currentHash !== existingHash) {
|
|
258
278
|
// Content changed — cache hash for reuse during insert, mark for DELETE + re-embed
|
|
259
279
|
computedStaleHashes.set(n.id, currentHash);
|
|
260
|
-
staleNodeIds.
|
|
280
|
+
staleNodeIds.add(n.id);
|
|
261
281
|
return true;
|
|
262
282
|
}
|
|
263
283
|
// Hash matches — skip (fresh); no need to cache hash for skipped nodes
|
|
264
284
|
return false;
|
|
265
285
|
});
|
|
266
|
-
// DELETE stale embedding rows so they can be re-inserted
|
|
267
|
-
// (Kuzu forbids SET on vector-indexed properties; DELETE-then-INSERT is the sanctioned pattern)
|
|
268
|
-
if (staleNodeIds.length > 0) {
|
|
269
|
-
if (isDev) {
|
|
270
|
-
logger.info(`🔄 Deleting ${staleNodeIds.length} stale embedding rows for re-embed`);
|
|
271
|
-
}
|
|
272
|
-
try {
|
|
273
|
-
await executeWithReusedStatement(`MATCH (e:${EMBEDDING_TABLE_NAME} {nodeId: $nodeId}) DELETE e`, staleNodeIds.map((nodeId) => ({ nodeId })));
|
|
274
|
-
}
|
|
275
|
-
catch (err) {
|
|
276
|
-
// "does not exist" = rows already gone — safe to proceed.
|
|
277
|
-
// All other errors risk vector-index corruption (Kuzu requires DELETE-before-INSERT
|
|
278
|
-
// for vector-indexed properties) — propagate so the pipeline aborts cleanly.
|
|
279
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
280
|
-
if (!msg.includes('does not exist')) {
|
|
281
|
-
throw new Error(`[embed] Failed to delete stale embedding rows — aborting to prevent vector-index corruption: ${msg}`);
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
286
|
if (isDev) {
|
|
286
|
-
logger.info(`📦 Incremental embeddings: ${beforeCount} total, ${existingEmbeddings.size} cached, ${staleNodeIds.
|
|
287
|
+
logger.info(`📦 Incremental embeddings: ${beforeCount} total, ${existingEmbeddings.size} cached, ${staleNodeIds.size} stale, ${nodes.length} to embed`);
|
|
287
288
|
}
|
|
288
289
|
}
|
|
289
290
|
const totalNodes = nodes.length;
|
|
@@ -373,6 +374,11 @@ export const runEmbeddingPipeline = async (executeQuery, executeWithReusedStatem
|
|
|
373
374
|
prevTail = overlap > 0 ? chunk.text.slice(-overlap) : '';
|
|
374
375
|
}
|
|
375
376
|
}
|
|
377
|
+
// U6 / KTD7: delete this batch's stale rows immediately before its inserts,
|
|
378
|
+
// so an interrupted re-embed loses at most one batch (not the whole index).
|
|
379
|
+
// Preserves Kuzu's required DELETE-before-INSERT for vector-indexed rows.
|
|
380
|
+
const batchStaleIds = batch.filter((n) => staleNodeIds.has(n.id)).map((n) => n.id);
|
|
381
|
+
await deleteStaleEmbeddingRows(executeWithReusedStatement, batchStaleIds);
|
|
376
382
|
// Embed chunk texts in sub-batches to control memory
|
|
377
383
|
const EMBED_SUB_BATCH = finalConfig.subBatchSize;
|
|
378
384
|
for (let si = 0; si < allTexts.length; si += EMBED_SUB_BATCH) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Text Generator Module
|
|
3
3
|
*
|
|
4
|
-
* Generates
|
|
4
|
+
* Generates compact, description-forward embedding text from code nodes.
|
|
5
5
|
* Supports chunkable labels (Function/Method with AST chunking),
|
|
6
6
|
* Class-specific structural text, and short-node direct embed.
|
|
7
7
|
*
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Text Generator Module
|
|
3
3
|
*
|
|
4
|
-
* Generates
|
|
4
|
+
* Generates compact, description-forward embedding text from code nodes.
|
|
5
5
|
* Supports chunkable labels (Function/Method with AST chunking),
|
|
6
6
|
* Class-specific structural text, and short-node direct embed.
|
|
7
7
|
*
|
|
@@ -41,27 +41,48 @@ const cleanContent = (content) => {
|
|
|
41
41
|
.trim();
|
|
42
42
|
};
|
|
43
43
|
/**
|
|
44
|
-
*
|
|
44
|
+
* Compact location signal for the embedding header: the last 1-2 path segments
|
|
45
|
+
* (immediate parent dir + basename), never the full deep path.
|
|
46
|
+
*
|
|
47
|
+
* #2333 / PR #2334 tri-review: U1 dropped the location entirely, which regressed
|
|
48
|
+
* path/service-qualified semantic search (e.g. `billing/handler` vs
|
|
49
|
+
* `identity/handler` in a monorepo) — and FTS indexes only name/content/description,
|
|
50
|
+
* never `filePath`, so there is no keyword backfill. The bounded form restores the
|
|
51
|
+
* discriminating tokens (service dir + filename-concept) at a fraction of the
|
|
52
|
+
* dilution the full path caused.
|
|
45
53
|
*/
|
|
46
|
-
const
|
|
54
|
+
const boundedLocation = (filePath) => {
|
|
55
|
+
const segments = filePath.replace(/\\/g, '/').split('/').filter(Boolean);
|
|
56
|
+
return segments.slice(-2).join('/');
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Build a compact, description-forward header for embedding text.
|
|
60
|
+
*
|
|
61
|
+
* Issue #2333 (sub-issue of #2326), Option A: lead the embedding text with the
|
|
62
|
+
* symbol name + doc-comment description and drop the low-signal metadata lines
|
|
63
|
+
* (`Repo`/`Server`/`Export` and the verbose full `Path`). For short doc comments
|
|
64
|
+
* those lines used to be ~25-30% of the embedding text, diluting the description's
|
|
65
|
+
* semantic weight in the vector and weakening description-shaped search — worst
|
|
66
|
+
* for CJK, where a complete concept is often 4-20 characters.
|
|
67
|
+
*
|
|
68
|
+
* A *bounded* location signal (last 1-2 path segments) is kept after the
|
|
69
|
+
* description — see `boundedLocation` for why the full path drop was reversed.
|
|
70
|
+
*
|
|
71
|
+
* Full metadata is unaffected: it lives on the graph node properties, which is
|
|
72
|
+
* what display/context tools read. Only the embedding text changes here.
|
|
73
|
+
*
|
|
74
|
+
* Option B (reorder only, keep metadata) was rejected — mean-pooled embeddings
|
|
75
|
+
* weight by token proportion, not position, so reordering alone barely moves the
|
|
76
|
+
* signal. Option C (a separate description-only embedding + hybrid merge) is
|
|
77
|
+
* deferred to follow-up; build it only if Option A proves insufficient against
|
|
78
|
+
* real measurement. Any change to this template MUST bump EMBEDDING_TEXT_VERSION.
|
|
79
|
+
*/
|
|
80
|
+
const buildEmbeddingHeader = (node, config) => {
|
|
47
81
|
const parts = [];
|
|
48
82
|
// Label + name
|
|
49
83
|
parts.push(`${node.label}: ${node.name}`);
|
|
50
|
-
//
|
|
51
|
-
|
|
52
|
-
parts.push(`Repo: ${node.repoName}`);
|
|
53
|
-
}
|
|
54
|
-
// Server name (optional)
|
|
55
|
-
if (node.serverName) {
|
|
56
|
-
parts.push(`Server: ${node.serverName}`);
|
|
57
|
-
}
|
|
58
|
-
// Full file path
|
|
59
|
-
parts.push(`Path: ${node.filePath}`);
|
|
60
|
-
// Export status
|
|
61
|
-
if (node.isExported !== undefined) {
|
|
62
|
-
parts.push(`Export: ${node.isExported}`);
|
|
63
|
-
}
|
|
64
|
-
// Description (truncated)
|
|
84
|
+
// Description hoisted above everything else so its semantic signal dominates
|
|
85
|
+
// the embedding vector and is never the part lost to token-limit truncation.
|
|
65
86
|
if (node.description) {
|
|
66
87
|
const maxLen = config.maxDescriptionLength ?? DEFAULT_EMBEDDING_CONFIG.maxDescriptionLength;
|
|
67
88
|
const truncated = truncateDescription(node.description, maxLen);
|
|
@@ -69,10 +90,19 @@ const buildMetadataHeader = (node, config) => {
|
|
|
69
90
|
parts.push(truncated);
|
|
70
91
|
}
|
|
71
92
|
}
|
|
93
|
+
// Bounded location signal — placed after the description so the description
|
|
94
|
+
// still leads the vector. Restores path/service disambiguation lost when the
|
|
95
|
+
// full Path line was dropped (FTS does not index filePath to backfill it).
|
|
96
|
+
if (node.filePath) {
|
|
97
|
+
const loc = boundedLocation(node.filePath);
|
|
98
|
+
if (loc) {
|
|
99
|
+
parts.push(`Loc: ${loc}`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
72
102
|
return parts.join('\n');
|
|
73
103
|
};
|
|
74
104
|
const generateCodeBodyText = (node, codeBody, config, prevTail) => {
|
|
75
|
-
const header =
|
|
105
|
+
const header = buildEmbeddingHeader(node, config);
|
|
76
106
|
const parts = [header];
|
|
77
107
|
if (prevTail) {
|
|
78
108
|
parts.push(`[preceding context]: ...${cleanContent(prevTail)}`);
|
|
@@ -87,7 +117,7 @@ const getCompactContainerContext = (cleanedContent, declarationOnly) => {
|
|
|
87
117
|
return firstLine ? `Container: ${firstLine}` : undefined;
|
|
88
118
|
};
|
|
89
119
|
const generateStructuralTypeText = (node, codeBody, config, chunkIndex, prevTail) => {
|
|
90
|
-
const header =
|
|
120
|
+
const header = buildEmbeddingHeader(node, config);
|
|
91
121
|
const parts = [header];
|
|
92
122
|
const isFirstChunk = chunkIndex === undefined || chunkIndex === 0;
|
|
93
123
|
const cleanedContent = cleanContent(node.content);
|
|
@@ -192,7 +222,7 @@ export const extractDeclarationOnly = (content) => {
|
|
|
192
222
|
*/
|
|
193
223
|
export const generateEmbeddingText = (node, codeBody, config = {}, chunkIndex, prevTail) => {
|
|
194
224
|
if (isShortLabel(node.label)) {
|
|
195
|
-
const header =
|
|
225
|
+
const header = buildEmbeddingHeader(node, config);
|
|
196
226
|
const cleaned = cleanContent(node.content);
|
|
197
227
|
return `${header}\n\n${cleaned}`;
|
|
198
228
|
}
|
|
@@ -168,13 +168,6 @@ export interface CachedEmbedding {
|
|
|
168
168
|
embedding: number[];
|
|
169
169
|
contentHash?: string;
|
|
170
170
|
}
|
|
171
|
-
/**
|
|
172
|
-
* Context info for embedding pipeline (repo/server metadata enrichment)
|
|
173
|
-
*/
|
|
174
|
-
export interface EmbeddingContext {
|
|
175
|
-
repoName?: string;
|
|
176
|
-
serverName?: string;
|
|
177
|
-
}
|
|
178
171
|
/**
|
|
179
172
|
* Model download progress from transformers.js
|
|
180
173
|
*/
|
package/dist/core/run-analyze.js
CHANGED
|
@@ -982,20 +982,6 @@ export async function runFullAnalysis(repoPath, options, callbacks) {
|
|
|
982
982
|
existingEmbeddings.set(e.nodeId, e.contentHash ?? STALE_HASH_SENTINEL);
|
|
983
983
|
}
|
|
984
984
|
}
|
|
985
|
-
const { readServerMapping } = await import('./embeddings/server-mapping.js');
|
|
986
|
-
// Mirror the registry's name-resolution chain so the server-mapping
|
|
987
|
-
// lookup key stays aligned with the final registry name (#1259):
|
|
988
|
-
// --name → remote-derived → canonical-root basename
|
|
989
|
-
// (preserved-alias is intentionally NOT consulted here — server
|
|
990
|
-
// mappings are addressed by the operationally-meaningful name the
|
|
991
|
-
// user configures, not by a sticky registry-only alias they may not
|
|
992
|
-
// know about. The previous canonical-only logic ignored both --name
|
|
993
|
-
// and remote-derived names, silently breaking server-mapping for
|
|
994
|
-
// anyone with a `--name` alias or remote-named repo.)
|
|
995
|
-
const projectName = options.registryName ??
|
|
996
|
-
getInferredRepoName(repoPath) ??
|
|
997
|
-
path.basename(resolveRepoIdentityRoot(repoPath));
|
|
998
|
-
const serverName = await readServerMapping(projectName);
|
|
999
985
|
const embeddingResult = await runEmbeddingPipeline(executeQuery, executeWithReusedStatement, (p) => {
|
|
1000
986
|
const scaled = 90 + Math.round((p.percent / 100) * 8);
|
|
1001
987
|
const label = p.phase === 'loading-model'
|
|
@@ -1004,7 +990,7 @@ export async function runFullAnalysis(repoPath, options, callbacks) {
|
|
|
1004
990
|
: 'Loading embedding model...'
|
|
1005
991
|
: `Embedding ${p.nodesProcessed || 0}/${p.totalNodes || '?'}`;
|
|
1006
992
|
progress('embeddings', scaled, label);
|
|
1007
|
-
}, {}, cachedEmbeddingNodeIds.size > 0 ? cachedEmbeddingNodeIds : undefined,
|
|
993
|
+
}, {}, cachedEmbeddingNodeIds.size > 0 ? cachedEmbeddingNodeIds : undefined, existingEmbeddings);
|
|
1008
994
|
if (embeddingResult.semanticMode === 'exact-scan') {
|
|
1009
995
|
semanticMode = 'exact-scan';
|
|
1010
996
|
log('Semantic embeddings were generated without a VECTOR index; ' +
|
package/dist/server/api.js
CHANGED
|
@@ -1520,7 +1520,6 @@ export const createServer = async (port, host = '127.0.0.1') => {
|
|
|
1520
1520
|
});
|
|
1521
1521
|
}, {}, // config: use defaults
|
|
1522
1522
|
undefined, // skipNodeIds
|
|
1523
|
-
undefined, // context
|
|
1524
1523
|
existingEmbeddings);
|
|
1525
1524
|
// Flush WAL so subsequent /api/search requests see the new
|
|
1526
1525
|
// embeddings immediately (#1149). In the CLI path closeLbug()
|
package/package.json
CHANGED