tr-plugin-embeddings 0.0.0-stage → 0.2.5

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/cli.mjs ADDED
@@ -0,0 +1,540 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Embeddings CLI Handler
4
+ * Executed via: npx total-recall embeddings <subcommand>
5
+ *
6
+ * Owns local embedding provider discovery and index coverage for a brain:
7
+ * which provider/model actually serves vectors, whether that endpoint is on
8
+ * this host, and how much of the vault has a vector core can still use.
9
+ * Building the index itself stays with `total-recall compile`, which owns the
10
+ * embeddings.db lifecycle; this plugin only ever opens it read-only.
11
+ *
12
+ * The selection and coverage rules mirror total-recall-brain core
13
+ * (src/core/ollama-embeddings.mjs, vault.mjs, embeddings.mjs). Core is not
14
+ * imported: its logger loads config.mjs, which loads the auth owner, and a
15
+ * read-only status must not unlock credentials. See the EMBEDDINGS_CARD
16
+ * architecture decision of 2026-11-05.
17
+ */
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+ import crypto from 'node:crypto';
21
+
22
+ const PLUGIN_ID = 'embeddings';
23
+ const PLUGIN_DIR = path.dirname(new URL(import.meta.url).pathname);
24
+ const PLUGIN_VERSION = JSON.parse(fs.readFileSync(path.join(PLUGIN_DIR, 'plugin.json'), 'utf8')).version;
25
+ const LOOPBACK_URL = 'http://127.0.0.1:11434';
26
+ // The vault index width (core embeddings.mjs EMBEDDING_DIMS). It is a storage
27
+ // constraint of the vss0 table, so a model of any other width is unusable.
28
+ const VAULT_DIMS = 768;
29
+ const PROBE_TIMEOUT_MS = 2500;
30
+ const SHOW_TIMEOUT_MS = 5000;
31
+ const EMBED_TIMEOUT_MS = 30000;
32
+ // The host runner kills a child at the manifest's timeout_ms; stay under it.
33
+ const PULL_DEADLINE_MS = 590000;
34
+ const BENCHMARK_DEADLINE_MS = 280000;
35
+ const BENCHMARK_MAX_SAMPLES = 20;
36
+ // Neutral benchmark input: never vault text, never a real contact.
37
+ const BENCHMARK_TEXT = 'The quick brown fox jumps over the lazy dog while the kettle boils.';
38
+
39
+ /** The brain this invocation targets: project brain when present, else global. */
40
+ function resolveVault() {
41
+ const candidates = [
42
+ path.join(process.cwd(), '.agent', 'skills', 'total-recall'),
43
+ path.join(process.env.HOME || '', '.agent', 'skills', 'total-recall'),
44
+ ];
45
+ for (const dir of candidates) {
46
+ if (dir && fs.existsSync(path.join(dir, 'memory-vault'))) return dir;
47
+ }
48
+ return null;
49
+ }
50
+
51
+ // ─── Provider: the same endpoint and model core would use ────────────────────
52
+
53
+ /** Accepts `host`, `host:port`, or a full URL, as core's normalizeBaseUrl does. */
54
+ export function normalizeBaseUrl(value) {
55
+ const raw = String(value || '').trim();
56
+ if (!raw) return null;
57
+ const withScheme = /^https?:\/\//i.test(raw) ? raw : `http://${raw}`;
58
+ try {
59
+ const u = new URL(withScheme);
60
+ if (u.username || u.password || u.search || u.hash || u.pathname !== '/') return null;
61
+ const authority = withScheme.match(/^https?:\/\/([^/]+)/i)?.[1];
62
+ if (!u.port && u.protocol === 'http:' && !/:\d+$/.test(authority)) u.port = '11434';
63
+ return u.origin;
64
+ } catch { return null; }
65
+ }
66
+
67
+ /** Configured endpoints first, then loopback: core's candidate order. */
68
+ function candidateUrls() {
69
+ const configured = [process.env.TR_OLLAMA_URL, process.env.OLLAMA_HOST].map(normalizeBaseUrl).filter(Boolean);
70
+ return [...new Set([...configured, LOOPBACK_URL])];
71
+ }
72
+
73
+ /** Whether text sent to this endpoint stays on this machine. */
74
+ export function endpointLocality(url) {
75
+ try {
76
+ const host = new URL(url).hostname.replace(/^\[|\]$/g, '');
77
+ if (host === 'localhost' || host === '::1' || /^127\./.test(host)) return 'local';
78
+ return 'remote';
79
+ } catch { return 'unknown'; }
80
+ }
81
+
82
+ async function fetchWithDeadline(url, options, timeoutMs) {
83
+ return fetch(url, { ...options, redirect: 'error', signal: AbortSignal.timeout(timeoutMs) });
84
+ }
85
+
86
+ async function listModels(url) {
87
+ try {
88
+ const res = await fetchWithDeadline(`${url}/api/tags`, {}, PROBE_TIMEOUT_MS);
89
+ if (!res.ok) return { ok: false, reason: `HTTP ${res.status}` };
90
+ const data = await res.json();
91
+ if (!Array.isArray(data?.models)) return { ok: false, reason: 'not an Ollama endpoint (no models array)' };
92
+ return { ok: true, models: data.models };
93
+ } catch (err) {
94
+ return { ok: false, reason: err.message };
95
+ }
96
+ }
97
+
98
+ /** First candidate that answers like Ollama, with every attempt recorded. */
99
+ async function resolveEndpoint() {
100
+ const attempts = [];
101
+ for (const url of candidateUrls()) {
102
+ const listed = await listModels(url);
103
+ attempts.push({ url, reachable: listed.ok, reason: listed.ok ? null : listed.reason });
104
+ if (listed.ok) return { url, models: listed.models, attempts };
105
+ }
106
+ return { url: null, models: [], attempts };
107
+ }
108
+
109
+ async function describeModel(url, name) {
110
+ try {
111
+ const res = await fetchWithDeadline(`${url}/api/show`, {
112
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
113
+ body: JSON.stringify({ model: name }),
114
+ }, SHOW_TIMEOUT_MS);
115
+ if (!res.ok) return null;
116
+ return await res.json();
117
+ } catch { return null; }
118
+ }
119
+
120
+ /** Family-scoped width only: generative models publish other towers' widths too. */
121
+ export function embeddingWidth(info) {
122
+ const family = info?.details?.family;
123
+ const width = family ? info?.model_info?.[`${family}.embedding_length`] : undefined;
124
+ return Number.isFinite(width) ? width : null;
125
+ }
126
+
127
+ /** The declared capability, never a name heuristic. */
128
+ export function canEmbed(info) {
129
+ return Array.isArray(info?.capabilities) && info.capabilities.includes('embedding');
130
+ }
131
+
132
+ /** Every model annotated, plus the one core would select. */
133
+ async function inspectModels(url, models) {
134
+ const preferred = process.env.TR_OLLAMA_EMBED_MODEL || null;
135
+ const rows = [];
136
+ for (const m of models) {
137
+ const name = m.name || m.model;
138
+ if (!name) continue;
139
+ const info = await describeModel(url, name);
140
+ const embeds = info ? canEmbed(info) : false;
141
+ const dims = info ? embeddingWidth(info) : null;
142
+ const upstream = Boolean(m.remote_host || m.remote_model || info?.remote_host || info?.remote_model);
143
+ rows.push({
144
+ name, size: m.size ?? null, described: Boolean(info),
145
+ embedding_capable: embeds, dims, compatible: embeds && dims === VAULT_DIMS, upstream,
146
+ });
147
+ }
148
+ return { rows, selected: chooseModel(rows, preferred), preferred };
149
+ }
150
+
151
+ /** A viable pin wins; otherwise the smallest viable model, as core selects. */
152
+ export function chooseModel(rows, preferred = null) {
153
+ const viable = rows.filter(r => r.compatible);
154
+ const pinned = preferred && viable.find(r => r.name === preferred || r.name.split(':')[0] === preferred);
155
+ if (pinned) return pinned.name;
156
+ viable.sort((a, b) => (a.size ?? Number.MAX_SAFE_INTEGER) - (b.size ?? Number.MAX_SAFE_INTEGER));
157
+ return viable[0]?.name ?? null;
158
+ }
159
+
160
+ /**
161
+ * Which provider core would use and whether the text leaves this host.
162
+ * Hosted fallback keys are resolved by the auth owner, so their availability
163
+ * is reported as unknown rather than guessed from environment variable names.
164
+ */
165
+ async function providerReport() {
166
+ const endpoint = await resolveEndpoint();
167
+ if (!endpoint.url) {
168
+ return { provider: 'hosted-fallback', locality: 'unknown', endpoint: null, selected_model: null, dims: null,
169
+ attempts: endpoint.attempts, models: [], hosted_fallback: 'unknown',
170
+ reason: 'No Ollama endpoint answered; core would try hosted providers whose keys the auth owner resolves.' };
171
+ }
172
+ const inspected = await inspectModels(endpoint.url, endpoint.models);
173
+ if (!inspected.selected) {
174
+ return { provider: 'hosted-fallback', locality: 'unknown', endpoint: endpoint.url, selected_model: null, dims: null,
175
+ attempts: endpoint.attempts, models: inspected.rows, hosted_fallback: 'unknown',
176
+ reason: `No model on ${endpoint.url} declares embedding at ${VAULT_DIMS} dims; core would try hosted providers.` };
177
+ }
178
+ const selected = inspected.rows.find(row => row.name === inspected.selected);
179
+ return { provider: 'ollama', locality: selected.upstream ? 'remote' : endpointLocality(endpoint.url), endpoint: endpoint.url,
180
+ selected_model: inspected.selected, dims: VAULT_DIMS, preferred: inspected.preferred,
181
+ attempts: endpoint.attempts, models: inspected.rows, hosted_fallback: 'not-used',
182
+ reason: selected.upstream ? 'The Ollama service reports an upstream model.' : null };
183
+ }
184
+
185
+ // ─── Coverage: rows core can still use for this vault ────────────────────────
186
+
187
+ const YAML_TAG = /(?:^|[:,\[{-])[ \t]*!!\S/m;
188
+
189
+ /** Core frontmatter.mjs matter(), on the same SSSS parser. Throws on what core refuses. */
190
+ function parseMarkdown(raw, fm) {
191
+ const text = fm.repairEscapedNewlines(raw.replace(/^/, ''));
192
+ const opening = /^---([^\r\n]*)\r?\n/.exec(text);
193
+ if (!opening || opening[1].startsWith('-')) return { data: {}, content: text };
194
+ const language = opening[1].trim().toLowerCase() || 'yaml';
195
+ if (!['yaml', 'yml', 'json'].includes(language)) throw new Error(`Unsupported frontmatter language: ${language}`);
196
+ const remainder = text.slice(opening[0].length);
197
+ const closing = /^---(?:\r?\n|$)/m.exec(remainder);
198
+ const metadata = closing ? remainder.slice(0, closing.index) : remainder;
199
+ if (language !== 'json' && YAML_TAG.test(metadata)) throw new Error('YAML tags are not allowed in frontmatter');
200
+ const data = (language === 'json' ? JSON.parse(metadata || '{}') : fm.parseFrontmatter(metadata.replace(/\r\n/g, '\n'), { strict: true })) || {};
201
+ return { data, content: closing ? remainder.slice(closing.index + closing[0].length) : '' };
202
+ }
203
+
204
+ /** Core vault.mjs walkMd: dot directories and proposals/ are not vault nodes. */
205
+ function walkMd(dir) {
206
+ const out = [];
207
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
208
+ const full = path.join(dir, entry.name);
209
+ if (entry.isDirectory()) {
210
+ if (!entry.name.startsWith('.') && entry.name !== 'proposals') out.push(...walkMd(full));
211
+ } else if (entry.isFile() && entry.name.endsWith('.md')) out.push(full);
212
+ }
213
+ return out;
214
+ }
215
+
216
+ /** Core vault.mjs loadNodes, returning parse failures instead of logging them. */
217
+ export async function loadVaultNodes(vaultDir) {
218
+ const fm = await import('@gregiteen/ssss-cli/frontmatter');
219
+ const nodes = [];
220
+ let parseErrors = 0;
221
+ for (const file of walkMd(vaultDir)) {
222
+ try {
223
+ const { data, content } = parseMarkdown(fs.readFileSync(file, 'utf8'), fm);
224
+ if (data.type !== 'memory' && data.type !== 'plugin_record') continue;
225
+ nodes.push({
226
+ ...data,
227
+ slug: data.slug || (data.plugin_id ? `plugin-${data.plugin_id}` : path.basename(file, '.md')),
228
+ category: data.category || (data.type === 'plugin_record' ? 'plugins' : undefined),
229
+ tags: Array.isArray(data.tags) ? data.tags : (data.use_cases || []),
230
+ body: content.trim(),
231
+ });
232
+ } catch { parseErrors++; }
233
+ }
234
+ return { nodes, parseErrors };
235
+ }
236
+
237
+ /** Core embeddings.mjs nodeToEmbedText: the text whose hash marks a row current. */
238
+ export function nodeToEmbedText(node) {
239
+ const parts = [`Title: ${node.title || node.slug}`];
240
+ if (node.category) parts.push(`Category: ${node.category}`);
241
+ if (node.tags?.length) parts.push(`Tags: ${node.tags.join(', ')}`);
242
+ if (node.description) parts.push(`Description: ${node.description}`);
243
+ if (node.commands?.length) parts.push(`Commands: ${node.commands.join(', ')}`);
244
+ if (node.body) parts.push(`Body: ${node.body.slice(0, 2000)}`);
245
+ return parts.join('\n\n');
246
+ }
247
+
248
+ function validVector(json) {
249
+ try {
250
+ const v = JSON.parse(json);
251
+ if (!Array.isArray(v) || !v.every(Number.isFinite)) return { ok: false, width: null };
252
+ return { ok: v.length === VAULT_DIMS, width: v.length };
253
+ } catch { return { ok: false, width: null }; }
254
+ }
255
+
256
+ /**
257
+ * Classify every index row against the active vault. Only `compatible` rows
258
+ * are vectors core search can use for current content; the rest are named.
259
+ */
260
+ export async function coverage(brainDir) {
261
+ const report = {
262
+ state: 'unknown', reason: null, vault_nodes: null, parse_errors: 0,
263
+ rows: null, embedded: null, stale: null, mismatched: null, orphaned: null, missing: null,
264
+ percent: null, model: null, models: [], db_bytes: null,
265
+ };
266
+ let nodes;
267
+ try {
268
+ const loaded = await loadVaultNodes(path.join(brainDir, 'memory-vault'));
269
+ nodes = loaded.nodes;
270
+ report.vault_nodes = nodes.length;
271
+ report.parse_errors = loaded.parseErrors;
272
+ } catch (err) {
273
+ report.state = 'unreadable';
274
+ report.reason = `vault could not be read: ${err.message}`;
275
+ return report;
276
+ }
277
+
278
+ const dbPath = path.join(brainDir, 'memory-derived', 'embeddings.db');
279
+ if (!fs.existsSync(dbPath)) {
280
+ report.state = 'no-index';
281
+ report.reason = 'no embeddings.db; run: total-recall compile';
282
+ report.missing = nodes.length;
283
+ return report;
284
+ }
285
+ let rows;
286
+ try {
287
+ report.db_bytes = fs.statSync(dbPath).size;
288
+ const { DatabaseSync } = await import('node:sqlite');
289
+ const db = new DatabaseSync(dbPath, { readOnly: true });
290
+ try {
291
+ rows = db.prepare('SELECT slug, model, content_sha256, embedding_json FROM vault_embeddings').all();
292
+ } finally { db.close(); }
293
+ } catch (err) {
294
+ report.state = 'unreadable';
295
+ report.reason = `embeddings.db could not be read: ${err.message}`;
296
+ return report;
297
+ }
298
+
299
+ const hashes = new Map(nodes.map(n => [n.slug, crypto.createHash('sha256').update(nodeToEmbedText(n)).digest('hex')]));
300
+ const counts = { embedded: 0, stale: 0, mismatched: 0, orphaned: 0 };
301
+ const models = new Map();
302
+ const indexed = new Set();
303
+ for (const row of rows) {
304
+ if (!hashes.has(row.slug)) { counts.orphaned++; continue; }
305
+ indexed.add(row.slug);
306
+ if (!validVector(row.embedding_json).ok) { counts.mismatched++; continue; }
307
+ if (!row.content_sha256 || row.content_sha256 !== hashes.get(row.slug)) { counts.stale++; continue; }
308
+ counts.embedded++;
309
+ models.set(row.model, (models.get(row.model) || 0) + 1);
310
+ }
311
+ Object.assign(report, counts, {
312
+ state: 'ok',
313
+ rows: rows.length,
314
+ missing: nodes.length - indexed.size,
315
+ models: [...models.entries()].sort((a, b) => b[1] - a[1]).map(([model, count]) => ({ model, count })),
316
+ });
317
+ report.model = report.models[0]?.model ?? null;
318
+ report.percent = nodes.length ? Math.round((counts.embedded / nodes.length) * 100) : null;
319
+ return report;
320
+ }
321
+
322
+ // ─── Subcommands ─────────────────────────────────────────────────────────────
323
+
324
+ function flagValue(args, name) {
325
+ const i = args.indexOf(name);
326
+ return i > -1 ? args[i + 1] : undefined;
327
+ }
328
+
329
+ const IMPLEMENTED = {};
330
+
331
+ IMPLEMENTED.status = async (args) => {
332
+ const json = args.includes('--json');
333
+ const provider = await providerReport();
334
+ const brain = resolveVault();
335
+ const report = {
336
+ plugin: PLUGIN_ID,
337
+ configured_urls: candidateUrls(),
338
+ provider: provider.provider,
339
+ endpoint: provider.endpoint,
340
+ locality: provider.locality,
341
+ // `local` is true only when the serving endpoint is on this host.
342
+ local: provider.locality === 'local',
343
+ selected_model: provider.selected_model,
344
+ embedding_dims: provider.dims,
345
+ hosted_fallback: provider.hosted_fallback,
346
+ reason: provider.reason,
347
+ attempts: provider.attempts,
348
+ brain: brain ? { dir: brain, ...(await coverage(brain)) } : null,
349
+ };
350
+ if (json) { console.log(JSON.stringify(report, null, 1)); return; }
351
+ const where = { local: 'yes — on this machine', remote: 'NO — the endpoint or selected model uses another machine', unknown: 'unknown — hosted fallback resolved by the auth owner' };
352
+ console.log(`Embeddings v${PLUGIN_VERSION}`);
353
+ for (const a of provider.attempts) console.log(` endpoint: ${a.url} ${a.reachable ? '(reachable)' : `(unreachable: ${a.reason})`}`);
354
+ console.log(` model: ${provider.selected_model ? `${provider.selected_model} (${provider.dims} dims)` : `none${provider.reason ? ` — ${provider.reason}` : ''}`}`);
355
+ console.log(` local: ${where[provider.locality]}`);
356
+ if (report.brain) printCoverage(report.brain);
357
+ };
358
+
359
+ function printCoverage(b) {
360
+ console.log(` brain: ${b.dir}`);
361
+ if (b.state !== 'ok') { console.log(` coverage: ${b.state} — ${b.reason}`); return; }
362
+ console.log(` vault: ${b.vault_nodes} nodes${b.parse_errors ? ` (${b.parse_errors} unparseable files)` : ''}`);
363
+ console.log(` usable: ${b.embedded}${b.model ? ` (model: ${b.model})` : ''}${b.percent != null ? ` — ${b.percent}%` : ''}`);
364
+ console.log(` not usable: ${b.stale} stale, ${b.mismatched} wrong width, ${b.missing} missing, ${b.orphaned} orphaned rows`);
365
+ }
366
+
367
+ IMPLEMENTED.models = async (args) => {
368
+ const json = args.includes('--json');
369
+ const endpoint = await resolveEndpoint();
370
+ if (!endpoint.url) {
371
+ if (json) console.log(JSON.stringify({ url: null, reachable: false, attempts: endpoint.attempts, models: [] }));
372
+ else for (const a of endpoint.attempts) console.error(`Embeddings: ${a.url} is unreachable (${a.reason}).`);
373
+ process.exitCode = 1;
374
+ return;
375
+ }
376
+ const { rows, selected } = await inspectModels(endpoint.url, endpoint.models);
377
+ if (json) {
378
+ const locality = rows.find(row => row.name === selected)?.upstream ? 'remote' : endpointLocality(endpoint.url);
379
+ console.log(JSON.stringify({ url: endpoint.url, reachable: true, locality, vault_dims: VAULT_DIMS, selected, models: rows }, null, 1));
380
+ return;
381
+ }
382
+ console.log(`Embeddings v${PLUGIN_VERSION} — ${endpoint.url}`);
383
+ for (const r of rows) console.log(` ${r.compatible ? '●' : '○'} ${r.name}${r.dims ? ` (${r.dims} dims)` : ''}${r.name === selected ? ' ← selected' : ''}`);
384
+ if (!selected) console.log(` no model embeds at ${VAULT_DIMS} dims — run: embeddings pull <model>`);
385
+ };
386
+
387
+ IMPLEMENTED.pull = async (args) => {
388
+ const json = args.includes('--json');
389
+ const model = args.find(a => !a.startsWith('-'));
390
+ const fail = (code, body, text) => {
391
+ if (json) console.log(JSON.stringify({ ok: false, ...body }));
392
+ else console.error(`Embeddings: ${text}`);
393
+ process.exitCode = code;
394
+ };
395
+ if (!model) return fail(2, { reason: 'model required' }, 'pull needs an explicit model: embeddings pull <model>');
396
+ const configured = process.env.TR_OLLAMA_URL || process.env.OLLAMA_HOST || LOOPBACK_URL;
397
+ const url = normalizeBaseUrl(configured);
398
+ if (!url || endpointLocality(url) !== 'local') {
399
+ return fail(2, { reason: 'pull requires a configured loopback Ollama origin' }, 'pull requires a configured loopback Ollama origin.');
400
+ }
401
+ const listed = await listModels(url);
402
+ if (!listed.ok) return fail(1, { model, url, reason: listed.reason }, 'the selected Ollama endpoint is unavailable.');
403
+ const existing = listed.models.find(entry => entry.name === model || entry.model === model || entry.name === `${model}:latest`);
404
+ if (existing?.remote_model || existing?.remote_host || /(?:[:-])cloud$/i.test(model)) {
405
+ return fail(2, { reason: 'pull requires a local model' }, 'pull requires a local model.');
406
+ }
407
+ if (!json) console.log(`Embeddings: pulling ${model} on ${url} ...`);
408
+ try {
409
+ const res = await fetchWithDeadline(`${url}/api/pull`, {
410
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
411
+ body: JSON.stringify({ model, stream: false }),
412
+ }, PULL_DEADLINE_MS);
413
+ const body = await res.json().catch(() => ({}));
414
+ if (!res.ok || body.error || body.status !== 'success') {
415
+ return fail(1, { model, url, status: res.status, reason: body.error || body.status || `HTTP ${res.status}` },
416
+ `pull failed: ${body.error || body.status || `HTTP ${res.status}`}`);
417
+ }
418
+ } catch (err) {
419
+ return fail(1, { model, url, reason: err.message }, `pull failed: ${err.message}`);
420
+ }
421
+ if (json) { console.log(JSON.stringify({ ok: true, model, url, locality: 'local' })); return; }
422
+ console.log(` ✅ ${model} ready on ${url}`);
423
+ };
424
+
425
+ IMPLEMENTED.benchmark = async (args) => {
426
+ const json = args.includes('--json');
427
+ const requested = Number(flagValue(args, '--count') ?? 10);
428
+ const fail = (body, text) => {
429
+ if (json) console.log(JSON.stringify({ ok: false, ...body }));
430
+ else console.error(`Embeddings: ${text}`);
431
+ process.exitCode = 1;
432
+ };
433
+ if (!Number.isInteger(requested) || requested < 1 || requested > BENCHMARK_MAX_SAMPLES) {
434
+ fail({ reason: `--count must be an integer from 1 to ${BENCHMARK_MAX_SAMPLES}` }, `--count must be an integer from 1 to ${BENCHMARK_MAX_SAMPLES}.`);
435
+ process.exitCode = 2;
436
+ return;
437
+ }
438
+ const provider = await providerReport();
439
+ if (provider.provider !== 'ollama') {
440
+ return fail({ reason: `no embedding-capable model at ${VAULT_DIMS} dims`, url: provider.endpoint, attempts: provider.attempts },
441
+ `no model embeds at ${VAULT_DIMS} dims. ${provider.reason || ''}`.trim());
442
+ }
443
+ if (provider.locality !== 'local') {
444
+ return fail({ reason: 'benchmark requires a local model on a loopback endpoint', locality: provider.locality },
445
+ 'benchmark requires a local model on a loopback endpoint.');
446
+ }
447
+ const started = Date.now();
448
+ const timings = [];
449
+ for (let i = 0; i < requested; i++) {
450
+ const left = BENCHMARK_DEADLINE_MS - (Date.now() - started);
451
+ if (left <= 0) return fail({ reason: 'benchmark deadline exceeded', completed: timings.length, url: provider.endpoint, model: provider.selected_model }, 'benchmark deadline exceeded.');
452
+ const t0 = Date.now();
453
+ try {
454
+ const res = await fetchWithDeadline(`${provider.endpoint}/api/embed`, {
455
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
456
+ body: JSON.stringify({ model: provider.selected_model, input: BENCHMARK_TEXT }),
457
+ }, Math.min(EMBED_TIMEOUT_MS, left));
458
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
459
+ const vector = (await res.json())?.embeddings?.[0];
460
+ if (!Array.isArray(vector) || !vector.every(Number.isFinite)) throw new Error('response carried no numeric vector');
461
+ if (vector.length !== VAULT_DIMS) throw new Error(`vector has ${vector.length} dims, vault requires ${VAULT_DIMS}`);
462
+ timings.push(Date.now() - t0);
463
+ } catch (err) {
464
+ return fail({ reason: err.message, url: provider.endpoint, model: provider.selected_model, completed: timings.length }, `benchmark failed: ${err.message}`);
465
+ }
466
+ }
467
+ const avg = timings.reduce((a, b) => a + b, 0) / timings.length;
468
+ const brain = resolveVault();
469
+ let nodes = null;
470
+ if (brain) { try { nodes = (await loadVaultNodes(path.join(brain, 'memory-vault'))).nodes.length; } catch { nodes = null; } }
471
+ const report = {
472
+ ok: true, url: provider.endpoint, locality: provider.locality, model: provider.selected_model,
473
+ dims: VAULT_DIMS, samples: timings.length,
474
+ ms_per_embedding: Math.round(avg),
475
+ min_ms: Math.min(...timings), max_ms: Math.max(...timings),
476
+ vault_nodes: nodes,
477
+ projected_minutes: nodes ? Math.round((avg * nodes) / 60000) : null,
478
+ };
479
+ if (json) { console.log(JSON.stringify(report, null, 1)); return; }
480
+ console.log(`Embeddings v${PLUGIN_VERSION} — benchmark (${report.samples} samples, ${report.model} on ${report.url})`);
481
+ console.log(` ${report.ms_per_embedding} ms/embedding (min ${report.min_ms}, max ${report.max_ms}), ${VAULT_DIMS}-dim vectors verified`);
482
+ if (nodes) console.log(` ${nodes} vault nodes → about ${report.projected_minutes} minutes to embed fully`);
483
+ };
484
+
485
+ IMPLEMENTED.coverage = async (args) => {
486
+ const json = args.includes('--json');
487
+ const brain = resolveVault();
488
+ if (!brain) {
489
+ if (json) console.log(JSON.stringify({ ok: false, reason: 'no brain found in the current directory or home' }));
490
+ else console.error('Embeddings: no brain found. Run from a project with .agent/skills/total-recall, or after total-recall init.');
491
+ process.exitCode = 1;
492
+ return;
493
+ }
494
+ const cov = await coverage(brain);
495
+ const ok = cov.state === 'ok' || cov.state === 'no-index';
496
+ const report = { ok, brain, ...cov };
497
+ if (!ok) process.exitCode = 1;
498
+ if (json) { console.log(JSON.stringify(report, null, 1)); return; }
499
+ console.log(`Embeddings v${PLUGIN_VERSION} — coverage`);
500
+ printCoverage({ dir: brain, ...cov });
501
+ if (cov.state === 'ok' && (cov.stale || cov.missing || cov.mismatched)) console.log(' run: total-recall compile (rebuilds the unusable vectors)');
502
+ };
503
+
504
+ export async function run(argv = []) {
505
+ const args = Array.isArray(argv) ? argv.slice(3) : [];
506
+ const sub = args[0] || 'status';
507
+ const wantsHelp = args.includes('--help') || args.includes('-h');
508
+
509
+ if (wantsHelp || sub === 'help') {
510
+ const subs = [...new Set(['status', ...Object.keys(IMPLEMENTED)])];
511
+ console.log(`Embeddings v${PLUGIN_VERSION}
512
+
513
+ Usage: total-recall embeddings <subcommand> [options]
514
+
515
+ Subcommands:
516
+ ${subs.map((s) => ` ${s}`).join('\n')}
517
+
518
+ Options:
519
+ --json Machine-readable output
520
+ --count <n> benchmark samples, 1-${BENCHMARK_MAX_SAMPLES} (default 10)
521
+ pull <model> pull an explicitly named local model to the selected loopback endpoint
522
+ --help, -h Show this help
523
+
524
+ Environment:
525
+ TR_OLLAMA_URL / OLLAMA_HOST Ollama endpoint, tried before loopback
526
+ (http://127.0.0.1:11434). A non-loopback
527
+ endpoint receives vault text over the network.
528
+ TR_OLLAMA_EMBED_MODEL Preferred model, used when it embeds at ${VAULT_DIMS} dims
529
+ Benchmark runs only for a local model. A loopback Ollama server may
530
+ advertise a remote model. Core may try hosted providers if local
531
+ selection fails. When it does, vault text leaves the machine.`);
532
+ return;
533
+ }
534
+
535
+ if (IMPLEMENTED[sub]) return IMPLEMENTED[sub](args.slice(1));
536
+
537
+ console.error(`Embeddings: "${sub}" is not implemented. Run 'total-recall embeddings --help' for available subcommands.`);
538
+ process.exitCode = 2;
539
+ }
540
+ export default run;
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "tr-plugin-embeddings",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.5",
4
+ "type": "module",
5
+ "description": "Local embedding model management: provider/model status, benchmark, index build and coverage",
6
+ "scripts": {
7
+ "test": "node --test test/*.test.mjs",
8
+ "ssss": "ssss"
9
+ },
10
+ "devDependencies": {
11
+ "total-recall-brain": "3.52.20"
12
+ },
13
+ "license": "MIT",
14
+ "files": [
15
+ "cli.mjs",
16
+ "plugin.json",
17
+ "README.md",
18
+ "LICENSE",
19
+ "DESIGN.md",
20
+ "ui/",
21
+ "skills/"
22
+ ],
23
+ "dependencies": {
24
+ "@gregiteen/ssss-cli": "0.14.8"
25
+ },
26
+ "overrides": {
27
+ "@ssss/cli": "npm:@gregiteen/ssss-cli@0.14.8"
28
+ }
29
+ }
package/plugin.json ADDED
@@ -0,0 +1,103 @@
1
+ {
2
+ "$schema": "https://github.com/gregiteen/total-recall/blob/main/metadata.plugin.schema.json",
3
+ "id": "embeddings",
4
+ "name": "Embeddings",
5
+ "version": "0.2.5",
6
+ "description": "Local embedding model management: provider/model status, benchmark, index build and coverage",
7
+ "license": "MIT",
8
+ "branding": {
9
+ "name": "Embeddings",
10
+ "color": "#10b981",
11
+ "badge": "Ollama Vector Engine",
12
+ "font": "space-grotesk"
13
+ },
14
+ "use_cases": [
15
+ "operations",
16
+ "ai"
17
+ ],
18
+ "gate": {
19
+ "tasks": [
20
+ "Check embedding models and index coverage",
21
+ "Pull or benchmark a local embedding model"
22
+ ],
23
+ "owned_commands": []
24
+ },
25
+ "cli": {
26
+ "answers_help": true,
27
+ "command": "embeddings",
28
+ "handler": "./cli.mjs",
29
+ "subcommands": [
30
+ {
31
+ "name": "status",
32
+ "description": "Provider, model, locality and vault coverage in one view",
33
+ "effect": "read",
34
+ "output": "json"
35
+ },
36
+ {
37
+ "name": "models",
38
+ "description": "List models on the endpoint and which can produce embeddings",
39
+ "effect": "read",
40
+ "output": "json"
41
+ },
42
+ {
43
+ "name": "pull",
44
+ "description": "Pull an explicitly named local model onto the configured loopback endpoint",
45
+ "effect": "write",
46
+ "output": "json",
47
+ "timeout_ms": 600000
48
+ },
49
+ {
50
+ "name": "benchmark",
51
+ "description": "Measure latency per verified local embedding and project full-vault time",
52
+ "effect": "read",
53
+ "output": "json",
54
+ "timeout_ms": 300000
55
+ },
56
+ {
57
+ "name": "coverage",
58
+ "description": "How many vault nodes have a current, correct-width vector, and why the rest do not",
59
+ "effect": "read",
60
+ "output": "json"
61
+ }
62
+ ]
63
+ },
64
+ "ui": {
65
+ "home": "home",
66
+ "design_tokens": "DESIGN.md",
67
+ "elements": [
68
+ {
69
+ "id": "home",
70
+ "kind": "panel",
71
+ "tag": "tr-embeddings-home",
72
+ "module": "ui/home.js",
73
+ "description": "Embeddings page: provider and locality, vault coverage, model roster, credentials ownership, benchmark and pull"
74
+ }
75
+ ]
76
+ },
77
+ "auth": {
78
+ "plugin": "auth",
79
+ "methods": [
80
+ "passkey",
81
+ "google-oauth2"
82
+ ],
83
+ "session_verification": true
84
+ },
85
+ "status": {
86
+ "command": "status",
87
+ "refresh_seconds": 60
88
+ },
89
+ "reuse": {
90
+ "commands": [
91
+ "total-recall auth secret",
92
+ "total-recall ssss status"
93
+ ],
94
+ "owned": "Local embedding provider/model status, Ollama model pulls, latency benchmarks, and vault vector coverage."
95
+ },
96
+ "skills": [
97
+ {
98
+ "id": "embeddings",
99
+ "path": "./skills/embeddings/SKILL.md",
100
+ "description": "Local embedding model management: provider/model status, benchmark, index build and coverage"
101
+ }
102
+ ]
103
+ }