humemory 0.2.5 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -43,6 +43,11 @@ pnpm test # bun test, single pass
43
43
  pnpm test:watch # bun test --watch
44
44
  pnpm consolidate # manual decay pass (cron-friendly)
45
45
  pnpm maintenance # process queued sessions (network-free by default)
46
+
47
+ pnpm cli maintenance status # is consolidation alive, and since when
48
+ pnpm cli maintenance run # force one pass here and now
49
+ pnpm cli maintenance dead-letters # sessions parked after exhausting their retries
50
+ pnpm cli maintenance requeue --all # give every dead-letter a fresh retry budget
46
51
  ```
47
52
 
48
53
  Single test file: `bun test tests/humemory.test.ts`
@@ -64,7 +69,9 @@ src/
64
69
  │ ├── session-parser.ts # parse Claude Code session transcripts
65
70
  │ ├── source-registry.ts # discover local AI runtimes without reading sessions
66
71
  │ ├── learning-extractor.ts # extract decisions/bugs/solutions
67
- │ ├── maintenance-queue.ts # durable async inbox, session checkpoints, dead-letter
72
+ │ ├── maintenance-queue.ts # durable async inbox, checkpoints, retry policy, dead-letter
73
+ │ ├── maintenance-runner.ts # one pass (codex import + drain), and the in-API loop
74
+ │ ├── maintenance-state.ts # durable health record of the loop (data/maintenance-state.json)
68
75
  │ ├── claude-hook.ts # worker-side session learning encoder
69
76
  │ └── session-context.ts # SessionStart → markdown block (open loops + traces)
70
77
  ├── core/
@@ -126,6 +133,40 @@ keywords >5. `photographic: true` disables decay entirely.
126
133
 
127
134
  ---
128
135
 
136
+ ## 🔁 Maintenance retry policy — an outage must not cost a session
137
+
138
+ The queue isolates jobs so one bad transcript cannot stop the others. That same
139
+ isolation once made an outage indistinguishable from a batch of bad sessions:
140
+ against an unopenable database every queued job simply failed, burned its five
141
+ attempts over five passes, and landed in a `.dead.json` file nothing ever read.
142
+ Three rules now separate "this transcript is bad" from "this machine is down":
143
+
144
+ 1. **Failures are classified** (`classifyMaintenanceFailure`). Anything that
145
+ names the machine — `unable to open database`, `database is locked`, `ENOSPC`,
146
+ `EROFS`, a `SQLITE_*` code that is not a constraint violation — is
147
+ *infrastructure* and costs no retry. Everything else is *job* and spends the
148
+ budget as before. The bias is deliberate: mislabelling a bad transcript wastes
149
+ a few passes, mislabelling an outage loses real sessions for good.
150
+ 2. **A circuit breaker ends the pass** after `failureThreshold` consecutive
151
+ failures (default 3, `false` disables it). The untouched jobs are never
152
+ claimed, so an outage costs one job's worth of damage instead of the queue's.
153
+ 3. **An aborted pass that encoded nothing refunds every retry it charged**, even
154
+ ones classified as job-level — a run of failures with zero successes is an
155
+ outage shape whatever the messages said. `processed > 0` proves the machine
156
+ works, and cancels the amnesty.
157
+
158
+ The verdict is therefore deferred: failures are held until the end of the pass,
159
+ because whether a retry is owed depends on how the pass finished.
160
+
161
+ A pass that discovers jobs and encodes none is still recorded as a **failure** in
162
+ `data/maintenance-state.json`, so `humemory maintenance status` shows it. Jobs
163
+ that genuinely exhaust their budget keep their raw transcript in `.dead.json` —
164
+ `humemory maintenance dead-letters` lists them and `humemory maintenance requeue`
165
+ puts them back with `attempts` reset. Requeuing never clobbers a live job for the
166
+ same session: that transcript is newer and supersedes the parked one.
167
+
168
+ ---
169
+
129
170
  ## 🧪 Autonomous test environment — REQUIRED
130
171
 
131
172
  **Non-negotiable design constraint** (set 2026-06-17). Every test run MUST be
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.7] - 2026-08-27
4
+ **Bug Fixes:**
5
+ - spend retries on bad jobs, not on outages (#2)
6
+
7
+
8
+
9
+ ## [0.2.6] - 2026-08-27
10
+ **Bug Fixes:**
11
+ - stop the 15-min console flash, and make consolidation supervised (#1)
12
+
13
+
14
+
3
15
  ## [0.2.5] - 2026-08-26
4
16
  **Features:**
5
17
  - ingest codex sessions, not just claude ones
@@ -11,6 +11,10 @@ export interface MaintenanceJob {
11
11
  queuedAt: string;
12
12
  attempts: number;
13
13
  lastError?: string;
14
+ /** Set when the job was moved to dead-letter; absent on a live job. */
15
+ deadLetteredAt?: string;
16
+ /** Set when a dead-letter was put back in the queue by hand. */
17
+ requeuedAt?: string;
14
18
  }
15
19
  export interface EnqueueOptions {
16
20
  queueDir: string;
@@ -33,6 +37,11 @@ export interface WorkerOptions {
33
37
  maxJobs?: number;
34
38
  lockStaleMs?: number;
35
39
  maxAttempts?: number;
40
+ /**
41
+ * Consecutive job failures that trip the circuit breaker and end the pass.
42
+ * `false` disables the breaker. See `processMaintenanceQueue`.
43
+ */
44
+ failureThreshold?: number | false;
36
45
  now?: () => Date;
37
46
  }
38
47
  export interface WorkerResult {
@@ -42,6 +51,84 @@ export interface WorkerResult {
42
51
  deadLettered: number;
43
52
  memoriesStored: number;
44
53
  busy: boolean;
54
+ /** Failures that look like the machine, not the transcript — these cost no retry. */
55
+ infrastructureFailures: number;
56
+ /** Retries handed back because the failure was an outage rather than a bad job. */
57
+ retriesRefunded: number;
58
+ /** True when the circuit breaker cut the pass short instead of working the queue. */
59
+ aborted: boolean;
45
60
  }
61
+ /**
62
+ * Why a job failed, as far as the retry budget is concerned.
63
+ *
64
+ * `job` — this transcript is the problem, and every future pass will fail on it
65
+ * the same way. Retrying a few times then dead-lettering is right.
66
+ *
67
+ * `infrastructure` — the machine is the problem (the database will not open,
68
+ * the disk is full, the file is locked). Every job in the queue would fail the
69
+ * same way right now and all of them would succeed once the machine is fixed,
70
+ * so burning a retry punishes the session for an outage it had no part in.
71
+ */
72
+ export type FailureKind = 'job' | 'infrastructure';
73
+ /**
74
+ * Classify a failure so an outage does not consume the queue's retry budget.
75
+ *
76
+ * Deliberately biased towards `job`: mislabelling a bad transcript as an outage
77
+ * only costs a few wasted passes, while mislabelling an outage as a bad job
78
+ * dead-letters real sessions permanently. Anything not recognisably about the
79
+ * machine is therefore treated as being about the transcript.
80
+ */
81
+ export declare function classifyMaintenanceFailure(error: unknown): FailureKind;
46
82
  export declare function enqueueSession(rawTranscript: string, options: EnqueueOptions): Promise<QueueResult>;
47
83
  export declare function processMaintenanceQueue(options: WorkerOptions): Promise<WorkerResult>;
84
+ export interface DeadLetter {
85
+ /** Filename in the queue directory, so a caller can name one precisely. */
86
+ file: string;
87
+ id: string;
88
+ /** Absent when the file could not be parsed — the bytes are still there. */
89
+ job?: MaintenanceJob;
90
+ sessionId?: string;
91
+ source?: string;
92
+ attempts?: number;
93
+ lastError?: string;
94
+ deadLetteredAt?: string;
95
+ }
96
+ export interface RequeueOptions {
97
+ queueDir: string;
98
+ /**
99
+ * Restrict to these dead-letters. Each entry matches a job id, a session id,
100
+ * or a filename. Omitted means every dead-letter in the directory.
101
+ */
102
+ ids?: string[];
103
+ /** Report what would happen and write nothing. */
104
+ dryRun?: boolean;
105
+ limit?: number;
106
+ now?: () => Date;
107
+ }
108
+ export interface RequeueResult {
109
+ scanned: number;
110
+ requeued: number;
111
+ /** A live job already holds the slot — the newer transcript wins, so the dead-letter is left alone. */
112
+ skippedLive: number;
113
+ /** The file is not a usable job; requeuing it would only dead-letter it again. */
114
+ unreadable: number;
115
+ /** What was (or would be) put back. */
116
+ entries: DeadLetter[];
117
+ }
118
+ /** Everything currently parked in dead-letter, newest failure first. */
119
+ export declare function listDeadLetters(queueDir: string): Promise<DeadLetter[]>;
120
+ /**
121
+ * Put dead-lettered jobs back in the queue with a fresh retry budget.
122
+ *
123
+ * Dead-lettering is not always a verdict on the transcript: before the retry
124
+ * budget learned to tell an outage from a bad job, a single unopenable database
125
+ * could park an entire afternoon of sessions in `.dead.json` files that nothing
126
+ * would ever look at again. This is the way back, and the reason the raw
127
+ * transcript is kept on disk rather than deleted.
128
+ *
129
+ * Restoring resets `attempts` to 0 — the point is a clean chance now that
130
+ * whatever broke has been fixed. A dead-letter whose slot is already held by a
131
+ * live job is left alone: that job carries a newer transcript for the same
132
+ * session and supersedes it.
133
+ */
134
+ export declare function requeueDeadLetters(options: RequeueOptions): Promise<RequeueResult>;
@@ -5,9 +5,70 @@ import { processSession } from './claude-hook.js';
5
5
  import { parseAgentSession } from './session-parser.js';
6
6
  const DEFAULT_LOCK_STALE_MS = 5 * 60 * 1000;
7
7
  const DEFAULT_MAX_ATTEMPTS = 5;
8
+ const DEFAULT_FAILURE_THRESHOLD = 3;
8
9
  const DEAD_LETTER_SUFFIX = '.dead.json';
9
10
  const PROCESSING_SUFFIX = '.processing';
10
11
  const CHECKPOINT_DIR = 'checkpoints';
12
+ /** errno values that mean "the machine", never "this transcript". */
13
+ const INFRASTRUCTURE_CODES = new Set([
14
+ 'EACCES', 'EAGAIN', 'EBUSY', 'EDQUOT', 'EIO', 'EISDIR', 'EMFILE',
15
+ 'ENFILE', 'ENOMEM', 'ENOSPC', 'EPERM', 'EROFS', 'ETIMEDOUT',
16
+ ]);
17
+ const INFRASTRUCTURE_PATTERNS = [
18
+ /unable to open database/i,
19
+ /database is locked/i,
20
+ /database disk image is malformed/i,
21
+ /attempt to write a readonly database/i,
22
+ /disk i\/o error/i,
23
+ /no space left/i,
24
+ /out of memory/i,
25
+ /too many open files/i,
26
+ /read-?only file system/i,
27
+ ];
28
+ /**
29
+ * Classify a failure so an outage does not consume the queue's retry budget.
30
+ *
31
+ * Deliberately biased towards `job`: mislabelling a bad transcript as an outage
32
+ * only costs a few wasted passes, while mislabelling an outage as a bad job
33
+ * dead-letters real sessions permanently. Anything not recognisably about the
34
+ * machine is therefore treated as being about the transcript.
35
+ */
36
+ export function classifyMaintenanceFailure(error) {
37
+ const err = error;
38
+ if (!err || typeof err !== 'object')
39
+ return 'job';
40
+ const message = typeof err.message === 'string' ? err.message : String(error);
41
+ if (INFRASTRUCTURE_PATTERNS.some((pattern) => pattern.test(message)))
42
+ return 'infrastructure';
43
+ if (typeof err.code === 'string') {
44
+ if (INFRASTRUCTURE_CODES.has(err.code))
45
+ return 'infrastructure';
46
+ // bun:sqlite reports the extended result code, e.g. SQLITE_CANTOPEN_ISDIR.
47
+ if (err.code.startsWith('SQLITE_') && !err.code.startsWith('SQLITE_CONSTRAINT'))
48
+ return 'infrastructure';
49
+ }
50
+ // A constraint violation is a schema bug, not an outage — retrying cannot fix
51
+ // it, so it stays on the job's own budget. Every other SQLite error is the
52
+ // storage layer refusing to work at all.
53
+ if (err.name === 'SQLiteError' && !/constraint/i.test(message))
54
+ return 'infrastructure';
55
+ if (err.cause !== undefined && err.cause !== err)
56
+ return classifyMaintenanceFailure(err.cause);
57
+ return 'job';
58
+ }
59
+ function emptyResult() {
60
+ return {
61
+ discovered: 0,
62
+ processed: 0,
63
+ failed: 0,
64
+ deadLettered: 0,
65
+ memoriesStored: 0,
66
+ busy: false,
67
+ infrastructureFailures: 0,
68
+ retriesRefunded: 0,
69
+ aborted: false,
70
+ };
71
+ }
11
72
  function jobPath(queueDir, id) {
12
73
  return join(queueDir, `${id}.json`);
13
74
  }
@@ -106,11 +167,11 @@ export async function processMaintenanceQueue(options) {
106
167
  }
107
168
  continue;
108
169
  }
109
- return { discovered: 0, processed: 0, failed: 0, deadLettered: 0, memoriesStored: 0, busy: true };
170
+ return { ...emptyResult(), busy: true };
110
171
  }
111
172
  }
112
173
  if (!lock)
113
- return { discovered: 0, processed: 0, failed: 0, deadLettered: 0, memoriesStored: 0, busy: true };
174
+ return { ...emptyResult(), busy: true };
114
175
  try {
115
176
  const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
116
177
  // We hold the exclusive lock, so any leftover `.processing` file belongs to
@@ -144,14 +205,15 @@ export async function processMaintenanceQueue(options) {
144
205
  .sort((a, b) => a.queuedAt.localeCompare(b.queuedAt))
145
206
  .slice(0, options.maxJobs ?? 20)
146
207
  .map((entry) => entry.file);
147
- const result = {
148
- discovered: files.length,
149
- processed: 0,
150
- failed: 0,
151
- deadLettered: 0,
152
- memoriesStored: 0,
153
- busy: false,
154
- };
208
+ const result = { ...emptyResult(), discovered: files.length };
209
+ const failureThreshold = options.failureThreshold === false
210
+ ? Number.POSITIVE_INFINITY
211
+ : options.failureThreshold ?? DEFAULT_FAILURE_THRESHOLD;
212
+ // Failures are held rather than settled on the spot: whether a retry should
213
+ // be charged depends on how the *pass* ended, which is not known until the
214
+ // loop is over. See the finalisation block below.
215
+ const pending = [];
216
+ let consecutiveFailures = 0;
155
217
  for (const file of files) {
156
218
  const path = join(options.queueDir, file);
157
219
  // Claim the job by moving it aside. The hook may enqueue a newer, longer
@@ -186,10 +248,15 @@ export async function processMaintenanceQueue(options) {
186
248
  await rm(claimed, { force: true });
187
249
  result.processed += 1;
188
250
  result.memoriesStored += processed.memoriesStored;
251
+ consecutiveFailures = 0;
189
252
  }
190
253
  catch (error) {
191
254
  result.failed += 1;
255
+ consecutiveFailures += 1;
192
256
  const lastError = error instanceof Error ? error.message.slice(0, 500) : String(error).slice(0, 500);
257
+ const kind = classifyMaintenanceFailure(error);
258
+ if (kind === 'infrastructure')
259
+ result.infrastructureFailures += 1;
193
260
  try {
194
261
  if (!job) {
195
262
  // Unparseable on disk: no attempt counter can live in it, so retrying
@@ -197,35 +264,65 @@ export async function processMaintenanceQueue(options) {
197
264
  // failing this file on every future pass.
198
265
  await rename(claimed, join(options.queueDir, `${file.replace(/\.json$/, '')}${DEAD_LETTER_SUFFIX}`));
199
266
  result.deadLettered += 1;
200
- continue;
201
- }
202
- job.attempts = (job.attempts ?? 0) + 1;
203
- job.lastError = lastError;
204
- if (job.attempts >= maxAttempts) {
205
- // Exhausted retries: move out of the active queue so it stops being
206
- // picked up and stops inflating `failed` on every future pass, but
207
- // keep the raw transcript on disk for manual inspection.
208
- await atomicWrite(join(options.queueDir, `${job.id}${DEAD_LETTER_SUFFIX}`), JSON.stringify(job));
209
- await rm(claimed, { force: true });
210
- result.deadLettered += 1;
211
267
  }
212
268
  else {
213
- // Restore for a later pass — unless a newer transcript already took
214
- // the slot, which supersedes this one.
215
- try {
216
- await stat(path);
217
- await rm(claimed, { force: true });
218
- }
219
- catch {
220
- await atomicWrite(path, JSON.stringify(job));
221
- await rm(claimed, { force: true });
222
- }
269
+ pending.push({ path, claimed, job, lastError, kind });
223
270
  }
224
271
  }
225
272
  catch {
226
273
  // Never erase evidence: the claimed file stays for manual inspection
227
274
  // and the orphan sweep restores it on the next pass.
228
275
  }
276
+ // Circuit breaker. Working through the rest of the queue during an
277
+ // outage is how every queued session used to burn its retries in a
278
+ // single afternoon; a run of failures this long is far more likely to
279
+ // be the machine than a coincidence of bad transcripts, so stop and
280
+ // leave the untouched jobs for the next pass.
281
+ if (consecutiveFailures >= failureThreshold) {
282
+ result.aborted = true;
283
+ break;
284
+ }
285
+ }
286
+ }
287
+ // A pass that aborted without encoding anything is an outage by definition,
288
+ // whatever the individual error messages happened to look like: refund those
289
+ // retries too, so an unrecognised failure mode cannot drain the queue either.
290
+ const wholesaleFailure = result.aborted && result.processed === 0;
291
+ for (const entry of pending) {
292
+ const refund = entry.kind === 'infrastructure' || wholesaleFailure;
293
+ try {
294
+ entry.job.lastError = entry.lastError;
295
+ if (refund) {
296
+ result.retriesRefunded += 1;
297
+ }
298
+ else {
299
+ entry.job.attempts = (entry.job.attempts ?? 0) + 1;
300
+ }
301
+ if (!refund && entry.job.attempts >= maxAttempts) {
302
+ // Exhausted retries: move out of the active queue so it stops being
303
+ // picked up and stops inflating `failed` on every future pass, but
304
+ // keep the raw transcript on disk for manual inspection.
305
+ entry.job.deadLetteredAt = now().toISOString();
306
+ await atomicWrite(join(options.queueDir, `${entry.job.id}${DEAD_LETTER_SUFFIX}`), JSON.stringify(entry.job));
307
+ await rm(entry.claimed, { force: true });
308
+ result.deadLettered += 1;
309
+ }
310
+ else {
311
+ // Restore for a later pass — unless a newer transcript already took
312
+ // the slot, which supersedes this one.
313
+ try {
314
+ await stat(entry.path);
315
+ await rm(entry.claimed, { force: true });
316
+ }
317
+ catch {
318
+ await atomicWrite(entry.path, JSON.stringify(entry.job));
319
+ await rm(entry.claimed, { force: true });
320
+ }
321
+ }
322
+ }
323
+ catch {
324
+ // Never erase evidence: the claimed file stays for manual inspection
325
+ // and the orphan sweep restores it on the next pass.
229
326
  }
230
327
  }
231
328
  return result;
@@ -244,3 +341,89 @@ export async function processMaintenanceQueue(options) {
244
341
  }
245
342
  }
246
343
  }
344
+ function toDeadLetter(file, raw) {
345
+ const id = file.slice(0, -DEAD_LETTER_SUFFIX.length);
346
+ try {
347
+ const job = JSON.parse(raw);
348
+ if (job?.version !== 1 || !job.rawTranscript || typeof job.id !== 'string')
349
+ return { file, id };
350
+ return {
351
+ file,
352
+ id: job.id,
353
+ job,
354
+ sessionId: job.sessionId,
355
+ source: job.source,
356
+ attempts: job.attempts,
357
+ lastError: job.lastError,
358
+ deadLetteredAt: job.deadLetteredAt,
359
+ };
360
+ }
361
+ catch {
362
+ return { file, id };
363
+ }
364
+ }
365
+ /** Everything currently parked in dead-letter, newest failure first. */
366
+ export async function listDeadLetters(queueDir) {
367
+ let files;
368
+ try {
369
+ files = (await readdir(queueDir)).filter((file) => file.endsWith(DEAD_LETTER_SUFFIX));
370
+ }
371
+ catch (error) {
372
+ if (error?.code === 'ENOENT')
373
+ return [];
374
+ throw error;
375
+ }
376
+ const entries = await Promise.all(files.map(async (file) => toDeadLetter(file, await readFile(join(queueDir, file), 'utf8').catch(() => ''))));
377
+ return entries.sort((a, b) => (b.deadLetteredAt ?? '').localeCompare(a.deadLetteredAt ?? ''));
378
+ }
379
+ /**
380
+ * Put dead-lettered jobs back in the queue with a fresh retry budget.
381
+ *
382
+ * Dead-lettering is not always a verdict on the transcript: before the retry
383
+ * budget learned to tell an outage from a bad job, a single unopenable database
384
+ * could park an entire afternoon of sessions in `.dead.json` files that nothing
385
+ * would ever look at again. This is the way back, and the reason the raw
386
+ * transcript is kept on disk rather than deleted.
387
+ *
388
+ * Restoring resets `attempts` to 0 — the point is a clean chance now that
389
+ * whatever broke has been fixed. A dead-letter whose slot is already held by a
390
+ * live job is left alone: that job carries a newer transcript for the same
391
+ * session and supersedes it.
392
+ */
393
+ export async function requeueDeadLetters(options) {
394
+ const now = options.now ?? (() => new Date());
395
+ const wanted = options.ids?.length ? new Set(options.ids) : undefined;
396
+ const result = { scanned: 0, requeued: 0, skippedLive: 0, unreadable: 0, entries: [] };
397
+ const all = await listDeadLetters(options.queueDir);
398
+ const selected = wanted
399
+ ? all.filter((entry) => wanted.has(entry.id) || wanted.has(entry.file) || (entry.sessionId !== undefined && wanted.has(entry.sessionId)))
400
+ : all;
401
+ for (const entry of selected) {
402
+ if (options.limit !== undefined && result.requeued >= options.limit)
403
+ break;
404
+ result.scanned += 1;
405
+ if (!entry.job) {
406
+ result.unreadable += 1;
407
+ continue;
408
+ }
409
+ const live = jobPath(options.queueDir, entry.job.id);
410
+ try {
411
+ await stat(live);
412
+ result.skippedLive += 1;
413
+ continue;
414
+ }
415
+ catch {
416
+ // Slot is free — the dead-letter is still the best copy of this session.
417
+ }
418
+ result.entries.push(entry);
419
+ result.requeued += 1;
420
+ if (options.dryRun)
421
+ continue;
422
+ const job = { ...entry.job, attempts: 0, requeuedAt: now().toISOString() };
423
+ delete job.lastError;
424
+ delete job.deadLetteredAt;
425
+ await atomicWrite(live, JSON.stringify(job));
426
+ await rm(join(options.queueDir, entry.file), { force: true });
427
+ }
428
+ return result;
429
+ }
@@ -0,0 +1,90 @@
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 type { LLMClient } from '../core/llm-generator.js';
17
+ import type { Clock } from '../core/clock.js';
18
+ import { type WorkerResult } from './maintenance-queue.js';
19
+ import { type CodexImportResult } from './codex-import.js';
20
+ export declare const DEFAULT_INTERVAL_MS: number;
21
+ export interface MaintenancePassOptions {
22
+ queueDir?: string;
23
+ dbPath?: string;
24
+ statePath?: string;
25
+ /** Days of codex rollouts to sweep in. `false` skips the codex import entirely. */
26
+ codexSinceDays?: number | false;
27
+ /** Overrides `$CODEX_HOME/sessions`; mainly a test seam. */
28
+ codexSessionsDir?: string;
29
+ client?: LLMClient;
30
+ llmTimeoutMs?: number;
31
+ maxJobs?: number;
32
+ clock?: Clock;
33
+ /** Recorded in the state file so two competing schedulers are visible. */
34
+ runner?: string;
35
+ }
36
+ export interface MaintenancePassResult {
37
+ codex?: CodexImportResult;
38
+ /** Set when the codex import failed; the queue is still drained regardless. */
39
+ codexError?: string;
40
+ worker: WorkerResult;
41
+ }
42
+ export declare function defaultQueueDir(): string;
43
+ export declare function defaultDbPath(): string;
44
+ export declare function defaultLlmTimeoutMs(): number;
45
+ export declare function configuredIntervalMs(): number;
46
+ /**
47
+ * The LLM the pass consolidates with. 'none' (the default) keeps consolidation
48
+ * deterministic and network-free; there is no API key on the production machine
49
+ * and none wanted, so 'codex' shells out to the logged-in CLI instead.
50
+ */
51
+ export declare function resolveMaintenanceClient(timeoutMs?: number): Promise<LLMClient | undefined>;
52
+ /**
53
+ * Import, then drain, then record. A failing codex import is contained: a
54
+ * missing or unreadable codex must never stall the queue, which holds sessions
55
+ * from every other source.
56
+ *
57
+ * Throws only if the queue itself could not be drained — the caller records
58
+ * that failure and stays alive.
59
+ */
60
+ export declare function runMaintenancePass(options?: MaintenancePassOptions): Promise<MaintenancePassResult>;
61
+ /** Minimal timer seam, so the loop is testable without waiting on wall time. */
62
+ export interface TimerLike {
63
+ setInterval(handler: () => void, ms: number): unknown;
64
+ clearInterval(handle: unknown): void;
65
+ }
66
+ export interface MaintenanceLoop {
67
+ /** Runs a pass now, outside the schedule. Resolves once it has finished. */
68
+ runNow(): Promise<void>;
69
+ stop(): void;
70
+ /** True while a pass is in flight — the next tick is suppressed until it clears. */
71
+ readonly busy: boolean;
72
+ }
73
+ export interface MaintenanceLoopOptions extends MaintenancePassOptions {
74
+ intervalMs?: number;
75
+ /** Run one pass immediately instead of waiting a full interval. */
76
+ runAtStart?: boolean;
77
+ timers?: TimerLike;
78
+ }
79
+ /**
80
+ * Run a pass every `intervalMs` inside the calling process. The API process is
81
+ * already resident and windowless, so hosting the loop there spawns nothing —
82
+ * which is the whole point of moving it off the Windows scheduler.
83
+ *
84
+ * Three properties this guarantees, each covered by a test:
85
+ * - passes never overlap, on top of the queue's own cross-process lock;
86
+ * - a throwing pass is contained and the loop keeps ticking, because the API
87
+ * must not die of a bad session transcript;
88
+ * - every pass, good or bad, lands in the state file.
89
+ */
90
+ export declare function startMaintenanceLoop(options?: MaintenanceLoopOptions): MaintenanceLoop;
@@ -0,0 +1,204 @@
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. The queue no longer
100
+ // dead-letters its way through an outage (retries are refunded and the
101
+ // circuit breaker cuts the pass short), but silence would still leave the
102
+ // machine broken and nothing consolidated, so the pass is recorded as a
103
+ // failure and `maintenance status` says so.
104
+ const wholesaleFailure = worker.discovered > 0 && worker.processed === 0 && worker.failed > 0;
105
+ await recordMaintenanceRun({
106
+ path: statePath,
107
+ startedAt,
108
+ clock,
109
+ runner: options.runner,
110
+ error: wholesaleFailure ? new Error(wholesaleFailureMessage(worker)) : 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
+ retriesRefunded: worker.retriesRefunded,
119
+ aborted: worker.aborted,
120
+ },
121
+ });
122
+ return { codex, codexError, worker };
123
+ }
124
+ catch (error) {
125
+ await recordMaintenanceRun({ path: statePath, startedAt, clock, runner: options.runner, error });
126
+ throw error;
127
+ }
128
+ }
129
+ /**
130
+ * One line naming what the pass looked like, so `maintenance status` can be
131
+ * read without opening the queue directory.
132
+ */
133
+ function wholesaleFailureMessage(worker) {
134
+ const scope = worker.aborted
135
+ ? `pass aborted after ${worker.failed} consecutive failures`
136
+ : `every job failed this pass (${worker.failed}/${worker.discovered})`;
137
+ const budget = worker.retriesRefunded > 0
138
+ ? `; ${worker.retriesRefunded} retry(ies) refunded, nothing dead-lettered`
139
+ : '';
140
+ return `${scope} — suspect the database or the disk, not the sessions${budget}`;
141
+ }
142
+ const REAL_TIMERS = {
143
+ setInterval: (handler, ms) => {
144
+ const handle = setInterval(handler, ms);
145
+ // Maintenance alone is no reason to hold the process alive.
146
+ if (typeof handle.unref === 'function') {
147
+ handle.unref();
148
+ }
149
+ return handle;
150
+ },
151
+ clearInterval: (handle) => clearInterval(handle),
152
+ };
153
+ /**
154
+ * Run a pass every `intervalMs` inside the calling process. The API process is
155
+ * already resident and windowless, so hosting the loop there spawns nothing —
156
+ * which is the whole point of moving it off the Windows scheduler.
157
+ *
158
+ * Three properties this guarantees, each covered by a test:
159
+ * - passes never overlap, on top of the queue's own cross-process lock;
160
+ * - a throwing pass is contained and the loop keeps ticking, because the API
161
+ * must not die of a bad session transcript;
162
+ * - every pass, good or bad, lands in the state file.
163
+ */
164
+ export function startMaintenanceLoop(options = {}) {
165
+ const intervalMs = options.intervalMs ?? configuredIntervalMs();
166
+ const timers = options.timers ?? REAL_TIMERS;
167
+ let running = false;
168
+ let stopped = false;
169
+ const pass = async () => {
170
+ if (running || stopped)
171
+ return;
172
+ running = true;
173
+ try {
174
+ const client = options.client ?? await resolveMaintenanceClient(options.llmTimeoutMs);
175
+ const { worker } = await runMaintenancePass({ ...options, client, runner: options.runner ?? 'api-loop' });
176
+ if (process.env.HUMEMORY_VERBOSE === '1' || worker.failed > 0) {
177
+ console.error(`[humemory] maintenance: ${worker.processed}/${worker.discovered} jobs, ` +
178
+ `${worker.memoriesStored} memories, ${worker.failed} failed, ${worker.deadLettered} dead-lettered` +
179
+ (worker.aborted ? ' (pass aborted — suspected outage)' : ''));
180
+ }
181
+ }
182
+ catch (error) {
183
+ // Contained on purpose: a crashing pass must never take the API down.
184
+ // The failure is already in the state file, so it stays visible.
185
+ console.error('[humemory] maintenance pass failed —', error.message);
186
+ }
187
+ finally {
188
+ running = false;
189
+ }
190
+ };
191
+ const handle = timers.setInterval(() => void pass(), intervalMs);
192
+ if (options.runAtStart)
193
+ void pass();
194
+ return {
195
+ runNow: pass,
196
+ get busy() {
197
+ return running;
198
+ },
199
+ stop() {
200
+ stopped = true;
201
+ timers.clearInterval(handle);
202
+ },
203
+ };
204
+ }
@@ -0,0 +1,77 @@
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
+ /** Retries handed back because the pass looked like an outage, not a bad job. */
35
+ retriesRefunded?: number;
36
+ /** True when the circuit breaker cut the pass short. */
37
+ aborted?: boolean;
38
+ };
39
+ /** Which process last wrote here, so two schedulers fighting is visible. */
40
+ lastRunner?: string;
41
+ }
42
+ export declare function defaultStatePath(queueDir: string): string;
43
+ /**
44
+ * Never throws: an absent file is a fresh install, and a corrupt one must not
45
+ * take down the caller that is merely asking for a status.
46
+ */
47
+ export declare function readMaintenanceState(path: string): Promise<MaintenanceState>;
48
+ export interface RecordRunOptions {
49
+ path: string;
50
+ startedAt: Date;
51
+ clock?: Clock;
52
+ runner?: string;
53
+ result?: MaintenanceState['lastResult'];
54
+ error?: unknown;
55
+ }
56
+ /**
57
+ * Fold one pass into the state file. Recording is best-effort by design: a
58
+ * read-only disk must degrade observability, never stop consolidation.
59
+ */
60
+ export declare function recordMaintenanceRun(options: RecordRunOptions): Promise<MaintenanceState>;
61
+ export interface MaintenanceHealth {
62
+ /** No success ever, or the last one is older than the staleness budget. */
63
+ stale: boolean;
64
+ /** Milliseconds since the last success; undefined when there has never been one. */
65
+ ageMs?: number;
66
+ consecutiveFailures: number;
67
+ lastSuccessAt?: string;
68
+ lastRunAt?: string;
69
+ lastError?: string;
70
+ lastResult?: MaintenanceState['lastResult'];
71
+ /** One line a human can act on. */
72
+ summary: string;
73
+ }
74
+ export declare function assessMaintenance(state: MaintenanceState, options?: {
75
+ staleAfterMs?: number;
76
+ clock?: Clock;
77
+ }): 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
+ }
@@ -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
  }
package/dist/cli/index.js CHANGED
@@ -792,6 +792,126 @@ for (const verb of ['approve', 'reject']) {
792
792
  }
793
793
  });
794
794
  }
795
+ // === MAINTENANCE ===
796
+ const maintenance = program
797
+ .command('maintenance')
798
+ .description('Health of the consolidation loop, and a way to force a pass');
799
+ maintenance
800
+ .command('status', { isDefault: true })
801
+ .description('Is consolidation still running, and when did it last succeed?')
802
+ .option('--json', 'Machine-readable output')
803
+ .option('--stale-after <minutes>', 'Staleness budget before the loop is called overdue', '60')
804
+ .action(async (options) => {
805
+ const { readMaintenanceState, assessMaintenance, defaultStatePath } = await import('../agent/maintenance-state.js');
806
+ const staleAfterMs = Math.max(1, Number(options.staleAfter)) * 60_000;
807
+ const health = assessMaintenance(await readMaintenanceState(defaultStatePath(QUEUE_DIR)), { staleAfterMs });
808
+ if (options.json) {
809
+ console.log(JSON.stringify(health, null, 2));
810
+ }
811
+ else {
812
+ console.log(`\n${health.stale ? '✗' : '✓'} ${health.summary}`);
813
+ if (health.lastRunAt)
814
+ console.log(` last attempt ${health.lastRunAt}`);
815
+ if (health.lastSuccessAt)
816
+ console.log(` last success ${health.lastSuccessAt}`);
817
+ if (health.lastError)
818
+ console.log(` last error ${health.lastError}`);
819
+ if (health.lastResult) {
820
+ const r = health.lastResult;
821
+ console.log(` last counts ${r.processed}/${r.discovered} jobs, ${r.memoriesStored} memories, ${r.failed} failed, ${r.deadLettered} dead-lettered`);
822
+ if (r.retriesRefunded)
823
+ console.log(` retries kept ${r.retriesRefunded} refunded — the failures looked like the machine, not the sessions`);
824
+ if (r.aborted)
825
+ console.log(' breaker pass aborted early; the untouched jobs are still queued');
826
+ }
827
+ console.log();
828
+ if (health.stale) {
829
+ console.log('The loop lives in the API process — check that it is running, then `humemory maintenance run`.\n');
830
+ }
831
+ }
832
+ // Non-zero on staleness so a checker can act on it without parsing text.
833
+ if (health.stale)
834
+ process.exitCode = 1;
835
+ });
836
+ maintenance
837
+ .command('run')
838
+ .description('Force one consolidation pass here and now, in this process')
839
+ .option('--skip-codex', 'Do not import codex rollouts first')
840
+ .action(async (options) => {
841
+ const { runMaintenancePass, resolveMaintenanceClient } = await import('../agent/maintenance-runner.js');
842
+ const client = await resolveMaintenanceClient();
843
+ const { worker } = await runMaintenancePass({
844
+ client,
845
+ codexSinceDays: options.skipCodex ? false : undefined,
846
+ runner: 'cli',
847
+ });
848
+ console.log(`✓ ${worker.processed}/${worker.discovered} jobs, ${worker.memoriesStored} memories, ` +
849
+ `${worker.failed} failed, ${worker.deadLettered} dead-lettered${worker.busy ? ' (another worker held the lock)' : ''}`);
850
+ });
851
+ maintenance
852
+ .command('dead-letters')
853
+ .description('Sessions parked after exhausting their retries, newest first')
854
+ .option('--json', 'Machine-readable output')
855
+ .action(async (options) => {
856
+ const { listDeadLetters } = await import('../agent/maintenance-queue.js');
857
+ const entries = await listDeadLetters(QUEUE_DIR);
858
+ if (options.json) {
859
+ // The raw transcript is deliberately left out: this is a triage listing,
860
+ // not an export, and a dump of every session is not what a terminal wants.
861
+ console.log(JSON.stringify(entries.map(({ job, ...rest }) => rest), null, 2));
862
+ return;
863
+ }
864
+ if (entries.length === 0) {
865
+ console.log('\n✓ No dead-lettered sessions.\n');
866
+ return;
867
+ }
868
+ console.log(`\n${entries.length} dead-lettered session(s):\n`);
869
+ for (const entry of entries) {
870
+ console.log(` ${entry.id.slice(0, 12)} ${entry.sessionId ?? '(unreadable)'}${entry.source ? ` [${entry.source}]` : ''}`);
871
+ if (entry.deadLetteredAt)
872
+ console.log(` parked ${entry.deadLetteredAt} after ${entry.attempts ?? '?'} attempt(s)`);
873
+ if (entry.lastError)
874
+ console.log(` last error ${entry.lastError}`);
875
+ }
876
+ console.log('\nPut them back with `humemory maintenance requeue --all` once the cause is fixed.\n');
877
+ });
878
+ maintenance
879
+ .command('requeue')
880
+ .description('Put dead-lettered sessions back in the queue with a fresh retry budget')
881
+ .argument('[ids...]', 'Job ids, session ids or filenames; omit with --all for every dead-letter')
882
+ .option('--all', 'Requeue every dead-lettered session')
883
+ .option('--limit <n>', 'Stop after N sessions')
884
+ .option('--dry-run', 'Report what would be requeued, write nothing')
885
+ .action(async (ids, options) => {
886
+ if (!options.all && ids.length === 0) {
887
+ console.error('Nothing selected — name at least one id, or pass --all.');
888
+ process.exitCode = 1;
889
+ return;
890
+ }
891
+ const { requeueDeadLetters } = await import('../agent/maintenance-queue.js');
892
+ const result = await requeueDeadLetters({
893
+ queueDir: QUEUE_DIR,
894
+ ids: options.all ? undefined : ids,
895
+ limit: options.limit ? parseInt(options.limit) : undefined,
896
+ dryRun: options.dryRun,
897
+ });
898
+ console.log(`\n${options.dryRun ? 'Would requeue' : '✓ Requeued'} ${result.requeued} of ${result.scanned} dead-letter(s).`);
899
+ for (const entry of result.entries) {
900
+ console.log(` ${entry.id.slice(0, 12)} ${entry.sessionId ?? '(unknown session)'}`);
901
+ }
902
+ if (result.skippedLive > 0) {
903
+ console.log(` skipped ${result.skippedLive} already superseded by a newer queued transcript`);
904
+ }
905
+ if (result.unreadable > 0) {
906
+ console.log(` skipped ${result.unreadable} unreadable file(s) — inspect them in ${QUEUE_DIR}`);
907
+ }
908
+ if (!options.dryRun && result.requeued > 0) {
909
+ console.log('\nRun `humemory maintenance run` to encode them (or wait for the scheduled pass).\n');
910
+ }
911
+ else {
912
+ console.log();
913
+ }
914
+ });
795
915
  // === LOCAL AGENT SOURCES ===
796
916
  const sources = program
797
917
  .command('sources')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "humemory",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
4
4
  "description": "Memory for AI agents that forgets like a human — decaying traces, inverse search, and prospective loops that resurface on a cue",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -88,6 +88,8 @@
88
88
  "cli": "bun run src/cli/index.ts",
89
89
  "consolidate": "bun run scripts/consolidate.js",
90
90
  "maintenance": "bun run scripts/maintenance-worker.ts",
91
+ "maintenance:status": "bun run src/cli/index.ts maintenance status",
92
+ "win:install": "pwsh -File scripts/windows/install.ps1",
91
93
  "dream": "bun run src/cli/index.ts dream",
92
94
  "mcp": "bun run src/mcp/server.ts",
93
95
  "build:web": "node -e \"require('fs').rmSync('public/app',{recursive:true,force:true})\" && bun build web/index.html --outdir public/app --production --splitting",
@@ -1,37 +1,23 @@
1
1
  #!/usr/bin/env bun
2
- /** One non-blocking maintenance pass over sessions queued by local agent hooks. */
2
+ /**
3
+ * One non-blocking maintenance pass over sessions queued by local agent hooks.
4
+ *
5
+ * The pass itself lives in src/agent/maintenance-runner.ts, shared with the API
6
+ * process, which runs it on a timer. This script stays for manual runs
7
+ * (`pnpm maintenance`) and for a machine that does not keep the API resident.
8
+ */
3
9
 
4
- import Anthropic from '@anthropic-ai/sdk';
5
- import { dirname, join } from 'path';
6
- import { fileURLToPath } from 'url';
7
- import type { LLMClient } from '../src/core/llm-generator.js';
8
- import { createCodexClient } from '../src/core/llm-cli-client.js';
9
- import { processMaintenanceQueue } from '../src/agent/maintenance-queue.js';
10
+ import { runMaintenancePass, resolveMaintenanceClient, defaultLlmTimeoutMs } from '../src/agent/maintenance-runner.js';
10
11
 
11
- const __dirname = dirname(fileURLToPath(import.meta.url));
12
- const queueDir = process.env.HUMEMORY_QUEUE ?? join(__dirname, '../data/maintenance-queue');
13
- const dbPath = process.env.HUMEMORY_DB ?? join(__dirname, '../data/humemory.db');
14
- const provider = process.env.HUMEMORY_MAINTENANCE_LLM ?? 'none';
12
+ const llmTimeoutMs = defaultLlmTimeoutMs();
13
+ const client = await resolveMaintenanceClient(llmTimeoutMs);
15
14
 
16
- const llmTimeoutMs = Number(process.env.HUMEMORY_MAINTENANCE_TIMEOUT_MS ?? 8_000);
15
+ // --skip-codex for a machine where the rollouts are imported some other way.
16
+ const codexSinceDays = process.argv.includes('--skip-codex')
17
+ ? false as const
18
+ : Number(process.env.HUMEMORY_MAINTENANCE_CODEX_DAYS ?? 1);
17
19
 
18
- // 'none' (the default) keeps consolidation deterministic and network-free.
19
- let client: LLMClient | undefined;
20
- if (provider === 'anthropic' && process.env.ANTHROPIC_API_KEY) {
21
- client = new Anthropic() as unknown as LLMClient;
22
- } else if (provider === 'codex') {
23
- // No API key needed: the logged-in `codex` CLI answers instead. Slower than an
24
- // SDK call (agent start-up), so it gets its own, larger budget.
25
- client = createCodexClient({ timeoutMs: llmTimeoutMs });
26
- }
27
-
28
- const result = await processMaintenanceQueue({
29
- queueDir,
30
- dbPath,
31
- client,
32
- llmTimeoutMs,
33
- maxJobs: Number(process.env.HUMEMORY_MAINTENANCE_BATCH ?? 20),
34
- });
20
+ const { worker: result } = await runMaintenancePass({ client, llmTimeoutMs, codexSinceDays });
35
21
 
36
22
  if (result.busy) {
37
23
  if (process.env.HUMEMORY_VERBOSE === '1') console.error('[humemory] maintenance: another worker is active');