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 CHANGED
@@ -24,7 +24,7 @@ On top of both: a **trust layer** (Phase 6) so several agents can write to one
24
24
  store without a wrong lesson becoming indestructible, a **dreamer** (6.1) that
25
25
  proposes cross-session/cross-agent patterns for human review, an **MCP server**
26
26
  (6.2) so Claude/Codex/Kimi/OpenCode share one memory, and **vector search**
27
- (Phase 7) as an opt-in second retrieval lane alongside BM25.
27
+ (Phase 7) as an opt-in second retrieval lane alongside the lexical one.
28
28
 
29
29
  The conceptual source for the prospective half is `SCRATCHPAD.md` (memoire
30
30
  prospective, scripts cognitifs, effet Zeigarnik).
@@ -61,7 +61,7 @@ src/
61
61
  ├── core/
62
62
  │ ├── types.ts # Memory, DecayLevel, SearchQuery, MemoryStore iface
63
63
  │ ├── decay.ts # degradation curve + thresholds
64
- │ ├── search.ts # inverse search (BM25, degraded-first)
64
+ │ ├── search.ts # inverse search (lexical, degraded-first)
65
65
  │ └── llm-generator.ts # deterministic L1/L2/L3; optional injected LLM
66
66
  ├── store/
67
67
  │ └── sqlite.ts # bun:sqlite store (WAL), findSimilar/merge/setPhotographic
@@ -81,6 +81,8 @@ src/
81
81
  │ ├── clock.ts # Clock seam (systemClock / FakeClock)
82
82
  │ ├── event-bus.ts # AppEvent + InMemoryEventBus
83
83
  │ ├── cue-arg.ts # cue syntax, shared by the CLI and the React form
84
+ │ ├── paths.ts # single resolver for data/db/queue/model-cache/install root
85
+ │ ├── doctor.ts # install diagnostic behind `humemory doctor` (no content read)
84
86
  │ └── cues.ts # cue resolver, cron matcher, loop ids
85
87
  ├── api/server.ts # Hono HTTP API + serves public/ dashboard
86
88
  ├── cli/index.ts # commander CLI
@@ -89,8 +91,10 @@ web/ # React front (bun bundler → public/app, served at /
89
91
  scripts/hook-session.ts # Claude Code Stop hook → queue raw session only
90
92
  scripts/hook-session-start.ts # Claude Code SessionStart hook → inject context
91
93
  scripts/maintenance-worker.ts # async extraction/storage; deterministic by default
94
+ scripts/verify-package.ts # packs, installs outside the checkout, drives every entry point
95
+ scripts/measure-recall.ts # cognitive-quality report over tests/fixtures/relevance.corpus.json
92
96
  tests/ # bun test (hermetic; helpers/ + fixtures/)
93
- data/humemory.db # shared DB (created on first run)
97
+ data/humemory.db # legacy in-checkout DB; new installs use the OS data dir (core/paths.ts)
94
98
  ```
95
99
 
96
100
  ---
package/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.10] - 2026-09-08
4
+ **Features:**
5
+ - measure whether the right memory comes back
6
+
7
+ **Bug Fixes:**
8
+ - answer a query whose terms straddle the decay levels
9
+
10
+
11
+
12
+ ## [0.2.9] - 2026-09-07
13
+ **Features:**
14
+ - diagnose an installation, and prove the packaged one
15
+
16
+ **Bug Fixes:**
17
+ - make audit validation deterministic and isolated
18
+ - spawn the pnpm/npm shims through a shell on Windows
19
+ - pull fast-uri onto a patched 3.x
20
+
21
+ **Documentation:**
22
+ - record the remediation status in the portability audit
23
+
24
+ **Chores:**
25
+ - drop the dead lockStaleMs knob
26
+
27
+
28
+
3
29
  ## [0.2.8] - 2026-09-06
4
30
  **Other:**
5
31
  - Add comprehensive tests for audit, maintenance, and import functionalities
package/README.md CHANGED
@@ -28,7 +28,7 @@ Past learnings are **encoded**, then **degraded** over time on a human curve:
28
28
  | L0 | full detail | fresh (<24h) | complete content |
29
29
  | L1 | summary | days | LLM-generated résumé |
30
30
  | L2 | essential | weeks | the gist |
31
- | L3 | keywords | months | BM25 retrieval tokens |
31
+ | L3 | keywords | months | lexical retrieval tokens |
32
32
  | L4 | lost / merged | beyond | folded into a sibling trace |
33
33
 
34
34
  Recall resists decay. Saillance (mnemonic strength, 0–100) and recall count slow
@@ -340,7 +340,8 @@ discovery never pretends otherwise.
340
340
 
341
341
  ## Stack
342
342
 
343
- TypeScript · `bun:sqlite` (WAL) · `flexsearch` (BM25) · `hono` (API) ·
343
+ TypeScript · `bun:sqlite` (WAL) · `flexsearch` (lexical index, heuristic
344
+ ranking — not a BM25 implementation) · `hono` (API) ·
344
345
  `commander` (CLI) · `@anthropic-ai/sdk` (optional maintenance adapter).
345
346
 
346
347
  ---
@@ -353,6 +354,22 @@ TypeScript · `bun:sqlite` (WAL) · `flexsearch` (BM25) · `hono` (API) ·
353
354
  pnpm install
354
355
  ```
355
356
 
357
+ New installations keep writable state in the user profile. Existing checkouts
358
+ with `data/humemory.db` keep that location; nothing is moved automatically.
359
+ `HUMEMORY_DATA_DIR` selects another data root, while `HUMEMORY_DB`,
360
+ `HUMEMORY_QUEUE` and `HUMEMORY_MODEL_CACHE` override individual locations.
361
+
362
+ To relocate a project's memory, preview the mapping before applying it:
363
+
364
+ ```bash
365
+ pnpm cli remap-project /old/project /new/project
366
+ pnpm cli remap-project /old/project /new/project --apply --backup /backups/before-remap.db
367
+ ```
368
+
369
+ The backup includes committed SQLite WAL contents. See
370
+ [portability and recovery guarantees](docs/PORTABILITY.md) for cron time zones,
371
+ model downloads, queue recovery and the limits of the platform checks.
372
+
356
373
  ### CLI Commands
357
374
 
358
375
  The CLI provides several commands to interact with humemory:
@@ -446,6 +463,18 @@ The CLI provides several commands to interact with humemory:
446
463
  - `-d, --directory <dir>`: Project mental space
447
464
  - `-n, --max <n>`: Max learnings to extract
448
465
 
466
+ - **Diagnose the installation**:
467
+ ```bash
468
+ pnpm cli doctor
469
+ ```
470
+ Prints the runtime, the resolved data/queue/model paths and whether they are
471
+ writable, the schema and journal mode, the state of both advisory locks, the
472
+ cached embedding models, and every auxiliary entry point (hooks, MCP server,
473
+ API, dashboard). Environment overrides are listed **by name only** — no value
474
+ is printed, and no memory content is read, so the output is safe to paste into
475
+ a bug report. `--json` for a machine-readable report; exit code 1 on a real
476
+ fault, 0 when everything that failed is merely "not set up yet".
477
+
449
478
  ### API
450
479
 
451
480
  Start the API server:
@@ -582,6 +611,35 @@ pnpm cli <command>
582
611
  pnpm consolidate
583
612
  ```
584
613
 
614
+ ### Measuring recall quality
615
+
616
+ ```bash
617
+ pnpm measure:recall
618
+ ```
619
+
620
+ Runs a frozen corpus of 26 traces at controlled ages against 14 queries and
621
+ prints, per query, what came back and what was missed — plus which open loops
622
+ come due at a given instant, and what a session actually opens with. The suite
623
+ proves the machinery works; this asks the question the machinery exists for:
624
+ does the *right* memory come back. `tests/relevance.test.ts` turns the same
625
+ measurement into a regression floor.
626
+
627
+ Thresholds there are floors recording current behaviour, not targets. Raising
628
+ one is a result; lowering one needs a reason in the commit that lowers it.
629
+
630
+ ### Verifying the published package
631
+
632
+ ```bash
633
+ pnpm verify:package
634
+ ```
635
+
636
+ Builds the archive, installs it into a temporary directory **outside** the
637
+ checkout — under a path containing a space and an accent — and drives the CLI,
638
+ the Stop hook, maintenance, the MCP server and the API from there against a
639
+ virgin profile. Nothing may reach back into the source tree, so a `files` list
640
+ that forgets a source an auxiliary entry point imports fails here rather than
641
+ days later on a user's machine. Runs on Linux, macOS and Windows in CI.
642
+
585
643
  ---
586
644
 
587
645
  ## Concepts
@@ -36,7 +36,6 @@ export interface WorkerOptions {
36
36
  client?: LLMClient;
37
37
  llmTimeoutMs?: number;
38
38
  maxJobs?: number;
39
- lockStaleMs?: number;
40
39
  maxAttempts?: number;
41
40
  /**
42
41
  * Consecutive job failures that trip the circuit breaker and end the pass.
@@ -4,7 +4,6 @@ import { join } from 'path';
4
4
  import { processSession } from './claude-hook.js';
5
5
  import { parseAgentSession } from './session-parser.js';
6
6
  import { AdvisoryLock } from '../store/sqlite.js';
7
- const DEFAULT_LOCK_STALE_MS = 5 * 60 * 1000;
8
7
  const DEFAULT_MAX_ATTEMPTS = 5;
9
8
  const DEFAULT_FAILURE_THRESHOLD = 3;
10
9
  const DEAD_LETTER_SUFFIX = '.dead.json';
@@ -29,7 +29,7 @@ export function createMemoryRoutes(store) {
29
29
  maxItemLength: MAX_KEYWORD_LENGTH,
30
30
  name: 'keywords',
31
31
  });
32
- // level3Keywords is the flat BM25 keyword line, not an array (core/types.ts).
32
+ // level3Keywords is the flat lexical keyword line, not an array (core/types.ts).
33
33
  const level3Keywords = boundedOptionalString(body.level3Keywords, MAX_CONTENT_LENGTH, 'level3Keywords');
34
34
  const directory = boundedOptionalString(body.directory, MAX_SHORT_FIELD_LENGTH, 'directory');
35
35
  const day = boundedOptionalString(body.day, MAX_SHORT_FIELD_LENGTH, 'day');
package/dist/cli/index.js CHANGED
@@ -8,6 +8,7 @@ import { join, dirname, resolve } from 'path';
8
8
  import { fileURLToPath } from 'url';
9
9
  import { readFileSync } from 'fs';
10
10
  import { discoverLocalAgentSources } from '../agent/source-registry.js';
11
+ import { runDoctor, renderDoctorReport } from '../core/doctor.js';
11
12
  const __filename = fileURLToPath(import.meta.url);
12
13
  const __dirname = dirname(__filename);
13
14
  // Shared store. HUMEMORY_DB points at another database — same convention as the
@@ -24,7 +25,10 @@ function getStore() {
24
25
  }
25
26
  const program = new Command();
26
27
  // Version read from the package: hard-coded, it drifted at every release.
27
- const { version } = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8'));
28
+ const { version, engines } = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8'));
29
+ // Declared minimum, not a hard-coded one: `humemory doctor` must fail when the
30
+ // runtime is below what the package claims to support, whatever that becomes.
31
+ const minimumBunVersion = engines?.bun;
28
32
  program
29
33
  .name('humemory')
30
34
  .description('Memory palace — mnemonic traces with progressive decay')
@@ -87,7 +91,7 @@ program
87
91
  .option('--to <date>', 'End date YYYY-MM-DD')
88
92
  .option('--min-saillance <n>', 'Minimum mnemonic strength (0-100)')
89
93
  .option('--min-recalls <n>', 'Minimum recall count')
90
- .option('--semantic', 'Hybrid search: fuse BM25 with vector similarity (Phase 7.4, needs the model)')
94
+ .option('--semantic', 'Hybrid search: fuse the lexical lane with vector similarity (Phase 7.4, needs the model)')
91
95
  .action(async (query, options) => {
92
96
  const s = getStore();
93
97
  let results;
@@ -1056,6 +1060,21 @@ program.command('remap-project <from> <to>')
1056
1060
  .action(async (from, to, options) => {
1057
1061
  console.log(JSON.stringify(await getStore().remapProjectRoot(from, to, { apply: options.apply, backupPath: options.backup }), null, 2));
1058
1062
  });
1063
+ // === DOCTOR ===
1064
+ // Deliberately does not go through getStore(): the point is to diagnose an
1065
+ // installation that may not have a usable store yet.
1066
+ program
1067
+ .command('doctor')
1068
+ .description('Diagnose the installation: runtime, paths, rights, schema, locks, models, entry points')
1069
+ .option('--json', 'Machine-readable report')
1070
+ .action(async (options) => {
1071
+ const report = await runDoctor({ minimumBun: minimumBunVersion });
1072
+ console.log(options.json ? JSON.stringify(report, null, 2) : renderDoctorReport(report));
1073
+ // Non-zero only on a real fault: warnings are states an install can sit in
1074
+ // (no model cached yet, a maintenance worker currently running).
1075
+ if (report.status === 'fail')
1076
+ process.exitCode = 1;
1077
+ });
1059
1078
  // Parse and run
1060
1079
  program.parse();
1061
1080
  // Cleanup
@@ -0,0 +1,28 @@
1
+ export type DoctorStatus = 'ok' | 'warn' | 'fail';
2
+ export interface DoctorCheck {
3
+ /** Stable machine-readable id, safe to grep in CI. */
4
+ id: string;
5
+ section: 'runtime' | 'paths' | 'storage' | 'locks' | 'models' | 'entrypoints';
6
+ status: DoctorStatus;
7
+ /** One line, no secrets, no memory content. */
8
+ detail: string;
9
+ }
10
+ export interface DoctorReport {
11
+ checks: DoctorCheck[];
12
+ /** Worst status across every check — the exit code the CLI maps to. */
13
+ status: DoctorStatus;
14
+ }
15
+ export interface DoctorOptions {
16
+ /** Overridden wholesale in tests so no probe touches the real palace. */
17
+ paths?: {
18
+ data: string;
19
+ database: string;
20
+ queue: string;
21
+ modelCache: string;
22
+ };
23
+ installRoot?: string;
24
+ /** Minimum runtime the package claims to support (`engines.bun`). */
25
+ minimumBun?: string;
26
+ }
27
+ export declare function runDoctor(options?: DoctorOptions): Promise<DoctorReport>;
28
+ export declare function renderDoctorReport(report: DoctorReport): string;
@@ -0,0 +1,320 @@
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 { dataDirectory, databasePath, installationDirectory, modelCacheDirectory, queueDirectory, } from './paths.js';
21
+ /** Env overrides worth reporting. Names only — a value can be a private path. */
22
+ const TRACKED_ENV = [
23
+ 'HUMEMORY_DATA_DIR',
24
+ 'HUMEMORY_DB',
25
+ 'HUMEMORY_QUEUE',
26
+ 'HUMEMORY_MODEL_CACHE',
27
+ 'HUMEMORY_HOST',
28
+ 'HUMEMORY_API_TOKEN',
29
+ 'PORT',
30
+ ];
31
+ /**
32
+ * Auxiliary entry points, relative to the installation root. `optional` covers
33
+ * what a source checkout legitimately lacks before a build (`dist`, the
34
+ * bundled dashboard); a missing required file means the published archive is
35
+ * broken for that entry point.
36
+ */
37
+ const ENTRY_POINTS = [
38
+ { path: 'bin/humemory.js', label: 'CLI shim' },
39
+ { path: 'dist/cli/index.js', label: 'CLI implementation', optional: true },
40
+ { path: 'src/mcp/server.ts', label: 'MCP server (registered by `humemory setup`)' },
41
+ { path: 'src/api/server.ts', label: 'HTTP API' },
42
+ { path: 'scripts/hook-session.ts', label: 'Stop hook' },
43
+ { path: 'scripts/hook-session-start.ts', label: 'SessionStart hook' },
44
+ { path: 'scripts/hook-post-commit.ts', label: 'post-commit hook' },
45
+ { path: 'scripts/maintenance-worker.ts', label: 'maintenance worker' },
46
+ { path: 'public/app', label: 'bundled dashboard', optional: true },
47
+ ];
48
+ /** Tables the store creates. A missing one means an interrupted migration. */
49
+ const EXPECTED_TABLES = [
50
+ 'memories',
51
+ 'intentions',
52
+ 'cues',
53
+ 'scripts',
54
+ 'contradictions',
55
+ ];
56
+ function compareSemver(actual, minimum) {
57
+ const parse = (v) => v.replace(/^[^\d]*/, '').split('.').map((n) => parseInt(n, 10) || 0);
58
+ const [a, b] = [parse(actual), parse(minimum)];
59
+ for (let i = 0; i < 3; i++) {
60
+ if ((a[i] ?? 0) !== (b[i] ?? 0))
61
+ return (a[i] ?? 0) - (b[i] ?? 0);
62
+ }
63
+ return 0;
64
+ }
65
+ /** Probe by writing, not by reading a permission bit: ACLs lie on Windows. */
66
+ async function probeWritable(directory) {
67
+ const probe = join(directory, `.humemory-doctor-${randomUUID()}`);
68
+ try {
69
+ await mkdir(directory, { recursive: true });
70
+ await writeFile(probe, '', { flag: 'wx' });
71
+ return { status: 'ok', detail: `writable — ${directory}` };
72
+ }
73
+ catch (error) {
74
+ return { status: 'fail', detail: `not writable (${error?.code ?? 'unknown'}) — ${directory}` };
75
+ }
76
+ finally {
77
+ await rm(probe, { force: true }).catch(() => { });
78
+ }
79
+ }
80
+ /**
81
+ * Is the advisory lock at `lockFile` held right now? Acquiring and releasing
82
+ * is the only honest answer — the lock has no wall-clock expiry to inspect
83
+ * (audit A08), and its owner is the OS, not a mtime.
84
+ */
85
+ function probeLock(lockFile) {
86
+ const sqlitePath = `${lockFile}.sqlite`;
87
+ if (!existsSync(sqlitePath))
88
+ return { status: 'ok', detail: `free (never taken) — ${lockFile}` };
89
+ let connection = null;
90
+ try {
91
+ connection = new Database(sqlitePath);
92
+ connection.exec('PRAGMA busy_timeout=0; BEGIN IMMEDIATE');
93
+ connection.exec('ROLLBACK');
94
+ return { status: 'ok', detail: `free — ${lockFile}` };
95
+ }
96
+ catch (error) {
97
+ const code = String(error?.code ?? '');
98
+ if (code.startsWith('SQLITE_BUSY') || code.startsWith('SQLITE_LOCKED')) {
99
+ // Held by a live process. Not a fault: a worker may simply be running.
100
+ return { status: 'warn', detail: `held by a live process — ${lockFile}` };
101
+ }
102
+ return { status: 'fail', detail: `unreadable (${code || 'unknown'}) — ${lockFile}` };
103
+ }
104
+ finally {
105
+ connection?.close();
106
+ }
107
+ }
108
+ function inspectDatabase(dbPath) {
109
+ if (dbPath === ':memory:') {
110
+ return [{ id: 'db.open', section: 'storage', status: 'warn', detail: 'in-memory database — nothing persists' }];
111
+ }
112
+ if (!existsSync(dbPath)) {
113
+ return [
114
+ { id: 'db.open', section: 'storage', status: 'warn', detail: `absent, created on first write — ${dbPath}` },
115
+ ];
116
+ }
117
+ let db = null;
118
+ try {
119
+ db = new Database(dbPath, { readonly: true });
120
+ const names = new Set(db.query("SELECT name FROM sqlite_master WHERE type='table'").all().map((r) => r.name));
121
+ const missing = EXPECTED_TABLES.filter((table) => !names.has(table));
122
+ const journal = db.query('PRAGMA journal_mode').get().journal_mode;
123
+ const checks = [
124
+ {
125
+ id: 'db.open',
126
+ section: 'storage',
127
+ status: 'ok',
128
+ detail: `opened, ${names.size} tables, journal_mode=${journal} — ${dbPath}`,
129
+ },
130
+ {
131
+ id: 'db.schema',
132
+ section: 'storage',
133
+ status: missing.length ? 'fail' : 'ok',
134
+ detail: missing.length
135
+ ? `missing tables: ${missing.join(', ')} — migration interrupted`
136
+ : `all ${EXPECTED_TABLES.length} expected tables present`,
137
+ },
138
+ ];
139
+ if (journal.toLowerCase() !== 'wal') {
140
+ checks.push({
141
+ id: 'db.wal',
142
+ section: 'storage',
143
+ status: 'warn',
144
+ detail: `journal_mode is ${journal}; multi-process access expects WAL`,
145
+ });
146
+ }
147
+ return checks;
148
+ }
149
+ catch (error) {
150
+ return [
151
+ { id: 'db.open', section: 'storage', status: 'fail', detail: `cannot open (${error?.code ?? 'unknown'}) — ${dbPath}` },
152
+ ];
153
+ }
154
+ finally {
155
+ db?.close();
156
+ }
157
+ }
158
+ function inspectModels(cacheDir) {
159
+ if (!existsSync(cacheDir)) {
160
+ return {
161
+ id: 'models.cache',
162
+ section: 'models',
163
+ status: 'warn',
164
+ detail: `no model cache — semantic recall downloads on first use (${cacheDir})`,
165
+ };
166
+ }
167
+ // One level of vendor/model directories is enough to name what is installed;
168
+ // walking the whole tree would be slow and tells the user nothing more.
169
+ const vendors = readdirSync(cacheDir).filter((entry) => {
170
+ try {
171
+ return statSync(join(cacheDir, entry)).isDirectory();
172
+ }
173
+ catch {
174
+ return false;
175
+ }
176
+ });
177
+ const models = [];
178
+ for (const vendor of vendors) {
179
+ try {
180
+ for (const model of readdirSync(join(cacheDir, vendor))) {
181
+ if (statSync(join(cacheDir, vendor, model)).isDirectory())
182
+ models.push(`${vendor}/${model}`);
183
+ }
184
+ }
185
+ catch {
186
+ /* unreadable subdirectory tells us nothing; the cache check above stands */
187
+ }
188
+ }
189
+ return {
190
+ id: 'models.cache',
191
+ section: 'models',
192
+ status: models.length ? 'ok' : 'warn',
193
+ detail: models.length ? `cached: ${models.join(', ')}` : `cache directory empty — ${cacheDir}`,
194
+ };
195
+ }
196
+ function inspectEntryPoints(installRoot) {
197
+ return ENTRY_POINTS.map(({ path, label, optional }) => {
198
+ const absolute = join(installRoot, path);
199
+ const present = existsSync(absolute);
200
+ return {
201
+ id: `entry.${path}`,
202
+ section: 'entrypoints',
203
+ status: present ? 'ok' : optional ? 'warn' : 'fail',
204
+ detail: present
205
+ ? `${label} — ${path}`
206
+ : optional
207
+ ? `${label} absent (build not run?) — ${path}`
208
+ : `${label} MISSING from the installation — ${path}`,
209
+ };
210
+ });
211
+ }
212
+ export async function runDoctor(options = {}) {
213
+ const paths = options.paths ?? {
214
+ data: dataDirectory(),
215
+ database: databasePath(),
216
+ queue: queueDirectory(),
217
+ modelCache: modelCacheDirectory(),
218
+ };
219
+ const installRoot = options.installRoot ?? installationDirectory();
220
+ const checks = [];
221
+ // --- runtime ---
222
+ const bunVersion = typeof Bun === 'undefined' ? null : Bun.version;
223
+ if (!bunVersion) {
224
+ checks.push({
225
+ id: 'runtime.bun',
226
+ section: 'runtime',
227
+ status: 'fail',
228
+ detail: 'not running under bun — the store needs bun:sqlite',
229
+ });
230
+ }
231
+ else if (options.minimumBun && compareSemver(bunVersion, options.minimumBun) < 0) {
232
+ checks.push({
233
+ id: 'runtime.bun',
234
+ section: 'runtime',
235
+ status: 'fail',
236
+ detail: `bun ${bunVersion} is below the declared minimum ${options.minimumBun}`,
237
+ });
238
+ }
239
+ else {
240
+ checks.push({ id: 'runtime.bun', section: 'runtime', status: 'ok', detail: `bun ${bunVersion}` });
241
+ }
242
+ checks.push({
243
+ id: 'runtime.platform',
244
+ section: 'runtime',
245
+ status: 'ok',
246
+ detail: `${platform()} ${arch()} (kernel ${release()})`,
247
+ });
248
+ const setEnv = TRACKED_ENV.filter((name) => (process.env[name] ?? '') !== '');
249
+ checks.push({
250
+ id: 'runtime.env',
251
+ section: 'runtime',
252
+ // Names only. HUMEMORY_API_TOKEN's value must never reach a log.
253
+ status: 'ok',
254
+ detail: setEnv.length ? `overrides set: ${setEnv.join(', ')}` : 'no environment overrides set',
255
+ });
256
+ // --- paths and write rights ---
257
+ for (const [id, directory] of [
258
+ ['paths.data', paths.data],
259
+ ['paths.queue', paths.queue],
260
+ ['paths.modelCache', paths.modelCache],
261
+ ]) {
262
+ const probe = await probeWritable(directory);
263
+ checks.push({ id, section: 'paths', status: probe.status, detail: probe.detail });
264
+ }
265
+ checks.push({
266
+ id: 'paths.database',
267
+ section: 'paths',
268
+ status: 'ok',
269
+ detail: `database resolves to ${paths.database}`,
270
+ });
271
+ checks.push({
272
+ id: 'paths.install',
273
+ section: 'paths',
274
+ status: 'ok',
275
+ detail: `installation root ${installRoot}`,
276
+ });
277
+ // --- storage, locks, models, entry points ---
278
+ checks.push(...inspectDatabase(paths.database));
279
+ if (paths.database !== ':memory:') {
280
+ const dbLock = probeLock(`${paths.database}.lock`);
281
+ checks.push({ id: 'locks.database', section: 'locks', ...dbLock });
282
+ }
283
+ const workerLock = probeLock(join(paths.queue, '.worker-lock'));
284
+ checks.push({ id: 'locks.maintenance', section: 'locks', ...workerLock });
285
+ checks.push(inspectModels(paths.modelCache));
286
+ checks.push(...inspectEntryPoints(installRoot));
287
+ const status = checks.some((c) => c.status === 'fail')
288
+ ? 'fail'
289
+ : checks.some((c) => c.status === 'warn')
290
+ ? 'warn'
291
+ : 'ok';
292
+ return { checks, status };
293
+ }
294
+ const SECTION_TITLES = {
295
+ runtime: 'Runtime',
296
+ paths: 'Paths and write rights',
297
+ storage: 'Database',
298
+ locks: 'Locks',
299
+ models: 'Embedding models',
300
+ entrypoints: 'Entry points',
301
+ };
302
+ const MARKS = { ok: '✅', warn: '⚠️ ', fail: '❌' };
303
+ export function renderDoctorReport(report) {
304
+ const lines = ['', '🩺 humemory doctor', ''];
305
+ for (const section of Object.keys(SECTION_TITLES)) {
306
+ const rows = report.checks.filter((check) => check.section === section);
307
+ if (!rows.length)
308
+ continue;
309
+ lines.push(`${SECTION_TITLES[section]}:`);
310
+ for (const row of rows)
311
+ lines.push(` ${MARKS[row.status]} ${row.detail}`);
312
+ lines.push('');
313
+ }
314
+ const failed = report.checks.filter((c) => c.status === 'fail').length;
315
+ const warned = report.checks.filter((c) => c.status === 'warn').length;
316
+ lines.push(report.status === 'ok'
317
+ ? 'All checks passed.'
318
+ : `${failed} failing, ${warned} to review out of ${report.checks.length} checks.`);
319
+ return lines.join('\n');
320
+ }
@@ -1,10 +1,14 @@
1
1
  /**
2
2
  * Hybrid search — Phase 7.4.
3
3
  *
4
- * Reciprocal Rank Fusion of the BM25 lane (exact identifiers: loop-ab12, file
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 BM25 ranking — no regression on bare installs.
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
@@ -1,10 +1,14 @@
1
1
  /**
2
2
  * Hybrid search — Phase 7.4.
3
3
  *
4
- * Reciprocal Rank Fusion of the BM25 lane (exact identifiers: loop-ab12, file
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 BM25 ranking — no regression on bare installs.
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
@@ -3,3 +3,10 @@ export declare function dataDirectory(): string;
3
3
  export declare function databasePath(): string;
4
4
  export declare function queueDirectory(): string;
5
5
  export declare function modelCacheDirectory(): string;
6
+ /**
7
+ * Root of the installed package — the anchor auxiliary entry points (hooks,
8
+ * MCP server, bundled dashboard) are resolved against. `humemory doctor`
9
+ * checks them from here so a package that ships the wrong `files` list fails
10
+ * loudly instead of at the first hook invocation.
11
+ */
12
+ export declare function installationDirectory(): string;
@@ -25,3 +25,12 @@ export function queueDirectory() {
25
25
  export function modelCacheDirectory() {
26
26
  return process.env.HUMEMORY_MODEL_CACHE ?? join(dataDirectory(), 'models');
27
27
  }
28
+ /**
29
+ * Root of the installed package — the anchor auxiliary entry points (hooks,
30
+ * MCP server, bundled dashboard) are resolved against. `humemory doctor`
31
+ * checks them from here so a package that ships the wrong `files` list fails
32
+ * loudly instead of at the first hook invocation.
33
+ */
34
+ export function installationDirectory() {
35
+ return installationRoot;
36
+ }