humemory 0.2.7 → 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.
Files changed (102) hide show
  1. package/AGENTS.md +14 -7
  2. package/CHANGELOG.md +23 -0
  3. package/README.md +66 -12
  4. package/dist/agent/kimi-import.d.ts +19 -0
  5. package/dist/agent/kimi-import.js +111 -0
  6. package/dist/agent/kimi-session-parser.d.ts +3 -0
  7. package/dist/agent/kimi-session-parser.js +102 -0
  8. package/dist/agent/maintenance-queue.d.ts +2 -1
  9. package/dist/agent/maintenance-queue.js +36 -62
  10. package/dist/agent/maintenance-runner.d.ts +17 -4
  11. package/dist/agent/maintenance-runner.js +45 -10
  12. package/dist/agent/mcp-client-setup.d.ts +16 -0
  13. package/dist/agent/mcp-client-setup.js +108 -0
  14. package/dist/agent/opencode-import.d.ts +22 -0
  15. package/dist/agent/opencode-import.js +71 -0
  16. package/dist/agent/opencode-session-parser.d.ts +3 -0
  17. package/dist/agent/opencode-session-parser.js +35 -0
  18. package/dist/agent/session-parser.d.ts +8 -0
  19. package/dist/agent/session-parser.js +18 -0
  20. package/dist/agent/source-registry.js +1 -1
  21. package/dist/api/memory-routes.js +1 -1
  22. package/dist/api/server.js +3 -2
  23. package/dist/cli/index.js +117 -6
  24. package/dist/core/cues.d.ts +1 -0
  25. package/dist/core/cues.js +19 -7
  26. package/dist/core/doctor.d.ts +28 -0
  27. package/dist/core/doctor.js +320 -0
  28. package/dist/core/embeddings.d.ts +0 -10
  29. package/dist/core/embeddings.js +2 -1
  30. package/dist/core/hybrid.d.ts +7 -3
  31. package/dist/core/hybrid.js +7 -3
  32. package/dist/core/llm-generator.d.ts +2 -10
  33. package/dist/core/paths.d.ts +12 -0
  34. package/dist/core/paths.js +36 -0
  35. package/dist/core/project-path.d.ts +3 -0
  36. package/dist/core/project-path.js +14 -0
  37. package/dist/core/search.d.ts +1 -1
  38. package/dist/core/search.js +7 -9
  39. package/dist/core/types.d.ts +13 -1
  40. package/dist/index.d.ts +5 -0
  41. package/dist/index.js +5 -0
  42. package/dist/store/sqlite.d.ts +37 -0
  43. package/dist/store/sqlite.js +94 -42
  44. package/docs/PORTABILITY.md +84 -0
  45. package/package.json +5 -3
  46. package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
  47. package/public/app/index.html +1 -1
  48. package/scripts/consolidate.js +4 -4
  49. package/scripts/hook-post-commit.ts +2 -1
  50. package/scripts/hook-session-start.ts +2 -1
  51. package/scripts/hook-session.ts +2 -1
  52. package/scripts/maintenance-worker.ts +7 -2
  53. package/src/agent/claude-hook.ts +126 -0
  54. package/src/agent/codex-import.ts +129 -0
  55. package/src/agent/codex-rollout-parser.ts +121 -0
  56. package/src/agent/commit-closer.ts +173 -0
  57. package/src/agent/kimi-import.ts +128 -0
  58. package/src/agent/kimi-session-parser.ts +127 -0
  59. package/src/agent/learning-extractor.ts +128 -0
  60. package/src/agent/maintenance-queue.ts +544 -0
  61. package/src/agent/maintenance-runner.ts +322 -0
  62. package/src/agent/maintenance-state.ts +168 -0
  63. package/src/agent/mcp-client-setup.ts +125 -0
  64. package/src/agent/opencode-import.ts +96 -0
  65. package/src/agent/opencode-session-parser.ts +53 -0
  66. package/src/agent/session-context.ts +302 -0
  67. package/src/agent/session-parser.ts +155 -0
  68. package/src/agent/source-registry.ts +135 -0
  69. package/src/api/cors.ts +42 -0
  70. package/src/api/dream-routes.ts +46 -0
  71. package/src/api/errors.ts +45 -0
  72. package/src/api/intentions-routes.ts +348 -0
  73. package/src/api/limits.ts +90 -0
  74. package/src/api/maintenance-routes.ts +73 -0
  75. package/src/api/memory-routes.ts +391 -0
  76. package/src/api/scripts-routes.ts +176 -0
  77. package/src/api/security-headers.ts +54 -0
  78. package/src/api/server.ts +292 -0
  79. package/src/cli/index.ts +1195 -0
  80. package/src/core/clock.ts +64 -0
  81. package/src/core/cue-arg.ts +79 -0
  82. package/src/core/cues.ts +511 -0
  83. package/src/core/decay.ts +198 -0
  84. package/src/core/doctor.ts +362 -0
  85. package/src/core/dreamer.ts +494 -0
  86. package/src/core/embeddings.ts +157 -0
  87. package/src/core/event-bus.ts +100 -0
  88. package/src/core/hybrid.ts +82 -0
  89. package/src/core/llm-cli-client.ts +118 -0
  90. package/src/core/llm-generator.ts +90 -0
  91. package/src/core/paths.ts +38 -0
  92. package/src/core/project-path.ts +14 -0
  93. package/src/core/sanitize.ts +116 -0
  94. package/src/core/scripts.ts +112 -0
  95. package/src/core/search.ts +189 -0
  96. package/src/core/trust.ts +67 -0
  97. package/src/core/types.ts +393 -0
  98. package/src/core/vector-clusterer.ts +131 -0
  99. package/src/index.ts +40 -0
  100. package/src/mcp/HTTP_TRANSPORT.md +359 -0
  101. package/src/mcp/server.ts +202 -0
  102. package/src/store/sqlite.ts +1958 -0
package/dist/cli/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command } from 'commander';
3
+ import { databasePath, queueDirectory } from '../core/paths.js';
3
4
  import { SQLiteStore } from '../store/sqlite.js';
4
5
  import { SqliteCueResolver, loopId, matchIntentionByShortId } from '../core/cues.js';
5
6
  import { parseCueArg, formatTriggerSpec } from '../core/cue-arg.js';
@@ -7,13 +8,14 @@ import { join, dirname, resolve } from 'path';
7
8
  import { fileURLToPath } from 'url';
8
9
  import { readFileSync } from 'fs';
9
10
  import { discoverLocalAgentSources } from '../agent/source-registry.js';
11
+ import { runDoctor, renderDoctorReport } from '../core/doctor.js';
10
12
  const __filename = fileURLToPath(import.meta.url);
11
13
  const __dirname = dirname(__filename);
12
14
  // Shared store. HUMEMORY_DB points at another database — same convention as the
13
15
  // hooks, and required to exercise the CLI without touching production.
14
- const DB_PATH = process.env.HUMEMORY_DB ?? join(__dirname, '../../data/humemory.db');
16
+ const DB_PATH = databasePath();
15
17
  // Same inbox the agent hooks write to — the CLI only ever queues, never encodes.
16
- const QUEUE_DIR = process.env.HUMEMORY_QUEUE ?? join(__dirname, '../../data/maintenance-queue');
18
+ const QUEUE_DIR = queueDirectory();
17
19
  let store;
18
20
  function getStore() {
19
21
  if (!store) {
@@ -23,7 +25,10 @@ function getStore() {
23
25
  }
24
26
  const program = new Command();
25
27
  // Version read from the package: hard-coded, it drifted at every release.
26
- 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;
27
32
  program
28
33
  .name('humemory')
29
34
  .description('Memory palace — mnemonic traces with progressive decay')
@@ -86,7 +91,7 @@ program
86
91
  .option('--to <date>', 'End date YYYY-MM-DD')
87
92
  .option('--min-saillance <n>', 'Minimum mnemonic strength (0-100)')
88
93
  .option('--min-recalls <n>', 'Minimum recall count')
89
- .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)')
90
95
  .action(async (query, options) => {
91
96
  const s = getStore();
92
97
  let results;
@@ -836,13 +841,18 @@ maintenance
836
841
  maintenance
837
842
  .command('run')
838
843
  .description('Force one consolidation pass here and now, in this process')
839
- .option('--skip-codex', 'Do not import codex rollouts first')
844
+ .option('--skip-imports', 'Do not import any local agent sessions first')
845
+ .option('--skip-codex', 'Do not import Codex rollouts first')
846
+ .option('--skip-kimi', 'Do not import Kimi Code sessions first')
847
+ .option('--skip-opencode', 'Do not import OpenCode sessions first')
840
848
  .action(async (options) => {
841
849
  const { runMaintenancePass, resolveMaintenanceClient } = await import('../agent/maintenance-runner.js');
842
850
  const client = await resolveMaintenanceClient();
843
851
  const { worker } = await runMaintenancePass({
844
852
  client,
845
- codexSinceDays: options.skipCodex ? false : undefined,
853
+ codexSinceDays: options.skipImports || options.skipCodex ? false : 1,
854
+ kimiSinceDays: options.skipImports || options.skipKimi ? false : 1,
855
+ opencodeSinceDays: options.skipImports || options.skipOpencode ? false : 1,
846
856
  runner: 'cli',
847
857
  });
848
858
  console.log(`✓ ${worker.processed}/${worker.discovered} jobs, ${worker.memoriesStored} memories, ` +
@@ -950,6 +960,85 @@ sources
950
960
  console.log('\nRun `pnpm maintenance` to encode them (or wait for the scheduled pass).');
951
961
  }
952
962
  });
963
+ sources
964
+ .command('import-kimi')
965
+ .description('Queue Kimi Code sessions for maintenance')
966
+ .option('--since <days>', 'Only sessions touched in the last N days', '7')
967
+ .option('--all', 'Every session ever recorded, ignoring --since')
968
+ .option('--limit <n>', 'Stop after N queued sessions')
969
+ .option('--dry-run', 'Report what would be queued, write nothing')
970
+ .option('--kimi-home <dir>', 'Override $KIMI_CODE_HOME')
971
+ .action(async (options) => {
972
+ const { importKimiSessions, defaultKimiHome } = await import('../agent/kimi-import.js');
973
+ const kimiHome = options.kimiHome ? resolve(options.kimiHome) : defaultKimiHome();
974
+ const days = Number(options.since);
975
+ const since = options.all || !Number.isFinite(days)
976
+ ? undefined
977
+ : new Date(Date.now() - days * 24 * 60 * 60 * 1000);
978
+ console.log(`⏳ Scanning ${kimiHome}${since ? ` (last ${days} day(s))` : ' (all)'}...`);
979
+ const result = await importKimiSessions({
980
+ queueDir: QUEUE_DIR,
981
+ kimiHome,
982
+ since,
983
+ limit: options.limit ? parseInt(options.limit) : undefined,
984
+ dryRun: options.dryRun,
985
+ });
986
+ console.log(`\n${options.dryRun ? 'Would queue' : '✓ Queued'} ${result.queued} session(s)` +
987
+ `${options.dryRun ? '' : ` (${result.created} new)`} out of ${result.scanned} scanned.\n` +
988
+ ` skipped — ${result.skippedOld} older than the window, ${result.skippedEmpty} without a complete turn, ` +
989
+ `${result.unreadable} unreadable`);
990
+ });
991
+ sources
992
+ .command('import-opencode')
993
+ .description('Queue OpenCode session exports for maintenance')
994
+ .option('--since <days>', 'Only sessions touched in the last N days', '7')
995
+ .option('--all', 'Every session ever recorded, ignoring --since')
996
+ .option('--limit <n>', 'Stop after N queued sessions')
997
+ .option('--include-subagents', 'Also import child sessions OpenCode spawned')
998
+ .option('--dry-run', 'Report what would be queued, write nothing')
999
+ .option('--command <path>', 'Override the OpenCode executable')
1000
+ .action(async (options) => {
1001
+ const { importOpenCodeSessions } = await import('../agent/opencode-import.js');
1002
+ const days = Number(options.since);
1003
+ const since = options.all || !Number.isFinite(days)
1004
+ ? undefined
1005
+ : new Date(Date.now() - days * 24 * 60 * 60 * 1000);
1006
+ console.log(`⏳ Asking OpenCode for sessions${since ? ` from the last ${days} day(s)` : ' from all time'}...`);
1007
+ const result = await importOpenCodeSessions({
1008
+ queueDir: QUEUE_DIR,
1009
+ since,
1010
+ limit: options.limit ? parseInt(options.limit) : undefined,
1011
+ includeSubagents: options.includeSubagents,
1012
+ dryRun: options.dryRun,
1013
+ command: options.command,
1014
+ });
1015
+ console.log(`\n${options.dryRun ? 'Would queue' : '✓ Queued'} ${result.queued} session(s)` +
1016
+ `${options.dryRun ? '' : ` (${result.created} new)`} out of ${result.scanned} scanned.\n` +
1017
+ ` skipped — ${result.skippedEmpty} without a complete turn, ${result.unreadable} unreadable`);
1018
+ });
1019
+ sources
1020
+ .command('setup')
1021
+ .description('Register humemory as a local MCP server in Kimi Code and OpenCode')
1022
+ .option('--kimi', 'Configure Kimi Code only')
1023
+ .option('--opencode', 'Configure OpenCode only')
1024
+ .option('--dry-run', 'Show which files would change, write nothing')
1025
+ .action(async (options) => {
1026
+ const { setupHumemoryMcpClients } = await import('../agent/mcp-client-setup.js');
1027
+ const clients = options.kimi || options.opencode
1028
+ ? [...(options.kimi ? ['kimi'] : []), ...(options.opencode ? ['opencode'] : [])]
1029
+ : ['kimi', 'opencode'];
1030
+ const projectRoot = resolve(__dirname, '../..');
1031
+ const result = await setupHumemoryMcpClients({
1032
+ clients: [...clients],
1033
+ projectRoot,
1034
+ dbPath: DB_PATH,
1035
+ dryRun: options.dryRun,
1036
+ });
1037
+ for (const entry of result) {
1038
+ const verb = entry.changed ? (options.dryRun ? 'would update' : 'updated') : 'already configured';
1039
+ console.log(`✓ ${entry.client}: ${verb} ${entry.path}`);
1040
+ }
1041
+ });
953
1042
  sources
954
1043
  .command('discover', { isDefault: true })
955
1044
  .description('Show known runtimes and the local evidence found for each one')
@@ -964,6 +1053,28 @@ sources
964
1053
  console.log(` ${evidence}`);
965
1054
  }
966
1055
  });
1056
+ program.command('remap-project <from> <to>')
1057
+ .description('Preview a project root relocation; --apply requires a coherent SQLite backup')
1058
+ .option('--apply', 'Apply the previewed mapping in a transaction')
1059
+ .option('--backup <path>', 'New SQLite backup destination (required with --apply)')
1060
+ .action(async (from, to, options) => {
1061
+ console.log(JSON.stringify(await getStore().remapProjectRoot(from, to, { apply: options.apply, backupPath: options.backup }), null, 2));
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
+ });
967
1078
  // Parse and run
968
1079
  program.parse();
969
1080
  // Cleanup
@@ -118,6 +118,7 @@ export declare class SqliteCueResolver implements CueResolver {
118
118
  private liveTargetDirectoryOf;
119
119
  resolveTimeCues(now?: Date): Promise<Cue[]>;
120
120
  resolveEventCues(event: AppEvent): Promise<Cue[]>;
121
+ private armedCues;
121
122
  /**
122
123
  * Marks cue and intention as fired. A cron cue is re-armed after firing: a
123
124
  * recurrence that does not re-arm is a one-shot in disguise.
package/dist/core/cues.js CHANGED
@@ -9,6 +9,7 @@
9
9
  * The data layer (tables, CRUD) is Phase 5.1, in `src/store/sqlite.ts`; there is
10
10
  * nothing but decisions here. See PHASE5_PLAN.md § 5.2.
11
11
  */
12
+ import { projectPath } from './project-path.js';
12
13
  import { systemClock } from './clock.js';
13
14
  // ─────────────────────────────────────────────────────────────────────────────
14
15
  // Cron — minimal matcher, 5 fields (minute hour day-of-month month day-of-week)
@@ -140,8 +141,8 @@ function normalizePath(p) {
140
141
  function directoryMatches(intentionDir, eventDir) {
141
142
  if (!eventDir)
142
143
  return true; // event without context: no filtering
143
- const a = normalizePath(intentionDir).replace(/\/$/, '');
144
- const b = normalizePath(eventDir).replace(/\/$/, '');
144
+ const a = projectPath(intentionDir);
145
+ const b = projectPath(eventDir);
145
146
  return b === a || b.startsWith(`${a}/`) || a.startsWith(`${b}/`);
146
147
  }
147
148
  /**
@@ -299,12 +300,13 @@ export class SqliteCueResolver {
299
300
  return script && script.status === 'active' ? script.directory : null;
300
301
  }
301
302
  const intention = await this.store.getIntention(cue.targetId);
302
- return intention && intention.status === 'armed' ? intention.directory : null;
303
+ const recurring = cue.triggerSpec.kind === 'time' && Boolean(cue.triggerSpec.cron);
304
+ return intention && (intention.status === 'armed' || (recurring && intention.status === 'fired'))
305
+ ? intention.directory : null;
303
306
  }
304
307
  async resolveTimeCues(now = this.clock.now()) {
305
- const cues = await this.store.listCues({ status: 'armed', kind: 'time', limit: 500 });
306
308
  const due = [];
307
- for (const cue of cues) {
309
+ for await (const cue of this.armedCues('time')) {
308
310
  const spec = cue.triggerSpec;
309
311
  if (spec.kind !== 'time')
310
312
  continue;
@@ -330,9 +332,8 @@ export class SqliteCueResolver {
330
332
  // post-commit hook's job (S5-03b), not this resolver's.
331
333
  if (event.type === 'commit')
332
334
  return [];
333
- const cues = await this.store.listCues({ status: 'armed', kind: 'event', limit: 500 });
334
335
  const matched = [];
335
- for (const cue of cues) {
336
+ for await (const cue of this.armedCues('event')) {
336
337
  const spec = cue.triggerSpec;
337
338
  if (spec.kind !== 'event')
338
339
  continue;
@@ -347,6 +348,17 @@ export class SqliteCueResolver {
347
348
  }
348
349
  return matched;
349
350
  }
351
+ async *armedCues(kind) {
352
+ let afterId = '';
353
+ while (true) {
354
+ const page = await this.store.listCues({ status: 'armed', kind, limit: 500, afterId });
355
+ for (const cue of page)
356
+ yield cue;
357
+ if (page.length < 500)
358
+ return;
359
+ afterId = page[page.length - 1].id;
360
+ }
361
+ }
350
362
  /**
351
363
  * Marks cue and intention as fired. A cron cue is re-armed after firing: a
352
364
  * recurrence that does not re-arm is a one-shot in disguise.
@@ -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,13 +1,3 @@
1
- /**
2
- * Embedders — Phase 7.1.
3
- *
4
- * The test seam (same pattern as `LLMClient`): tests use the deterministic,
5
- * offline `HashEmbedder`; production uses `OnnxEmbedder` (e5-small, local,
6
- * loaded lazily — absent model ⇒ disabled, never a crash).
7
- *
8
- * e5 models expect `query:`/`passage:` prefixes; the Embedder owns them so
9
- * callers never think about it.
10
- */
11
1
  export interface Embedder {
12
2
  readonly modelId: string;
13
3
  readonly dims: number;
@@ -1,3 +1,4 @@
1
+ import { modelCacheDirectory } from './paths.js';
1
2
  /**
2
3
  * Embedders — Phase 7.1.
3
4
  *
@@ -99,7 +100,7 @@ export class OnnxEmbedder {
99
100
  return this.extractor;
100
101
  this.loading ??= (async () => {
101
102
  const { pipeline, env } = await import('@huggingface/transformers');
102
- env.cacheDir = this.options.cacheDir ?? './data/models';
103
+ env.cacheDir = this.options.cacheDir ?? modelCacheDirectory();
103
104
  env.allowLocalModels = true;
104
105
  const model = this.options.model ?? BGE_M3_MODEL_ID;
105
106
  return pipeline('feature-extraction', model, { dtype: this.options.dtype ?? 'q8' });
@@ -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