@hivelore/embeddings 0.30.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hivelore contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,157 @@
1
+ <p align="center">
2
+ <a href="https://github.com/Doucs91/hivelore">
3
+ <img src="https://raw.githubusercontent.com/Doucs91/hivelore/main/packages/vscode/media/logo.svg" alt="Hivelore logo" width="96" />
4
+ </a>
5
+ </p>
6
+
7
+ # @hivelore/embeddings
8
+
9
+ > **Optional add-on for Hivelore** — local semantic ranking for Hivelore briefings and memory search. No data leaves your machine.
10
+
11
+ When installed alongside `@hivelore/cli`, this package helps Hivelore surface the right policy context even when the agent's task wording does not match your memories exactly. It improves `get_briefing`, `mem_relevant_to`, and `mem_search`; it is not required for enforcement.
12
+
13
+ ---
14
+
15
+ ## Why optional?
16
+
17
+ This package pulls in heavy ML dependencies (`@xenova/transformers`, `onnxruntime-node`, `sharp`) and downloads a ~110MB model on first use. It is **not installed by default** so that the core Hivelore experience stays lightweight.
18
+
19
+ Install it explicitly when you want semantic search:
20
+
21
+ ```bash
22
+ npm install -g @hivelore/embeddings
23
+ # or alongside the CLI:
24
+ npm install -g @hivelore/cli @hivelore/embeddings
25
+ ```
26
+
27
+ ---
28
+
29
+ ## Quick start
30
+
31
+ ```bash
32
+ # Build (or refresh) the index. First run downloads the model (~110MB, cached locally).
33
+ hivelore embeddings index
34
+
35
+ # Check index status
36
+ hivelore embeddings status
37
+
38
+ # Run a semantic search from the terminal
39
+ hivelore embeddings query "how do we handle retries on payment failures"
40
+ ```
41
+
42
+ From an MCP client, pass `semantic: true` to `mem_search` or `get_briefing`:
43
+
44
+ ```json
45
+ { "task": "add a mobile payment provider", "semantic": true }
46
+ ```
47
+
48
+ ---
49
+
50
+ ## Commands
51
+
52
+ ### `hivelore embeddings index`
53
+
54
+ Build or refresh the embeddings index for all memories.
55
+
56
+ ```bash
57
+ hivelore embeddings index # Index all memories in the current project
58
+ hivelore embeddings index --dir /path # Specify project root
59
+ hivelore embeddings index --force # Force full rebuild (ignore content hashes)
60
+ ```
61
+
62
+ The index is stored at `.ai/.cache/embeddings/embeddings-index.json`. Each entry is keyed by content hash, so only changed memories are re-embedded on subsequent runs.
63
+
64
+ ### `hivelore embeddings status`
65
+
66
+ Show the current state of the embeddings index.
67
+
68
+ ```bash
69
+ hivelore embeddings status
70
+ # Output:
71
+ # Index: .ai/.cache/embeddings/embeddings-index.json
72
+ # Entries: 24
73
+ # Model: Xenova/bge-small-en-v1.5 (384 dimensions)
74
+ # Last updated: 2025-01-20T14:32:00Z
75
+ ```
76
+
77
+ ### `hivelore embeddings query`
78
+
79
+ Run a semantic query against the local index.
80
+
81
+ ```bash
82
+ hivelore embeddings query "payment retry logic"
83
+ hivelore embeddings query "JWT expiration handling" --limit 5
84
+ hivelore embeddings query "database migration" --dir /path/to/project
85
+ ```
86
+
87
+ ---
88
+
89
+ ## How it works
90
+
91
+ 1. **Model**: [`Xenova/bge-small-en-v1.5`](https://huggingface.co/BAAI/bge-small-en-v1.5) — a 33M-parameter sentence embedding model, 384 dimensions, optimized for retrieval tasks. Downloaded once and cached in `~/.cache/huggingface/` (or `TRANSFORMERS_CACHE`).
92
+
93
+ 2. **Indexing**: Each memory's body is converted to a 384-dimensional vector and stored alongside its id and content hash.
94
+
95
+ 3. **Search**: At query time, the query text is embedded and cosine similarity is computed against all indexed memories. The top-k results are returned ranked by score.
96
+
97
+ 4. **Integration**: When `@hivelore/embeddings` is installed and the index exists, `get_briefing` and `mem_search` automatically use semantic ranking. If the package is missing or the index is empty, they fall back to literal (keyword) search transparently.
98
+
99
+ ---
100
+
101
+ ## Auto-rebuild on sync
102
+
103
+ Add `--embed` to `hivelore sync` to automatically rebuild the index after every sync:
104
+
105
+ ```bash
106
+ hivelore sync --embed
107
+
108
+ # Or in your git hook / CI:
109
+ hivelore sync --quiet --embed
110
+ ```
111
+
112
+ ---
113
+
114
+ ## Programmatic API
115
+
116
+ ```typescript
117
+ import { rebuildIndex, semanticSearch } from "@hivelore/embeddings";
118
+ import { resolveHaivePaths, findProjectRoot } from "@hivelore/core";
119
+
120
+ const paths = resolveHaivePaths(findProjectRoot());
121
+
122
+ // Rebuild the full index
123
+ const report = await rebuildIndex(paths);
124
+ // report.added, report.updated, report.removed, report.skipped
125
+
126
+ // Search
127
+ const result = await semanticSearch(paths, "payment retry logic", { limit: 5 });
128
+ if (result) {
129
+ for (const hit of result.hits) {
130
+ console.log(hit.id, hit.score); // score: 0.0–1.0
131
+ }
132
+ }
133
+
134
+ // Custom embedder (for testing or alternative models)
135
+ import { Embedder, type EmbedderLike } from "@hivelore/embeddings";
136
+
137
+ const embedder: EmbedderLike = {
138
+ model: "Xenova/bge-small-en-v1.5",
139
+ dimension: 384,
140
+ encode: async (texts) => { /* ... */ return [[0.1, 0.2, ...]]; },
141
+ };
142
+ ```
143
+
144
+ ---
145
+
146
+ ## Privacy
147
+
148
+ - The model runs **entirely locally** via [Transformers.js](https://huggingface.co/docs/transformers.js) + ONNX Runtime.
149
+ - No API keys required.
150
+ - No network calls during search or indexing (only on first model download).
151
+ - Memory content never leaves your machine.
152
+
153
+ ---
154
+
155
+ ## License
156
+
157
+ MIT
@@ -0,0 +1,144 @@
1
+ import { HaivePaths } from '@hivelore/core';
2
+
3
+ declare const DEFAULT_MODEL = "Xenova/bge-small-en-v1.5";
4
+ declare const DEFAULT_DIMENSION = 384;
5
+ interface EmbedderLike {
6
+ readonly model: string;
7
+ readonly dimension: number;
8
+ encode(text: string): Promise<Float32Array>;
9
+ }
10
+ declare class Embedder implements EmbedderLike {
11
+ private readonly pipe;
12
+ readonly model: string;
13
+ readonly dimension: number;
14
+ private constructor();
15
+ static create(model?: string): Promise<Embedder>;
16
+ encode(text: string): Promise<Float32Array>;
17
+ encodeMany(texts: string[]): Promise<Float32Array[]>;
18
+ }
19
+ declare function cosine(a: Float32Array | number[], b: Float32Array | number[]): number;
20
+
21
+ interface EmbeddingEntry {
22
+ id: string;
23
+ file_path: string;
24
+ hash: string;
25
+ vector: number[];
26
+ }
27
+ interface EmbeddingIndex {
28
+ model: string;
29
+ dimension: number;
30
+ updated_at: string;
31
+ entries: EmbeddingEntry[];
32
+ }
33
+ declare function cacheDir(paths: HaivePaths): string;
34
+ declare function indexPath(paths: HaivePaths): string;
35
+ declare function hashContent(text: string): string;
36
+ declare function emptyIndex(model?: string, dimension?: number): EmbeddingIndex;
37
+ declare function loadIndex(paths: HaivePaths): Promise<EmbeddingIndex | null>;
38
+ declare function saveIndex(paths: HaivePaths, index: EmbeddingIndex): Promise<void>;
39
+ declare function indexStat(paths: HaivePaths): Promise<{
40
+ exists: boolean;
41
+ count: number;
42
+ model: string | null;
43
+ updatedAt: string | null;
44
+ sizeBytes: number;
45
+ }>;
46
+ declare function buildEntryText(id: string, tags: string[], body: string): string;
47
+
48
+ interface IndexUpdateReport {
49
+ total: number;
50
+ added: number;
51
+ updated: number;
52
+ unchanged: number;
53
+ removed: number;
54
+ }
55
+ declare function rebuildIndex(paths: HaivePaths, embedder: EmbedderLike): Promise<{
56
+ index: EmbeddingIndex;
57
+ report: IndexUpdateReport;
58
+ }>;
59
+
60
+ interface SemanticHit {
61
+ id: string;
62
+ file_path: string;
63
+ score: number;
64
+ }
65
+ declare function semanticSearch(paths: HaivePaths, query: string, options?: {
66
+ limit?: number;
67
+ minScore?: number;
68
+ embedder?: EmbedderLike;
69
+ index?: EmbeddingIndex;
70
+ }): Promise<{
71
+ hits: SemanticHit[];
72
+ index: EmbeddingIndex;
73
+ } | null>;
74
+
75
+ interface CodeEmbeddingEntry {
76
+ /** stable id: `${file}#${name}` */
77
+ id: string;
78
+ file: string;
79
+ name: string;
80
+ kind: string;
81
+ line: number;
82
+ description?: string;
83
+ hash: string;
84
+ vector: number[];
85
+ }
86
+ interface CodeEmbeddingIndex {
87
+ model: string;
88
+ dimension: number;
89
+ updated_at: string;
90
+ source_generated_at: string;
91
+ entries: CodeEmbeddingEntry[];
92
+ }
93
+ declare function codeIndexPath(paths: HaivePaths): string;
94
+ /**
95
+ * Is the code-search embeddings index stale relative to the current code-map?
96
+ * The indexer stamps `source_generated_at` with the code-map's `generated_at` it was built from,
97
+ * so a mismatch means the code-map was rebuilt afterwards and the index may miss or mislocate symbols.
98
+ * Unknown timestamps (empty strings) are treated as not-stale to avoid false alarms.
99
+ */
100
+ declare function isCodeIndexStale(indexSourceGeneratedAt: string, codeMapGeneratedAt: string): boolean;
101
+ declare function emptyCodeIndex(model?: string, dimension?: number, sourceGeneratedAt?: string): CodeEmbeddingIndex;
102
+ declare function loadCodeIndex(paths: HaivePaths): Promise<CodeEmbeddingIndex | null>;
103
+ declare function saveCodeIndex(paths: HaivePaths, index: CodeEmbeddingIndex): Promise<void>;
104
+ declare function buildCodeEntryText(file: string, name: string, kind: string, description?: string): string;
105
+
106
+ interface CodeIndexUpdateReport {
107
+ total: number;
108
+ added: number;
109
+ updated: number;
110
+ unchanged: number;
111
+ removed: number;
112
+ }
113
+ /**
114
+ * Build (or refresh) the code semantic-search index from the code-map.
115
+ * Each exported symbol becomes one embedding entry — granularity stays at the
116
+ * symbol level so search returns a precise file:line:name target.
117
+ *
118
+ * Re-uses entries whose embedded text is unchanged (hash check) so subsequent
119
+ * builds only embed the diff.
120
+ */
121
+ declare function rebuildCodeIndex(paths: HaivePaths, embedder: EmbedderLike): Promise<{
122
+ index: CodeEmbeddingIndex;
123
+ report: CodeIndexUpdateReport;
124
+ }>;
125
+
126
+ interface CodeSearchHit {
127
+ file: string;
128
+ name: string;
129
+ kind: string;
130
+ line: number;
131
+ description?: string;
132
+ score: number;
133
+ }
134
+ declare function codeSemanticSearch(paths: HaivePaths, query: string, options?: {
135
+ limit?: number;
136
+ minScore?: number;
137
+ embedder?: EmbedderLike;
138
+ index?: CodeEmbeddingIndex;
139
+ }): Promise<{
140
+ hits: CodeSearchHit[];
141
+ index: CodeEmbeddingIndex;
142
+ } | null>;
143
+
144
+ export { type CodeEmbeddingEntry, type CodeEmbeddingIndex, type CodeIndexUpdateReport, type CodeSearchHit, DEFAULT_DIMENSION, DEFAULT_MODEL, Embedder, type EmbedderLike, type EmbeddingEntry, type EmbeddingIndex, type IndexUpdateReport, type SemanticHit, buildCodeEntryText, buildEntryText, cacheDir, codeIndexPath, codeSemanticSearch, cosine, emptyCodeIndex, emptyIndex, hashContent, indexPath, indexStat, isCodeIndexStale, loadCodeIndex, loadIndex, rebuildCodeIndex, rebuildIndex, saveCodeIndex, saveIndex, semanticSearch };
package/dist/index.js ADDED
@@ -0,0 +1,366 @@
1
+ // src/embedder.ts
2
+ var DEFAULT_MODEL = "Xenova/bge-small-en-v1.5";
3
+ var DEFAULT_DIMENSION = 384;
4
+ var cachedPipeline = null;
5
+ var cachedModel = null;
6
+ var cachedEmbedders = /* @__PURE__ */ new Map();
7
+ async function loadPipeline(model) {
8
+ if (cachedPipeline && cachedModel === model) return cachedPipeline;
9
+ const { pipeline, env } = await import("@xenova/transformers");
10
+ env.allowLocalModels = true;
11
+ env.allowRemoteModels = true;
12
+ const pipe = await pipeline("feature-extraction", model);
13
+ cachedPipeline = pipe;
14
+ cachedModel = model;
15
+ return pipe;
16
+ }
17
+ var Embedder = class _Embedder {
18
+ constructor(pipe, model, dimension) {
19
+ this.pipe = pipe;
20
+ this.model = model;
21
+ this.dimension = dimension;
22
+ }
23
+ pipe;
24
+ model;
25
+ dimension;
26
+ static async create(model = DEFAULT_MODEL) {
27
+ const cached = cachedEmbedders.get(model);
28
+ if (cached) return cached;
29
+ const pipe = await loadPipeline(model);
30
+ const probe = await pipe("dimension probe", { pooling: "mean", normalize: true });
31
+ const dim = probe.data instanceof Float32Array ? probe.data.length : probe.data.length;
32
+ const embedder = new _Embedder(pipe, model, dim);
33
+ cachedEmbedders.set(model, embedder);
34
+ return embedder;
35
+ }
36
+ async encode(text) {
37
+ const result = await this.pipe(text, { pooling: "mean", normalize: true });
38
+ return result.data instanceof Float32Array ? result.data : Float32Array.from(result.data);
39
+ }
40
+ async encodeMany(texts) {
41
+ const out = [];
42
+ for (const t of texts) {
43
+ out.push(await this.encode(t));
44
+ }
45
+ return out;
46
+ }
47
+ };
48
+ function cosine(a, b) {
49
+ if (a.length !== b.length) {
50
+ throw new Error(`vector dimension mismatch: ${a.length} vs ${b.length}`);
51
+ }
52
+ let dot = 0;
53
+ let na = 0;
54
+ let nb = 0;
55
+ for (let i = 0; i < a.length; i++) {
56
+ const av = a[i];
57
+ const bv = b[i];
58
+ dot += av * bv;
59
+ na += av * av;
60
+ nb += bv * bv;
61
+ }
62
+ if (na === 0 || nb === 0) return 0;
63
+ return dot / (Math.sqrt(na) * Math.sqrt(nb));
64
+ }
65
+
66
+ // src/index-cache.ts
67
+ import { createHash } from "crypto";
68
+ import { mkdir, readFile, stat, writeFile } from "fs/promises";
69
+ import { existsSync } from "fs";
70
+ import path from "path";
71
+ var INDEX_FILE = "embeddings-index.json";
72
+ function cacheDir(paths) {
73
+ return path.join(paths.haiveDir, ".cache", "embeddings");
74
+ }
75
+ function indexPath(paths) {
76
+ return path.join(cacheDir(paths), INDEX_FILE);
77
+ }
78
+ function hashContent(text) {
79
+ return createHash("sha256").update(text).digest("hex");
80
+ }
81
+ function emptyIndex(model = DEFAULT_MODEL, dimension = DEFAULT_DIMENSION) {
82
+ return {
83
+ model,
84
+ dimension,
85
+ updated_at: (/* @__PURE__ */ new Date()).toISOString(),
86
+ entries: []
87
+ };
88
+ }
89
+ async function loadIndex(paths) {
90
+ const file = indexPath(paths);
91
+ if (!existsSync(file)) return null;
92
+ const raw = await readFile(file, "utf8");
93
+ return JSON.parse(raw);
94
+ }
95
+ async function saveIndex(paths, index) {
96
+ const dir = cacheDir(paths);
97
+ await mkdir(dir, { recursive: true });
98
+ index.updated_at = (/* @__PURE__ */ new Date()).toISOString();
99
+ await writeFile(indexPath(paths), JSON.stringify(index, null, 2), "utf8");
100
+ }
101
+ async function indexStat(paths) {
102
+ const file = indexPath(paths);
103
+ if (!existsSync(file)) {
104
+ return { exists: false, count: 0, model: null, updatedAt: null, sizeBytes: 0 };
105
+ }
106
+ const idx = await loadIndex(paths);
107
+ const st = await stat(file);
108
+ return {
109
+ exists: true,
110
+ count: idx?.entries.length ?? 0,
111
+ model: idx?.model ?? null,
112
+ updatedAt: idx?.updated_at ?? null,
113
+ sizeBytes: st.size
114
+ };
115
+ }
116
+ function buildEntryText(id, tags, body) {
117
+ const tagPart = tags.length ? `${tags.join(" ")} ${tags.join(" ")} ` : "";
118
+ return `${id} ${tagPart}${body}`;
119
+ }
120
+
121
+ // src/indexer.ts
122
+ import { loadMemoriesFromDir } from "@hivelore/core";
123
+ async function rebuildIndex(paths, embedder) {
124
+ const existing = await loadIndex(paths) ?? emptyIndex(embedder.model, embedder.dimension);
125
+ if (existing.model !== embedder.model || existing.dimension !== embedder.dimension) {
126
+ existing.entries = [];
127
+ existing.model = embedder.model;
128
+ existing.dimension = embedder.dimension;
129
+ }
130
+ const memories = await loadMemoriesFromDir(paths.memoriesDir);
131
+ const byId = new Map(existing.entries.map((e) => [e.id, e]));
132
+ const seenIds = /* @__PURE__ */ new Set();
133
+ let added = 0;
134
+ let updated = 0;
135
+ let unchanged = 0;
136
+ const nextEntries = [];
137
+ for (const { memory, filePath } of memories) {
138
+ const id = memory.frontmatter.id;
139
+ seenIds.add(id);
140
+ const text = buildEntryText(id, memory.frontmatter.tags, memory.body);
141
+ const hash = hashContent(text);
142
+ const prior = byId.get(id);
143
+ if (prior && prior.hash === hash) {
144
+ nextEntries.push({ ...prior, file_path: filePath });
145
+ unchanged++;
146
+ continue;
147
+ }
148
+ const vector = Array.from(await embedder.encode(text));
149
+ nextEntries.push({ id, file_path: filePath, hash, vector });
150
+ if (prior) {
151
+ updated++;
152
+ } else {
153
+ added++;
154
+ }
155
+ }
156
+ const removed = existing.entries.filter((e) => !seenIds.has(e.id)).length;
157
+ existing.entries = nextEntries;
158
+ await saveIndex(paths, existing);
159
+ return {
160
+ index: existing,
161
+ report: {
162
+ total: nextEntries.length,
163
+ added,
164
+ updated,
165
+ unchanged,
166
+ removed
167
+ }
168
+ };
169
+ }
170
+
171
+ // src/search.ts
172
+ async function semanticSearch(paths, query, options = {}) {
173
+ const index = options.index ?? await loadIndex(paths);
174
+ if (!index || index.entries.length === 0) return null;
175
+ const embedder = options.embedder ?? await Embedder.create(index.model);
176
+ if (embedder.dimension !== index.dimension) {
177
+ throw new Error(
178
+ `Embedder dimension (${embedder.dimension}) differs from index (${index.dimension}). Re-run \`hivelore embeddings index\`.`
179
+ );
180
+ }
181
+ const queryVec = await embedder.encode(query);
182
+ const minScore = options.minScore ?? 0;
183
+ const limit = options.limit ?? 10;
184
+ const scored = index.entries.map((e) => ({ id: e.id, file_path: e.file_path, score: cosine(queryVec, e.vector) })).filter((h) => h.score >= minScore).sort((a, b) => b.score - a.score).slice(0, limit);
185
+ return { hits: scored, index };
186
+ }
187
+
188
+ // src/code-index-cache.ts
189
+ import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
190
+ import { existsSync as existsSync2 } from "fs";
191
+ import path2 from "path";
192
+ var CODE_INDEX_FILE = "code-embeddings-index.json";
193
+ function codeIndexPath(paths) {
194
+ return path2.join(cacheDir(paths), CODE_INDEX_FILE);
195
+ }
196
+ function isCodeIndexStale(indexSourceGeneratedAt, codeMapGeneratedAt) {
197
+ if (!indexSourceGeneratedAt || !codeMapGeneratedAt) return false;
198
+ return indexSourceGeneratedAt !== codeMapGeneratedAt;
199
+ }
200
+ function emptyCodeIndex(model = DEFAULT_MODEL, dimension = DEFAULT_DIMENSION, sourceGeneratedAt = "") {
201
+ return {
202
+ model,
203
+ dimension,
204
+ updated_at: (/* @__PURE__ */ new Date()).toISOString(),
205
+ source_generated_at: sourceGeneratedAt,
206
+ entries: []
207
+ };
208
+ }
209
+ async function loadCodeIndex(paths) {
210
+ const file = codeIndexPath(paths);
211
+ if (!existsSync2(file)) return null;
212
+ return JSON.parse(await readFile2(file, "utf8"));
213
+ }
214
+ async function saveCodeIndex(paths, index) {
215
+ const dir = cacheDir(paths);
216
+ await mkdir2(dir, { recursive: true });
217
+ index.updated_at = (/* @__PURE__ */ new Date()).toISOString();
218
+ await writeFile2(codeIndexPath(paths), JSON.stringify(index, null, 2), "utf8");
219
+ }
220
+ function buildCodeEntryText(file, name, kind, description) {
221
+ const filenameHints = file.split("/").pop()?.replace(/\.[^.]+$/, "").replace(/[._-]+/g, " ") ?? "";
222
+ return `${name} ${kind} ${filenameHints} ${description ?? ""}`.trim();
223
+ }
224
+
225
+ // src/code-indexer.ts
226
+ import { loadCodeMap } from "@hivelore/core";
227
+ import { createHash as createHash2 } from "crypto";
228
+ function hashEntry(text) {
229
+ return createHash2("sha256").update(text).digest("hex").slice(0, 32);
230
+ }
231
+ async function rebuildCodeIndex(paths, embedder) {
232
+ const codeMap = await loadCodeMap(paths);
233
+ if (!codeMap) {
234
+ throw new Error(
235
+ "No code-map found. Run `hivelore index code` to generate `.ai/code-map.json` first."
236
+ );
237
+ }
238
+ const existing = await loadCodeIndex(paths) ?? emptyCodeIndex(embedder.model, embedder.dimension, codeMap.generated_at);
239
+ if (existing.model !== embedder.model || existing.dimension !== embedder.dimension) {
240
+ existing.entries = [];
241
+ existing.model = embedder.model;
242
+ existing.dimension = embedder.dimension;
243
+ }
244
+ const byId = new Map(existing.entries.map((e) => [e.id, e]));
245
+ const nextEntries = [];
246
+ const seenIds = /* @__PURE__ */ new Set();
247
+ let added = 0;
248
+ let updated = 0;
249
+ let unchanged = 0;
250
+ for (const [filePath, fileEntry] of Object.entries(codeMap.files)) {
251
+ for (const exp of fileEntry.exports) {
252
+ const id = `${filePath}#${exp.name}`;
253
+ seenIds.add(id);
254
+ const text = buildCodeEntryText(filePath, exp.name, exp.kind, exp.description);
255
+ const hash = hashEntry(text);
256
+ const prior = byId.get(id);
257
+ if (prior && prior.hash === hash && prior.line === exp.line) {
258
+ nextEntries.push({ ...prior, file: filePath, name: exp.name, kind: exp.kind, line: exp.line, ...exp.description ? { description: exp.description } : {} });
259
+ unchanged++;
260
+ continue;
261
+ }
262
+ const vector = Array.from(await embedder.encode(text));
263
+ nextEntries.push({
264
+ id,
265
+ file: filePath,
266
+ name: exp.name,
267
+ kind: exp.kind,
268
+ line: exp.line,
269
+ ...exp.description ? { description: exp.description } : {},
270
+ hash,
271
+ vector
272
+ });
273
+ if (prior) updated++;
274
+ else added++;
275
+ }
276
+ }
277
+ const removed = existing.entries.filter((e) => !seenIds.has(e.id)).length;
278
+ existing.entries = nextEntries;
279
+ existing.source_generated_at = codeMap.generated_at;
280
+ await saveCodeIndex(paths, existing);
281
+ return {
282
+ index: existing,
283
+ report: {
284
+ total: nextEntries.length,
285
+ added,
286
+ updated,
287
+ unchanged,
288
+ removed
289
+ }
290
+ };
291
+ }
292
+
293
+ // src/code-search.ts
294
+ async function codeSemanticSearch(paths, query, options = {}) {
295
+ const index = options.index ?? await loadCodeIndex(paths);
296
+ if (!index || index.entries.length === 0) return null;
297
+ const embedder = options.embedder ?? await Embedder.create(index.model);
298
+ if (embedder.dimension !== index.dimension) {
299
+ throw new Error(
300
+ `Embedder dimension (${embedder.dimension}) differs from code index (${index.dimension}). Re-run \`hivelore index code-search\`.`
301
+ );
302
+ }
303
+ const queryVec = await embedder.encode(query);
304
+ const minScore = options.minScore ?? 0;
305
+ const limit = options.limit ?? 5;
306
+ const queryTokens = tokenize(query);
307
+ const normalizedQuery = query.trim().toLowerCase();
308
+ const scored = index.entries.map((e) => {
309
+ const semantic = cosine(queryVec, e.vector);
310
+ const boost = lexicalBoost(queryTokens, normalizedQuery, e.name, e.file);
311
+ return {
312
+ file: e.file,
313
+ name: e.name,
314
+ kind: e.kind,
315
+ line: e.line,
316
+ ...e.description ? { description: e.description } : {},
317
+ // Hybrid score: semantic cosine is the base, a small deterministic lexical bonus
318
+ // promotes exact/partial symbol-name and filename matches above merely-similar neighbours.
319
+ score: Math.min(1, semantic + boost),
320
+ semantic
321
+ };
322
+ }).filter((h) => h.semantic >= minScore).sort((a, b) => b.score - a.score || b.semantic - a.semantic || a.file.localeCompare(b.file) || a.line - b.line).slice(0, limit).map(({ semantic: _semantic, ...hit }) => hit);
323
+ return { hits: scored, index };
324
+ }
325
+ function tokenize(text) {
326
+ return text.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[^a-zA-Z0-9]+/).map((t) => t.toLowerCase()).filter((t) => t.length >= 2);
327
+ }
328
+ function lexicalBoost(queryTokens, normalizedQuery, name, file) {
329
+ if (queryTokens.length === 0) return 0;
330
+ let nameComponent;
331
+ if (normalizedQuery === name.toLowerCase()) {
332
+ nameComponent = 0.3;
333
+ } else {
334
+ const nameTokens = new Set(tokenize(name));
335
+ const matched = queryTokens.filter((t) => nameTokens.has(t)).length;
336
+ nameComponent = matched / queryTokens.length * 0.2;
337
+ }
338
+ const fileTokens = new Set(tokenize(file.split("/").pop() ?? ""));
339
+ const pathComponent = queryTokens.some((t) => fileTokens.has(t)) ? 0.05 : 0;
340
+ return Math.min(0.3, nameComponent + pathComponent);
341
+ }
342
+ export {
343
+ DEFAULT_DIMENSION,
344
+ DEFAULT_MODEL,
345
+ Embedder,
346
+ buildCodeEntryText,
347
+ buildEntryText,
348
+ cacheDir,
349
+ codeIndexPath,
350
+ codeSemanticSearch,
351
+ cosine,
352
+ emptyCodeIndex,
353
+ emptyIndex,
354
+ hashContent,
355
+ indexPath,
356
+ indexStat,
357
+ isCodeIndexStale,
358
+ loadCodeIndex,
359
+ loadIndex,
360
+ rebuildCodeIndex,
361
+ rebuildIndex,
362
+ saveCodeIndex,
363
+ saveIndex,
364
+ semanticSearch
365
+ };
366
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/embedder.ts","../src/index-cache.ts","../src/indexer.ts","../src/search.ts","../src/code-index-cache.ts","../src/code-indexer.ts","../src/code-search.ts"],"sourcesContent":["export const DEFAULT_MODEL = \"Xenova/bge-small-en-v1.5\";\nexport const DEFAULT_DIMENSION = 384;\n\nexport interface EmbedderLike {\n readonly model: string;\n readonly dimension: number;\n encode(text: string): Promise<Float32Array>;\n}\n\ninterface FeatureExtractionPipeline {\n (text: string | string[], options: { pooling: \"mean\"; normalize: boolean }): Promise<{\n data: Float32Array | number[];\n dims: number[];\n }>;\n}\n\nlet cachedPipeline: FeatureExtractionPipeline | null = null;\nlet cachedModel: string | null = null;\nconst cachedEmbedders = new Map<string, Embedder>();\n\nasync function loadPipeline(model: string): Promise<FeatureExtractionPipeline> {\n if (cachedPipeline && cachedModel === model) return cachedPipeline;\n const { pipeline, env } = await import(\"@xenova/transformers\");\n // Allow remote model download by default; users can pre-cache for offline use.\n env.allowLocalModels = true;\n env.allowRemoteModels = true;\n const pipe = (await pipeline(\"feature-extraction\", model)) as unknown as FeatureExtractionPipeline;\n cachedPipeline = pipe;\n cachedModel = model;\n return pipe;\n}\n\nexport class Embedder implements EmbedderLike {\n private constructor(\n private readonly pipe: FeatureExtractionPipeline,\n public readonly model: string,\n public readonly dimension: number,\n ) {}\n\n static async create(model: string = DEFAULT_MODEL): Promise<Embedder> {\n // Reuse the fully-initialized embedder per model: the pipeline is already cached, but each\n // create() otherwise runs a \"dimension probe\" inference — wasteful when an agent issues several\n // code_search / semantic-search calls in one session. Caching the instance makes calls 2..N free.\n const cached = cachedEmbedders.get(model);\n if (cached) return cached;\n const pipe = await loadPipeline(model);\n const probe = await pipe(\"dimension probe\", { pooling: \"mean\", normalize: true });\n const dim = probe.data instanceof Float32Array ? probe.data.length : probe.data.length;\n const embedder = new Embedder(pipe, model, dim);\n cachedEmbedders.set(model, embedder);\n return embedder;\n }\n\n async encode(text: string): Promise<Float32Array> {\n const result = await this.pipe(text, { pooling: \"mean\", normalize: true });\n return result.data instanceof Float32Array\n ? result.data\n : Float32Array.from(result.data);\n }\n\n async encodeMany(texts: string[]): Promise<Float32Array[]> {\n const out: Float32Array[] = [];\n for (const t of texts) {\n out.push(await this.encode(t));\n }\n return out;\n }\n}\n\nexport function cosine(a: Float32Array | number[], b: Float32Array | number[]): number {\n if (a.length !== b.length) {\n throw new Error(`vector dimension mismatch: ${a.length} vs ${b.length}`);\n }\n let dot = 0;\n let na = 0;\n let nb = 0;\n for (let i = 0; i < a.length; i++) {\n const av = a[i] as number;\n const bv = b[i] as number;\n dot += av * bv;\n na += av * av;\n nb += bv * bv;\n }\n if (na === 0 || nb === 0) return 0;\n return dot / (Math.sqrt(na) * Math.sqrt(nb));\n}\n","import { createHash } from \"node:crypto\";\nimport { mkdir, readFile, stat, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { HaivePaths } from \"@hivelore/core\";\nimport { DEFAULT_DIMENSION, DEFAULT_MODEL } from \"./embedder.js\";\n\nexport const INDEX_FILE = \"embeddings-index.json\";\n\nexport interface EmbeddingEntry {\n id: string;\n file_path: string;\n hash: string;\n vector: number[];\n}\n\nexport interface EmbeddingIndex {\n model: string;\n dimension: number;\n updated_at: string;\n entries: EmbeddingEntry[];\n}\n\nexport function cacheDir(paths: HaivePaths): string {\n return path.join(paths.haiveDir, \".cache\", \"embeddings\");\n}\n\nexport function indexPath(paths: HaivePaths): string {\n return path.join(cacheDir(paths), INDEX_FILE);\n}\n\nexport function hashContent(text: string): string {\n return createHash(\"sha256\").update(text).digest(\"hex\");\n}\n\nexport function emptyIndex(model = DEFAULT_MODEL, dimension = DEFAULT_DIMENSION): EmbeddingIndex {\n return {\n model,\n dimension,\n updated_at: new Date().toISOString(),\n entries: [],\n };\n}\n\nexport async function loadIndex(paths: HaivePaths): Promise<EmbeddingIndex | null> {\n const file = indexPath(paths);\n if (!existsSync(file)) return null;\n const raw = await readFile(file, \"utf8\");\n return JSON.parse(raw) as EmbeddingIndex;\n}\n\nexport async function saveIndex(paths: HaivePaths, index: EmbeddingIndex): Promise<void> {\n const dir = cacheDir(paths);\n await mkdir(dir, { recursive: true });\n index.updated_at = new Date().toISOString();\n await writeFile(indexPath(paths), JSON.stringify(index, null, 2), \"utf8\");\n}\n\nexport async function indexStat(paths: HaivePaths): Promise<{\n exists: boolean;\n count: number;\n model: string | null;\n updatedAt: string | null;\n sizeBytes: number;\n}> {\n const file = indexPath(paths);\n if (!existsSync(file)) {\n return { exists: false, count: 0, model: null, updatedAt: null, sizeBytes: 0 };\n }\n const idx = await loadIndex(paths);\n const st = await stat(file);\n return {\n exists: true,\n count: idx?.entries.length ?? 0,\n model: idx?.model ?? null,\n updatedAt: idx?.updated_at ?? null,\n sizeBytes: st.size,\n };\n}\n\nexport function buildEntryText(id: string, tags: string[], body: string): string {\n // Concatenate id + tags + body so search works on metadata too.\n // Tags are weighted by repetition so they contribute more to the embedding.\n const tagPart = tags.length ? `${tags.join(\" \")} ${tags.join(\" \")} ` : \"\";\n return `${id} ${tagPart}${body}`;\n}\n","import { loadMemoriesFromDir, type HaivePaths } from \"@hivelore/core\";\nimport type { EmbedderLike } from \"./embedder.js\";\nimport {\n buildEntryText,\n emptyIndex,\n hashContent,\n loadIndex,\n saveIndex,\n type EmbeddingEntry,\n type EmbeddingIndex,\n} from \"./index-cache.js\";\n\nexport interface IndexUpdateReport {\n total: number;\n added: number;\n updated: number;\n unchanged: number;\n removed: number;\n}\n\nexport async function rebuildIndex(\n paths: HaivePaths,\n embedder: EmbedderLike,\n): Promise<{ index: EmbeddingIndex; report: IndexUpdateReport }> {\n const existing = (await loadIndex(paths)) ?? emptyIndex(embedder.model, embedder.dimension);\n // If model changed, reset.\n if (existing.model !== embedder.model || existing.dimension !== embedder.dimension) {\n existing.entries = [];\n existing.model = embedder.model;\n existing.dimension = embedder.dimension;\n }\n\n const memories = await loadMemoriesFromDir(paths.memoriesDir);\n const byId = new Map(existing.entries.map((e) => [e.id, e]));\n const seenIds = new Set<string>();\n\n let added = 0;\n let updated = 0;\n let unchanged = 0;\n\n const nextEntries: EmbeddingEntry[] = [];\n\n for (const { memory, filePath } of memories) {\n const id = memory.frontmatter.id;\n seenIds.add(id);\n const text = buildEntryText(id, memory.frontmatter.tags, memory.body);\n const hash = hashContent(text);\n const prior = byId.get(id);\n\n if (prior && prior.hash === hash) {\n nextEntries.push({ ...prior, file_path: filePath });\n unchanged++;\n continue;\n }\n\n const vector = Array.from(await embedder.encode(text));\n nextEntries.push({ id, file_path: filePath, hash, vector });\n if (prior) {\n updated++;\n } else {\n added++;\n }\n }\n\n const removed = existing.entries.filter((e) => !seenIds.has(e.id)).length;\n existing.entries = nextEntries;\n await saveIndex(paths, existing);\n\n return {\n index: existing,\n report: {\n total: nextEntries.length,\n added,\n updated,\n unchanged,\n removed,\n },\n };\n}\n","import type { HaivePaths } from \"@hivelore/core\";\nimport { cosine, Embedder, type EmbedderLike } from \"./embedder.js\";\nimport { loadIndex, type EmbeddingIndex } from \"./index-cache.js\";\n\nexport interface SemanticHit {\n id: string;\n file_path: string;\n score: number;\n}\n\nexport async function semanticSearch(\n paths: HaivePaths,\n query: string,\n options: {\n limit?: number;\n minScore?: number;\n embedder?: EmbedderLike;\n index?: EmbeddingIndex;\n } = {},\n): Promise<{ hits: SemanticHit[]; index: EmbeddingIndex } | null> {\n const index = options.index ?? (await loadIndex(paths));\n if (!index || index.entries.length === 0) return null;\n\n const embedder = options.embedder ?? (await Embedder.create(index.model));\n if (embedder.dimension !== index.dimension) {\n throw new Error(\n `Embedder dimension (${embedder.dimension}) differs from index (${index.dimension}). Re-run \\`hivelore embeddings index\\`.`,\n );\n }\n\n const queryVec = await embedder.encode(query);\n const minScore = options.minScore ?? 0;\n const limit = options.limit ?? 10;\n\n const scored = index.entries\n .map((e) => ({ id: e.id, file_path: e.file_path, score: cosine(queryVec, e.vector) }))\n .filter((h) => h.score >= minScore)\n .sort((a, b) => b.score - a.score)\n .slice(0, limit);\n\n return { hits: scored, index };\n}\n","import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { HaivePaths } from \"@hivelore/core\";\nimport { DEFAULT_DIMENSION, DEFAULT_MODEL } from \"./embedder.js\";\nimport { cacheDir } from \"./index-cache.js\";\n\nexport const CODE_INDEX_FILE = \"code-embeddings-index.json\";\n\nexport interface CodeEmbeddingEntry {\n /** stable id: `${file}#${name}` */\n id: string;\n file: string;\n name: string;\n kind: string;\n line: number;\n description?: string;\n hash: string;\n vector: number[];\n}\n\nexport interface CodeEmbeddingIndex {\n model: string;\n dimension: number;\n updated_at: string;\n source_generated_at: string;\n entries: CodeEmbeddingEntry[];\n}\n\nexport function codeIndexPath(paths: HaivePaths): string {\n return path.join(cacheDir(paths), CODE_INDEX_FILE);\n}\n\n/**\n * Is the code-search embeddings index stale relative to the current code-map?\n * The indexer stamps `source_generated_at` with the code-map's `generated_at` it was built from,\n * so a mismatch means the code-map was rebuilt afterwards and the index may miss or mislocate symbols.\n * Unknown timestamps (empty strings) are treated as not-stale to avoid false alarms.\n */\nexport function isCodeIndexStale(indexSourceGeneratedAt: string, codeMapGeneratedAt: string): boolean {\n if (!indexSourceGeneratedAt || !codeMapGeneratedAt) return false;\n return indexSourceGeneratedAt !== codeMapGeneratedAt;\n}\n\nexport function emptyCodeIndex(\n model = DEFAULT_MODEL,\n dimension = DEFAULT_DIMENSION,\n sourceGeneratedAt = \"\",\n): CodeEmbeddingIndex {\n return {\n model,\n dimension,\n updated_at: new Date().toISOString(),\n source_generated_at: sourceGeneratedAt,\n entries: [],\n };\n}\n\nexport async function loadCodeIndex(paths: HaivePaths): Promise<CodeEmbeddingIndex | null> {\n const file = codeIndexPath(paths);\n if (!existsSync(file)) return null;\n return JSON.parse(await readFile(file, \"utf8\")) as CodeEmbeddingIndex;\n}\n\nexport async function saveCodeIndex(paths: HaivePaths, index: CodeEmbeddingIndex): Promise<void> {\n const dir = cacheDir(paths);\n await mkdir(dir, { recursive: true });\n index.updated_at = new Date().toISOString();\n await writeFile(codeIndexPath(paths), JSON.stringify(index, null, 2), \"utf8\");\n}\n\nexport function buildCodeEntryText(file: string, name: string, kind: string, description?: string): string {\n // The embedded text is what we search against — keep it tight and signal-dense.\n // Filename tokens often carry intent (e.g. \"auth.controller.ts\" → \"auth controller\").\n const filenameHints = file\n .split(\"/\")\n .pop()\n ?.replace(/\\.[^.]+$/, \"\")\n .replace(/[._-]+/g, \" \") ?? \"\";\n return `${name} ${kind} ${filenameHints} ${description ?? \"\"}`.trim();\n}\n","import { loadCodeMap, type HaivePaths } from \"@hivelore/core\";\nimport { createHash } from \"node:crypto\";\nimport type { EmbedderLike } from \"./embedder.js\";\nimport {\n buildCodeEntryText,\n emptyCodeIndex,\n loadCodeIndex,\n saveCodeIndex,\n type CodeEmbeddingEntry,\n type CodeEmbeddingIndex,\n} from \"./code-index-cache.js\";\n\nexport interface CodeIndexUpdateReport {\n total: number;\n added: number;\n updated: number;\n unchanged: number;\n removed: number;\n}\n\nfunction hashEntry(text: string): string {\n return createHash(\"sha256\").update(text).digest(\"hex\").slice(0, 32);\n}\n\n/**\n * Build (or refresh) the code semantic-search index from the code-map.\n * Each exported symbol becomes one embedding entry — granularity stays at the\n * symbol level so search returns a precise file:line:name target.\n *\n * Re-uses entries whose embedded text is unchanged (hash check) so subsequent\n * builds only embed the diff.\n */\nexport async function rebuildCodeIndex(\n paths: HaivePaths,\n embedder: EmbedderLike,\n): Promise<{ index: CodeEmbeddingIndex; report: CodeIndexUpdateReport }> {\n const codeMap = await loadCodeMap(paths);\n if (!codeMap) {\n throw new Error(\n \"No code-map found. Run `hivelore index code` to generate `.ai/code-map.json` first.\",\n );\n }\n\n const existing =\n (await loadCodeIndex(paths)) ??\n emptyCodeIndex(embedder.model, embedder.dimension, codeMap.generated_at);\n\n if (existing.model !== embedder.model || existing.dimension !== embedder.dimension) {\n existing.entries = [];\n existing.model = embedder.model;\n existing.dimension = embedder.dimension;\n }\n\n const byId = new Map(existing.entries.map((e) => [e.id, e]));\n const nextEntries: CodeEmbeddingEntry[] = [];\n const seenIds = new Set<string>();\n let added = 0;\n let updated = 0;\n let unchanged = 0;\n\n for (const [filePath, fileEntry] of Object.entries(codeMap.files)) {\n for (const exp of fileEntry.exports) {\n const id = `${filePath}#${exp.name}`;\n seenIds.add(id);\n const text = buildCodeEntryText(filePath, exp.name, exp.kind, exp.description);\n const hash = hashEntry(text);\n const prior = byId.get(id);\n\n if (prior && prior.hash === hash && prior.line === exp.line) {\n nextEntries.push({ ...prior, file: filePath, name: exp.name, kind: exp.kind, line: exp.line, ...(exp.description ? { description: exp.description } : {}) });\n unchanged++;\n continue;\n }\n\n const vector = Array.from(await embedder.encode(text));\n nextEntries.push({\n id,\n file: filePath,\n name: exp.name,\n kind: exp.kind,\n line: exp.line,\n ...(exp.description ? { description: exp.description } : {}),\n hash,\n vector,\n });\n if (prior) updated++;\n else added++;\n }\n }\n\n const removed = existing.entries.filter((e) => !seenIds.has(e.id)).length;\n existing.entries = nextEntries;\n existing.source_generated_at = codeMap.generated_at;\n await saveCodeIndex(paths, existing);\n\n return {\n index: existing,\n report: {\n total: nextEntries.length,\n added,\n updated,\n unchanged,\n removed,\n },\n };\n}\n","import type { HaivePaths } from \"@hivelore/core\";\nimport { cosine, Embedder, type EmbedderLike } from \"./embedder.js\";\nimport { loadCodeIndex, type CodeEmbeddingIndex } from \"./code-index-cache.js\";\n\nexport interface CodeSearchHit {\n file: string;\n name: string;\n kind: string;\n line: number;\n description?: string;\n score: number;\n}\n\nexport async function codeSemanticSearch(\n paths: HaivePaths,\n query: string,\n options: {\n limit?: number;\n minScore?: number;\n embedder?: EmbedderLike;\n index?: CodeEmbeddingIndex;\n } = {},\n): Promise<{ hits: CodeSearchHit[]; index: CodeEmbeddingIndex } | null> {\n const index = options.index ?? (await loadCodeIndex(paths));\n if (!index || index.entries.length === 0) return null;\n\n const embedder = options.embedder ?? (await Embedder.create(index.model));\n if (embedder.dimension !== index.dimension) {\n throw new Error(\n `Embedder dimension (${embedder.dimension}) differs from code index (${index.dimension}). Re-run \\`hivelore index code-search\\`.`,\n );\n }\n\n const queryVec = await embedder.encode(query);\n const minScore = options.minScore ?? 0;\n const limit = options.limit ?? 5;\n\n const queryTokens = tokenize(query);\n const normalizedQuery = query.trim().toLowerCase();\n\n const scored = index.entries\n .map((e) => {\n const semantic = cosine(queryVec, e.vector);\n const boost = lexicalBoost(queryTokens, normalizedQuery, e.name, e.file);\n return {\n file: e.file,\n name: e.name,\n kind: e.kind,\n line: e.line,\n ...(e.description ? { description: e.description } : {}),\n // Hybrid score: semantic cosine is the base, a small deterministic lexical bonus\n // promotes exact/partial symbol-name and filename matches above merely-similar neighbours.\n score: Math.min(1, semantic + boost),\n semantic,\n };\n })\n // Keep min_score a pure-semantic noise floor (its documented meaning) so the lexical bonus\n // re-ranks the relevant set without letting incidental filename tokens leak noise past the gate.\n .filter((h) => h.semantic >= minScore)\n .sort((a, b) => b.score - a.score || b.semantic - a.semantic || a.file.localeCompare(b.file) || a.line - b.line)\n .slice(0, limit)\n .map(({ semantic: _semantic, ...hit }) => hit);\n\n return { hits: scored, index };\n}\n\n/** Split a query or symbol name into lowercase tokens, breaking on camelCase and any non-alphanumeric run. */\nfunction tokenize(text: string): string[] {\n return text\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .split(/[^a-zA-Z0-9]+/)\n .map((t) => t.toLowerCase())\n .filter((t) => t.length >= 2);\n}\n\n/**\n * Small additive bonus (≤ 0.30) layered on top of the semantic cosine so that exact symbol-name\n * matches outrank distant-but-similar code. Reuses only data already in the index entry — no new\n * index, model, or dependency.\n */\nfunction lexicalBoost(queryTokens: string[], normalizedQuery: string, name: string, file: string): number {\n if (queryTokens.length === 0) return 0;\n\n let nameComponent: number;\n if (normalizedQuery === name.toLowerCase()) {\n nameComponent = 0.3; // exact symbol name typed verbatim\n } else {\n const nameTokens = new Set(tokenize(name));\n const matched = queryTokens.filter((t) => nameTokens.has(t)).length;\n nameComponent = (matched / queryTokens.length) * 0.2; // proportional partial-name match\n }\n\n const fileTokens = new Set(tokenize(file.split(\"/\").pop() ?? \"\"));\n const pathComponent = queryTokens.some((t) => fileTokens.has(t)) ? 0.05 : 0;\n\n return Math.min(0.3, nameComponent + pathComponent);\n}\n"],"mappings":";AAAO,IAAM,gBAAgB;AACtB,IAAM,oBAAoB;AAejC,IAAI,iBAAmD;AACvD,IAAI,cAA6B;AACjC,IAAM,kBAAkB,oBAAI,IAAsB;AAElD,eAAe,aAAa,OAAmD;AAC7E,MAAI,kBAAkB,gBAAgB,MAAO,QAAO;AACpD,QAAM,EAAE,UAAU,IAAI,IAAI,MAAM,OAAO,sBAAsB;AAE7D,MAAI,mBAAmB;AACvB,MAAI,oBAAoB;AACxB,QAAM,OAAQ,MAAM,SAAS,sBAAsB,KAAK;AACxD,mBAAiB;AACjB,gBAAc;AACd,SAAO;AACT;AAEO,IAAM,WAAN,MAAM,UAAiC;AAAA,EACpC,YACW,MACD,OACA,WAChB;AAHiB;AACD;AACA;AAAA,EACf;AAAA,EAHgB;AAAA,EACD;AAAA,EACA;AAAA,EAGlB,aAAa,OAAO,QAAgB,eAAkC;AA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AK,EAAE,CAAC;AAChE,QAAM,gBAAgB,YAAY,KAAK,CAAC,MAAM,WAAW,IAAI,CAAC,CAAC,IAAI,OAAO;AAE1E,SAAO,KAAK,IAAI,KAAK,gBAAgB,aAAa;AACpD;","names":["mkdir","readFile","writeFile","existsSync","path","path","existsSync","readFile","mkdir","writeFile","createHash","createHash"]}
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@hivelore/embeddings",
3
+ "version": "0.30.0",
4
+ "description": "Hivelore embeddings - local semantic ranking for agent briefings and code search",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Doucs91/hivelore.git",
9
+ "directory": "packages/embeddings"
10
+ },
11
+ "bugs": "https://github.com/Doucs91/hivelore/issues",
12
+ "homepage": "https://github.com/Doucs91/hivelore#readme",
13
+ "keywords": [
14
+ "ai",
15
+ "enforcement",
16
+ "context",
17
+ "breadcrumbs",
18
+ "memory",
19
+ "embeddings",
20
+ "transformers",
21
+ "semantic-search",
22
+ "haive"
23
+ ],
24
+ "type": "module",
25
+ "main": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/index.d.ts",
30
+ "import": "./dist/index.js"
31
+ }
32
+ },
33
+ "files": [
34
+ "dist",
35
+ "LICENSE"
36
+ ],
37
+ "dependencies": {
38
+ "@xenova/transformers": "^2.17.2",
39
+ "@hivelore/core": "0.30.0"
40
+ },
41
+ "overrides": {
42
+ "protobufjs": "^7.5.5"
43
+ },
44
+ "scripts": {
45
+ "build": "tsup",
46
+ "test": "vitest run",
47
+ "test:watch": "vitest",
48
+ "typecheck": "node ../../scripts/ensure-workspace-dists.mjs @hivelore/core && tsc --noEmit",
49
+ "clean": "rm -rf dist .tsbuildinfo"
50
+ }
51
+ }