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
@@ -0,0 +1,198 @@
1
+ import type { Memory, DecayLevel } from './types.js';
2
+
3
+ /**
4
+ * Decay configuration.
5
+ */
6
+ export const DECAY_CONFIG = {
7
+ // Base time for each level, in hours
8
+ levelThresholds: [0, 24, 168, 720, 2160], // 0h, 1j, 1sem, 1mois, 3mois
9
+
10
+ // How much each recall slows decay
11
+ recallBonus: 0.3, // every recall adds 30% more time
12
+
13
+ // Salience threshold above which decay slows down
14
+ saillanceThreshold: 70,
15
+
16
+ // Phase 6.0.1 — verified traces age more slowly
17
+ verifiedMultiplier: 1.5,
18
+
19
+ // Phase 6.0.1 / Claude R3-B8 — cap on the PRODUCT of all slowdown
20
+ // multipliers (recall × salience × verified). Without this, the unbounded
21
+ // `1 + recallCount * recallBonus` term makes verified+salient+recalled
22
+ // traces effectively photographic — which is not forgetting.
23
+ maxTotalSlowdown: 2.5,
24
+
25
+ // Phase 6.0.2 — contradiction collapse (Kimi B9, accepted by Claude R3):
26
+ // first refutation divides saillance by `contradictionDivisor`, further ones
27
+ // by `refuteDivisor` (cap `refuteCap` refutations), never below the floor.
28
+ contradictionDivisor: 4,
29
+ refuteDivisor: 2,
30
+ refuteCap: 3,
31
+ contradictionFloor: 5,
32
+
33
+ // Decay cycle: how often the sweep runs, in hours
34
+ decayCycleHours: 24,
35
+ };
36
+
37
+ /**
38
+ * Current decay level of a trace.
39
+ */
40
+ export function calculateDecayLevel(memory: Memory, now: Date = new Date()): DecayLevel {
41
+ if (memory.photographic) {
42
+ return 0; // Photographic mode — no decay
43
+ }
44
+ if (memory.currentLevel === 4 || memory.mergedIntoId) {
45
+ return 4; // already lost or merged
46
+ }
47
+
48
+ const hoursSinceCreation = (now.getTime() - memory.createdAt.getTime()) / (1000 * 60 * 60);
49
+ const hoursSinceRecall = memory.lastRecalled
50
+ ? (now.getTime() - memory.lastRecalled.getTime()) / (1000 * 60 * 60)
51
+ : Infinity;
52
+
53
+ // Use whichever of the two is more recent
54
+ const effectiveAge = Math.min(hoursSinceCreation, hoursSinceRecall);
55
+
56
+ // Appliquer le bonus de rappel
57
+ const recallMultiplier = 1 + (memory.recallCount * DECAY_CONFIG.recallBonus);
58
+
59
+ // Appliquer le bonus de saillance
60
+ const saillanceMultiplier = memory.saillance >= DECAY_CONFIG.saillanceThreshold ? 1.5 : 1;
61
+
62
+ // Phase 6.0.1 — le bonus de vérification
63
+ const verifiedMultiplier = memory.verified ? DECAY_CONFIG.verifiedMultiplier : 1;
64
+
65
+ // Cap on the PRODUCT (R3/B8): the unbounded recall term counts toward it.
66
+ const totalSlowdown = Math.min(
67
+ recallMultiplier * saillanceMultiplier * verifiedMultiplier,
68
+ DECAY_CONFIG.maxTotalSlowdown
69
+ );
70
+ const finalAge = effectiveAge / totalSlowdown;
71
+
72
+ // Determine the level
73
+ for (let i = 3; i >= 0; i--) {
74
+ if (finalAge >= DECAY_CONFIG.levelThresholds[i]) {
75
+ return i as DecayLevel;
76
+ }
77
+ }
78
+
79
+ return 0;
80
+ }
81
+
82
+ /**
83
+ * Salience score of a trace.
84
+ * Based on recent recalls, connections and emotional charge.
85
+ */
86
+ export function calculateSaillance(memory: Memory, now: Date = new Date()): number {
87
+ let score = 50; // baseline
88
+
89
+ // Bonus for recent recalls (within 7 days)
90
+ if (memory.lastRecalled) {
91
+ const daysSinceRecall = (now.getTime() - memory.lastRecalled.getTime()) / (1000 * 60 * 60 * 24);
92
+ if (daysSinceRecall < 7) {
93
+ score += 20;
94
+ } else if (daysSinceRecall < 30) {
95
+ score += 10;
96
+ }
97
+ }
98
+
99
+ // Bonus for how often it was recalled
100
+ score += Math.min(memory.recallCount * 5, 20);
101
+
102
+ // Bonus for keywords: more tags means better connected
103
+ score += Math.min(memory.keywords.length * 3, 15);
104
+
105
+ // Crude emotional-charge detection. The list stays bilingual on purpose: traces
106
+ // are written in whatever language the developer works in, and dropping the
107
+ // French markers would silently weaken salience on French content.
108
+ const emotionalWords = [
109
+ 'important', 'urgent', 'critical', 'attention', 'wow', 'awesome', 'damn', 'problem', 'error', 'broken',
110
+ 'génial', 'merde', 'problème', 'erreur', 'super',
111
+ ];
112
+ const contentLower = memory.content.toLowerCase();
113
+ const hasEmotion = emotionalWords.some(word => contentLower.includes(word));
114
+ if (hasEmotion) {
115
+ score += 10;
116
+ }
117
+
118
+ return Math.min(score, 100);
119
+ }
120
+
121
+ /**
122
+ * Initial decay rate.
123
+ * 0.0 = very slow, 1.0 = very fast.
124
+ */
125
+ export function calculateDecayRate(content: string, keywords: string[]): number {
126
+ // Base rate
127
+ let rate = 0.5;
128
+
129
+ // Long content decays more slowly: there is more detail worth keeping
130
+ if (content.length > 500) {
131
+ rate -= 0.1;
132
+ } else if (content.length < 100) {
133
+ rate += 0.1;
134
+ }
135
+
136
+ // Many keywords means better connected, so slower decay
137
+ if (keywords.length > 5) {
138
+ rate -= 0.1;
139
+ }
140
+
141
+ return Math.max(0.1, Math.min(1.0, rate));
142
+ }
143
+
144
+ export interface DecayCurvePoint {
145
+ time: Date;
146
+ level: DecayLevel;
147
+ saillance: number;
148
+ hoursElapsed: number;
149
+ }
150
+
151
+ /**
152
+ * Projects a trace's forgetting curve over `daysAhead` days, one point every six
153
+ * hours.
154
+ *
155
+ * It lives here, next to the rules it samples, rather than in the visualisation
156
+ * code: a curve drawn from a diverging copy of the algorithm would tell a story
157
+ * the system does not actually live.
158
+ */
159
+ export function projectDecayCurve(memory: Memory, daysAhead = 90): DecayCurvePoint[] {
160
+ const points: DecayCurvePoint[] = [];
161
+ const createdAt = new Date(memory.createdAt).getTime();
162
+ const totalMs = daysAhead * 24 * 3600_000;
163
+ const stepMs = 6 * 3600_000;
164
+
165
+ for (let t = 0; t <= totalMs; t += stepMs) {
166
+ const at = new Date(createdAt + t);
167
+ points.push({
168
+ time: at,
169
+ level: calculateDecayLevel(memory, at),
170
+ saillance: calculateSaillance(memory, at),
171
+ hoursElapsed: t / 3600_000,
172
+ });
173
+ }
174
+
175
+ return points;
176
+ }
177
+
178
+ /**
179
+ * Updates every trace in a collection.
180
+ */
181
+ export function updateAllDecay(memories: Memory[], now: Date = new Date()): Memory[] {
182
+ return memories.map(memory => {
183
+ const newLevel = calculateDecayLevel(memory, now);
184
+ const newSaillance = calculateSaillance(memory, now);
185
+
186
+ // Mark as lost/merged once level 4 is reached
187
+ if (newLevel === 4 && memory.currentLevel !== 4) {
188
+ // TODO: merging logic still to implement
189
+ console.log(`Memory ${memory.id} marked as decayed (level 4)`);
190
+ }
191
+
192
+ return {
193
+ ...memory,
194
+ currentLevel: newLevel,
195
+ saillance: newSaillance,
196
+ };
197
+ });
198
+ }
@@ -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
+ }