humemory 0.2.4 → 0.2.6

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.
@@ -0,0 +1,188 @@
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
+ import { dirname, join } from 'path';
17
+ import { fileURLToPath } from 'url';
18
+ import { systemClock } from '../core/clock.js';
19
+ import { createCodexClient } from '../core/llm-cli-client.js';
20
+ import { processMaintenanceQueue } from './maintenance-queue.js';
21
+ import { importCodexRollouts, defaultCodexSessionsDir } from './codex-import.js';
22
+ import { defaultStatePath, recordMaintenanceRun } from './maintenance-state.js';
23
+ const __dirname = dirname(fileURLToPath(import.meta.url));
24
+ export const DEFAULT_INTERVAL_MS = 15 * 60 * 1000;
25
+ export function defaultQueueDir() {
26
+ return process.env.HUMEMORY_QUEUE ?? join(__dirname, '../../data/maintenance-queue');
27
+ }
28
+ export function defaultDbPath() {
29
+ return process.env.HUMEMORY_DB ?? join(__dirname, '../../data/humemory.db');
30
+ }
31
+ export function defaultLlmTimeoutMs() {
32
+ return Number(process.env.HUMEMORY_MAINTENANCE_TIMEOUT_MS ?? 8_000);
33
+ }
34
+ export function configuredIntervalMs() {
35
+ const raw = Number(process.env.HUMEMORY_MAINTENANCE_INTERVAL_MS ?? DEFAULT_INTERVAL_MS);
36
+ return Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_INTERVAL_MS;
37
+ }
38
+ /**
39
+ * The LLM the pass consolidates with. 'none' (the default) keeps consolidation
40
+ * deterministic and network-free; there is no API key on the production machine
41
+ * and none wanted, so 'codex' shells out to the logged-in CLI instead.
42
+ */
43
+ export async function resolveMaintenanceClient(timeoutMs = defaultLlmTimeoutMs()) {
44
+ const provider = process.env.HUMEMORY_MAINTENANCE_LLM ?? 'none';
45
+ if (provider === 'anthropic' && process.env.ANTHROPIC_API_KEY) {
46
+ const { default: Anthropic } = await import('@anthropic-ai/sdk');
47
+ return new Anthropic();
48
+ }
49
+ if (provider === 'codex') {
50
+ // No API key needed: the logged-in `codex` CLI answers instead. Slower than
51
+ // an SDK call (agent start-up), so it gets its own, larger budget.
52
+ return createCodexClient({ timeoutMs });
53
+ }
54
+ return undefined;
55
+ }
56
+ /**
57
+ * Import, then drain, then record. A failing codex import is contained: a
58
+ * missing or unreadable codex must never stall the queue, which holds sessions
59
+ * from every other source.
60
+ *
61
+ * Throws only if the queue itself could not be drained — the caller records
62
+ * that failure and stays alive.
63
+ */
64
+ export async function runMaintenancePass(options = {}) {
65
+ const clock = options.clock ?? systemClock;
66
+ const queueDir = options.queueDir ?? defaultQueueDir();
67
+ const dbPath = options.dbPath ?? defaultDbPath();
68
+ const statePath = options.statePath ?? defaultStatePath(queueDir);
69
+ const llmTimeoutMs = options.llmTimeoutMs ?? defaultLlmTimeoutMs();
70
+ const sinceDays = options.codexSinceDays ?? 1;
71
+ const startedAt = clock.now();
72
+ let codex;
73
+ let codexError;
74
+ if (sinceDays !== false) {
75
+ try {
76
+ codex = await importCodexRollouts({
77
+ queueDir,
78
+ sessionsDir: options.codexSessionsDir ?? defaultCodexSessionsDir(),
79
+ since: new Date(startedAt.getTime() - sinceDays * 24 * 60 * 60 * 1000),
80
+ });
81
+ }
82
+ catch (error) {
83
+ codexError = error.message;
84
+ console.error('[humemory] maintenance: codex import failed —', codexError);
85
+ }
86
+ }
87
+ try {
88
+ const worker = await processMaintenanceQueue({
89
+ queueDir,
90
+ dbPath,
91
+ client: options.client,
92
+ llmTimeoutMs,
93
+ maxJobs: options.maxJobs ?? Number(process.env.HUMEMORY_MAINTENANCE_BATCH ?? 20),
94
+ now: () => clock.now(),
95
+ });
96
+ // A pass where every job failed is not a healthy pass. The queue isolates
97
+ // jobs on purpose — a bad transcript must not stop the others — but that
98
+ // isolation also makes an infrastructure failure (unopenable database, full
99
+ // disk) look exactly like a batch of bad sessions, and after `maxAttempts`
100
+ // it quietly dead-letters everything. Recording it as a failure is what
101
+ // makes that case visible before the queue has drained itself into nothing.
102
+ const wholesaleFailure = worker.discovered > 0 && worker.processed === 0 && worker.failed > 0;
103
+ await recordMaintenanceRun({
104
+ path: statePath,
105
+ startedAt,
106
+ clock,
107
+ runner: options.runner,
108
+ error: wholesaleFailure
109
+ ? new Error(`every job failed this pass (${worker.failed}/${worker.discovered}) — suspect the database or the disk, not the sessions`)
110
+ : undefined,
111
+ result: {
112
+ discovered: worker.discovered,
113
+ processed: worker.processed,
114
+ failed: worker.failed,
115
+ deadLettered: worker.deadLettered,
116
+ memoriesStored: worker.memoriesStored,
117
+ busy: worker.busy,
118
+ },
119
+ });
120
+ return { codex, codexError, worker };
121
+ }
122
+ catch (error) {
123
+ await recordMaintenanceRun({ path: statePath, startedAt, clock, runner: options.runner, error });
124
+ throw error;
125
+ }
126
+ }
127
+ const REAL_TIMERS = {
128
+ setInterval: (handler, ms) => {
129
+ const handle = setInterval(handler, ms);
130
+ // Maintenance alone is no reason to hold the process alive.
131
+ if (typeof handle.unref === 'function') {
132
+ handle.unref();
133
+ }
134
+ return handle;
135
+ },
136
+ clearInterval: (handle) => clearInterval(handle),
137
+ };
138
+ /**
139
+ * Run a pass every `intervalMs` inside the calling process. The API process is
140
+ * already resident and windowless, so hosting the loop there spawns nothing —
141
+ * which is the whole point of moving it off the Windows scheduler.
142
+ *
143
+ * Three properties this guarantees, each covered by a test:
144
+ * - passes never overlap, on top of the queue's own cross-process lock;
145
+ * - a throwing pass is contained and the loop keeps ticking, because the API
146
+ * must not die of a bad session transcript;
147
+ * - every pass, good or bad, lands in the state file.
148
+ */
149
+ export function startMaintenanceLoop(options = {}) {
150
+ const intervalMs = options.intervalMs ?? configuredIntervalMs();
151
+ const timers = options.timers ?? REAL_TIMERS;
152
+ let running = false;
153
+ let stopped = false;
154
+ const pass = async () => {
155
+ if (running || stopped)
156
+ return;
157
+ running = true;
158
+ try {
159
+ const client = options.client ?? await resolveMaintenanceClient(options.llmTimeoutMs);
160
+ const { worker } = await runMaintenancePass({ ...options, client, runner: options.runner ?? 'api-loop' });
161
+ if (process.env.HUMEMORY_VERBOSE === '1' || worker.failed > 0) {
162
+ console.error(`[humemory] maintenance: ${worker.processed}/${worker.discovered} jobs, ` +
163
+ `${worker.memoriesStored} memories, ${worker.failed} failed, ${worker.deadLettered} dead-lettered`);
164
+ }
165
+ }
166
+ catch (error) {
167
+ // Contained on purpose: a crashing pass must never take the API down.
168
+ // The failure is already in the state file, so it stays visible.
169
+ console.error('[humemory] maintenance pass failed —', error.message);
170
+ }
171
+ finally {
172
+ running = false;
173
+ }
174
+ };
175
+ const handle = timers.setInterval(() => void pass(), intervalMs);
176
+ if (options.runAtStart)
177
+ void pass();
178
+ return {
179
+ runNow: pass,
180
+ get busy() {
181
+ return running;
182
+ },
183
+ stop() {
184
+ stopped = true;
185
+ timers.clearInterval(handle);
186
+ },
187
+ };
188
+ }
@@ -0,0 +1,73 @@
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
+ import type { Clock } from '../core/clock.js';
15
+ /** A pass is considered overdue at four intervals without a success. */
16
+ export declare const DEFAULT_STALE_AFTER_MS: number;
17
+ export interface MaintenanceState {
18
+ /** Start of the most recent pass, successful or not. */
19
+ lastRunAt?: string;
20
+ lastSuccessAt?: string;
21
+ lastDurationMs?: number;
22
+ /** Reset to 0 by any success — a non-zero value means the loop is degraded, not dead. */
23
+ consecutiveFailures: number;
24
+ /** Message only, never a stack: this is read back over the API. */
25
+ lastError?: string;
26
+ lastResult?: {
27
+ discovered: number;
28
+ processed: number;
29
+ failed: number;
30
+ deadLettered: number;
31
+ memoriesStored: number;
32
+ /** True when another worker held the lock — not a failure. */
33
+ busy: boolean;
34
+ };
35
+ /** Which process last wrote here, so two schedulers fighting is visible. */
36
+ lastRunner?: string;
37
+ }
38
+ export declare function defaultStatePath(queueDir: string): string;
39
+ /**
40
+ * Never throws: an absent file is a fresh install, and a corrupt one must not
41
+ * take down the caller that is merely asking for a status.
42
+ */
43
+ export declare function readMaintenanceState(path: string): Promise<MaintenanceState>;
44
+ export interface RecordRunOptions {
45
+ path: string;
46
+ startedAt: Date;
47
+ clock?: Clock;
48
+ runner?: string;
49
+ result?: MaintenanceState['lastResult'];
50
+ error?: unknown;
51
+ }
52
+ /**
53
+ * Fold one pass into the state file. Recording is best-effort by design: a
54
+ * read-only disk must degrade observability, never stop consolidation.
55
+ */
56
+ export declare function recordMaintenanceRun(options: RecordRunOptions): Promise<MaintenanceState>;
57
+ export interface MaintenanceHealth {
58
+ /** No success ever, or the last one is older than the staleness budget. */
59
+ stale: boolean;
60
+ /** Milliseconds since the last success; undefined when there has never been one. */
61
+ ageMs?: number;
62
+ consecutiveFailures: number;
63
+ lastSuccessAt?: string;
64
+ lastRunAt?: string;
65
+ lastError?: string;
66
+ lastResult?: MaintenanceState['lastResult'];
67
+ /** One line a human can act on. */
68
+ summary: string;
69
+ }
70
+ export declare function assessMaintenance(state: MaintenanceState, options?: {
71
+ staleAfterMs?: number;
72
+ clock?: Clock;
73
+ }): MaintenanceHealth;
@@ -0,0 +1,108 @@
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
+ import { readFile, rename, writeFile, mkdir } from 'fs/promises';
15
+ import { dirname, join } from 'path';
16
+ import { systemClock } from '../core/clock.js';
17
+ /** A pass is considered overdue at four intervals without a success. */
18
+ export const DEFAULT_STALE_AFTER_MS = 60 * 60 * 1000;
19
+ const EMPTY = { consecutiveFailures: 0 };
20
+ export function defaultStatePath(queueDir) {
21
+ return join(dirname(queueDir), 'maintenance-state.json');
22
+ }
23
+ /**
24
+ * Never throws: an absent file is a fresh install, and a corrupt one must not
25
+ * take down the caller that is merely asking for a status.
26
+ */
27
+ export async function readMaintenanceState(path) {
28
+ try {
29
+ const parsed = JSON.parse(await readFile(path, 'utf-8'));
30
+ if (!parsed || typeof parsed !== 'object')
31
+ return { ...EMPTY };
32
+ return { ...EMPTY, ...parsed };
33
+ }
34
+ catch {
35
+ return { ...EMPTY };
36
+ }
37
+ }
38
+ async function writeAtomic(path, state) {
39
+ await mkdir(dirname(path), { recursive: true });
40
+ const tmp = `${path}.${process.pid}.tmp`;
41
+ await writeFile(tmp, JSON.stringify(state, null, 2), 'utf-8');
42
+ await rename(tmp, path);
43
+ }
44
+ /**
45
+ * Fold one pass into the state file. Recording is best-effort by design: a
46
+ * read-only disk must degrade observability, never stop consolidation.
47
+ */
48
+ export async function recordMaintenanceRun(options) {
49
+ const clock = options.clock ?? systemClock;
50
+ const previous = await readMaintenanceState(options.path);
51
+ const finishedAt = clock.now();
52
+ const succeeded = options.error === undefined;
53
+ const next = {
54
+ ...previous,
55
+ lastRunAt: options.startedAt.toISOString(),
56
+ lastDurationMs: Math.max(0, finishedAt.getTime() - options.startedAt.getTime()),
57
+ consecutiveFailures: succeeded ? 0 : previous.consecutiveFailures + 1,
58
+ lastRunner: options.runner ?? previous.lastRunner,
59
+ };
60
+ // Counts are recorded either way: a pass that failed wholesale still says how
61
+ // many jobs it saw, which is the first thing to look at when diagnosing it.
62
+ if (options.result)
63
+ next.lastResult = options.result;
64
+ if (succeeded) {
65
+ next.lastSuccessAt = finishedAt.toISOString();
66
+ delete next.lastError;
67
+ }
68
+ else {
69
+ next.lastError = options.error instanceof Error ? options.error.message : String(options.error);
70
+ }
71
+ try {
72
+ await writeAtomic(options.path, next);
73
+ }
74
+ catch (error) {
75
+ console.error('[humemory] maintenance: could not record state —', error.message);
76
+ }
77
+ return next;
78
+ }
79
+ export function assessMaintenance(state, options = {}) {
80
+ const staleAfterMs = options.staleAfterMs ?? DEFAULT_STALE_AFTER_MS;
81
+ const now = (options.clock ?? systemClock).now().getTime();
82
+ const lastSuccess = state.lastSuccessAt ? Date.parse(state.lastSuccessAt) : undefined;
83
+ const ageMs = lastSuccess !== undefined && Number.isFinite(lastSuccess) ? now - lastSuccess : undefined;
84
+ const stale = ageMs === undefined || ageMs > staleAfterMs;
85
+ let summary;
86
+ if (ageMs === undefined) {
87
+ summary = 'no maintenance pass has ever succeeded';
88
+ }
89
+ else if (stale) {
90
+ summary = `last success ${Math.round(ageMs / 60_000)} min ago — over the ${Math.round(staleAfterMs / 60_000)} min budget`;
91
+ }
92
+ else {
93
+ summary = `healthy — last success ${Math.round(ageMs / 60_000)} min ago`;
94
+ }
95
+ if (state.consecutiveFailures > 0) {
96
+ summary += `, ${state.consecutiveFailures} consecutive failure(s)`;
97
+ }
98
+ return {
99
+ stale,
100
+ ageMs,
101
+ consecutiveFailures: state.consecutiveFailures,
102
+ lastSuccessAt: state.lastSuccessAt,
103
+ lastRunAt: state.lastRunAt,
104
+ lastError: state.lastError,
105
+ lastResult: state.lastResult,
106
+ summary,
107
+ };
108
+ }
@@ -8,5 +8,22 @@ export interface ParsedSession {
8
8
  directory: string;
9
9
  messages: SessionMessage[];
10
10
  rawText: string;
11
+ /**
12
+ * When the session was *lived*, not when it was read. A rollout swept weeks
13
+ * after the fact must encode as a trace of that day, otherwise every import
14
+ * lands on the import date and the memory loses its timeline — and, with it,
15
+ * the age decay works from.
16
+ */
17
+ occurredAt?: Date;
11
18
  }
19
+ /** The instant a transcript line carries, when it carries a usable one. */
20
+ export declare function messageTime(message: SessionMessage | undefined): Date | undefined;
21
+ /** The last usable instant in a run of messages — the session's own clock. */
22
+ export declare function lastMessageTime(messages: SessionMessage[]): Date | undefined;
12
23
  export declare function parseClaudeHookPayload(raw: string, directory: string): ParsedSession;
24
+ /**
25
+ * Entry point for any local agent transcript: detects the producer and hands
26
+ * off. Claude hook payloads and Codex rollouts are both JSON on stdin, so the
27
+ * dispatch is on shape, not on a flag the caller has to remember to pass.
28
+ */
29
+ export declare function parseAgentSession(raw: string, directory: string): ParsedSession;
@@ -1,3 +1,20 @@
1
+ import { isCodexRollout, parseCodexRollout } from './codex-rollout-parser.js';
2
+ /** The instant a transcript line carries, when it carries a usable one. */
3
+ export function messageTime(message) {
4
+ if (!message?.timestamp)
5
+ return undefined;
6
+ const at = new Date(message.timestamp);
7
+ return Number.isNaN(at.getTime()) ? undefined : at;
8
+ }
9
+ /** The last usable instant in a run of messages — the session's own clock. */
10
+ export function lastMessageTime(messages) {
11
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
12
+ const at = messageTime(messages[i]);
13
+ if (at)
14
+ return at;
15
+ }
16
+ return undefined;
17
+ }
1
18
  function extractText(content) {
2
19
  if (typeof content === 'string')
3
20
  return content;
@@ -33,6 +50,7 @@ export function parseClaudeHookPayload(raw, directory) {
33
50
  directory: payload.cwd ?? directory,
34
51
  messages,
35
52
  rawText: messages.map(m => `${m.role}: ${m.content}`).join('\n\n'),
53
+ occurredAt: lastMessageTime(messages),
36
54
  };
37
55
  }
38
56
  // Format: array of messages directly
@@ -47,6 +65,7 @@ export function parseClaudeHookPayload(raw, directory) {
47
65
  directory,
48
66
  messages,
49
67
  rawText: messages.map(m => `${m.role}: ${m.content}`).join('\n\n'),
68
+ occurredAt: lastMessageTime(messages),
50
69
  };
51
70
  }
52
71
  }
@@ -73,6 +92,7 @@ export function parseClaudeHookPayload(raw, directory) {
73
92
  directory,
74
93
  messages,
75
94
  rawText: messages.map(m => `${m.role}: ${m.content}`).join('\n\n'),
95
+ occurredAt: lastMessageTime(messages),
76
96
  };
77
97
  }
78
98
  // Fallback: plain text
@@ -83,3 +103,11 @@ export function parseClaudeHookPayload(raw, directory) {
83
103
  rawText: raw,
84
104
  };
85
105
  }
106
+ /**
107
+ * Entry point for any local agent transcript: detects the producer and hands
108
+ * off. Claude hook payloads and Codex rollouts are both JSON on stdin, so the
109
+ * dispatch is on shape, not on a flag the caller has to remember to pass.
110
+ */
111
+ export function parseAgentSession(raw, directory) {
112
+ return isCodexRollout(raw) ? parseCodexRollout(raw, directory) : parseClaudeHookPayload(raw, directory);
113
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * HTTP surface for maintenance health (same testable-sub-router pattern as
3
+ * dream-routes.ts: every path is a parameter, no production files in tests).
4
+ *
5
+ * These routes sit behind the API token like every other data route. `/health`
6
+ * deliberately stays coarse and public — the watchdog only needs liveness, and
7
+ * `lastError` is internal detail that has no business on an unauthenticated
8
+ * endpoint (SECURITY_AUDIT.md L-01).
9
+ */
10
+ import { Hono } from 'hono';
11
+ export interface MaintenanceLoopHandle {
12
+ runNow(): Promise<void>;
13
+ readonly busy: boolean;
14
+ }
15
+ export interface MaintenanceRoutesOptions {
16
+ statePath: string;
17
+ staleAfterMs?: number;
18
+ /**
19
+ * Resolves the loop this process hosts, or undefined when an external
20
+ * scheduler drives maintenance instead. A getter rather than a value because
21
+ * the server binds the routes before it decides to start the loop.
22
+ */
23
+ loop?: () => MaintenanceLoopHandle | undefined;
24
+ }
25
+ export declare function createMaintenanceRoutes(options: MaintenanceRoutesOptions): Hono<import("hono/types").BlankEnv, import("hono/types").BlankSchema, "/">;
@@ -0,0 +1,54 @@
1
+ /**
2
+ * HTTP surface for maintenance health (same testable-sub-router pattern as
3
+ * dream-routes.ts: every path is a parameter, no production files in tests).
4
+ *
5
+ * These routes sit behind the API token like every other data route. `/health`
6
+ * deliberately stays coarse and public — the watchdog only needs liveness, and
7
+ * `lastError` is internal detail that has no business on an unauthenticated
8
+ * endpoint (SECURITY_AUDIT.md L-01).
9
+ */
10
+ import { Hono } from 'hono';
11
+ import { assessMaintenance, readMaintenanceState, DEFAULT_STALE_AFTER_MS } from '../agent/maintenance-state.js';
12
+ import { serverErrorBody } from './errors.js';
13
+ export function createMaintenanceRoutes(options) {
14
+ const app = new Hono();
15
+ const staleAfterMs = options.staleAfterMs ?? DEFAULT_STALE_AFTER_MS;
16
+ app.get('/maintenance/status', async (c) => {
17
+ try {
18
+ const state = await readMaintenanceState(options.statePath);
19
+ const health = assessMaintenance(state, { staleAfterMs });
20
+ return c.json({
21
+ success: true,
22
+ maintenance: {
23
+ ...health,
24
+ hostedHere: options.loop?.() !== undefined,
25
+ running: options.loop?.()?.busy ?? false,
26
+ staleAfterMs,
27
+ },
28
+ });
29
+ }
30
+ catch (error) {
31
+ return c.json(serverErrorBody('maintenance status', error), 500);
32
+ }
33
+ });
34
+ // Force a pass — the dashboard's "consolidate now", and the escape hatch when
35
+ // the schedule is known to have missed a window.
36
+ app.post('/maintenance/run', async (c) => {
37
+ const loop = options.loop?.();
38
+ if (!loop) {
39
+ return c.json({ success: false, error: 'No maintenance loop in this process' }, 409);
40
+ }
41
+ if (loop.busy) {
42
+ return c.json({ success: false, error: 'A maintenance pass is already running' }, 409);
43
+ }
44
+ try {
45
+ await loop.runNow();
46
+ const state = await readMaintenanceState(options.statePath);
47
+ return c.json({ success: true, maintenance: assessMaintenance(state, { staleAfterMs }) });
48
+ }
49
+ catch (error) {
50
+ return c.json(serverErrorBody('maintenance run', error), 500);
51
+ }
52
+ });
53
+ return app;
54
+ }
@@ -41,6 +41,9 @@ import { createIntentionRoutes } from './intentions-routes.js';
41
41
  import { createMemoryRoutes } from './memory-routes.js';
42
42
  import { createDreamRoutes } from './dream-routes.js';
43
43
  import { createScriptRoutes } from './scripts-routes.js';
44
+ import { createMaintenanceRoutes } from './maintenance-routes.js';
45
+ import { defaultStatePath } from '../agent/maintenance-state.js';
46
+ import { startMaintenanceLoop, configuredIntervalMs, } from '../agent/maintenance-runner.js';
44
47
  import { join, dirname, resolve, sep } from 'path';
45
48
  import { fileURLToPath } from 'url';
46
49
  import { readFileSync } from 'fs';
@@ -64,6 +67,11 @@ function safeJoin(baseDir, ...segments) {
64
67
  const DB_PATH = process.env.HUMEMORY_DB ?? join(__dirname, '../../data/humemory.db');
65
68
  const store = new SQLiteStore(DB_PATH);
66
69
  const PUBLIC_DIR = join(__dirname, '../../public');
70
+ const QUEUE_DIR = process.env.HUMEMORY_QUEUE ?? join(__dirname, '../../data/maintenance-queue');
71
+ const MAINTENANCE_STATE_PATH = defaultStatePath(QUEUE_DIR);
72
+ // Assigned only when this process hosts the loop; the routes read it to report
73
+ // whether maintenance lives here and whether a pass is in flight right now.
74
+ let maintenanceLoop;
67
75
  // Configure CORS securely (allow localhost for development, restrict in production)
68
76
  const allowedOrigins = process.env.NODE_ENV === 'production'
69
77
  ? (process.env.CORS_ORIGINS || 'http://localhost:3456').split(',')
@@ -182,6 +190,12 @@ app.route('/', createIntentionRoutes(store));
182
190
  app.route('/', createDreamRoutes(store));
183
191
  // === COGNITIVE SCRIPTS (Phase 8.3) ===
184
192
  app.route('/', createScriptRoutes(store));
193
+ // === MAINTENANCE HEALTH ===
194
+ // Behind the token like every other data route: `lastError` is internal detail.
195
+ app.route('/', createMaintenanceRoutes({
196
+ statePath: MAINTENANCE_STATE_PATH,
197
+ loop: () => maintenanceLoop,
198
+ }));
185
199
  // === HEALTH ===
186
200
  app.get('/health', (c) => {
187
201
  return c.json({ status: 'ok', timestamp: new Date().toISOString() });
@@ -207,4 +221,37 @@ if (import.meta.main) {
207
221
  console.warn('⚠️ HUMEMORY_API_TOKEN not set — data routes are unauthenticated (loopback only).');
208
222
  }
209
223
  serve({ fetch: app.fetch, port, hostname });
224
+ // Maintenance runs here rather than in an external scheduler: on Windows a
225
+ // scheduled task under an interactive token flashes a console window at every
226
+ // tick, and running it "whether the user is logged on or not" needs elevation
227
+ // this machine does not grant. This process is already resident and hidden.
228
+ // HUMEMORY_MAINTENANCE_INTERVAL_MS=0 hands the job back to a scheduler; the
229
+ // state file and /maintenance/status stay meaningful either way.
230
+ const maintenanceInterval = configuredIntervalMs();
231
+ if (maintenanceInterval > 0) {
232
+ maintenanceLoop = startMaintenanceLoop({
233
+ intervalMs: maintenanceInterval,
234
+ queueDir: QUEUE_DIR,
235
+ dbPath: DB_PATH,
236
+ statePath: MAINTENANCE_STATE_PATH,
237
+ runner: `api:${process.pid}`,
238
+ });
239
+ console.log(`🧹 Maintenance pass every ${Math.round(maintenanceInterval / 60_000)} min (in-process)`);
240
+ }
241
+ else {
242
+ console.log('🧹 Maintenance loop disabled — an external scheduler is expected to run it.');
243
+ }
244
+ // In-flight work finishes before the process goes: a pass killed mid-write
245
+ // leaves a job in `.processing` that only the stale-lock timeout recovers.
246
+ const shutdown = (signal) => {
247
+ console.log(`\n${signal} — stopping maintenance loop and closing the store.`);
248
+ maintenanceLoop?.stop();
249
+ try {
250
+ store.close?.();
251
+ }
252
+ catch { /* already closed */ }
253
+ process.exit(0);
254
+ };
255
+ process.on('SIGINT', () => shutdown('SIGINT'));
256
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
210
257
  }