humemory 0.2.6 → 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,11 @@
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
+
3
9
  ## [0.2.6] - 2026-08-27
4
10
  **Bug Fixes:**
5
11
  - stop the 15-min console flash, and make consolidation supervised (#1)
@@ -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
+ }
@@ -96,18 +96,18 @@ export async function runMaintenancePass(options = {}) {
96
96
  // A pass where every job failed is not a healthy pass. The queue isolates
97
97
  // jobs on purpose — a bad transcript must not stop the others — but that
98
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.
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.
102
104
  const wholesaleFailure = worker.discovered > 0 && worker.processed === 0 && worker.failed > 0;
103
105
  await recordMaintenanceRun({
104
106
  path: statePath,
105
107
  startedAt,
106
108
  clock,
107
109
  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,
110
+ error: wholesaleFailure ? new Error(wholesaleFailureMessage(worker)) : undefined,
111
111
  result: {
112
112
  discovered: worker.discovered,
113
113
  processed: worker.processed,
@@ -115,6 +115,8 @@ export async function runMaintenancePass(options = {}) {
115
115
  deadLettered: worker.deadLettered,
116
116
  memoriesStored: worker.memoriesStored,
117
117
  busy: worker.busy,
118
+ retriesRefunded: worker.retriesRefunded,
119
+ aborted: worker.aborted,
118
120
  },
119
121
  });
120
122
  return { codex, codexError, worker };
@@ -124,6 +126,19 @@ export async function runMaintenancePass(options = {}) {
124
126
  throw error;
125
127
  }
126
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
+ }
127
142
  const REAL_TIMERS = {
128
143
  setInterval: (handler, ms) => {
129
144
  const handle = setInterval(handler, ms);
@@ -160,7 +175,8 @@ export function startMaintenanceLoop(options = {}) {
160
175
  const { worker } = await runMaintenancePass({ ...options, client, runner: options.runner ?? 'api-loop' });
161
176
  if (process.env.HUMEMORY_VERBOSE === '1' || worker.failed > 0) {
162
177
  console.error(`[humemory] maintenance: ${worker.processed}/${worker.discovered} jobs, ` +
163
- `${worker.memoriesStored} memories, ${worker.failed} failed, ${worker.deadLettered} dead-lettered`);
178
+ `${worker.memoriesStored} memories, ${worker.failed} failed, ${worker.deadLettered} dead-lettered` +
179
+ (worker.aborted ? ' (pass aborted — suspected outage)' : ''));
164
180
  }
165
181
  }
166
182
  catch (error) {
@@ -31,6 +31,10 @@ export interface MaintenanceState {
31
31
  memoriesStored: number;
32
32
  /** True when another worker held the lock — not a failure. */
33
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;
34
38
  };
35
39
  /** Which process last wrote here, so two schedulers fighting is visible. */
36
40
  lastRunner?: string;
package/dist/cli/index.js CHANGED
@@ -819,6 +819,10 @@ maintenance
819
819
  if (health.lastResult) {
820
820
  const r = health.lastResult;
821
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');
822
826
  }
823
827
  console.log();
824
828
  if (health.stale) {
@@ -844,6 +848,70 @@ maintenance
844
848
  console.log(`✓ ${worker.processed}/${worker.discovered} jobs, ${worker.memoriesStored} memories, ` +
845
849
  `${worker.failed} failed, ${worker.deadLettered} dead-lettered${worker.busy ? ' (another worker held the lock)' : ''}`);
846
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
+ });
847
915
  // === LOCAL AGENT SOURCES ===
848
916
  const sources = program
849
917
  .command('sources')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "humemory",
3
- "version": "0.2.6",
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",