humemory 0.2.8 → 0.2.10
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/AGENTS.md +7 -3
- package/CHANGELOG.md +26 -0
- package/README.md +60 -2
- package/dist/agent/maintenance-queue.d.ts +0 -1
- package/dist/agent/maintenance-queue.js +0 -1
- package/dist/api/memory-routes.js +1 -1
- package/dist/cli/index.js +21 -2
- package/dist/core/doctor.d.ts +28 -0
- package/dist/core/doctor.js +320 -0
- package/dist/core/hybrid.d.ts +7 -3
- package/dist/core/hybrid.js +7 -3
- package/dist/core/paths.d.ts +7 -0
- package/dist/core/paths.js +9 -0
- package/dist/core/search.d.ts +23 -1
- package/dist/core/search.js +86 -28
- package/docs/PORTABILITY.md +84 -0
- package/package.json +3 -1
- package/scripts/maintenance-worker.ts +7 -2
- package/src/agent/maintenance-queue.ts +0 -2
- package/src/api/memory-routes.ts +1 -1
- package/src/cli/index.ts +22 -2
- package/src/core/doctor.ts +362 -0
- package/src/core/hybrid.ts +7 -3
- package/src/core/paths.ts +10 -0
- package/src/core/search.ts +100 -28
- package/src/core/types.ts +1 -1
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Install diagnostic — audit improvement #4.
|
|
3
|
+
*
|
|
4
|
+
* Reports what an installation actually resolved to: runtime, paths, write
|
|
5
|
+
* rights, schema, lock state, models and auxiliary entry points. Deliberately
|
|
6
|
+
* blind to content: it never opens a transcript, never reads a memory row and
|
|
7
|
+
* never prints an environment variable's value — only whether one is set. A
|
|
8
|
+
* diagnostic that leaks the palace it is diagnosing is worse than none.
|
|
9
|
+
*
|
|
10
|
+
* The entry-point check is the reason this exists at all: a package whose
|
|
11
|
+
* `files` list omits a source an auxiliary entry imports (audit A04) is silent
|
|
12
|
+
* until a hook fires days later. Here it fails immediately, on demand.
|
|
13
|
+
*/
|
|
14
|
+
import { Database } from 'bun:sqlite';
|
|
15
|
+
import { existsSync, readdirSync, statSync } from 'fs';
|
|
16
|
+
import { mkdir, rm, writeFile } from 'fs/promises';
|
|
17
|
+
import { arch, platform, release } from 'os';
|
|
18
|
+
import { join } from 'path';
|
|
19
|
+
import { randomUUID } from 'crypto';
|
|
20
|
+
import {
|
|
21
|
+
dataDirectory,
|
|
22
|
+
databasePath,
|
|
23
|
+
installationDirectory,
|
|
24
|
+
modelCacheDirectory,
|
|
25
|
+
queueDirectory,
|
|
26
|
+
} from './paths.js';
|
|
27
|
+
|
|
28
|
+
export type DoctorStatus = 'ok' | 'warn' | 'fail';
|
|
29
|
+
|
|
30
|
+
export interface DoctorCheck {
|
|
31
|
+
/** Stable machine-readable id, safe to grep in CI. */
|
|
32
|
+
id: string;
|
|
33
|
+
section: 'runtime' | 'paths' | 'storage' | 'locks' | 'models' | 'entrypoints';
|
|
34
|
+
status: DoctorStatus;
|
|
35
|
+
/** One line, no secrets, no memory content. */
|
|
36
|
+
detail: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface DoctorReport {
|
|
40
|
+
checks: DoctorCheck[];
|
|
41
|
+
/** Worst status across every check — the exit code the CLI maps to. */
|
|
42
|
+
status: DoctorStatus;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface DoctorOptions {
|
|
46
|
+
/** Overridden wholesale in tests so no probe touches the real palace. */
|
|
47
|
+
paths?: {
|
|
48
|
+
data: string;
|
|
49
|
+
database: string;
|
|
50
|
+
queue: string;
|
|
51
|
+
modelCache: string;
|
|
52
|
+
};
|
|
53
|
+
installRoot?: string;
|
|
54
|
+
/** Minimum runtime the package claims to support (`engines.bun`). */
|
|
55
|
+
minimumBun?: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Env overrides worth reporting. Names only — a value can be a private path. */
|
|
59
|
+
const TRACKED_ENV = [
|
|
60
|
+
'HUMEMORY_DATA_DIR',
|
|
61
|
+
'HUMEMORY_DB',
|
|
62
|
+
'HUMEMORY_QUEUE',
|
|
63
|
+
'HUMEMORY_MODEL_CACHE',
|
|
64
|
+
'HUMEMORY_HOST',
|
|
65
|
+
'HUMEMORY_API_TOKEN',
|
|
66
|
+
'PORT',
|
|
67
|
+
] as const;
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Auxiliary entry points, relative to the installation root. `optional` covers
|
|
71
|
+
* what a source checkout legitimately lacks before a build (`dist`, the
|
|
72
|
+
* bundled dashboard); a missing required file means the published archive is
|
|
73
|
+
* broken for that entry point.
|
|
74
|
+
*/
|
|
75
|
+
const ENTRY_POINTS: { path: string; label: string; optional?: boolean }[] = [
|
|
76
|
+
{ path: 'bin/humemory.js', label: 'CLI shim' },
|
|
77
|
+
{ path: 'dist/cli/index.js', label: 'CLI implementation', optional: true },
|
|
78
|
+
{ path: 'src/mcp/server.ts', label: 'MCP server (registered by `humemory setup`)' },
|
|
79
|
+
{ path: 'src/api/server.ts', label: 'HTTP API' },
|
|
80
|
+
{ path: 'scripts/hook-session.ts', label: 'Stop hook' },
|
|
81
|
+
{ path: 'scripts/hook-session-start.ts', label: 'SessionStart hook' },
|
|
82
|
+
{ path: 'scripts/hook-post-commit.ts', label: 'post-commit hook' },
|
|
83
|
+
{ path: 'scripts/maintenance-worker.ts', label: 'maintenance worker' },
|
|
84
|
+
{ path: 'public/app', label: 'bundled dashboard', optional: true },
|
|
85
|
+
];
|
|
86
|
+
|
|
87
|
+
/** Tables the store creates. A missing one means an interrupted migration. */
|
|
88
|
+
const EXPECTED_TABLES = [
|
|
89
|
+
'memories',
|
|
90
|
+
'intentions',
|
|
91
|
+
'cues',
|
|
92
|
+
'scripts',
|
|
93
|
+
'contradictions',
|
|
94
|
+
];
|
|
95
|
+
|
|
96
|
+
function compareSemver(actual: string, minimum: string): number {
|
|
97
|
+
const parse = (v: string) => v.replace(/^[^\d]*/, '').split('.').map((n) => parseInt(n, 10) || 0);
|
|
98
|
+
const [a, b] = [parse(actual), parse(minimum)];
|
|
99
|
+
for (let i = 0; i < 3; i++) {
|
|
100
|
+
if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) - (b[i] ?? 0);
|
|
101
|
+
}
|
|
102
|
+
return 0;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Probe by writing, not by reading a permission bit: ACLs lie on Windows. */
|
|
106
|
+
async function probeWritable(directory: string): Promise<{ status: DoctorStatus; detail: string }> {
|
|
107
|
+
const probe = join(directory, `.humemory-doctor-${randomUUID()}`);
|
|
108
|
+
try {
|
|
109
|
+
await mkdir(directory, { recursive: true });
|
|
110
|
+
await writeFile(probe, '', { flag: 'wx' });
|
|
111
|
+
return { status: 'ok', detail: `writable — ${directory}` };
|
|
112
|
+
} catch (error: any) {
|
|
113
|
+
return { status: 'fail', detail: `not writable (${error?.code ?? 'unknown'}) — ${directory}` };
|
|
114
|
+
} finally {
|
|
115
|
+
await rm(probe, { force: true }).catch(() => {});
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Is the advisory lock at `lockFile` held right now? Acquiring and releasing
|
|
121
|
+
* is the only honest answer — the lock has no wall-clock expiry to inspect
|
|
122
|
+
* (audit A08), and its owner is the OS, not a mtime.
|
|
123
|
+
*/
|
|
124
|
+
function probeLock(lockFile: string): { status: DoctorStatus; detail: string } {
|
|
125
|
+
const sqlitePath = `${lockFile}.sqlite`;
|
|
126
|
+
if (!existsSync(sqlitePath)) return { status: 'ok', detail: `free (never taken) — ${lockFile}` };
|
|
127
|
+
let connection: Database | null = null;
|
|
128
|
+
try {
|
|
129
|
+
connection = new Database(sqlitePath);
|
|
130
|
+
connection.exec('PRAGMA busy_timeout=0; BEGIN IMMEDIATE');
|
|
131
|
+
connection.exec('ROLLBACK');
|
|
132
|
+
return { status: 'ok', detail: `free — ${lockFile}` };
|
|
133
|
+
} catch (error: any) {
|
|
134
|
+
const code = String(error?.code ?? '');
|
|
135
|
+
if (code.startsWith('SQLITE_BUSY') || code.startsWith('SQLITE_LOCKED')) {
|
|
136
|
+
// Held by a live process. Not a fault: a worker may simply be running.
|
|
137
|
+
return { status: 'warn', detail: `held by a live process — ${lockFile}` };
|
|
138
|
+
}
|
|
139
|
+
return { status: 'fail', detail: `unreadable (${code || 'unknown'}) — ${lockFile}` };
|
|
140
|
+
} finally {
|
|
141
|
+
connection?.close();
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function inspectDatabase(dbPath: string): DoctorCheck[] {
|
|
146
|
+
if (dbPath === ':memory:') {
|
|
147
|
+
return [{ id: 'db.open', section: 'storage', status: 'warn', detail: 'in-memory database — nothing persists' }];
|
|
148
|
+
}
|
|
149
|
+
if (!existsSync(dbPath)) {
|
|
150
|
+
return [
|
|
151
|
+
{ id: 'db.open', section: 'storage', status: 'warn', detail: `absent, created on first write — ${dbPath}` },
|
|
152
|
+
];
|
|
153
|
+
}
|
|
154
|
+
let db: Database | null = null;
|
|
155
|
+
try {
|
|
156
|
+
db = new Database(dbPath, { readonly: true });
|
|
157
|
+
const names = new Set(
|
|
158
|
+
(db.query("SELECT name FROM sqlite_master WHERE type='table'").all() as { name: string }[]).map((r) => r.name)
|
|
159
|
+
);
|
|
160
|
+
const missing = EXPECTED_TABLES.filter((table) => !names.has(table));
|
|
161
|
+
const journal = (db.query('PRAGMA journal_mode').get() as { journal_mode: string }).journal_mode;
|
|
162
|
+
const checks: DoctorCheck[] = [
|
|
163
|
+
{
|
|
164
|
+
id: 'db.open',
|
|
165
|
+
section: 'storage',
|
|
166
|
+
status: 'ok',
|
|
167
|
+
detail: `opened, ${names.size} tables, journal_mode=${journal} — ${dbPath}`,
|
|
168
|
+
},
|
|
169
|
+
{
|
|
170
|
+
id: 'db.schema',
|
|
171
|
+
section: 'storage',
|
|
172
|
+
status: missing.length ? 'fail' : 'ok',
|
|
173
|
+
detail: missing.length
|
|
174
|
+
? `missing tables: ${missing.join(', ')} — migration interrupted`
|
|
175
|
+
: `all ${EXPECTED_TABLES.length} expected tables present`,
|
|
176
|
+
},
|
|
177
|
+
];
|
|
178
|
+
if (journal.toLowerCase() !== 'wal') {
|
|
179
|
+
checks.push({
|
|
180
|
+
id: 'db.wal',
|
|
181
|
+
section: 'storage',
|
|
182
|
+
status: 'warn',
|
|
183
|
+
detail: `journal_mode is ${journal}; multi-process access expects WAL`,
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
return checks;
|
|
187
|
+
} catch (error: any) {
|
|
188
|
+
return [
|
|
189
|
+
{ id: 'db.open', section: 'storage', status: 'fail', detail: `cannot open (${error?.code ?? 'unknown'}) — ${dbPath}` },
|
|
190
|
+
];
|
|
191
|
+
} finally {
|
|
192
|
+
db?.close();
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function inspectModels(cacheDir: string): DoctorCheck {
|
|
197
|
+
if (!existsSync(cacheDir)) {
|
|
198
|
+
return {
|
|
199
|
+
id: 'models.cache',
|
|
200
|
+
section: 'models',
|
|
201
|
+
status: 'warn',
|
|
202
|
+
detail: `no model cache — semantic recall downloads on first use (${cacheDir})`,
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
// One level of vendor/model directories is enough to name what is installed;
|
|
206
|
+
// walking the whole tree would be slow and tells the user nothing more.
|
|
207
|
+
const vendors = readdirSync(cacheDir).filter((entry) => {
|
|
208
|
+
try {
|
|
209
|
+
return statSync(join(cacheDir, entry)).isDirectory();
|
|
210
|
+
} catch {
|
|
211
|
+
return false;
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
const models: string[] = [];
|
|
215
|
+
for (const vendor of vendors) {
|
|
216
|
+
try {
|
|
217
|
+
for (const model of readdirSync(join(cacheDir, vendor))) {
|
|
218
|
+
if (statSync(join(cacheDir, vendor, model)).isDirectory()) models.push(`${vendor}/${model}`);
|
|
219
|
+
}
|
|
220
|
+
} catch {
|
|
221
|
+
/* unreadable subdirectory tells us nothing; the cache check above stands */
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return {
|
|
225
|
+
id: 'models.cache',
|
|
226
|
+
section: 'models',
|
|
227
|
+
status: models.length ? 'ok' : 'warn',
|
|
228
|
+
detail: models.length ? `cached: ${models.join(', ')}` : `cache directory empty — ${cacheDir}`,
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function inspectEntryPoints(installRoot: string): DoctorCheck[] {
|
|
233
|
+
return ENTRY_POINTS.map(({ path, label, optional }) => {
|
|
234
|
+
const absolute = join(installRoot, path);
|
|
235
|
+
const present = existsSync(absolute);
|
|
236
|
+
return {
|
|
237
|
+
id: `entry.${path}`,
|
|
238
|
+
section: 'entrypoints' as const,
|
|
239
|
+
status: present ? 'ok' : optional ? 'warn' : 'fail',
|
|
240
|
+
detail: present
|
|
241
|
+
? `${label} — ${path}`
|
|
242
|
+
: optional
|
|
243
|
+
? `${label} absent (build not run?) — ${path}`
|
|
244
|
+
: `${label} MISSING from the installation — ${path}`,
|
|
245
|
+
};
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
export async function runDoctor(options: DoctorOptions = {}): Promise<DoctorReport> {
|
|
250
|
+
const paths = options.paths ?? {
|
|
251
|
+
data: dataDirectory(),
|
|
252
|
+
database: databasePath(),
|
|
253
|
+
queue: queueDirectory(),
|
|
254
|
+
modelCache: modelCacheDirectory(),
|
|
255
|
+
};
|
|
256
|
+
const installRoot = options.installRoot ?? installationDirectory();
|
|
257
|
+
const checks: DoctorCheck[] = [];
|
|
258
|
+
|
|
259
|
+
// --- runtime ---
|
|
260
|
+
const bunVersion = typeof Bun === 'undefined' ? null : Bun.version;
|
|
261
|
+
if (!bunVersion) {
|
|
262
|
+
checks.push({
|
|
263
|
+
id: 'runtime.bun',
|
|
264
|
+
section: 'runtime',
|
|
265
|
+
status: 'fail',
|
|
266
|
+
detail: 'not running under bun — the store needs bun:sqlite',
|
|
267
|
+
});
|
|
268
|
+
} else if (options.minimumBun && compareSemver(bunVersion, options.minimumBun) < 0) {
|
|
269
|
+
checks.push({
|
|
270
|
+
id: 'runtime.bun',
|
|
271
|
+
section: 'runtime',
|
|
272
|
+
status: 'fail',
|
|
273
|
+
detail: `bun ${bunVersion} is below the declared minimum ${options.minimumBun}`,
|
|
274
|
+
});
|
|
275
|
+
} else {
|
|
276
|
+
checks.push({ id: 'runtime.bun', section: 'runtime', status: 'ok', detail: `bun ${bunVersion}` });
|
|
277
|
+
}
|
|
278
|
+
checks.push({
|
|
279
|
+
id: 'runtime.platform',
|
|
280
|
+
section: 'runtime',
|
|
281
|
+
status: 'ok',
|
|
282
|
+
detail: `${platform()} ${arch()} (kernel ${release()})`,
|
|
283
|
+
});
|
|
284
|
+
const setEnv = TRACKED_ENV.filter((name) => (process.env[name] ?? '') !== '');
|
|
285
|
+
checks.push({
|
|
286
|
+
id: 'runtime.env',
|
|
287
|
+
section: 'runtime',
|
|
288
|
+
// Names only. HUMEMORY_API_TOKEN's value must never reach a log.
|
|
289
|
+
status: 'ok',
|
|
290
|
+
detail: setEnv.length ? `overrides set: ${setEnv.join(', ')}` : 'no environment overrides set',
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
// --- paths and write rights ---
|
|
294
|
+
for (const [id, directory] of [
|
|
295
|
+
['paths.data', paths.data],
|
|
296
|
+
['paths.queue', paths.queue],
|
|
297
|
+
['paths.modelCache', paths.modelCache],
|
|
298
|
+
] as const) {
|
|
299
|
+
const probe = await probeWritable(directory);
|
|
300
|
+
checks.push({ id, section: 'paths', status: probe.status, detail: probe.detail });
|
|
301
|
+
}
|
|
302
|
+
checks.push({
|
|
303
|
+
id: 'paths.database',
|
|
304
|
+
section: 'paths',
|
|
305
|
+
status: 'ok',
|
|
306
|
+
detail: `database resolves to ${paths.database}`,
|
|
307
|
+
});
|
|
308
|
+
checks.push({
|
|
309
|
+
id: 'paths.install',
|
|
310
|
+
section: 'paths',
|
|
311
|
+
status: 'ok',
|
|
312
|
+
detail: `installation root ${installRoot}`,
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
// --- storage, locks, models, entry points ---
|
|
316
|
+
checks.push(...inspectDatabase(paths.database));
|
|
317
|
+
if (paths.database !== ':memory:') {
|
|
318
|
+
const dbLock = probeLock(`${paths.database}.lock`);
|
|
319
|
+
checks.push({ id: 'locks.database', section: 'locks', ...dbLock });
|
|
320
|
+
}
|
|
321
|
+
const workerLock = probeLock(join(paths.queue, '.worker-lock'));
|
|
322
|
+
checks.push({ id: 'locks.maintenance', section: 'locks', ...workerLock });
|
|
323
|
+
checks.push(inspectModels(paths.modelCache));
|
|
324
|
+
checks.push(...inspectEntryPoints(installRoot));
|
|
325
|
+
|
|
326
|
+
const status: DoctorStatus = checks.some((c) => c.status === 'fail')
|
|
327
|
+
? 'fail'
|
|
328
|
+
: checks.some((c) => c.status === 'warn')
|
|
329
|
+
? 'warn'
|
|
330
|
+
: 'ok';
|
|
331
|
+
return { checks, status };
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const SECTION_TITLES: Record<DoctorCheck['section'], string> = {
|
|
335
|
+
runtime: 'Runtime',
|
|
336
|
+
paths: 'Paths and write rights',
|
|
337
|
+
storage: 'Database',
|
|
338
|
+
locks: 'Locks',
|
|
339
|
+
models: 'Embedding models',
|
|
340
|
+
entrypoints: 'Entry points',
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
const MARKS: Record<DoctorStatus, string> = { ok: '✅', warn: '⚠️ ', fail: '❌' };
|
|
344
|
+
|
|
345
|
+
export function renderDoctorReport(report: DoctorReport): string {
|
|
346
|
+
const lines: string[] = ['', '🩺 humemory doctor', ''];
|
|
347
|
+
for (const section of Object.keys(SECTION_TITLES) as DoctorCheck['section'][]) {
|
|
348
|
+
const rows = report.checks.filter((check) => check.section === section);
|
|
349
|
+
if (!rows.length) continue;
|
|
350
|
+
lines.push(`${SECTION_TITLES[section]}:`);
|
|
351
|
+
for (const row of rows) lines.push(` ${MARKS[row.status]} ${row.detail}`);
|
|
352
|
+
lines.push('');
|
|
353
|
+
}
|
|
354
|
+
const failed = report.checks.filter((c) => c.status === 'fail').length;
|
|
355
|
+
const warned = report.checks.filter((c) => c.status === 'warn').length;
|
|
356
|
+
lines.push(
|
|
357
|
+
report.status === 'ok'
|
|
358
|
+
? 'All checks passed.'
|
|
359
|
+
: `${failed} failing, ${warned} to review out of ${report.checks.length} checks.`
|
|
360
|
+
);
|
|
361
|
+
return lines.join('\n');
|
|
362
|
+
}
|
package/src/core/hybrid.ts
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Hybrid search — Phase 7.4.
|
|
3
3
|
*
|
|
4
|
-
* Reciprocal Rank Fusion of the
|
|
5
|
-
* paths) and the vector lane (paraphrases). Additive by design: with no
|
|
4
|
+
* Reciprocal Rank Fusion of the lexical lane (exact identifiers: loop-ab12,
|
|
5
|
+
* file paths) and the vector lane (paraphrases). Additive by design: with no
|
|
6
6
|
* embeddings in the store, the vector lane contributes nothing and the result
|
|
7
|
-
* is exactly the
|
|
7
|
+
* is exactly the lexical ranking — no regression on bare installs.
|
|
8
|
+
*
|
|
9
|
+
* The `bm25` identifiers below name that lexical lane for historical reasons:
|
|
10
|
+
* it is a FlexSearch index with the heuristic ranking in `search.ts`, not an
|
|
11
|
+
* Okapi BM25 implementation (audit A06).
|
|
8
12
|
*
|
|
9
13
|
* Exclusion filters are inherited from the lanes themselves: the vector lane
|
|
10
14
|
* reads `memory_embeddings`, whose rows are deleted on merge (A4), so merged
|
package/src/core/paths.ts
CHANGED
|
@@ -26,3 +26,13 @@ export function queueDirectory(): string {
|
|
|
26
26
|
export function modelCacheDirectory(): string {
|
|
27
27
|
return process.env.HUMEMORY_MODEL_CACHE ?? join(dataDirectory(), 'models');
|
|
28
28
|
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Root of the installed package — the anchor auxiliary entry points (hooks,
|
|
32
|
+
* MCP server, bundled dashboard) are resolved against. `humemory doctor`
|
|
33
|
+
* checks them from here so a package that ships the wrong `files` list fails
|
|
34
|
+
* loudly instead of at the first hook invocation.
|
|
35
|
+
*/
|
|
36
|
+
export function installationDirectory(): string {
|
|
37
|
+
return installationRoot;
|
|
38
|
+
}
|
package/src/core/search.ts
CHANGED
|
@@ -7,6 +7,23 @@ import type { Memory, SearchQuery, SearchResult, DecayLevel } from './types.js';
|
|
|
7
7
|
import { systemClock, type Clock } from './clock.js';
|
|
8
8
|
import { projectPath } from './project-path.js';
|
|
9
9
|
|
|
10
|
+
/**
|
|
11
|
+
* Cost of having matched only part of the query. Larger than the widest level
|
|
12
|
+
* bonus (3 * 10) so no partial match can outrank an exact one.
|
|
13
|
+
*/
|
|
14
|
+
const PARTIAL_MATCH_PENALTY = 35;
|
|
15
|
+
|
|
16
|
+
/** FlexSearch answers as [{field, result: [ids]}] or, sometimes, bare ids. */
|
|
17
|
+
function flattenIds(matches: any): string[] {
|
|
18
|
+
if (!Array.isArray(matches)) return [];
|
|
19
|
+
const ids: string[] = [];
|
|
20
|
+
for (const match of matches) {
|
|
21
|
+
if (typeof match === 'string') ids.push(match);
|
|
22
|
+
else if (Array.isArray(match?.result)) ids.push(...(match.result as string[]));
|
|
23
|
+
}
|
|
24
|
+
return ids;
|
|
25
|
+
}
|
|
26
|
+
|
|
10
27
|
/**
|
|
11
28
|
* Inverse search engine, FlexSearch candidates with heuristic ranking.
|
|
12
29
|
* Queries the degraded layers first (level 3), then escalates.
|
|
@@ -64,10 +81,18 @@ export class InverseSearchEngine {
|
|
|
64
81
|
}
|
|
65
82
|
|
|
66
83
|
/**
|
|
67
|
-
* Inverse search: starts at level 3 and escalates when needed
|
|
84
|
+
* Inverse search: starts at level 3 and escalates when needed.
|
|
85
|
+
*
|
|
86
|
+
* Two passes. The first is strict, and answers almost every query. The second
|
|
87
|
+
* only runs when the first found nothing anywhere, and exists because of
|
|
88
|
+
* audit A13: FlexSearch requires EVERY query term inside a SINGLE field, and
|
|
89
|
+
* the decay levels are indexed as separate fields — so a query whose terms
|
|
90
|
+
* straddle the L3 keyword line and the full content matched neither and
|
|
91
|
+
* returned nothing at all. "sqlite lock" found the trace; "sqlite concurrent
|
|
92
|
+
* write lock" found silence, which is the worst possible answer to a user
|
|
93
|
+
* being more precise.
|
|
68
94
|
*/
|
|
69
95
|
search(query: SearchQuery): SearchResult[] {
|
|
70
|
-
const results: SearchResult[] = [];
|
|
71
96
|
const { query: searchQuery, maxLevel = 3, limit = 10 } = query;
|
|
72
97
|
|
|
73
98
|
// Level-by-level strategy, from most degraded to most detailed
|
|
@@ -77,33 +102,32 @@ export class InverseSearchEngine {
|
|
|
77
102
|
{ field: 'level1Summary', level: 1 },
|
|
78
103
|
{ field: 'content', level: 0 },
|
|
79
104
|
];
|
|
105
|
+
const levels = searchOrder.filter(({ level }) => level <= maxLevel);
|
|
80
106
|
|
|
81
|
-
const
|
|
107
|
+
const strict = this.collect(query, levels, (field) => this.strictIds(searchQuery, field));
|
|
108
|
+
// Whole-query match found something: it is the better answer by definition,
|
|
109
|
+
// and relaxing further would only add neighbours below it.
|
|
110
|
+
const results = strict.length
|
|
111
|
+
? strict
|
|
112
|
+
: this.collect(query, levels, (field) => this.nearMissIds(searchQuery, field), true);
|
|
82
113
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
114
|
+
return results
|
|
115
|
+
.sort((a, b) => b.score - a.score || a.memory.id.localeCompare(b.memory.id))
|
|
116
|
+
.slice(0, Math.max(0, limit));
|
|
117
|
+
}
|
|
86
118
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
const ids: string[] = [];
|
|
97
|
-
for (const match of matches) {
|
|
98
|
-
if (match && typeof match === 'object' && 'result' in match) {
|
|
99
|
-
ids.push(...(match.result as string[]));
|
|
100
|
-
} else if (typeof match === 'string') {
|
|
101
|
-
ids.push(match);
|
|
102
|
-
}
|
|
103
|
-
}
|
|
119
|
+
/** Runs one pass over the levels, filtering and scoring what the ids yield. */
|
|
120
|
+
private collect(
|
|
121
|
+
query: SearchQuery,
|
|
122
|
+
levels: { field: string; level: DecayLevel }[],
|
|
123
|
+
idsFor: (field: string) => string[],
|
|
124
|
+
partial = false
|
|
125
|
+
): SearchResult[] {
|
|
126
|
+
const results: SearchResult[] = [];
|
|
127
|
+
const seenIds = new Set<string>();
|
|
104
128
|
|
|
105
|
-
|
|
106
|
-
for (const id of
|
|
129
|
+
for (const { field, level } of levels) {
|
|
130
|
+
for (const id of idsFor(field)) {
|
|
107
131
|
if (seenIds.has(id)) continue;
|
|
108
132
|
seenIds.add(id);
|
|
109
133
|
|
|
@@ -122,25 +146,73 @@ export class InverseSearchEngine {
|
|
|
122
146
|
results.push({
|
|
123
147
|
memory,
|
|
124
148
|
matchLevel: level,
|
|
125
|
-
score: this.calculateScore(memory,
|
|
149
|
+
score: this.calculateScore(memory, query.query, level, partial),
|
|
126
150
|
});
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return results;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Ids matching the whole query inside one field — FlexSearch's own AND. */
|
|
158
|
+
private strictIds(searchQuery: string, field: string): string[] {
|
|
159
|
+
return flattenIds(
|
|
160
|
+
this.index.search({
|
|
161
|
+
query: searchQuery,
|
|
162
|
+
field,
|
|
163
|
+
limit: Math.max(1, this.memories.size), // rank all candidates after filtering
|
|
164
|
+
})
|
|
165
|
+
);
|
|
166
|
+
}
|
|
127
167
|
|
|
168
|
+
/**
|
|
169
|
+
* Ids matching all but at most one term of the query inside one field.
|
|
170
|
+
*
|
|
171
|
+
* FlexSearch's own `suggest: true` would accept a single term out of five,
|
|
172
|
+
* which turns a missed recall into a confident wrong neighbour — measurably:
|
|
173
|
+
* it put an auth token race at the top of "sqlite concurrent write lock".
|
|
174
|
+
* Counting the terms ourselves keeps the near-misses and drops the strangers.
|
|
175
|
+
*/
|
|
176
|
+
private nearMissIds(searchQuery: string, field: string): string[] {
|
|
177
|
+
const terms = searchQuery.split(/\s+/).filter(Boolean);
|
|
178
|
+
if (terms.length < 2) return [];
|
|
179
|
+
|
|
180
|
+
const hits = new Map<string, number>();
|
|
181
|
+
for (const term of terms) {
|
|
182
|
+
for (const id of this.strictIds(term, field)) {
|
|
183
|
+
hits.set(id, (hits.get(id) ?? 0) + 1);
|
|
128
184
|
}
|
|
129
185
|
}
|
|
130
186
|
|
|
131
|
-
|
|
187
|
+
const required = terms.length - 1;
|
|
188
|
+
return [...hits.entries()]
|
|
189
|
+
.filter(([, count]) => count >= required)
|
|
190
|
+
// More terms satisfied first: the pass keeps insertion order downstream.
|
|
191
|
+
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
|
|
192
|
+
.map(([id]) => id);
|
|
132
193
|
}
|
|
133
194
|
|
|
134
195
|
/**
|
|
135
196
|
* Calcule un score de pertinence
|
|
136
197
|
*/
|
|
137
|
-
private calculateScore(
|
|
198
|
+
private calculateScore(
|
|
199
|
+
memory: Memory,
|
|
200
|
+
query: string,
|
|
201
|
+
matchLevel: DecayLevel,
|
|
202
|
+
partial = false
|
|
203
|
+
): number {
|
|
138
204
|
let score = 100;
|
|
139
205
|
|
|
140
206
|
// Bonus for matching on a degraded level: cheaper to reach, more useful
|
|
141
207
|
const levelBonus = matchLevel * 10;
|
|
142
208
|
score += levelBonus;
|
|
143
209
|
|
|
210
|
+
// A partial match satisfied only some of the query terms (A13 fallback).
|
|
211
|
+
// The penalty exceeds the widest level bonus on purpose: an exact match at
|
|
212
|
+
// any level must outrank a partial one at every level, or a loose hit on
|
|
213
|
+
// the keyword line would bury an exact hit in the full content.
|
|
214
|
+
if (partial) score -= PARTIAL_MATCH_PENALTY;
|
|
215
|
+
|
|
144
216
|
// Recency bonus
|
|
145
217
|
const daysSinceCreation =
|
|
146
218
|
(this.clock.now().getTime() - memory.createdAt.getTime()) / (1000 * 60 * 60 * 24);
|
package/src/core/types.ts
CHANGED
|
@@ -28,7 +28,7 @@ export interface Memory {
|
|
|
28
28
|
content: string; // Level 0 (full detail)
|
|
29
29
|
level1Summary?: string; // Level 1 (summary)
|
|
30
30
|
level2Essential?: string; // Level 2 (gist)
|
|
31
|
-
level3Keywords?: string; // Level 3 (keywords for
|
|
31
|
+
level3Keywords?: string; // Level 3 (keywords for the lexical index)
|
|
32
32
|
|
|
33
33
|
// Lightweight metadata
|
|
34
34
|
directory: string; // Project / source
|