humemory 0.2.7 → 0.2.8

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 (94) hide show
  1. package/AGENTS.md +8 -4
  2. package/CHANGELOG.md +6 -0
  3. package/README.md +22 -10
  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 -0
  9. package/dist/agent/maintenance-queue.js +36 -61
  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/server.js +3 -2
  22. package/dist/cli/index.js +96 -4
  23. package/dist/core/cues.d.ts +1 -0
  24. package/dist/core/cues.js +19 -7
  25. package/dist/core/embeddings.d.ts +0 -10
  26. package/dist/core/embeddings.js +2 -1
  27. package/dist/core/llm-generator.d.ts +2 -10
  28. package/dist/core/paths.d.ts +5 -0
  29. package/dist/core/paths.js +27 -0
  30. package/dist/core/project-path.d.ts +3 -0
  31. package/dist/core/project-path.js +14 -0
  32. package/dist/core/search.d.ts +1 -1
  33. package/dist/core/search.js +7 -9
  34. package/dist/core/types.d.ts +13 -1
  35. package/dist/index.d.ts +5 -0
  36. package/dist/index.js +5 -0
  37. package/dist/store/sqlite.d.ts +37 -0
  38. package/dist/store/sqlite.js +94 -42
  39. package/package.json +4 -3
  40. package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
  41. package/public/app/index.html +1 -1
  42. package/scripts/consolidate.js +4 -4
  43. package/scripts/hook-post-commit.ts +2 -1
  44. package/scripts/hook-session-start.ts +2 -1
  45. package/scripts/hook-session.ts +2 -1
  46. package/src/agent/claude-hook.ts +126 -0
  47. package/src/agent/codex-import.ts +129 -0
  48. package/src/agent/codex-rollout-parser.ts +121 -0
  49. package/src/agent/commit-closer.ts +173 -0
  50. package/src/agent/kimi-import.ts +128 -0
  51. package/src/agent/kimi-session-parser.ts +127 -0
  52. package/src/agent/learning-extractor.ts +128 -0
  53. package/src/agent/maintenance-queue.ts +546 -0
  54. package/src/agent/maintenance-runner.ts +322 -0
  55. package/src/agent/maintenance-state.ts +168 -0
  56. package/src/agent/mcp-client-setup.ts +125 -0
  57. package/src/agent/opencode-import.ts +96 -0
  58. package/src/agent/opencode-session-parser.ts +53 -0
  59. package/src/agent/session-context.ts +302 -0
  60. package/src/agent/session-parser.ts +155 -0
  61. package/src/agent/source-registry.ts +135 -0
  62. package/src/api/cors.ts +42 -0
  63. package/src/api/dream-routes.ts +46 -0
  64. package/src/api/errors.ts +45 -0
  65. package/src/api/intentions-routes.ts +348 -0
  66. package/src/api/limits.ts +90 -0
  67. package/src/api/maintenance-routes.ts +73 -0
  68. package/src/api/memory-routes.ts +391 -0
  69. package/src/api/scripts-routes.ts +176 -0
  70. package/src/api/security-headers.ts +54 -0
  71. package/src/api/server.ts +292 -0
  72. package/src/cli/index.ts +1175 -0
  73. package/src/core/clock.ts +64 -0
  74. package/src/core/cue-arg.ts +79 -0
  75. package/src/core/cues.ts +511 -0
  76. package/src/core/decay.ts +198 -0
  77. package/src/core/dreamer.ts +494 -0
  78. package/src/core/embeddings.ts +157 -0
  79. package/src/core/event-bus.ts +100 -0
  80. package/src/core/hybrid.ts +78 -0
  81. package/src/core/llm-cli-client.ts +118 -0
  82. package/src/core/llm-generator.ts +90 -0
  83. package/src/core/paths.ts +28 -0
  84. package/src/core/project-path.ts +14 -0
  85. package/src/core/sanitize.ts +116 -0
  86. package/src/core/scripts.ts +112 -0
  87. package/src/core/search.ts +189 -0
  88. package/src/core/trust.ts +67 -0
  89. package/src/core/types.ts +393 -0
  90. package/src/core/vector-clusterer.ts +131 -0
  91. package/src/index.ts +40 -0
  92. package/src/mcp/HTTP_TRANSPORT.md +359 -0
  93. package/src/mcp/server.ts +202 -0
  94. package/src/store/sqlite.ts +1958 -0
@@ -0,0 +1,322 @@
1
+ /**
2
+ * One maintenance pass: pull in what the local agents wrote since last time,
3
+ * then drain the queue into memory.
4
+ *
5
+ * The pass has exactly one definition here, callable from two places:
6
+ * `scripts/maintenance-worker.ts` (a one-shot CLI run) and the long-lived API
7
+ * process (`startMaintenanceLoop`). It used to live only in the script, driven
8
+ * by a Windows scheduled task whose `cmd` action flashed a console window every
9
+ * 15 minutes; hosting it in the already-resident, windowless API process is what
10
+ * removed the flash.
11
+ *
12
+ * Every pass writes to the state file (src/agent/maintenance-state.ts) whether
13
+ * it succeeds or fails, so a loop that has silently stopped is detectable from
14
+ * the CLI and the API instead of being noticed weeks later.
15
+ */
16
+
17
+ import { dirname, join } from 'path';
18
+ import { fileURLToPath } from 'url';
19
+ import type { LLMClient } from '../core/llm-generator.js';
20
+ import type { Clock } from '../core/clock.js';
21
+ import { systemClock } from '../core/clock.js';
22
+ import { databasePath, queueDirectory } from '../core/paths.js';
23
+ import { createCodexClient } from '../core/llm-cli-client.js';
24
+ import { processMaintenanceQueue, type WorkerResult } from './maintenance-queue.js';
25
+ import { importCodexRollouts, defaultCodexSessionsDir, type CodexImportResult } from './codex-import.js';
26
+ import { importKimiSessions, defaultKimiHome, type KimiImportResult } from './kimi-import.js';
27
+ import {
28
+ importOpenCodeSessions,
29
+ type OpenCodeCommandRunner,
30
+ type OpenCodeImportResult,
31
+ } from './opencode-import.js';
32
+ import { defaultStatePath, recordMaintenanceRun } from './maintenance-state.js';
33
+
34
+ const __dirname = dirname(fileURLToPath(import.meta.url));
35
+
36
+ export const DEFAULT_INTERVAL_MS = 15 * 60 * 1000;
37
+
38
+ export interface MaintenancePassOptions {
39
+ queueDir?: string;
40
+ dbPath?: string;
41
+ statePath?: string;
42
+ /** Days of codex rollouts to sweep in. `false` skips the codex import entirely. */
43
+ codexSinceDays?: number | false;
44
+ /** Overrides `$CODEX_HOME/sessions`; mainly a test seam. */
45
+ codexSessionsDir?: string;
46
+ /** Days of Kimi Code sessions to sweep in. `false` skips Kimi. */
47
+ kimiSinceDays?: number | false;
48
+ /** Overrides `$KIMI_CODE_HOME`; mainly a test seam. */
49
+ kimiHome?: string;
50
+ /** Days of OpenCode sessions to sweep in. `false` skips OpenCode. */
51
+ opencodeSinceDays?: number | false;
52
+ /** Test seam for the otherwise local, logged-in OpenCode CLI. */
53
+ opencodeRun?: OpenCodeCommandRunner;
54
+ opencodeCommand?: string;
55
+ client?: LLMClient;
56
+ llmTimeoutMs?: number;
57
+ maxJobs?: number;
58
+ clock?: Clock;
59
+ /** Recorded in the state file so two competing schedulers are visible. */
60
+ runner?: string;
61
+ }
62
+
63
+ export interface MaintenancePassResult {
64
+ codex?: CodexImportResult;
65
+ codexError?: string;
66
+ kimi?: KimiImportResult;
67
+ kimiError?: string;
68
+ opencode?: OpenCodeImportResult;
69
+ opencodeError?: string;
70
+ worker: WorkerResult;
71
+ }
72
+
73
+ export function defaultQueueDir(): string {
74
+ return queueDirectory();
75
+ }
76
+
77
+ export function defaultDbPath(): string {
78
+ return databasePath();
79
+ }
80
+
81
+ export function defaultLlmTimeoutMs(): number {
82
+ return Number(process.env.HUMEMORY_MAINTENANCE_TIMEOUT_MS ?? 8_000);
83
+ }
84
+
85
+ export function configuredIntervalMs(): number {
86
+ const raw = Number(process.env.HUMEMORY_MAINTENANCE_INTERVAL_MS ?? DEFAULT_INTERVAL_MS);
87
+ return Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_INTERVAL_MS;
88
+ }
89
+
90
+ /**
91
+ * The LLM the pass consolidates with. 'none' (the default) keeps consolidation
92
+ * deterministic and network-free; there is no API key on the production machine
93
+ * and none wanted, so 'codex' shells out to the logged-in CLI instead.
94
+ */
95
+ export async function resolveMaintenanceClient(
96
+ timeoutMs = defaultLlmTimeoutMs()
97
+ ): Promise<LLMClient | undefined> {
98
+ const provider = process.env.HUMEMORY_MAINTENANCE_LLM ?? 'none';
99
+
100
+ if (provider === 'anthropic' && process.env.ANTHROPIC_API_KEY) {
101
+ const { default: Anthropic } = await import('@anthropic-ai/sdk');
102
+ return new Anthropic() as unknown as LLMClient;
103
+ }
104
+ if (provider === 'codex') {
105
+ // No API key needed: the logged-in `codex` CLI answers instead. Slower than
106
+ // an SDK call (agent start-up), so it gets its own, larger budget.
107
+ return createCodexClient({ timeoutMs });
108
+ }
109
+ return undefined;
110
+ }
111
+
112
+ /**
113
+ * Import, then drain, then record. Every producer is isolated: a missing or
114
+ * unreadable runtime must never stall the queue or another producer.
115
+ *
116
+ * Throws only if the queue itself could not be drained — the caller records
117
+ * that failure and stays alive.
118
+ */
119
+ export async function runMaintenancePass(
120
+ options: MaintenancePassOptions = {}
121
+ ): Promise<MaintenancePassResult> {
122
+ const clock = options.clock ?? systemClock;
123
+ const queueDir = options.queueDir ?? defaultQueueDir();
124
+ const dbPath = options.dbPath ?? defaultDbPath();
125
+ const statePath = options.statePath ?? defaultStatePath(queueDir);
126
+ const llmTimeoutMs = options.llmTimeoutMs ?? defaultLlmTimeoutMs();
127
+ const codexSinceDays = options.codexSinceDays ?? 1;
128
+ const kimiSinceDays = options.kimiSinceDays ?? 1;
129
+ const opencodeSinceDays = options.opencodeSinceDays ?? 1;
130
+ const startedAt = clock.now();
131
+
132
+ let codex: CodexImportResult | undefined;
133
+ let codexError: string | undefined;
134
+ if (codexSinceDays !== false) {
135
+ try {
136
+ codex = await importCodexRollouts({
137
+ queueDir,
138
+ sessionsDir: options.codexSessionsDir ?? defaultCodexSessionsDir(),
139
+ since: new Date(startedAt.getTime() - codexSinceDays * 24 * 60 * 60 * 1000),
140
+ });
141
+ } catch (error) {
142
+ codexError = (error as Error).message;
143
+ console.error('[humemory] maintenance: codex import failed —', codexError);
144
+ }
145
+ }
146
+
147
+ let kimi: KimiImportResult | undefined;
148
+ let kimiError: string | undefined;
149
+ if (kimiSinceDays !== false) {
150
+ try {
151
+ kimi = await importKimiSessions({
152
+ queueDir,
153
+ kimiHome: options.kimiHome ?? defaultKimiHome(),
154
+ since: new Date(startedAt.getTime() - kimiSinceDays * 24 * 60 * 60 * 1000),
155
+ });
156
+ } catch (error) {
157
+ kimiError = (error as Error).message;
158
+ console.error('[humemory] maintenance: Kimi import failed —', kimiError);
159
+ }
160
+ }
161
+
162
+ let opencode: OpenCodeImportResult | undefined;
163
+ let opencodeError: string | undefined;
164
+ if (opencodeSinceDays !== false) {
165
+ try {
166
+ opencode = await importOpenCodeSessions({
167
+ queueDir,
168
+ since: new Date(startedAt.getTime() - opencodeSinceDays * 24 * 60 * 60 * 1000),
169
+ run: options.opencodeRun,
170
+ command: options.opencodeCommand,
171
+ });
172
+ } catch (error) {
173
+ opencodeError = (error as Error).message;
174
+ console.error('[humemory] maintenance: OpenCode import failed —', opencodeError);
175
+ }
176
+ }
177
+
178
+ try {
179
+ const worker = await processMaintenanceQueue({
180
+ queueDir,
181
+ dbPath,
182
+ client: options.client,
183
+ llmTimeoutMs,
184
+ maxJobs: options.maxJobs ?? Number(process.env.HUMEMORY_MAINTENANCE_BATCH ?? 20),
185
+ now: () => clock.now(),
186
+ });
187
+
188
+ // A pass where every job failed is not a healthy pass. The queue isolates
189
+ // jobs on purpose — a bad transcript must not stop the others — but that
190
+ // isolation also makes an infrastructure failure (unopenable database, full
191
+ // disk) look exactly like a batch of bad sessions. The queue no longer
192
+ // dead-letters its way through an outage (retries are refunded and the
193
+ // circuit breaker cuts the pass short), but silence would still leave the
194
+ // machine broken and nothing consolidated, so the pass is recorded as a
195
+ // failure and `maintenance status` says so.
196
+ const wholesaleFailure = worker.discovered > 0 && worker.processed === 0 && worker.failed > 0;
197
+
198
+ await recordMaintenanceRun({
199
+ path: statePath,
200
+ startedAt,
201
+ clock,
202
+ runner: options.runner,
203
+ error: wholesaleFailure ? new Error(wholesaleFailureMessage(worker)) : undefined,
204
+ result: {
205
+ discovered: worker.discovered,
206
+ processed: worker.processed,
207
+ failed: worker.failed,
208
+ deadLettered: worker.deadLettered,
209
+ memoriesStored: worker.memoriesStored,
210
+ busy: worker.busy,
211
+ retriesRefunded: worker.retriesRefunded,
212
+ aborted: worker.aborted,
213
+ },
214
+ });
215
+
216
+ return { codex, codexError, kimi, kimiError, opencode, opencodeError, worker };
217
+ } catch (error) {
218
+ await recordMaintenanceRun({ path: statePath, startedAt, clock, runner: options.runner, error });
219
+ throw error;
220
+ }
221
+ }
222
+
223
+ /**
224
+ * One line naming what the pass looked like, so `maintenance status` can be
225
+ * read without opening the queue directory.
226
+ */
227
+ function wholesaleFailureMessage(worker: WorkerResult): string {
228
+ const scope = worker.aborted
229
+ ? `pass aborted after ${worker.failed} consecutive failures`
230
+ : `every job failed this pass (${worker.failed}/${worker.discovered})`;
231
+ const budget = worker.retriesRefunded > 0
232
+ ? `; ${worker.retriesRefunded} retry(ies) refunded, nothing dead-lettered`
233
+ : '';
234
+ return `${scope} — suspect the database or the disk, not the sessions${budget}`;
235
+ }
236
+
237
+ /** Minimal timer seam, so the loop is testable without waiting on wall time. */
238
+ export interface TimerLike {
239
+ setInterval(handler: () => void, ms: number): unknown;
240
+ clearInterval(handle: unknown): void;
241
+ }
242
+
243
+ const REAL_TIMERS: TimerLike = {
244
+ setInterval: (handler, ms) => {
245
+ const handle = setInterval(handler, ms);
246
+ // Maintenance alone is no reason to hold the process alive.
247
+ if (typeof (handle as { unref?: () => void }).unref === 'function') {
248
+ (handle as unknown as { unref: () => void }).unref();
249
+ }
250
+ return handle;
251
+ },
252
+ clearInterval: (handle) => clearInterval(handle as ReturnType<typeof setInterval>),
253
+ };
254
+
255
+ export interface MaintenanceLoop {
256
+ /** Runs a pass now, outside the schedule. Resolves once it has finished. */
257
+ runNow(): Promise<void>;
258
+ stop(): void;
259
+ /** True while a pass is in flight — the next tick is suppressed until it clears. */
260
+ readonly busy: boolean;
261
+ }
262
+
263
+ export interface MaintenanceLoopOptions extends MaintenancePassOptions {
264
+ intervalMs?: number;
265
+ /** Run one pass immediately instead of waiting a full interval. */
266
+ runAtStart?: boolean;
267
+ timers?: TimerLike;
268
+ }
269
+
270
+ /**
271
+ * Run a pass every `intervalMs` inside the calling process. The API process is
272
+ * already resident and windowless, so hosting the loop there spawns nothing —
273
+ * which is the whole point of moving it off the Windows scheduler.
274
+ *
275
+ * Three properties this guarantees, each covered by a test:
276
+ * - passes never overlap, on top of the queue's own cross-process lock;
277
+ * - a throwing pass is contained and the loop keeps ticking, because the API
278
+ * must not die of a bad session transcript;
279
+ * - every pass, good or bad, lands in the state file.
280
+ */
281
+ export function startMaintenanceLoop(options: MaintenanceLoopOptions = {}): MaintenanceLoop {
282
+ const intervalMs = options.intervalMs ?? configuredIntervalMs();
283
+ const timers = options.timers ?? REAL_TIMERS;
284
+ let running = false;
285
+ let stopped = false;
286
+
287
+ const pass = async (): Promise<void> => {
288
+ if (running || stopped) return;
289
+ running = true;
290
+ try {
291
+ const client = options.client ?? await resolveMaintenanceClient(options.llmTimeoutMs);
292
+ const { worker } = await runMaintenancePass({ ...options, client, runner: options.runner ?? 'api-loop' });
293
+ if (process.env.HUMEMORY_VERBOSE === '1' || worker.failed > 0) {
294
+ console.error(
295
+ `[humemory] maintenance: ${worker.processed}/${worker.discovered} jobs, ` +
296
+ `${worker.memoriesStored} memories, ${worker.failed} failed, ${worker.deadLettered} dead-lettered` +
297
+ (worker.aborted ? ' (pass aborted — suspected outage)' : '')
298
+ );
299
+ }
300
+ } catch (error) {
301
+ // Contained on purpose: a crashing pass must never take the API down.
302
+ // The failure is already in the state file, so it stays visible.
303
+ console.error('[humemory] maintenance pass failed —', (error as Error).message);
304
+ } finally {
305
+ running = false;
306
+ }
307
+ };
308
+
309
+ const handle = timers.setInterval(() => void pass(), intervalMs);
310
+ if (options.runAtStart) void pass();
311
+
312
+ return {
313
+ runNow: pass,
314
+ get busy() {
315
+ return running;
316
+ },
317
+ stop() {
318
+ stopped = true;
319
+ timers.clearInterval(handle);
320
+ },
321
+ };
322
+ }
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Durable record of how maintenance is actually going.
3
+ *
4
+ * Without this, a stopped maintenance loop is invisible: the queue simply stops
5
+ * draining and nothing says so until someone notices memories are missing. The
6
+ * state file is the answer to "is consolidation still alive, and since when".
7
+ *
8
+ * It is a plain JSON file rather than a table on purpose. This is the health
9
+ * signal *about* the system, so it must not depend on the part of the system
10
+ * most likely to be broken — a locked or corrupt database still leaves a
11
+ * readable answer here. Writes are atomic (temp file + rename) so a crash
12
+ * mid-write cannot leave a truncated state behind.
13
+ */
14
+
15
+ import { readFile, rename, writeFile, mkdir } from 'fs/promises';
16
+ import { dirname, join } from 'path';
17
+ import type { Clock } from '../core/clock.js';
18
+ import { systemClock } from '../core/clock.js';
19
+
20
+ /** A pass is considered overdue at four intervals without a success. */
21
+ export const DEFAULT_STALE_AFTER_MS = 60 * 60 * 1000;
22
+
23
+ export interface MaintenanceState {
24
+ /** Start of the most recent pass, successful or not. */
25
+ lastRunAt?: string;
26
+ lastSuccessAt?: string;
27
+ lastDurationMs?: number;
28
+ /** Reset to 0 by any success — a non-zero value means the loop is degraded, not dead. */
29
+ consecutiveFailures: number;
30
+ /** Message only, never a stack: this is read back over the API. */
31
+ lastError?: string;
32
+ lastResult?: {
33
+ discovered: number;
34
+ processed: number;
35
+ failed: number;
36
+ deadLettered: number;
37
+ memoriesStored: number;
38
+ /** True when another worker held the lock — not a failure. */
39
+ busy: boolean;
40
+ /** Retries handed back because the pass looked like an outage, not a bad job. */
41
+ retriesRefunded?: number;
42
+ /** True when the circuit breaker cut the pass short. */
43
+ aborted?: boolean;
44
+ };
45
+ /** Which process last wrote here, so two schedulers fighting is visible. */
46
+ lastRunner?: string;
47
+ }
48
+
49
+ const EMPTY: MaintenanceState = { consecutiveFailures: 0 };
50
+
51
+ export function defaultStatePath(queueDir: string): string {
52
+ return join(dirname(queueDir), 'maintenance-state.json');
53
+ }
54
+
55
+ /**
56
+ * Never throws: an absent file is a fresh install, and a corrupt one must not
57
+ * take down the caller that is merely asking for a status.
58
+ */
59
+ export async function readMaintenanceState(path: string): Promise<MaintenanceState> {
60
+ try {
61
+ const parsed = JSON.parse(await readFile(path, 'utf-8')) as MaintenanceState;
62
+ if (!parsed || typeof parsed !== 'object') return { ...EMPTY };
63
+ return { ...EMPTY, ...parsed };
64
+ } catch {
65
+ return { ...EMPTY };
66
+ }
67
+ }
68
+
69
+ async function writeAtomic(path: string, state: MaintenanceState): Promise<void> {
70
+ await mkdir(dirname(path), { recursive: true });
71
+ const tmp = `${path}.${process.pid}.tmp`;
72
+ await writeFile(tmp, JSON.stringify(state, null, 2), 'utf-8');
73
+ await rename(tmp, path);
74
+ }
75
+
76
+ export interface RecordRunOptions {
77
+ path: string;
78
+ startedAt: Date;
79
+ clock?: Clock;
80
+ runner?: string;
81
+ result?: MaintenanceState['lastResult'];
82
+ error?: unknown;
83
+ }
84
+
85
+ /**
86
+ * Fold one pass into the state file. Recording is best-effort by design: a
87
+ * read-only disk must degrade observability, never stop consolidation.
88
+ */
89
+ export async function recordMaintenanceRun(options: RecordRunOptions): Promise<MaintenanceState> {
90
+ const clock = options.clock ?? systemClock;
91
+ const previous = await readMaintenanceState(options.path);
92
+ const finishedAt = clock.now();
93
+ const succeeded = options.error === undefined;
94
+
95
+ const next: MaintenanceState = {
96
+ ...previous,
97
+ lastRunAt: options.startedAt.toISOString(),
98
+ lastDurationMs: Math.max(0, finishedAt.getTime() - options.startedAt.getTime()),
99
+ consecutiveFailures: succeeded ? 0 : previous.consecutiveFailures + 1,
100
+ lastRunner: options.runner ?? previous.lastRunner,
101
+ };
102
+
103
+ // Counts are recorded either way: a pass that failed wholesale still says how
104
+ // many jobs it saw, which is the first thing to look at when diagnosing it.
105
+ if (options.result) next.lastResult = options.result;
106
+
107
+ if (succeeded) {
108
+ next.lastSuccessAt = finishedAt.toISOString();
109
+ delete next.lastError;
110
+ } else {
111
+ next.lastError = options.error instanceof Error ? options.error.message : String(options.error);
112
+ }
113
+
114
+ try {
115
+ await writeAtomic(options.path, next);
116
+ } catch (error) {
117
+ console.error('[humemory] maintenance: could not record state —', (error as Error).message);
118
+ }
119
+ return next;
120
+ }
121
+
122
+ export interface MaintenanceHealth {
123
+ /** No success ever, or the last one is older than the staleness budget. */
124
+ stale: boolean;
125
+ /** Milliseconds since the last success; undefined when there has never been one. */
126
+ ageMs?: number;
127
+ consecutiveFailures: number;
128
+ lastSuccessAt?: string;
129
+ lastRunAt?: string;
130
+ lastError?: string;
131
+ lastResult?: MaintenanceState['lastResult'];
132
+ /** One line a human can act on. */
133
+ summary: string;
134
+ }
135
+
136
+ export function assessMaintenance(
137
+ state: MaintenanceState,
138
+ options: { staleAfterMs?: number; clock?: Clock } = {}
139
+ ): MaintenanceHealth {
140
+ const staleAfterMs = options.staleAfterMs ?? DEFAULT_STALE_AFTER_MS;
141
+ const now = (options.clock ?? systemClock).now().getTime();
142
+ const lastSuccess = state.lastSuccessAt ? Date.parse(state.lastSuccessAt) : undefined;
143
+ const ageMs = lastSuccess !== undefined && Number.isFinite(lastSuccess) ? now - lastSuccess : undefined;
144
+ const stale = ageMs === undefined || ageMs > staleAfterMs;
145
+
146
+ let summary: string;
147
+ if (ageMs === undefined) {
148
+ summary = 'no maintenance pass has ever succeeded';
149
+ } else if (stale) {
150
+ summary = `last success ${Math.round(ageMs / 60_000)} min ago — over the ${Math.round(staleAfterMs / 60_000)} min budget`;
151
+ } else {
152
+ summary = `healthy — last success ${Math.round(ageMs / 60_000)} min ago`;
153
+ }
154
+ if (state.consecutiveFailures > 0) {
155
+ summary += `, ${state.consecutiveFailures} consecutive failure(s)`;
156
+ }
157
+
158
+ return {
159
+ stale,
160
+ ageMs,
161
+ consecutiveFailures: state.consecutiveFailures,
162
+ lastSuccessAt: state.lastSuccessAt,
163
+ lastRunAt: state.lastRunAt,
164
+ lastError: state.lastError,
165
+ lastResult: state.lastResult,
166
+ summary,
167
+ };
168
+ }
@@ -0,0 +1,125 @@
1
+ /** Safe, merge-only MCP registration for locally installed agent clients. */
2
+ import { mkdir, readFile, writeFile, rename, rm } from 'fs/promises';
3
+ import { randomUUID } from 'crypto';
4
+ import { dirname, join, resolve } from 'path';
5
+ import { homedir } from 'os';
6
+ import { databasePath } from '../core/paths.js';
7
+ import { AdvisoryLock } from '../store/sqlite.js';
8
+
9
+ export type HumemoryMcpClient = 'kimi' | 'opencode';
10
+
11
+ export interface McpClientSetupOptions {
12
+ clients: HumemoryMcpClient[];
13
+ projectRoot: string;
14
+ dbPath?: string;
15
+ bunPath?: string;
16
+ kimiHome?: string;
17
+ openCodeConfig?: string;
18
+ dryRun?: boolean;
19
+ }
20
+
21
+ export interface McpClientSetupEntry {
22
+ client: HumemoryMcpClient;
23
+ path: string;
24
+ changed: boolean;
25
+ }
26
+
27
+ async function readOptional(path: string): Promise<string | null> {
28
+ try {
29
+ return await readFile(path, 'utf8');
30
+ } catch (error: any) {
31
+ if (error?.code === 'ENOENT') return null;
32
+ throw error;
33
+ }
34
+ }
35
+
36
+ function readJson(raw: string | null, path: string): Record<string, unknown> {
37
+ if (raw === null) return {};
38
+ try {
39
+ const parsed = JSON.parse(raw);
40
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('expected an object');
41
+ for (const key of ['mcp', 'mcpServers']) {
42
+ if (key in parsed && (!parsed[key] || typeof parsed[key] !== 'object' || Array.isArray(parsed[key]))) {
43
+ throw new Error(`${key} must be an object`);
44
+ }
45
+ }
46
+ return parsed;
47
+ } catch (error) {
48
+ throw new Error(`Refusing to rewrite invalid or commented JSON: ${path} (${(error as Error).message})`);
49
+ }
50
+ }
51
+
52
+ async function mergeFile(
53
+ path: string,
54
+ update: (current: Record<string, unknown>) => Record<string, unknown>,
55
+ dryRun: boolean,
56
+ ): Promise<boolean> {
57
+ const apply = async () => {
58
+ const original = await readOptional(path);
59
+ const current = readJson(original, path);
60
+ const before = JSON.stringify(current);
61
+ const next = update(current);
62
+ const changed = before !== JSON.stringify(next);
63
+ if (changed && !dryRun) {
64
+ await mkdir(dirname(path), { recursive: true });
65
+ const temporary = `${path}.${randomUUID()}.tmp`;
66
+ try {
67
+ await writeFile(temporary, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
68
+ if (original !== null) await writeFile(`${path}.${randomUUID()}.bak`, original, { mode: 0o600, flag: 'wx' });
69
+ if (await readOptional(path) !== original) throw new Error(`Configuration changed during setup: ${path}`);
70
+ await rename(temporary, path);
71
+ } finally { await rm(temporary, { force: true }); }
72
+ }
73
+ return changed;
74
+ };
75
+ if (dryRun) return apply();
76
+ await mkdir(dirname(path), { recursive: true });
77
+ return new AdvisoryLock(path + '.setup', 50).withLock(apply);
78
+ }
79
+
80
+ export async function setupHumemoryMcpClients(options: McpClientSetupOptions): Promise<McpClientSetupEntry[]> {
81
+ const projectRoot = resolve(options.projectRoot);
82
+ const serverPath = join(projectRoot, 'src', 'mcp', 'server.ts');
83
+ const configuredDb = options.dbPath ?? databasePath();
84
+ const dbPath = configuredDb === ':memory:' ? configuredDb : resolve(configuredDb);
85
+ const bunPath = resolve(options.bunPath ?? process.execPath);
86
+ const dryRun = options.dryRun ?? false;
87
+ const entries: McpClientSetupEntry[] = [];
88
+
89
+ for (const client of [...new Set(options.clients)]) {
90
+ if (client === 'kimi') {
91
+ const path = join(options.kimiHome ?? process.env.KIMI_CODE_HOME ?? join(homedir(), '.kimi-code'), 'mcp.json');
92
+ const changed = await mergeFile(path, (current) => ({
93
+ ...current,
94
+ mcpServers: {
95
+ ...((current.mcpServers as Record<string, unknown> | undefined) ?? {}),
96
+ humemory: {
97
+ command: bunPath,
98
+ args: ['run', serverPath],
99
+ env: { HUMEMORY_AGENT: 'kimi', HUMEMORY_DB: dbPath },
100
+ },
101
+ },
102
+ }), dryRun);
103
+ entries.push({ client, path, changed });
104
+ continue;
105
+ }
106
+
107
+ const path = options.openCodeConfig ?? process.env.OPENCODE_CONFIG ??
108
+ join(homedir(), '.config', 'opencode', 'opencode.json');
109
+ const changed = await mergeFile(path, (current) => ({
110
+ ...current,
111
+ $schema: current.$schema ?? 'https://opencode.ai/config.json',
112
+ mcp: {
113
+ ...((current.mcp as Record<string, unknown> | undefined) ?? {}),
114
+ humemory: {
115
+ type: 'local',
116
+ command: [bunPath, 'run', serverPath],
117
+ enabled: true,
118
+ environment: { HUMEMORY_AGENT: 'opencode', HUMEMORY_DB: dbPath },
119
+ },
120
+ },
121
+ }), dryRun);
122
+ entries.push({ client, path, changed });
123
+ }
124
+ return entries;
125
+ }