mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-12-04 06:21:59 +09:00
Merge pull request #4919 from ruvnet/fix/2305-embedding-config
fix(cli): memory path honours .claude-flow/embeddings.json (#2305)
This commit is contained in:
5 files changed
+654
-32
No files matched your search
@@ -0,0 +1,262 @@
|
||||
/**
|
||||
* #2305 — the memory path ignored `.claude-flow/embeddings.json`.
|
||||
*
|
||||
* `embeddings init` writes `{ model, dimension }` there, but memory init
|
||||
* (memory-initializer.ts), the AgentDB bridge and the router's task embedder
|
||||
* all hardcoded 'Xenova/all-MiniLM-L6-v2' / 384. These tests pin:
|
||||
*
|
||||
* 1. no config → MiniLM/384, unchanged;
|
||||
* 2. a 768-dim model in the config → used by memory init and task-embedder;
|
||||
* 3. an existing store whose recorded dimension differs → recorded dimension
|
||||
* kept, plus exactly one warning (no mixing, no rebuild);
|
||||
* 4. malformed JSON → defaults plus a warning.
|
||||
*
|
||||
* London-school: the transformers packages are mocked and only record which
|
||||
* model id `pipeline()` was asked for; the project root is a temp dir served
|
||||
* through a `process.cwd()` spy.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const local = vi.hoisted(() => ({
|
||||
hfModels: [] as string[],
|
||||
xenModels: [] as string[],
|
||||
dimFor(model: string): number {
|
||||
return /mpnet/i.test(model) ? 768 : 384;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('@huggingface/transformers', () => ({
|
||||
pipeline: async (_task: string, model: string) => {
|
||||
local.hfModels.push(model);
|
||||
const dim = local.dimFor(model);
|
||||
return async () => ({ data: new Float32Array(dim).fill(0.25) });
|
||||
},
|
||||
env: {},
|
||||
}));
|
||||
vi.mock('@xenova/transformers', () => ({
|
||||
pipeline: async (_task: string, model: string) => {
|
||||
local.xenModels.push(model);
|
||||
const dim = local.dimFor(model);
|
||||
return async (input: string | string[]) => {
|
||||
const n = Array.isArray(input) ? input.length : 1;
|
||||
return { data: new Float32Array(n * dim).fill(0.25), dims: [n, dim] };
|
||||
};
|
||||
},
|
||||
env: {},
|
||||
}));
|
||||
vi.mock('agentic-flow/reasoningbank', () => ({ computeEmbedding: undefined }));
|
||||
vi.mock('ruvector', () => ({ initOnnxEmbedder: undefined, getOptimizedOnnxEmbedder: undefined }));
|
||||
vi.mock('../src/memory/intelligence.js', () => ({
|
||||
initializeIntelligence: vi.fn(async () => ({ reasoningBankEnabled: false, sonaEnabled: false })),
|
||||
}));
|
||||
|
||||
const MPNET_CONFIG = { model: 'Xenova/all-mpnet-base-v2', modelPath: '/x', dimension: 768 };
|
||||
|
||||
let root: string;
|
||||
|
||||
function writeConfig(body: string): void {
|
||||
mkdirSync(join(root, '.claude-flow'), { recursive: true });
|
||||
writeFileSync(join(root, '.claude-flow', 'embeddings.json'), body);
|
||||
}
|
||||
|
||||
/** A memory.db whose newest real vector is `dimension`-dim, written by sql.js. */
|
||||
async function writeStore(dimension: number, model: string): Promise<string> {
|
||||
const initSqlJs = (await import('sql.js')).default;
|
||||
const SQL = await initSqlJs();
|
||||
const db = new SQL.Database();
|
||||
db.run(`CREATE TABLE memory_entries (id TEXT, key TEXT, embedding TEXT,
|
||||
embedding_dimensions INTEGER, embedding_model TEXT)`);
|
||||
db.run(`INSERT INTO memory_entries VALUES ('a', 'k', ?, ?, ?)`, [
|
||||
JSON.stringify(new Array(dimension).fill(0.1)), dimension, model,
|
||||
]);
|
||||
const dir = join(root, '.swarm');
|
||||
mkdirSync(dir, { recursive: true });
|
||||
const dbPath = join(dir, 'memory.db');
|
||||
writeFileSync(dbPath, Buffer.from(db.export()));
|
||||
db.close();
|
||||
return dbPath;
|
||||
}
|
||||
|
||||
async function freshConfigModule() {
|
||||
const mod = await import('../src/memory/embedding-config.js');
|
||||
mod._resetEmbeddingConfigCache();
|
||||
return mod;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
root = realpathSync(mkdtempSync(join(tmpdir(), 'ruflo-2305-')));
|
||||
vi.spyOn(process, 'cwd').mockReturnValue(root);
|
||||
local.hfModels = [];
|
||||
local.xenModels = [];
|
||||
delete process.env.CLAUDE_FLOW_MEMORY_PATH;
|
||||
delete process.env.CLAUDE_FLOW_DB_PATH;
|
||||
delete process.env.RUFLO_REQUIRE_REAL_EMBEDDINGS;
|
||||
process.env.CLAUDE_FLOW_DISABLE_BRIDGE = '1';
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
delete process.env.CLAUDE_FLOW_DISABLE_BRIDGE;
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('resolveEmbeddingConfig', () => {
|
||||
it('defaults to MiniLM/384 when no embeddings.json exists', async () => {
|
||||
const { resolveEmbeddingConfig } = await freshConfigModule();
|
||||
expect(resolveEmbeddingConfig(root)).toMatchObject({
|
||||
model: 'Xenova/all-MiniLM-L6-v2',
|
||||
dimension: 384,
|
||||
source: 'default',
|
||||
});
|
||||
});
|
||||
|
||||
it('reads model and dimension written by `embeddings init`, namespacing a bare model name', async () => {
|
||||
writeConfig(JSON.stringify({ model: 'all-mpnet-base-v2', dimension: 768 }));
|
||||
const { resolveEmbeddingConfig } = await freshConfigModule();
|
||||
expect(resolveEmbeddingConfig(root)).toMatchObject({
|
||||
model: 'Xenova/all-mpnet-base-v2',
|
||||
dimension: 768,
|
||||
source: 'config',
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to defaults with one warning when the JSON is malformed', async () => {
|
||||
writeConfig('{ "model": "Xenova/all-mpnet-base-v2", ');
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const { resolveEmbeddingConfig } = await freshConfigModule();
|
||||
const cfg = resolveEmbeddingConfig(root);
|
||||
resolveEmbeddingConfig(root);
|
||||
expect(cfg).toMatchObject({ model: 'Xenova/all-MiniLM-L6-v2', dimension: 384, source: 'default' });
|
||||
expect(warn).toHaveBeenCalledTimes(1);
|
||||
expect(String(warn.mock.calls[0][0])).toMatch(/not valid JSON/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('existing store with a different recorded dimension', () => {
|
||||
it('keeps the recorded dimension and warns once instead of mixing vectors', async () => {
|
||||
writeConfig(JSON.stringify(MPNET_CONFIG));
|
||||
const dbPath = await writeStore(384, 'Xenova/all-MiniLM-L6-v2');
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const { resolveEffectiveEmbeddingConfig } = await freshConfigModule();
|
||||
|
||||
const eff = await resolveEffectiveEmbeddingConfig({ root, dbPaths: [dbPath] });
|
||||
await resolveEffectiveEmbeddingConfig({ root, dbPaths: [dbPath] });
|
||||
|
||||
expect(eff).toMatchObject({ model: 'Xenova/all-MiniLM-L6-v2', dimension: 384, source: 'recorded' });
|
||||
expect(warn).toHaveBeenCalledTimes(1);
|
||||
expect(String(warn.mock.calls[0][0])).toMatch(/384-dim vectors.*768-dim/s);
|
||||
});
|
||||
|
||||
it('follows the config when the store holds no real vectors yet', async () => {
|
||||
writeConfig(JSON.stringify(MPNET_CONFIG));
|
||||
const dbPath = await writeStore(128, 'hash-fallback');
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const { resolveEffectiveEmbeddingConfig } = await freshConfigModule();
|
||||
|
||||
const eff = await resolveEffectiveEmbeddingConfig({ root, dbPaths: [dbPath] });
|
||||
expect(eff).toMatchObject({ model: 'Xenova/all-mpnet-base-v2', dimension: 768, source: 'config' });
|
||||
expect(warn).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('memory init (loadEmbeddingModel) uses the resolved config', () => {
|
||||
it('loads MiniLM/384 when nothing is configured (unchanged default)', async () => {
|
||||
const init = await import('../src/memory/memory-initializer.js');
|
||||
const res = await init.loadEmbeddingModel();
|
||||
expect(local.hfModels).toEqual(['Xenova/all-MiniLM-L6-v2']);
|
||||
expect(res).toMatchObject({ success: true, dimensions: 384, modelName: 'Xenova/all-MiniLM-L6-v2' });
|
||||
});
|
||||
|
||||
it('loads the configured 768-dim model', async () => {
|
||||
writeConfig(JSON.stringify(MPNET_CONFIG));
|
||||
const init = await import('../src/memory/memory-initializer.js');
|
||||
const res = await init.loadEmbeddingModel();
|
||||
expect(local.hfModels).toEqual(['Xenova/all-mpnet-base-v2']);
|
||||
expect(res).toMatchObject({ success: true, dimensions: 768, modelName: 'Xenova/all-mpnet-base-v2' });
|
||||
});
|
||||
|
||||
it('keeps an existing 384-dim store on MiniLM and warns', async () => {
|
||||
writeConfig(JSON.stringify(MPNET_CONFIG));
|
||||
await writeStore(384, 'Xenova/all-MiniLM-L6-v2');
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const init = await import('../src/memory/memory-initializer.js');
|
||||
const res = await init.loadEmbeddingModel();
|
||||
expect(local.hfModels).toEqual(['Xenova/all-MiniLM-L6-v2']);
|
||||
expect(res.dimensions).toBe(384);
|
||||
expect(warn.mock.calls.filter((c) => /Keeping 384 dimensions/.test(String(c[0])))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('seeds a fresh store\'s vector_indexes with the configured dimension', async () => {
|
||||
const init = await import('../src/memory/memory-initializer.js');
|
||||
const sql = init.getInitialMetadata('hybrid', 768);
|
||||
expect(sql).toMatch(/\('default', 'default', 768\)/);
|
||||
expect(init.getInitialMetadata('hybrid')).toMatch(/\('default', 'default', 384\)/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('task-embedder uses the resolved config', () => {
|
||||
it('loads MiniLM when nothing is configured', async () => {
|
||||
const te = await import('../src/ruvector/task-embedder.js');
|
||||
te.__resetTaskEmbedderForTests();
|
||||
const v = await te.embedTaskWithCache('route this task');
|
||||
expect(local.xenModels).toEqual(['Xenova/all-MiniLM-L6-v2']);
|
||||
expect(v).toHaveLength(384);
|
||||
});
|
||||
|
||||
it('loads the configured 768-dim model', async () => {
|
||||
writeConfig(JSON.stringify(MPNET_CONFIG));
|
||||
const te = await import('../src/ruvector/task-embedder.js');
|
||||
te.__resetTaskEmbedderForTests();
|
||||
const v = await te.embedTaskWithCache('route this task');
|
||||
expect(local.xenModels).toEqual(['Xenova/all-mpnet-base-v2']);
|
||||
expect(v).toHaveLength(768);
|
||||
});
|
||||
});
|
||||
|
||||
describe('AgentDB bridge registry uses the resolved config', () => {
|
||||
class RecordingRegistry {
|
||||
static options: Array<{ dbPath: string; embeddingModel: string; dimension: number }> = [];
|
||||
async initialize(options: { dbPath: string; embeddingModel: string; dimension: number }) {
|
||||
RecordingRegistry.options.push(options);
|
||||
}
|
||||
get() { return null; }
|
||||
getAgentDB() { return null; }
|
||||
async shutdown() {}
|
||||
}
|
||||
|
||||
async function openBridge() {
|
||||
delete process.env.CLAUDE_FLOW_DISABLE_BRIDGE;
|
||||
RecordingRegistry.options = [];
|
||||
const bridge = await import('../src/memory/memory-bridge.js');
|
||||
bridge._resetRegistryCacheForTest();
|
||||
bridge.__setMemoryBridgeRegistryFactoryForTests(() => new RecordingRegistry());
|
||||
const agentdbPath = join(root, '.swarm', 'agentdb-memory.db');
|
||||
expect(await bridge.getControllerRegistry(agentdbPath)).not.toBeNull();
|
||||
await bridge.shutdownBridge();
|
||||
return RecordingRegistry.options;
|
||||
}
|
||||
|
||||
it('opens AgentDB with MiniLM/384 when nothing is configured', async () => {
|
||||
const [opts] = await openBridge();
|
||||
expect(opts).toMatchObject({ embeddingModel: 'Xenova/all-MiniLM-L6-v2', dimension: 384 });
|
||||
});
|
||||
|
||||
it('opens AgentDB with the configured 768-dim model', async () => {
|
||||
writeConfig(JSON.stringify(MPNET_CONFIG));
|
||||
const [opts] = await openBridge();
|
||||
expect(opts).toMatchObject({ embeddingModel: 'Xenova/all-mpnet-base-v2', dimension: 768 });
|
||||
});
|
||||
|
||||
it('keeps 384 when only memory.db holds 384-dim vectors, so the bridge cannot mix stores', async () => {
|
||||
writeConfig(JSON.stringify(MPNET_CONFIG));
|
||||
await writeStore(384, 'Xenova/all-MiniLM-L6-v2'); // memory.db only; agentdb-memory.db absent
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const [opts] = await openBridge();
|
||||
expect(opts).toMatchObject({ embeddingModel: 'Xenova/all-MiniLM-L6-v2', dimension: 384 });
|
||||
expect(warn.mock.calls.filter((c) => /Keeping 384 dimensions/.test(String(c[0])))).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,295 @@
|
||||
/**
|
||||
* embedding-config.ts — one place that decides which embedding model the
|
||||
* memory path loads and what dimension its vectors have (#2305).
|
||||
*
|
||||
* `embeddings init` (commands/embeddings.ts) and the `embeddings_init` MCP
|
||||
* tool write `<project>/.claude-flow/embeddings.json` with `{ model,
|
||||
* dimension, ... }`. Before this module only those two files read it: the
|
||||
* memory path, the AgentDB bridge and the router's task embedder all loaded
|
||||
* 'Xenova/all-MiniLM-L6-v2' and assumed 384 dimensions regardless of what the
|
||||
* user configured.
|
||||
*
|
||||
* Precedence: `.claude-flow/embeddings.json` → defaults (MiniLM / 384). There
|
||||
* is no embedding-model environment override in this codebase today, so none
|
||||
* is invented here.
|
||||
*
|
||||
* Safety: a store that already holds vectors keeps its recorded dimension.
|
||||
* When the configured dimension differs, `resolveEffectiveEmbeddingConfig()`
|
||||
* returns the recorded shape and warns once — it never mixes dimensions in one
|
||||
* store and never rebuilds or rewrites existing vectors.
|
||||
*/
|
||||
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { readFileMaybeEncrypted } from '../fs-secure.js';
|
||||
import { resolveAgentdbBetterSqlite3 } from './shared-sqlite.js';
|
||||
|
||||
export const DEFAULT_EMBEDDING_MODEL = 'Xenova/all-MiniLM-L6-v2';
|
||||
export const DEFAULT_EMBEDDING_DIMENSION = 384;
|
||||
|
||||
/** Same directory + file name commands/embeddings.ts and embeddings-tools.ts write. */
|
||||
export const EMBEDDINGS_CONFIG_DIR = '.claude-flow';
|
||||
export const EMBEDDINGS_CONFIG_FILE = 'embeddings.json';
|
||||
|
||||
/** Output dimension of models the CLI offers (`embeddings init`, `init --embedding-model`). */
|
||||
const KNOWN_MODELS: ReadonlyArray<{ id: string; dimension: number }> = [
|
||||
{ id: DEFAULT_EMBEDDING_MODEL, dimension: DEFAULT_EMBEDDING_DIMENSION },
|
||||
{ id: 'Xenova/all-mpnet-base-v2', dimension: 768 },
|
||||
{ id: 'Xenova/bge-small-en-v1.5', dimension: 384 },
|
||||
];
|
||||
|
||||
export interface EmbeddingConfig {
|
||||
/** Model id passed to the transformers `pipeline()` (always namespaced, e.g. `Xenova/...`). */
|
||||
model: string;
|
||||
dimension: number;
|
||||
/** `config` = read from embeddings.json; `recorded` = kept from an existing store; `default` otherwise. */
|
||||
source: 'default' | 'config' | 'recorded';
|
||||
configPath: string;
|
||||
}
|
||||
|
||||
/** Shape of the vectors an existing store already holds. */
|
||||
export interface RecordedEmbeddingShape {
|
||||
dimension: number;
|
||||
model?: string | null;
|
||||
}
|
||||
|
||||
export type RecordedShapeReader = (dbPath: string) => Promise<RecordedEmbeddingShape | null>;
|
||||
|
||||
const configCache = new Map<string, EmbeddingConfig>();
|
||||
const effectiveCache = new Map<string, Promise<EmbeddingConfig>>();
|
||||
const warned = new Set<string>();
|
||||
|
||||
function warnOnce(key: string, message: string): void {
|
||||
if (warned.has(key)) return;
|
||||
warned.add(key);
|
||||
console.warn(message);
|
||||
}
|
||||
|
||||
function knownDimension(model: string): number | undefined {
|
||||
const base = model.split('/').pop()?.toLowerCase() ?? '';
|
||||
return KNOWN_MODELS.find((m) => m.id.split('/').pop()!.toLowerCase() === base)?.dimension;
|
||||
}
|
||||
|
||||
/**
|
||||
* `embeddings init` records the bare name it was given (default
|
||||
* `all-MiniLM-L6-v2`), while the MCP tool records `Xenova/...`. The
|
||||
* transformers pipeline needs the namespaced id, so bare names get `Xenova/`.
|
||||
*/
|
||||
export function normalizeEmbeddingModel(model: string): string {
|
||||
const trimmed = model.trim();
|
||||
return trimmed.includes('/') ? trimmed : `Xenova/${trimmed}`;
|
||||
}
|
||||
|
||||
function defaults(configPath: string): EmbeddingConfig {
|
||||
return {
|
||||
model: DEFAULT_EMBEDDING_MODEL,
|
||||
dimension: DEFAULT_EMBEDDING_DIMENSION,
|
||||
source: 'default',
|
||||
configPath,
|
||||
};
|
||||
}
|
||||
|
||||
function isPositiveInt(v: unknown): v is number {
|
||||
return typeof v === 'number' && Number.isInteger(v) && v > 0;
|
||||
}
|
||||
|
||||
function readConfigFile(configPath: string): EmbeddingConfig {
|
||||
if (!fs.existsSync(configPath)) return defaults(configPath);
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
} catch (err) {
|
||||
warnOnce(
|
||||
`malformed:${configPath}`,
|
||||
`[embeddings] ${configPath} is not valid JSON (${err instanceof Error ? err.message : String(err)}); ` +
|
||||
`using the default embedding model ${DEFAULT_EMBEDDING_MODEL} (${DEFAULT_EMBEDDING_DIMENSION}-dim).`,
|
||||
);
|
||||
return defaults(configPath);
|
||||
}
|
||||
|
||||
const obj = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
||||
? (parsed as Record<string, unknown>)
|
||||
: null;
|
||||
const rawModel = obj && typeof obj.model === 'string' && obj.model.trim() ? obj.model : null;
|
||||
if (!rawModel) {
|
||||
warnOnce(
|
||||
`nomodel:${configPath}`,
|
||||
`[embeddings] ${configPath} has no "model" string; ` +
|
||||
`using the default embedding model ${DEFAULT_EMBEDDING_MODEL} (${DEFAULT_EMBEDDING_DIMENSION}-dim).`,
|
||||
);
|
||||
return defaults(configPath);
|
||||
}
|
||||
|
||||
const model = normalizeEmbeddingModel(rawModel);
|
||||
const dimension = isPositiveInt(obj!.dimension) ? obj!.dimension : knownDimension(model);
|
||||
if (dimension === undefined) {
|
||||
warnOnce(
|
||||
`nodim:${configPath}`,
|
||||
`[embeddings] ${configPath} sets model "${rawModel}" without a valid "dimension", and its ` +
|
||||
`dimension is not known; using the default embedding model ${DEFAULT_EMBEDDING_MODEL} ` +
|
||||
`(${DEFAULT_EMBEDDING_DIMENSION}-dim).`,
|
||||
);
|
||||
return defaults(configPath);
|
||||
}
|
||||
return { model, dimension, source: 'config', configPath };
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the configured embedding model + dimension for a project root
|
||||
* (default: cwd, which is where `embeddings init` writes its config).
|
||||
* Cached per root; never throws.
|
||||
*/
|
||||
export function resolveEmbeddingConfig(root: string = process.cwd()): EmbeddingConfig {
|
||||
const configPath = path.join(path.resolve(root), EMBEDDINGS_CONFIG_DIR, EMBEDDINGS_CONFIG_FILE);
|
||||
const cached = configCache.get(configPath);
|
||||
if (cached) return cached;
|
||||
const resolved = readConfigFile(configPath);
|
||||
configCache.set(configPath, resolved);
|
||||
return resolved;
|
||||
}
|
||||
|
||||
/** Pick a model that produces `dimension`-dim vectors, preferring what the store recorded. */
|
||||
function modelForRecorded(recorded: RecordedEmbeddingShape, configured: EmbeddingConfig): string {
|
||||
const recordedModel = recorded.model ? normalizeEmbeddingModel(recorded.model) : null;
|
||||
if (recordedModel && knownDimension(recordedModel) === recorded.dimension) return recordedModel;
|
||||
// KNOWN_MODELS lists the default first, so a 384-dim store maps to MiniLM.
|
||||
const known = KNOWN_MODELS.find((m) => m.dimension === recorded.dimension);
|
||||
return known?.id ?? recordedModel ?? configured.model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep an existing store's recorded dimension when it differs from the
|
||||
* configured one. Warns once per store; returns the configured value
|
||||
* untouched when there is nothing recorded or the dimensions agree.
|
||||
*/
|
||||
export function reconcileWithRecordedShape(
|
||||
configured: EmbeddingConfig,
|
||||
recorded: RecordedEmbeddingShape | null,
|
||||
storeLabel: string,
|
||||
): EmbeddingConfig {
|
||||
if (!recorded || !isPositiveInt(recorded.dimension) || recorded.dimension === configured.dimension) {
|
||||
return configured;
|
||||
}
|
||||
const model = modelForRecorded(recorded, configured);
|
||||
warnOnce(
|
||||
`mismatch:${storeLabel}`,
|
||||
`[embeddings] ${storeLabel} already holds ${recorded.dimension}-dim vectors, but the configured ` +
|
||||
`embedding model ${configured.model} produces ${configured.dimension}-dim vectors ` +
|
||||
`(${configured.configPath}). Keeping ${recorded.dimension} dimensions (${model}) for this store so ` +
|
||||
`vectors are not mixed; nothing was rebuilt. To switch models, start a new memory store.`,
|
||||
);
|
||||
return { model, dimension: recorded.dimension, source: 'recorded', configPath: configured.configPath };
|
||||
}
|
||||
|
||||
/** The most recently written real (non-hash) vector. */
|
||||
const RECORDED_SHAPE_SQL = `
|
||||
SELECT embedding_dimensions, embedding_model FROM memory_entries
|
||||
WHERE embedding IS NOT NULL AND embedding_dimensions > 0
|
||||
AND COALESCE(embedding_model, '') NOT LIKE '%hash%'
|
||||
ORDER BY rowid DESC LIMIT 1
|
||||
`;
|
||||
|
||||
function toShape(dim: unknown, model: unknown): RecordedEmbeddingShape | null {
|
||||
const dimension = Number(dim);
|
||||
if (!isPositiveInt(dimension)) return null;
|
||||
return { dimension, model: model == null ? null : String(model) };
|
||||
}
|
||||
|
||||
type NativeReadResult = { ok: true; shape: RecordedEmbeddingShape | null } | { ok: false };
|
||||
|
||||
/**
|
||||
* Readonly native open: cheap, no whole-file load. Uses the better-sqlite3
|
||||
* copy AgentDB uses (#3693), so closing it cannot strip AgentDB's WAL.
|
||||
* Fails (→ sql.js) on an encrypted file or when no native driver exists.
|
||||
*/
|
||||
function readShapeNative(dbPath: string): NativeReadResult {
|
||||
const Database = resolveAgentdbBetterSqlite3();
|
||||
if (!Database) return { ok: false };
|
||||
let db: { prepare(sql: string): { get(): unknown }; close(): void } | undefined;
|
||||
try {
|
||||
db = new Database(dbPath, { readonly: true, fileMustExist: true });
|
||||
const row = db!.prepare(RECORDED_SHAPE_SQL).get() as
|
||||
| { embedding_dimensions?: unknown; embedding_model?: unknown }
|
||||
| undefined;
|
||||
return { ok: true, shape: row ? toShape(row.embedding_dimensions, row.embedding_model) : null };
|
||||
} catch {
|
||||
return { ok: false };
|
||||
} finally {
|
||||
try { db?.close(); } catch { /* best-effort */ }
|
||||
}
|
||||
}
|
||||
|
||||
async function readShapeSqlJs(dbPath: string): Promise<RecordedEmbeddingShape | null> {
|
||||
const initSqlJs = (await import('sql.js')).default;
|
||||
const SQL = await initSqlJs();
|
||||
const db = new SQL.Database(readFileMaybeEncrypted(dbPath, null));
|
||||
try {
|
||||
const row = db.exec(RECORDED_SHAPE_SQL)[0]?.values?.[0];
|
||||
return row ? toShape(row[0], row[1]) : null;
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Default reader: the most recently written real (non-hash) vector in
|
||||
* `memory_entries`. A store with no such vector records nothing, so a fresh
|
||||
* or empty database follows the configuration.
|
||||
*/
|
||||
export const readRecordedEmbeddingShape: RecordedShapeReader = async (dbPath) => {
|
||||
if (dbPath === ':memory:' || !fs.existsSync(dbPath)) return null;
|
||||
const native = readShapeNative(dbPath);
|
||||
if (native.ok) return native.shape;
|
||||
try {
|
||||
return await readShapeSqlJs(dbPath);
|
||||
} catch {
|
||||
// Unreadable / legacy schema — nothing recorded we can trust.
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The embedding config to actually use: the configured model, unless one of
|
||||
* the stores in `dbPaths` already holds vectors of another dimension. The
|
||||
* memory path writes the same vectors to memory.db and (through the AgentDB
|
||||
* bridge) agentdb-memory.db, so callers pass both and every caller converges
|
||||
* on one answer: the first store with recorded vectors wins. Cached per
|
||||
* (root, dbPaths).
|
||||
*/
|
||||
export function resolveEffectiveEmbeddingConfig(options: {
|
||||
root?: string;
|
||||
dbPaths?: ReadonlyArray<string | undefined>;
|
||||
readRecordedShape?: RecordedShapeReader;
|
||||
} = {}): Promise<EmbeddingConfig> {
|
||||
const root = path.resolve(options.root ?? process.cwd());
|
||||
const dbPaths = (options.dbPaths ?? [])
|
||||
.filter((p): p is string => typeof p === 'string' && p.length > 0 && p !== ':memory:')
|
||||
.map((p) => path.resolve(p));
|
||||
const key = `${root}\0${dbPaths.join('\0')}`;
|
||||
const cached = effectiveCache.get(key);
|
||||
if (cached) return cached;
|
||||
const configured = resolveEmbeddingConfig(root);
|
||||
const reader = options.readRecordedShape ?? readRecordedEmbeddingShape;
|
||||
const pending = (async () => {
|
||||
for (const dbPath of dbPaths) {
|
||||
let recorded: RecordedEmbeddingShape | null = null;
|
||||
try {
|
||||
recorded = await reader(dbPath);
|
||||
} catch {
|
||||
recorded = null;
|
||||
}
|
||||
if (recorded) return reconcileWithRecordedShape(configured, recorded, dbPath);
|
||||
}
|
||||
return configured;
|
||||
})();
|
||||
effectiveCache.set(key, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** Test seam: forget cached resolutions and emitted warnings. */
|
||||
export function _resetEmbeddingConfigCache(): void {
|
||||
configCache.clear();
|
||||
effectiveCache.clear();
|
||||
warned.clear();
|
||||
}
|
||||
@@ -28,6 +28,12 @@ import { mkdirSync, realpathSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
import { validateFeedbackPatterns } from './feedback-patterns.js';
|
||||
import {
|
||||
DEFAULT_EMBEDDING_MODEL,
|
||||
resolveEffectiveEmbeddingConfig,
|
||||
resolveEmbeddingConfig,
|
||||
type EmbeddingConfig,
|
||||
} from './embedding-config.js';
|
||||
|
||||
// ===== Lazy registry cache, keyed by database path =====
|
||||
|
||||
@@ -48,6 +54,25 @@ import { validateFeedbackPatterns } from './feedback-patterns.js';
|
||||
*/
|
||||
const registryPromises = new Map<string, Promise<any>>();
|
||||
const registryInstances = new Map<string, any>();
|
||||
|
||||
/**
|
||||
* #2305: the embedding model/dimension the AgentDB registry was opened with —
|
||||
* `.claude-flow/embeddings.json`, or the store's recorded dimension when that
|
||||
* differs. Falls back to the configured value before any registry opened.
|
||||
*/
|
||||
let bridgeEmbeddingConfig: EmbeddingConfig | null = null;
|
||||
|
||||
function activeEmbeddingConfig(): EmbeddingConfig {
|
||||
return bridgeEmbeddingConfig ?? resolveEmbeddingConfig(process.cwd());
|
||||
}
|
||||
|
||||
/** Model name recorded next to a vector of `dimension` length. */
|
||||
function embeddingModelLabel(dimension: number): string {
|
||||
const cfg = activeEmbeddingConfig();
|
||||
if (dimension === cfg.dimension) return cfg.model;
|
||||
// Unchanged pre-#2305 label for any other size.
|
||||
return DEFAULT_EMBEDDING_MODEL;
|
||||
}
|
||||
// One lease spans an entire bridge operation, including its awaited controller
|
||||
// effects and nested bridge calls. Initializer ownership alone is insufficient:
|
||||
// a ReasoningBank write can still be pending after its registry has opened.
|
||||
@@ -288,11 +313,22 @@ async function getRegistry(dbPath?: string): Promise<any | null> {
|
||||
// lifetime and hierarchical memory silently ran volatile.
|
||||
try {
|
||||
if (resolvedPath !== ':memory:') mkdirSync(path.dirname(resolvedPath), { recursive: true });
|
||||
// Check memory.db as well as this store: the memory path mirrors
|
||||
// the same vectors into both, so an old 384-dim memory.db must keep
|
||||
// an empty agentdb-memory.db at 384 too (same order as the
|
||||
// initializer, so both converge on one answer).
|
||||
const embCfg = await resolveEffectiveEmbeddingConfig({
|
||||
root: process.cwd(),
|
||||
dbPaths: resolvedPath === ':memory:'
|
||||
? []
|
||||
: [path.join(path.dirname(resolvedPath), 'memory.db'), resolvedPath],
|
||||
});
|
||||
bridgeEmbeddingConfig = embCfg;
|
||||
await (registry as any).initialize({
|
||||
// #2786: use agentdb-memory.db (plaintext) so native better-sqlite3 doesn't hit the encrypted memory.db.
|
||||
dbPath: resolvedPath,
|
||||
embeddingModel: 'Xenova/all-MiniLM-L6-v2',
|
||||
dimension: 384,
|
||||
embeddingModel: embCfg.model,
|
||||
dimension: embCfg.dimension,
|
||||
vectorBackend: 'auto',
|
||||
controllers: {
|
||||
reasoningBank: true,
|
||||
@@ -542,6 +578,7 @@ export function _resetRegistryCacheForTest(): void {
|
||||
testRegistryOverride = null;
|
||||
testRegistryFactory = null;
|
||||
bridgeFailureReasons.clear();
|
||||
bridgeEmbeddingConfig = null;
|
||||
}
|
||||
|
||||
/** Inject registry construction without requiring the optional native package in tests. */
|
||||
@@ -1033,7 +1070,7 @@ async function embedForBridge(
|
||||
try {
|
||||
const emb = await embedder.embed(text);
|
||||
if (emb && emb.length > 0) {
|
||||
return { vector: Array.from(emb), model: 'Xenova/all-MiniLM-L6-v2' };
|
||||
return { vector: Array.from(emb), model: embeddingModelLabel(emb.length) };
|
||||
}
|
||||
agentdbProblem = 'agentdb embedder returned no vector';
|
||||
} catch (err) {
|
||||
@@ -2091,18 +2128,19 @@ export async function bridgeGenerateEmbedding(
|
||||
// yet) and silently fall back to a 128-dim hash stub. The embedder doesn't
|
||||
// expose isMock=true in that path, so the wrapper above was reporting
|
||||
// backend='onnx' on what's actually 128-dim hash garbage. The model name
|
||||
// we hardcode ('Xenova/all-MiniLM-L6-v2') always produces 384-dim, so a
|
||||
// dimensions mismatch is a definitive stub signal: return null and let
|
||||
// the caller fall through to generateLocalEmbedding which routes to
|
||||
// transformers.js / ruvector ONNX directly.
|
||||
if (emb.length !== 384) {
|
||||
// the registry was opened with (#2305: from embeddings.json, default
|
||||
// MiniLM/384) has a fixed dimension, so a dimensions mismatch is a
|
||||
// definitive stub signal: return null and let the caller fall through to
|
||||
// generateLocalEmbedding which routes to transformers.js / ruvector ONNX.
|
||||
const embCfg = activeEmbeddingConfig();
|
||||
if (emb.length !== embCfg.dimension) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
embedding: Array.from(emb),
|
||||
dimensions: emb.length,
|
||||
model: 'Xenova/all-MiniLM-L6-v2',
|
||||
model: embCfg.model,
|
||||
backend: isMock ? 'mock' : 'onnx',
|
||||
};
|
||||
} catch {
|
||||
@@ -2139,7 +2177,7 @@ export async function bridgeLoadEmbeddingModel(
|
||||
return {
|
||||
success: true,
|
||||
dimensions: test.length,
|
||||
modelName: 'Xenova/all-MiniLM-L6-v2',
|
||||
modelName: embeddingModelLabel(test.length),
|
||||
loadTime: Date.now() - startTime,
|
||||
};
|
||||
} catch {
|
||||
@@ -2406,7 +2444,7 @@ export async function bridgeAddEmbedding(
|
||||
id, key, namespace, content, type,
|
||||
embedding, embedding_dimensions, embedding_model,
|
||||
created_at, updated_at, status
|
||||
) VALUES (?, ?, ?, ?, 'semantic', ?, ?, 'Xenova/all-MiniLM-L6-v2', ?, ?, 'active')
|
||||
) VALUES (?, ?, ?, ?, 'semantic', ?, ?, ?, ?, ?, 'active')
|
||||
ON CONFLICT(namespace, key) DO UPDATE SET
|
||||
id = excluded.id,
|
||||
content = excluded.content,
|
||||
@@ -2418,7 +2456,7 @@ export async function bridgeAddEmbedding(
|
||||
status = 'active'
|
||||
`).run(
|
||||
id, entry.key, entry.namespace, entry.content,
|
||||
embeddingJson, embedding.length,
|
||||
embeddingJson, embedding.length, embeddingModelLabel(embedding.length),
|
||||
now, now,
|
||||
);
|
||||
return true;
|
||||
@@ -2542,6 +2580,7 @@ export function __setMemoryBridgeRegistryForTests(registry: any | null): void {
|
||||
testRegistryOverride = registry;
|
||||
testRegistryFactory = null;
|
||||
bridgeFailureReasons.clear();
|
||||
bridgeEmbeddingConfig = null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -20,6 +20,12 @@ import * as path from 'path';
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
import { createRequire } from 'node:module';
|
||||
import { readFileMaybeEncrypted, writeDbImagePreservingFormat, writeFileAtomic, writeFileRestricted } from '../fs-secure.js';
|
||||
import {
|
||||
_resetEmbeddingConfigCache,
|
||||
DEFAULT_EMBEDDING_DIMENSION,
|
||||
resolveEffectiveEmbeddingConfig,
|
||||
resolveEmbeddingConfig,
|
||||
} from './embedding-config.js';
|
||||
import { restoreMemoryDbFromBackup } from '../services/memory-backup.js';
|
||||
import { validateIdentifier } from '../mcp-tools/validate-input.js';
|
||||
import { resolveModelCacheDir } from './model-cache-dir.js';
|
||||
@@ -1283,7 +1289,7 @@ export function flashAttentionSearch(
|
||||
/**
|
||||
* Initial metadata to insert after schema creation
|
||||
*/
|
||||
export function getInitialMetadata(backend: string): string {
|
||||
export function getInitialMetadata(backend: string, dimension: number = DEFAULT_EMBEDDING_DIMENSION): string {
|
||||
return `
|
||||
INSERT OR REPLACE INTO metadata (key, value) VALUES
|
||||
('schema_version', '3.0.0'),
|
||||
@@ -1295,13 +1301,13 @@ INSERT OR REPLACE INTO metadata (key, value) VALUES
|
||||
('temporal_decay', 'enabled'),
|
||||
('hnsw_indexing', 'enabled');
|
||||
|
||||
-- Create default vector index configuration. Dimension matches the default
|
||||
-- ONNX embedding model (Xenova/all-MiniLM-L6-v2, 384-dim); HNSW rejects
|
||||
-- inserts whose dim does not match this row, so a 768 here breaks every
|
||||
-- memory_store --vector and memory_search on a fresh install (#1947).
|
||||
-- Create default vector index configuration. Dimension matches the
|
||||
-- configured embedding model (#2305; default Xenova/all-MiniLM-L6-v2,
|
||||
-- 384-dim); HNSW rejects inserts whose dim does not match this row, so a
|
||||
-- mismatch here breaks every memory_store --vector and memory_search (#1947).
|
||||
INSERT OR IGNORE INTO vector_indexes (id, name, dimensions) VALUES
|
||||
('default', 'default', 384),
|
||||
('patterns', 'patterns', 384);
|
||||
('default', 'default', ${dimension}),
|
||||
('patterns', 'patterns', ${dimension});
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -1971,6 +1977,8 @@ export async function initializeMemoryDatabase(options: {
|
||||
// Load existing database or create new
|
||||
if (fs.existsSync(dbPath) && force) {
|
||||
fs.unlinkSync(dbPath);
|
||||
// #2305: the recorded dimension of the deleted store no longer binds.
|
||||
_resetEmbeddingConfigCache();
|
||||
}
|
||||
|
||||
db = new SQL.Database();
|
||||
@@ -1987,7 +1995,7 @@ export async function initializeMemoryDatabase(options: {
|
||||
db.run(MEMORY_SCHEMA_V3);
|
||||
|
||||
// Insert initial metadata
|
||||
db.run(getInitialMetadata(backend));
|
||||
db.run(getInitialMetadata(backend, resolveEmbeddingConfig(process.cwd()).dimension));
|
||||
|
||||
// Save to file
|
||||
const data = db.export();
|
||||
@@ -1999,7 +2007,7 @@ export async function initializeMemoryDatabase(options: {
|
||||
|
||||
// Also create schema file for reference
|
||||
const schemaPath = path.join(dbDir, 'schema.sql');
|
||||
fs.writeFileSync(schemaPath, MEMORY_SCHEMA_V3 + '\n' + getInitialMetadata(backend));
|
||||
fs.writeFileSync(schemaPath, MEMORY_SCHEMA_V3 + '\n' + getInitialMetadata(backend, resolveEmbeddingConfig(process.cwd()).dimension));
|
||||
|
||||
// ADR-053: Activate ControllerRegistry so controllers (ReasoningBank,
|
||||
// SkillLibrary, ExplainableRecall, etc.) are instantiated during init
|
||||
@@ -2048,7 +2056,7 @@ export async function initializeMemoryDatabase(options: {
|
||||
} else {
|
||||
// Fall back to schema file approach
|
||||
const schemaPath = path.join(dbDir, 'schema.sql');
|
||||
fs.writeFileSync(schemaPath, MEMORY_SCHEMA_V3 + '\n' + getInitialMetadata(backend));
|
||||
fs.writeFileSync(schemaPath, MEMORY_SCHEMA_V3 + '\n' + getInitialMetadata(backend, resolveEmbeddingConfig(process.cwd()).dimension));
|
||||
|
||||
// Create minimal valid SQLite file
|
||||
const sqliteHeader = Buffer.alloc(4096, 0);
|
||||
@@ -2355,6 +2363,20 @@ async function loadLocalEmbeddingChain(verbose = false, startTime = Date.now()):
|
||||
|
||||
let sawRetryableFailure = false;
|
||||
|
||||
// #2305: honour `.claude-flow/embeddings.json` instead of always loading
|
||||
// MiniLM/384 — unless the memory store already holds vectors of another
|
||||
// dimension, in which case its recorded dimension is kept (with a warning).
|
||||
// Both stores the memory path writes vectors to are checked, in the same
|
||||
// order the bridge uses, so the local chain and the bridge agree.
|
||||
const memoryDbPath = resolveDbPath();
|
||||
const embCfg = await resolveEffectiveEmbeddingConfig({
|
||||
root: process.cwd(),
|
||||
dbPaths: [memoryDbPath, path.join(path.dirname(memoryDbPath), 'agentdb-memory.db')],
|
||||
});
|
||||
// The agentic-flow and ruvector fallbacks below bundle MiniLM only; using
|
||||
// them for any other configured dimension would mix vector sizes.
|
||||
const bundledMiniLmFits = embCfg.dimension === DEFAULT_EMBEDDING_DIMENSION;
|
||||
|
||||
try {
|
||||
// ADR-094: prefer @huggingface/transformers (clears protobufjs <7.5.5
|
||||
// critical RCE chain), fall back to legacy @xenova/transformers.
|
||||
@@ -2396,7 +2418,7 @@ async function loadLocalEmbeddingChain(verbose = false, startTime = Date.now()):
|
||||
// (reading 'model')" on every memory store / search call.
|
||||
try {
|
||||
if (verbose) {
|
||||
console.log(`Loading ONNX embedding model via ${transformersSource} (all-MiniLM-L6-v2)...`);
|
||||
console.log(`Loading ONNX embedding model via ${transformersSource} (${embCfg.model})...`);
|
||||
}
|
||||
|
||||
// ADR-454: route model downloads to a user-writable cache dir —
|
||||
@@ -2407,19 +2429,19 @@ async function loadLocalEmbeddingChain(verbose = false, startTime = Date.now()):
|
||||
const env = transformersModule?.env as { cacheDir: string } | undefined;
|
||||
if (env) env.cacheDir = cacheDir;
|
||||
|
||||
const embedder = await pipelineFn('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
|
||||
const embedder = await pipelineFn('feature-extraction', embCfg.model);
|
||||
|
||||
embeddingModelState = {
|
||||
loaded: true,
|
||||
model: embedder,
|
||||
tokenizer: null,
|
||||
dimensions: 384 // MiniLM-L6 produces 384-dim vectors
|
||||
dimensions: embCfg.dimension
|
||||
};
|
||||
|
||||
return {
|
||||
success: true,
|
||||
dimensions: 384,
|
||||
modelName: 'Xenova/all-MiniLM-L6-v2',
|
||||
dimensions: embCfg.dimension,
|
||||
modelName: embCfg.model,
|
||||
loadTime: Date.now() - startTime
|
||||
};
|
||||
} catch (err) {
|
||||
@@ -2440,7 +2462,7 @@ async function loadLocalEmbeddingChain(verbose = false, startTime = Date.now()):
|
||||
// Fallback: Check for agentic-flow ReasoningBank embeddings (v3)
|
||||
const reasoningBank = await import('agentic-flow/reasoningbank').catch(() => null);
|
||||
|
||||
if (reasoningBank?.computeEmbedding) {
|
||||
if (bundledMiniLmFits && reasoningBank?.computeEmbedding) {
|
||||
if (verbose) {
|
||||
console.log('Loading agentic-flow ReasoningBank embedding model...');
|
||||
}
|
||||
@@ -2479,7 +2501,7 @@ async function loadLocalEmbeddingChain(verbose = false, startTime = Date.now()):
|
||||
if (onnxEmb?.embed) {
|
||||
// Probe embed to trigger lazy ONNX init and verify it works
|
||||
const probe = await onnxEmb.embed('test');
|
||||
if (probe && probe.length > 0 && (Array.isArray(probe) ? probe.some((v: number) => v !== 0) : true)) {
|
||||
if (probe && probe.length > 0 && probe.length === embCfg.dimension && (Array.isArray(probe) ? probe.some((v: number) => v !== 0) : true)) {
|
||||
if (verbose) {
|
||||
console.log(`Loading ruvector ONNX embedder (all-MiniLM-L6-v2, ${probe.length}d)...`);
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
|
||||
import * as fs from 'node:fs';
|
||||
import { resolveModelCacheDir } from '../memory/model-cache-dir.js';
|
||||
import { resolveEmbeddingConfig } from '../memory/embedding-config.js';
|
||||
|
||||
// ============================================================================
|
||||
// FNV-1a-32 hash (matches scripts/gen-seed-corpus.mjs + router-trajectory.ts)
|
||||
@@ -93,7 +94,9 @@ function loadExtractor(): Promise<ExtractorFn | null> {
|
||||
const env = (mod as Record<string, unknown>).env as { cacheDir: string } | undefined;
|
||||
if (env) env.cacheDir = cacheDir;
|
||||
|
||||
const extractor = await mod.pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2', { quantized: true });
|
||||
// #2305: honour `.claude-flow/embeddings.json` (default MiniLM/384).
|
||||
const { model } = resolveEmbeddingConfig(process.cwd());
|
||||
const extractor = await mod.pipeline('feature-extraction', model, { quantized: true });
|
||||
_extractorDegradedReason = null;
|
||||
return extractor;
|
||||
} catch {
|
||||
@@ -125,7 +128,7 @@ async function loadEmbedderBatch(): Promise<EmbedBatchFn | null> {
|
||||
if (!ex) return null;
|
||||
return async (texts: string[]): Promise<number[][]> => {
|
||||
const out = await ex(texts, { pooling: 'mean', normalize: true });
|
||||
const dims = out.dims ?? [texts.length, 384];
|
||||
const dims = out.dims ?? [texts.length, resolveEmbeddingConfig(process.cwd()).dimension];
|
||||
const N = dims[0] ?? texts.length;
|
||||
const dim = dims[1] ?? Math.floor(out.data.length / N);
|
||||
const data = out.data;
|
||||
@@ -175,7 +178,8 @@ function lruSet(key: string, value: number[]): void {
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Compute (or fetch from cache) the 384-dim MiniLM embedding for `task`.
|
||||
* Compute (or fetch from cache) the embedding for `task` with the configured
|
||||
* model (`.claude-flow/embeddings.json`; default 384-dim MiniLM).
|
||||
* Returns `undefined` on any failure (missing @xenova/transformers, ONNX
|
||||
* runtime error, etc.) so callers can gracefully fall back to the
|
||||
* heuristic+bandit path. Best-effort and never throws.
|
||||
|
||||
Reference in new issue
Block a user