humemory 0.2.8 → 0.2.9

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,9 @@ 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
92
95
  tests/ # bun test (hermetic; helpers/ + fixtures/)
93
- data/humemory.db # shared DB (created on first run)
96
+ data/humemory.db # legacy in-checkout DB; new installs use the OS data dir (core/paths.ts)
94
97
  ```
95
98
 
96
99
  ---
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.9] - 2026-09-07
4
+ **Features:**
5
+ - diagnose an installation, and prove the packaged one
6
+
7
+ **Bug Fixes:**
8
+ - make audit validation deterministic and isolated
9
+ - spawn the pnpm/npm shims through a shell on Windows
10
+ - pull fast-uri onto a patched 3.x
11
+
12
+ **Documentation:**
13
+ - record the remediation status in the portability audit
14
+
15
+ **Chores:**
16
+ - drop the dead lockStaleMs knob
17
+
18
+
19
+
3
20
  ## [0.2.8] - 2026-09-06
4
21
  **Other:**
5
22
  - 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,19 @@ pnpm cli <command>
582
611
  pnpm consolidate
583
612
  ```
584
613
 
614
+ ### Verifying the published package
615
+
616
+ ```bash
617
+ pnpm verify:package
618
+ ```
619
+
620
+ Builds the archive, installs it into a temporary directory **outside** the
621
+ checkout — under a path containing a space and an accent — and drives the CLI,
622
+ the Stop hook, maintenance, the MCP server and the API from there against a
623
+ virgin profile. Nothing may reach back into the source tree, so a `files` list
624
+ that forgets a source an auxiliary entry point imports fails here rather than
625
+ days later on a user's machine. Runs on Linux, macOS and Windows in CI.
626
+
585
627
  ---
586
628
 
587
629
  ## 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
+ }
@@ -0,0 +1,84 @@
1
+ # Portability and recovery guarantees
2
+
3
+ ## Installation and data
4
+
5
+ Humemory requires Bun 1.3.14 or newer. The archive deliberately includes `src`
6
+ alongside `dist`: hooks and MCP use those shipped sources, while the executable
7
+ uses the compiled CLI. A checkout is not required at runtime.
8
+
9
+ `HUMEMORY_DATA_DIR` takes precedence over the default data root. Without it, an
10
+ existing installation containing `data/humemory.db` keeps that location. New
11
+ installations use `%LOCALAPPDATA%/humemory` on Windows,
12
+ `~/Library/Application Support/humemory` on macOS, and
13
+ `$XDG_DATA_HOME/humemory` (or `~/.local/share/humemory`) on Linux.
14
+ No existing database is copied, migrated or overwritten implicitly.
15
+
16
+ `HUMEMORY_DB`, `HUMEMORY_QUEUE` and `HUMEMORY_MODEL_CACHE` select individual
17
+ locations. Restart every resident API/MCP/worker process with the same overrides
18
+ when moving shared state. Updating one process does not reconfigure the others.
19
+
20
+ `remap-project <from> <to>` previews directory changes. Applying requires
21
+ `--apply --backup <new-file>` and uses a SQLite snapshot followed by a
22
+ transaction. It covers trace, intention and script directories, plus absolute
23
+ file-open cue paths. It does not rewrite prose, MCP installation paths or queued
24
+ transcripts. Drain or preserve the queue separately before relocating projects.
25
+ The backup contains the database, not model files or pending transcripts.
26
+
27
+ ## Discovery, configuration and encoding
28
+
29
+ Discovery reports local runtime evidence without importing conversations.
30
+ An available import adapter, an installed MCP configuration and a successfully
31
+ encoded trace are distinct states. Use source discovery, configuration reports,
32
+ maintenance status and memory search respectively to check them.
33
+
34
+ To process only already queued transcripts without scanning local agent history:
35
+
36
+ ```bash
37
+ pnpm maintenance --skip-imports
38
+ ```
39
+
40
+ Maintenance uses deterministic extraction by default. Models used by vector
41
+ search require a separate initial download or a populated model cache. An empty
42
+ cache is not proof of an offline-ready vector installation; `humemory doctor`
43
+ reports cache presence, not ONNX execution compatibility.
44
+
45
+ ## Timing, concurrency and recovery
46
+
47
+ Cron expressions are evaluated in UTC. Time cues should use an ISO timestamp
48
+ with an explicit offset. Cron catch-up examines the most recent seven days;
49
+ it does not replay every missed occurrence after a long shutdown. A recurring
50
+ intention remains eligible after firing until it is closed or expires.
51
+
52
+ SQLite advisory locks have no age-based expiry. A live worker retains its lock,
53
+ and the operating system releases it when the process dies. Persistent
54
+ `.sqlite` coordination files are normal and must not be deleted to unlock a
55
+ running process. Stop all old-version workers when upgrading from file locks;
56
+ old and new lock mechanisms do not coordinate with each other.
57
+
58
+ Queue replacements use unique temporary files. If replacement fails, the
59
+ previous destination and the complete temporary remain available for recovery.
60
+ The worker restores abandoned `.processing` files on a later pass. Checkpoints
61
+ avoid ordinary repeated imports, but a crash between memory storage and the
62
+ checkpoint can replay work: this is not a claim of exactly-once encoding.
63
+ Rename-based replacement is not a guarantee against power loss without an
64
+ explicit persistence protocol.
65
+
66
+ MCP setup preserves a backup of the original, checks for changes before the
67
+ rename, and serializes cooperating setup processes. It cannot lock an unrelated
68
+ editor that ignores that protocol; a change in the final check-to-rename window
69
+ remains possible. Keep the `.bak` files until the resulting configuration has
70
+ been checked.
71
+
72
+ ## What the checks establish
73
+
74
+ `pnpm test` is the isolated, deterministic suite with mocked external services.
75
+ `pnpm verify:package` is a separate installation check: dependency installation
76
+ requires network access, while its runtime inputs are synthetic and its HTTP
77
+ requests target the test server on loopback. It verifies the shipped CLI, hooks,
78
+ queue processing, consolidation, MCP and API from a temporary location outside
79
+ the checkout, with spaces and accents in the path and a fresh data profile.
80
+
81
+ The CI defines this sequence for Windows, Linux and macOS. A configured job is
82
+ not evidence that a particular run passed. Real ONNX inference per OS and
83
+ architecture, enforced read-only installation permissions, power-loss recovery,
84
+ and complete database-plus-queue restoration need separate validation.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "humemory",
3
- "version": "0.2.8",
3
+ "version": "0.2.9",
4
4
  "description": "Memory for AI agents that forgets like a human — decaying traces, inverse search, and prospective loops that resurface on a cue",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -96,6 +96,7 @@
96
96
  "build:web": "node -e \"require('fs').rmSync('public/app',{recursive:true,force:true})\" && bun build web/index.html --outdir public/app --production --splitting",
97
97
  "dev:web": "bun build web/index.html --outdir public/app --splitting --watch",
98
98
  "typecheck:web": "tsc -p web/tsconfig.json",
99
+ "verify:package": "bun run scripts/verify-package.ts",
99
100
  "clean:web": "node -e \"require('fs').rmSync('public/app',{recursive:true,force:true})\""
100
101
  }
101
102
  }
@@ -13,11 +13,16 @@ const llmTimeoutMs = defaultLlmTimeoutMs();
13
13
  const client = await resolveMaintenanceClient(llmTimeoutMs);
14
14
 
15
15
  // --skip-codex for a machine where the rollouts are imported some other way.
16
- const codexSinceDays = process.argv.includes('--skip-codex')
16
+ const skipImports = process.argv.includes('--skip-imports');
17
+ const codexSinceDays = skipImports || process.argv.includes('--skip-codex')
17
18
  ? false as const
18
19
  : Number(process.env.HUMEMORY_MAINTENANCE_CODEX_DAYS ?? 1);
19
20
 
20
- const { worker: result } = await runMaintenancePass({ client, llmTimeoutMs, codexSinceDays });
21
+ const { worker: result } = await runMaintenancePass({
22
+ client, llmTimeoutMs, codexSinceDays,
23
+ kimiSinceDays: skipImports ? false : undefined,
24
+ opencodeSinceDays: skipImports ? false : undefined,
25
+ });
21
26
 
22
27
  if (result.busy) {
23
28
  if (process.env.HUMEMORY_VERBOSE === '1') console.error('[humemory] maintenance: another worker is active');
@@ -45,7 +45,6 @@ export interface WorkerOptions {
45
45
  client?: LLMClient;
46
46
  llmTimeoutMs?: number;
47
47
  maxJobs?: number;
48
- lockStaleMs?: number;
49
48
  maxAttempts?: number;
50
49
  /**
51
50
  * Consecutive job failures that trip the circuit breaker and end the pass.
@@ -70,7 +69,6 @@ export interface WorkerResult {
70
69
  aborted: boolean;
71
70
  }
72
71
 
73
- const DEFAULT_LOCK_STALE_MS = 5 * 60 * 1000;
74
72
  const DEFAULT_MAX_ATTEMPTS = 5;
75
73
  const DEFAULT_FAILURE_THRESHOLD = 3;
76
74
  const DEAD_LETTER_SUFFIX = '.dead.json';
@@ -48,7 +48,7 @@ export function createMemoryRoutes(store: SQLiteStore) {
48
48
  maxItemLength: MAX_KEYWORD_LENGTH,
49
49
  name: 'keywords',
50
50
  });
51
- // level3Keywords is the flat BM25 keyword line, not an array (core/types.ts).
51
+ // level3Keywords is the flat lexical keyword line, not an array (core/types.ts).
52
52
  const level3Keywords = boundedOptionalString(body.level3Keywords, MAX_CONTENT_LENGTH, 'level3Keywords');
53
53
  const directory = boundedOptionalString(body.directory, MAX_SHORT_FIELD_LENGTH, 'directory');
54
54
  const day = boundedOptionalString(body.day, MAX_SHORT_FIELD_LENGTH, 'day');
package/src/cli/index.ts CHANGED
@@ -10,6 +10,7 @@ import { join, dirname, resolve } from 'path';
10
10
  import { fileURLToPath } from 'url';
11
11
  import { readFileSync } from 'fs';
12
12
  import { discoverLocalAgentSources } from '../agent/source-registry.js';
13
+ import { runDoctor, renderDoctorReport } from '../core/doctor.js';
13
14
 
14
15
  const __filename = fileURLToPath(import.meta.url);
15
16
  const __dirname = dirname(__filename);
@@ -31,9 +32,13 @@ function getStore(): SQLiteStore {
31
32
  const program = new Command();
32
33
 
33
34
  // Version read from the package: hard-coded, it drifted at every release.
34
- const { version } = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8')) as {
35
+ const { version, engines } = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8')) as {
35
36
  version: string;
37
+ engines?: { bun?: string };
36
38
  };
39
+ // Declared minimum, not a hard-coded one: `humemory doctor` must fail when the
40
+ // runtime is below what the package claims to support, whatever that becomes.
41
+ const minimumBunVersion = engines?.bun;
37
42
 
38
43
  program
39
44
  .name('humemory')
@@ -103,7 +108,7 @@ program
103
108
  .option('--to <date>', 'End date YYYY-MM-DD')
104
109
  .option('--min-saillance <n>', 'Minimum mnemonic strength (0-100)')
105
110
  .option('--min-recalls <n>', 'Minimum recall count')
106
- .option('--semantic', 'Hybrid search: fuse BM25 with vector similarity (Phase 7.4, needs the model)')
111
+ .option('--semantic', 'Hybrid search: fuse the lexical lane with vector similarity (Phase 7.4, needs the model)')
107
112
  .action(async (query, options) => {
108
113
  const s = getStore();
109
114
 
@@ -1166,6 +1171,21 @@ program.command('remap-project <from> <to>')
1166
1171
  console.log(JSON.stringify(await getStore().remapProjectRoot(from, to, { apply: options.apply, backupPath: options.backup }), null, 2));
1167
1172
  });
1168
1173
 
1174
+ // === DOCTOR ===
1175
+ // Deliberately does not go through getStore(): the point is to diagnose an
1176
+ // installation that may not have a usable store yet.
1177
+ program
1178
+ .command('doctor')
1179
+ .description('Diagnose the installation: runtime, paths, rights, schema, locks, models, entry points')
1180
+ .option('--json', 'Machine-readable report')
1181
+ .action(async (options) => {
1182
+ const report = await runDoctor({ minimumBun: minimumBunVersion });
1183
+ console.log(options.json ? JSON.stringify(report, null, 2) : renderDoctorReport(report));
1184
+ // Non-zero only on a real fault: warnings are states an install can sit in
1185
+ // (no model cached yet, a maintenance worker currently running).
1186
+ if (report.status === 'fail') process.exitCode = 1;
1187
+ });
1188
+
1169
1189
  // Parse and run
1170
1190
  program.parse();
1171
1191
 
@@ -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
+ }
@@ -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
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/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 BM25)
31
+ level3Keywords?: string; // Level 3 (keywords for the lexical index)
32
32
 
33
33
  // Lightweight metadata
34
34
  directory: string; // Project / source