humemory 0.2.7 → 0.2.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +14 -7
- package/CHANGELOG.md +23 -0
- package/README.md +66 -12
- package/dist/agent/kimi-import.d.ts +19 -0
- package/dist/agent/kimi-import.js +111 -0
- package/dist/agent/kimi-session-parser.d.ts +3 -0
- package/dist/agent/kimi-session-parser.js +102 -0
- package/dist/agent/maintenance-queue.d.ts +2 -1
- package/dist/agent/maintenance-queue.js +36 -62
- package/dist/agent/maintenance-runner.d.ts +17 -4
- package/dist/agent/maintenance-runner.js +45 -10
- package/dist/agent/mcp-client-setup.d.ts +16 -0
- package/dist/agent/mcp-client-setup.js +108 -0
- package/dist/agent/opencode-import.d.ts +22 -0
- package/dist/agent/opencode-import.js +71 -0
- package/dist/agent/opencode-session-parser.d.ts +3 -0
- package/dist/agent/opencode-session-parser.js +35 -0
- package/dist/agent/session-parser.d.ts +8 -0
- package/dist/agent/session-parser.js +18 -0
- package/dist/agent/source-registry.js +1 -1
- package/dist/api/memory-routes.js +1 -1
- package/dist/api/server.js +3 -2
- package/dist/cli/index.js +117 -6
- package/dist/core/cues.d.ts +1 -0
- package/dist/core/cues.js +19 -7
- package/dist/core/doctor.d.ts +28 -0
- package/dist/core/doctor.js +320 -0
- package/dist/core/embeddings.d.ts +0 -10
- package/dist/core/embeddings.js +2 -1
- package/dist/core/hybrid.d.ts +7 -3
- package/dist/core/hybrid.js +7 -3
- package/dist/core/llm-generator.d.ts +2 -10
- package/dist/core/paths.d.ts +12 -0
- package/dist/core/paths.js +36 -0
- package/dist/core/project-path.d.ts +3 -0
- package/dist/core/project-path.js +14 -0
- package/dist/core/search.d.ts +1 -1
- package/dist/core/search.js +7 -9
- package/dist/core/types.d.ts +13 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/store/sqlite.d.ts +37 -0
- package/dist/store/sqlite.js +94 -42
- package/docs/PORTABILITY.md +84 -0
- package/package.json +5 -3
- package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
- package/public/app/index.html +1 -1
- package/scripts/consolidate.js +4 -4
- package/scripts/hook-post-commit.ts +2 -1
- package/scripts/hook-session-start.ts +2 -1
- package/scripts/hook-session.ts +2 -1
- package/scripts/maintenance-worker.ts +7 -2
- package/src/agent/claude-hook.ts +126 -0
- package/src/agent/codex-import.ts +129 -0
- package/src/agent/codex-rollout-parser.ts +121 -0
- package/src/agent/commit-closer.ts +173 -0
- package/src/agent/kimi-import.ts +128 -0
- package/src/agent/kimi-session-parser.ts +127 -0
- package/src/agent/learning-extractor.ts +128 -0
- package/src/agent/maintenance-queue.ts +544 -0
- package/src/agent/maintenance-runner.ts +322 -0
- package/src/agent/maintenance-state.ts +168 -0
- package/src/agent/mcp-client-setup.ts +125 -0
- package/src/agent/opencode-import.ts +96 -0
- package/src/agent/opencode-session-parser.ts +53 -0
- package/src/agent/session-context.ts +302 -0
- package/src/agent/session-parser.ts +155 -0
- package/src/agent/source-registry.ts +135 -0
- package/src/api/cors.ts +42 -0
- package/src/api/dream-routes.ts +46 -0
- package/src/api/errors.ts +45 -0
- package/src/api/intentions-routes.ts +348 -0
- package/src/api/limits.ts +90 -0
- package/src/api/maintenance-routes.ts +73 -0
- package/src/api/memory-routes.ts +391 -0
- package/src/api/scripts-routes.ts +176 -0
- package/src/api/security-headers.ts +54 -0
- package/src/api/server.ts +292 -0
- package/src/cli/index.ts +1195 -0
- package/src/core/clock.ts +64 -0
- package/src/core/cue-arg.ts +79 -0
- package/src/core/cues.ts +511 -0
- package/src/core/decay.ts +198 -0
- package/src/core/doctor.ts +362 -0
- package/src/core/dreamer.ts +494 -0
- package/src/core/embeddings.ts +157 -0
- package/src/core/event-bus.ts +100 -0
- package/src/core/hybrid.ts +82 -0
- package/src/core/llm-cli-client.ts +118 -0
- package/src/core/llm-generator.ts +90 -0
- package/src/core/paths.ts +38 -0
- package/src/core/project-path.ts +14 -0
- package/src/core/sanitize.ts +116 -0
- package/src/core/scripts.ts +112 -0
- package/src/core/search.ts +189 -0
- package/src/core/trust.ts +67 -0
- package/src/core/types.ts +393 -0
- package/src/core/vector-clusterer.ts +131 -0
- package/src/index.ts +40 -0
- package/src/mcp/HTTP_TRANSPORT.md +359 -0
- package/src/mcp/server.ts +202 -0
- package/src/store/sqlite.ts +1958 -0
|
@@ -0,0 +1,544 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'crypto';
|
|
2
|
+
import { mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from 'fs/promises';
|
|
3
|
+
import { join } from 'path';
|
|
4
|
+
import type { LLMClient } from '../core/llm-generator.js';
|
|
5
|
+
import { processSession } from './claude-hook.js';
|
|
6
|
+
import { parseAgentSession } from './session-parser.js';
|
|
7
|
+
import { AdvisoryLock } from '../store/sqlite.js';
|
|
8
|
+
|
|
9
|
+
export interface MaintenanceJob {
|
|
10
|
+
version: 1;
|
|
11
|
+
id: string;
|
|
12
|
+
source: string;
|
|
13
|
+
agent: string;
|
|
14
|
+
sessionId: string;
|
|
15
|
+
directory: string;
|
|
16
|
+
rawTranscript: string;
|
|
17
|
+
maxLearnings: number;
|
|
18
|
+
queuedAt: string;
|
|
19
|
+
attempts: number;
|
|
20
|
+
lastError?: string;
|
|
21
|
+
/** Set when the job was moved to dead-letter; absent on a live job. */
|
|
22
|
+
deadLetteredAt?: string;
|
|
23
|
+
/** Set when a dead-letter was put back in the queue by hand. */
|
|
24
|
+
requeuedAt?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface EnqueueOptions {
|
|
28
|
+
queueDir: string;
|
|
29
|
+
directory?: string;
|
|
30
|
+
source?: string;
|
|
31
|
+
agent?: string;
|
|
32
|
+
maxLearnings?: number;
|
|
33
|
+
now?: () => Date;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface QueueResult {
|
|
37
|
+
job: MaintenanceJob;
|
|
38
|
+
created: boolean;
|
|
39
|
+
path: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface WorkerOptions {
|
|
43
|
+
queueDir: string;
|
|
44
|
+
dbPath: string;
|
|
45
|
+
client?: LLMClient;
|
|
46
|
+
llmTimeoutMs?: number;
|
|
47
|
+
maxJobs?: number;
|
|
48
|
+
maxAttempts?: number;
|
|
49
|
+
/**
|
|
50
|
+
* Consecutive job failures that trip the circuit breaker and end the pass.
|
|
51
|
+
* `false` disables the breaker. See `processMaintenanceQueue`.
|
|
52
|
+
*/
|
|
53
|
+
failureThreshold?: number | false;
|
|
54
|
+
now?: () => Date;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface WorkerResult {
|
|
58
|
+
discovered: number;
|
|
59
|
+
processed: number;
|
|
60
|
+
failed: number;
|
|
61
|
+
deadLettered: number;
|
|
62
|
+
memoriesStored: number;
|
|
63
|
+
busy: boolean;
|
|
64
|
+
/** Failures that look like the machine, not the transcript — these cost no retry. */
|
|
65
|
+
infrastructureFailures: number;
|
|
66
|
+
/** Retries handed back because the failure was an outage rather than a bad job. */
|
|
67
|
+
retriesRefunded: number;
|
|
68
|
+
/** True when the circuit breaker cut the pass short instead of working the queue. */
|
|
69
|
+
aborted: boolean;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const DEFAULT_MAX_ATTEMPTS = 5;
|
|
73
|
+
const DEFAULT_FAILURE_THRESHOLD = 3;
|
|
74
|
+
const DEAD_LETTER_SUFFIX = '.dead.json';
|
|
75
|
+
const PROCESSING_SUFFIX = '.processing';
|
|
76
|
+
const CHECKPOINT_DIR = 'checkpoints';
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Why a job failed, as far as the retry budget is concerned.
|
|
80
|
+
*
|
|
81
|
+
* `job` — this transcript is the problem, and every future pass will fail on it
|
|
82
|
+
* the same way. Retrying a few times then dead-lettering is right.
|
|
83
|
+
*
|
|
84
|
+
* `infrastructure` — the machine is the problem (the database will not open,
|
|
85
|
+
* the disk is full, the file is locked). Every job in the queue would fail the
|
|
86
|
+
* same way right now and all of them would succeed once the machine is fixed,
|
|
87
|
+
* so burning a retry punishes the session for an outage it had no part in.
|
|
88
|
+
*/
|
|
89
|
+
export type FailureKind = 'job' | 'infrastructure';
|
|
90
|
+
|
|
91
|
+
/** errno values that mean "the machine", never "this transcript". */
|
|
92
|
+
const INFRASTRUCTURE_CODES = new Set([
|
|
93
|
+
'EACCES', 'EAGAIN', 'EBUSY', 'EDQUOT', 'EIO', 'EISDIR', 'EMFILE',
|
|
94
|
+
'ENFILE', 'ENOMEM', 'ENOSPC', 'EPERM', 'EROFS', 'ETIMEDOUT',
|
|
95
|
+
]);
|
|
96
|
+
|
|
97
|
+
const INFRASTRUCTURE_PATTERNS = [
|
|
98
|
+
/unable to open database/i,
|
|
99
|
+
/database is locked/i,
|
|
100
|
+
/database disk image is malformed/i,
|
|
101
|
+
/attempt to write a readonly database/i,
|
|
102
|
+
/disk i\/o error/i,
|
|
103
|
+
/no space left/i,
|
|
104
|
+
/out of memory/i,
|
|
105
|
+
/too many open files/i,
|
|
106
|
+
/read-?only file system/i,
|
|
107
|
+
];
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Classify a failure so an outage does not consume the queue's retry budget.
|
|
111
|
+
*
|
|
112
|
+
* Deliberately biased towards `job`: mislabelling a bad transcript as an outage
|
|
113
|
+
* only costs a few wasted passes, while mislabelling an outage as a bad job
|
|
114
|
+
* dead-letters real sessions permanently. Anything not recognisably about the
|
|
115
|
+
* machine is therefore treated as being about the transcript.
|
|
116
|
+
*/
|
|
117
|
+
export function classifyMaintenanceFailure(error: unknown): FailureKind {
|
|
118
|
+
const err = error as { code?: unknown; name?: unknown; message?: unknown; cause?: unknown } | null;
|
|
119
|
+
if (!err || typeof err !== 'object') return 'job';
|
|
120
|
+
|
|
121
|
+
const message = typeof err.message === 'string' ? err.message : String(error);
|
|
122
|
+
if (INFRASTRUCTURE_PATTERNS.some((pattern) => pattern.test(message))) return 'infrastructure';
|
|
123
|
+
if (typeof err.code === 'string') {
|
|
124
|
+
if (INFRASTRUCTURE_CODES.has(err.code)) return 'infrastructure';
|
|
125
|
+
// bun:sqlite reports the extended result code, e.g. SQLITE_CANTOPEN_ISDIR.
|
|
126
|
+
if (err.code.startsWith('SQLITE_') && !err.code.startsWith('SQLITE_CONSTRAINT')) return 'infrastructure';
|
|
127
|
+
}
|
|
128
|
+
// A constraint violation is a schema bug, not an outage — retrying cannot fix
|
|
129
|
+
// it, so it stays on the job's own budget. Every other SQLite error is the
|
|
130
|
+
// storage layer refusing to work at all.
|
|
131
|
+
if (err.name === 'SQLiteError' && !/constraint/i.test(message)) return 'infrastructure';
|
|
132
|
+
if (err.cause !== undefined && err.cause !== err) return classifyMaintenanceFailure(err.cause);
|
|
133
|
+
return 'job';
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function emptyResult(): WorkerResult {
|
|
137
|
+
return {
|
|
138
|
+
discovered: 0,
|
|
139
|
+
processed: 0,
|
|
140
|
+
failed: 0,
|
|
141
|
+
deadLettered: 0,
|
|
142
|
+
memoriesStored: 0,
|
|
143
|
+
busy: false,
|
|
144
|
+
infrastructureFailures: 0,
|
|
145
|
+
retriesRefunded: 0,
|
|
146
|
+
aborted: false,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** One failed job, held until the end of the pass so the verdict has full context. */
|
|
151
|
+
interface PendingFailure {
|
|
152
|
+
path: string;
|
|
153
|
+
claimed: string;
|
|
154
|
+
job: MaintenanceJob;
|
|
155
|
+
lastError: string;
|
|
156
|
+
kind: FailureKind;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
interface SessionCheckpoint {
|
|
160
|
+
sessionId: string;
|
|
161
|
+
messagesSeen: number;
|
|
162
|
+
updatedAt: string;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function jobPath(queueDir: string, id: string): string {
|
|
166
|
+
return join(queueDir, `${id}.json`);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function checkpointPath(queueDir: string, id: string): string {
|
|
170
|
+
return join(queueDir, CHECKPOINT_DIR, `${id}.json`);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async function readCheckpoint(queueDir: string, id: string): Promise<SessionCheckpoint | null> {
|
|
174
|
+
try {
|
|
175
|
+
return JSON.parse(await readFile(checkpointPath(queueDir, id), 'utf8')) as SessionCheckpoint;
|
|
176
|
+
} catch {
|
|
177
|
+
return null;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export async function atomicWrite(path: string, content: string, replace: typeof rename = rename): Promise<void> {
|
|
182
|
+
const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
183
|
+
await writeFile(temporary, content, { encoding: 'utf8', mode: 0o600 });
|
|
184
|
+
try {
|
|
185
|
+
await replace(temporary, path);
|
|
186
|
+
} catch (error) {
|
|
187
|
+
// Leave the destination intact and the complete temporary recoverable.
|
|
188
|
+
// Never emulate replacement by deleting the only acknowledged version.
|
|
189
|
+
throw error;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export async function enqueueSession(rawTranscript: string, options: EnqueueOptions): Promise<QueueResult> {
|
|
194
|
+
const raw = rawTranscript.trim();
|
|
195
|
+
if (!raw) throw new Error('Cannot queue an empty session');
|
|
196
|
+
|
|
197
|
+
const directory = options.directory ?? process.cwd();
|
|
198
|
+
const parsed = parseAgentSession(rawTranscript, directory);
|
|
199
|
+
const source = options.source ?? 'claude-code';
|
|
200
|
+
// Keyed on session, not transcript content: `Stop` fires once per turn and the
|
|
201
|
+
// transcript grows each time, so hashing the raw text would enqueue one job
|
|
202
|
+
// per turn instead of one per session. Re-enqueuing overwrites with the
|
|
203
|
+
// latest (fuller) transcript and resets attempts — new content, new chance.
|
|
204
|
+
const id = createHash('sha256').update(`${source}\0${parsed.sessionId}`).digest('hex');
|
|
205
|
+
const path = jobPath(options.queueDir, id);
|
|
206
|
+
const now = options.now ?? (() => new Date());
|
|
207
|
+
const job: MaintenanceJob = {
|
|
208
|
+
version: 1,
|
|
209
|
+
id,
|
|
210
|
+
source,
|
|
211
|
+
agent: options.agent ?? source,
|
|
212
|
+
sessionId: parsed.sessionId,
|
|
213
|
+
directory: parsed.directory,
|
|
214
|
+
rawTranscript,
|
|
215
|
+
maxLearnings: options.maxLearnings ?? 5,
|
|
216
|
+
queuedAt: now().toISOString(),
|
|
217
|
+
attempts: 0,
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
await mkdir(options.queueDir, { recursive: true });
|
|
221
|
+
return new AdvisoryLock(path + '.enqueue', 50).withLock(async () => {
|
|
222
|
+
let created = true;
|
|
223
|
+
try {
|
|
224
|
+
const previous = JSON.parse(await readFile(path, 'utf8')) as MaintenanceJob;
|
|
225
|
+
created = false;
|
|
226
|
+
const previousMessages = parseAgentSession(previous.rawTranscript, previous.directory).messages.length;
|
|
227
|
+
if (previousMessages > parsed.messages.length ||
|
|
228
|
+
(previousMessages === parsed.messages.length && previous.rawTranscript.length > rawTranscript.length)) {
|
|
229
|
+
return { job: previous, created: false, path };
|
|
230
|
+
}
|
|
231
|
+
} catch (error: any) {
|
|
232
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
await atomicWrite(path, JSON.stringify(job));
|
|
236
|
+
return { job, created, path };
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export async function processMaintenanceQueue(options: WorkerOptions): Promise<WorkerResult> {
|
|
241
|
+
await mkdir(options.queueDir, { recursive: true });
|
|
242
|
+
await mkdir(join(options.queueDir, CHECKPOINT_DIR), { recursive: true });
|
|
243
|
+
const now = options.now ?? (() => new Date());
|
|
244
|
+
// Ownership is an OS-backed SQLite lock, with no wall-clock expiry. A slow
|
|
245
|
+
// worker retains it; a killed worker releases it without a lease takeover race.
|
|
246
|
+
const lock = new AdvisoryLock(join(options.queueDir, '.worker-lock'), 1);
|
|
247
|
+
try { await lock.acquire(); }
|
|
248
|
+
catch (error: any) {
|
|
249
|
+
if (error?.code === 'SQLITE_BUSY') return { ...emptyResult(), busy: true };
|
|
250
|
+
throw error;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
try {
|
|
254
|
+
const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
255
|
+
|
|
256
|
+
// We hold the exclusive lock, so any leftover `.processing` file belongs to
|
|
257
|
+
// a worker that died mid-job. Restore it unless a newer session arrived in
|
|
258
|
+
// the meantime, in which case the newer transcript supersedes it.
|
|
259
|
+
for (const orphan of (await readdir(options.queueDir)).filter((file) => file.endsWith(PROCESSING_SUFFIX))) {
|
|
260
|
+
const orphanPath = join(options.queueDir, orphan);
|
|
261
|
+
const restored = join(options.queueDir, orphan.slice(0, -PROCESSING_SUFFIX.length));
|
|
262
|
+
try {
|
|
263
|
+
await stat(restored);
|
|
264
|
+
await rm(orphanPath, { force: true });
|
|
265
|
+
} catch {
|
|
266
|
+
await rename(orphanPath, restored).catch(() => undefined);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const candidates = (await readdir(options.queueDir)).filter((file) => file.endsWith('.json') && !file.endsWith(DEAD_LETTER_SUFFIX));
|
|
271
|
+
const withMeta = await Promise.all(
|
|
272
|
+
candidates.map(async (file) => {
|
|
273
|
+
const path = join(options.queueDir, file);
|
|
274
|
+
try {
|
|
275
|
+
const job = JSON.parse(await readFile(path, 'utf8')) as MaintenanceJob;
|
|
276
|
+
return { file, path, queuedAt: job.queuedAt ?? '' };
|
|
277
|
+
} catch {
|
|
278
|
+
return { file, path, queuedAt: '' };
|
|
279
|
+
}
|
|
280
|
+
}),
|
|
281
|
+
);
|
|
282
|
+
// Oldest-first: queuedAt is the enqueue timestamp, not the filename (a
|
|
283
|
+
// sha256 id sorts arbitrarily and would starve unlucky hashes forever).
|
|
284
|
+
const files = withMeta
|
|
285
|
+
.sort((a, b) => a.queuedAt.localeCompare(b.queuedAt))
|
|
286
|
+
.slice(0, options.maxJobs ?? 20)
|
|
287
|
+
.map((entry) => entry.file);
|
|
288
|
+
|
|
289
|
+
const result: WorkerResult = { ...emptyResult(), discovered: files.length };
|
|
290
|
+
const failureThreshold = options.failureThreshold === false
|
|
291
|
+
? Number.POSITIVE_INFINITY
|
|
292
|
+
: options.failureThreshold ?? DEFAULT_FAILURE_THRESHOLD;
|
|
293
|
+
// Failures are held rather than settled on the spot: whether a retry should
|
|
294
|
+
// be charged depends on how the *pass* ended, which is not known until the
|
|
295
|
+
// loop is over. See the finalisation block below.
|
|
296
|
+
const pending: PendingFailure[] = [];
|
|
297
|
+
let consecutiveFailures = 0;
|
|
298
|
+
|
|
299
|
+
for (const file of files) {
|
|
300
|
+
const path = join(options.queueDir, file);
|
|
301
|
+
// Claim the job by moving it aside. The hook may enqueue a newer, longer
|
|
302
|
+
// transcript for the same session while we work; it lands on the now-free
|
|
303
|
+
// job path and survives, instead of being deleted by our own cleanup.
|
|
304
|
+
const claimed = `${path}${PROCESSING_SUFFIX}`;
|
|
305
|
+
try {
|
|
306
|
+
await rename(path, claimed);
|
|
307
|
+
} catch {
|
|
308
|
+
continue; // Vanished between listing and claiming — nothing to do.
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
let job: MaintenanceJob | undefined;
|
|
312
|
+
try {
|
|
313
|
+
job = JSON.parse(await readFile(claimed, 'utf8')) as MaintenanceJob;
|
|
314
|
+
if (job.version !== 1 || !job.rawTranscript) throw new Error('Unsupported maintenance job');
|
|
315
|
+
const checkpoint = await readCheckpoint(options.queueDir, job.id);
|
|
316
|
+
const processed = await processSession(job.rawTranscript, {
|
|
317
|
+
dbPath: options.dbPath,
|
|
318
|
+
directory: job.directory,
|
|
319
|
+
maxLearnings: job.maxLearnings,
|
|
320
|
+
client: options.client,
|
|
321
|
+
llmTimeoutMs: options.llmTimeoutMs,
|
|
322
|
+
source: 'hook',
|
|
323
|
+
agent: job.agent,
|
|
324
|
+
sinceMessage: checkpoint?.messagesSeen ?? 0,
|
|
325
|
+
});
|
|
326
|
+
// Record how far this session has been encoded before dropping the job,
|
|
327
|
+
// so a later `Stop` resending the full transcript only adds the delta.
|
|
328
|
+
await atomicWrite(
|
|
329
|
+
checkpointPath(options.queueDir, job.id),
|
|
330
|
+
JSON.stringify({ sessionId: job.sessionId, messagesSeen: processed.messagesSeen, updatedAt: now().toISOString() } satisfies SessionCheckpoint),
|
|
331
|
+
);
|
|
332
|
+
await rm(claimed, { force: true });
|
|
333
|
+
result.processed += 1;
|
|
334
|
+
result.memoriesStored += processed.memoriesStored;
|
|
335
|
+
consecutiveFailures = 0;
|
|
336
|
+
} catch (error) {
|
|
337
|
+
result.failed += 1;
|
|
338
|
+
consecutiveFailures += 1;
|
|
339
|
+
const lastError = error instanceof Error ? error.message.slice(0, 500) : String(error).slice(0, 500);
|
|
340
|
+
const kind = classifyMaintenanceFailure(error);
|
|
341
|
+
if (kind === 'infrastructure') result.infrastructureFailures += 1;
|
|
342
|
+
try {
|
|
343
|
+
if (!job) {
|
|
344
|
+
// Unparseable on disk: no attempt counter can live in it, so retrying
|
|
345
|
+
// is pointless. Dead-letter the raw bytes immediately rather than
|
|
346
|
+
// failing this file on every future pass.
|
|
347
|
+
await rename(claimed, join(options.queueDir, `${file.replace(/\.json$/, '')}${DEAD_LETTER_SUFFIX}`));
|
|
348
|
+
result.deadLettered += 1;
|
|
349
|
+
} else {
|
|
350
|
+
pending.push({ path, claimed, job, lastError, kind });
|
|
351
|
+
}
|
|
352
|
+
} catch {
|
|
353
|
+
// Never erase evidence: the claimed file stays for manual inspection
|
|
354
|
+
// and the orphan sweep restores it on the next pass.
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// Circuit breaker. Working through the rest of the queue during an
|
|
358
|
+
// outage is how every queued session used to burn its retries in a
|
|
359
|
+
// single afternoon; a run of failures this long is far more likely to
|
|
360
|
+
// be the machine than a coincidence of bad transcripts, so stop and
|
|
361
|
+
// leave the untouched jobs for the next pass.
|
|
362
|
+
if (consecutiveFailures >= failureThreshold) {
|
|
363
|
+
result.aborted = true;
|
|
364
|
+
break;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// A pass that aborted without encoding anything is an outage by definition,
|
|
370
|
+
// whatever the individual error messages happened to look like: refund those
|
|
371
|
+
// retries too, so an unrecognised failure mode cannot drain the queue either.
|
|
372
|
+
const wholesaleFailure = result.aborted && result.processed === 0;
|
|
373
|
+
for (const entry of pending) {
|
|
374
|
+
const refund = entry.kind === 'infrastructure' || wholesaleFailure;
|
|
375
|
+
try {
|
|
376
|
+
entry.job.lastError = entry.lastError;
|
|
377
|
+
if (refund) {
|
|
378
|
+
result.retriesRefunded += 1;
|
|
379
|
+
} else {
|
|
380
|
+
entry.job.attempts = (entry.job.attempts ?? 0) + 1;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
if (!refund && entry.job.attempts >= maxAttempts) {
|
|
384
|
+
// Exhausted retries: move out of the active queue so it stops being
|
|
385
|
+
// picked up and stops inflating `failed` on every future pass, but
|
|
386
|
+
// keep the raw transcript on disk for manual inspection.
|
|
387
|
+
entry.job.deadLetteredAt = now().toISOString();
|
|
388
|
+
await atomicWrite(join(options.queueDir, `${entry.job.id}${DEAD_LETTER_SUFFIX}`), JSON.stringify(entry.job));
|
|
389
|
+
await rm(entry.claimed, { force: true });
|
|
390
|
+
result.deadLettered += 1;
|
|
391
|
+
} else {
|
|
392
|
+
// Restore for a later pass — unless a newer transcript already took
|
|
393
|
+
// the slot, which supersedes this one.
|
|
394
|
+
try {
|
|
395
|
+
await stat(entry.path);
|
|
396
|
+
await rm(entry.claimed, { force: true });
|
|
397
|
+
} catch {
|
|
398
|
+
await atomicWrite(entry.path, JSON.stringify(entry.job));
|
|
399
|
+
await rm(entry.claimed, { force: true });
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
} catch {
|
|
403
|
+
// Never erase evidence: the claimed file stays for manual inspection
|
|
404
|
+
// and the orphan sweep restores it on the next pass.
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
return result;
|
|
409
|
+
} finally {
|
|
410
|
+
lock.release();
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
// === DEAD-LETTER RECOVERY ===
|
|
416
|
+
|
|
417
|
+
export interface DeadLetter {
|
|
418
|
+
/** Filename in the queue directory, so a caller can name one precisely. */
|
|
419
|
+
file: string;
|
|
420
|
+
id: string;
|
|
421
|
+
/** Absent when the file could not be parsed — the bytes are still there. */
|
|
422
|
+
job?: MaintenanceJob;
|
|
423
|
+
sessionId?: string;
|
|
424
|
+
source?: string;
|
|
425
|
+
attempts?: number;
|
|
426
|
+
lastError?: string;
|
|
427
|
+
deadLetteredAt?: string;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
export interface RequeueOptions {
|
|
431
|
+
queueDir: string;
|
|
432
|
+
/**
|
|
433
|
+
* Restrict to these dead-letters. Each entry matches a job id, a session id,
|
|
434
|
+
* or a filename. Omitted means every dead-letter in the directory.
|
|
435
|
+
*/
|
|
436
|
+
ids?: string[];
|
|
437
|
+
/** Report what would happen and write nothing. */
|
|
438
|
+
dryRun?: boolean;
|
|
439
|
+
limit?: number;
|
|
440
|
+
now?: () => Date;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
export interface RequeueResult {
|
|
444
|
+
scanned: number;
|
|
445
|
+
requeued: number;
|
|
446
|
+
/** A live job already holds the slot — the newer transcript wins, so the dead-letter is left alone. */
|
|
447
|
+
skippedLive: number;
|
|
448
|
+
/** The file is not a usable job; requeuing it would only dead-letter it again. */
|
|
449
|
+
unreadable: number;
|
|
450
|
+
/** What was (or would be) put back. */
|
|
451
|
+
entries: DeadLetter[];
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function toDeadLetter(file: string, raw: string): DeadLetter {
|
|
455
|
+
const id = file.slice(0, -DEAD_LETTER_SUFFIX.length);
|
|
456
|
+
try {
|
|
457
|
+
const job = JSON.parse(raw) as MaintenanceJob;
|
|
458
|
+
if (job?.version !== 1 || !job.rawTranscript || typeof job.id !== 'string') return { file, id };
|
|
459
|
+
return {
|
|
460
|
+
file,
|
|
461
|
+
id: job.id,
|
|
462
|
+
job,
|
|
463
|
+
sessionId: job.sessionId,
|
|
464
|
+
source: job.source,
|
|
465
|
+
attempts: job.attempts,
|
|
466
|
+
lastError: job.lastError,
|
|
467
|
+
deadLetteredAt: job.deadLetteredAt,
|
|
468
|
+
};
|
|
469
|
+
} catch {
|
|
470
|
+
return { file, id };
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/** Everything currently parked in dead-letter, newest failure first. */
|
|
475
|
+
export async function listDeadLetters(queueDir: string): Promise<DeadLetter[]> {
|
|
476
|
+
let files: string[];
|
|
477
|
+
try {
|
|
478
|
+
files = (await readdir(queueDir)).filter((file) => file.endsWith(DEAD_LETTER_SUFFIX));
|
|
479
|
+
} catch (error: any) {
|
|
480
|
+
if (error?.code === 'ENOENT') return [];
|
|
481
|
+
throw error;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
const entries = await Promise.all(
|
|
485
|
+
files.map(async (file) => toDeadLetter(file, await readFile(join(queueDir, file), 'utf8').catch(() => ''))),
|
|
486
|
+
);
|
|
487
|
+
return entries.sort((a, b) => (b.deadLetteredAt ?? '').localeCompare(a.deadLetteredAt ?? ''));
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Put dead-lettered jobs back in the queue with a fresh retry budget.
|
|
492
|
+
*
|
|
493
|
+
* Dead-lettering is not always a verdict on the transcript: before the retry
|
|
494
|
+
* budget learned to tell an outage from a bad job, a single unopenable database
|
|
495
|
+
* could park an entire afternoon of sessions in `.dead.json` files that nothing
|
|
496
|
+
* would ever look at again. This is the way back, and the reason the raw
|
|
497
|
+
* transcript is kept on disk rather than deleted.
|
|
498
|
+
*
|
|
499
|
+
* Restoring resets `attempts` to 0 — the point is a clean chance now that
|
|
500
|
+
* whatever broke has been fixed. A dead-letter whose slot is already held by a
|
|
501
|
+
* live job is left alone: that job carries a newer transcript for the same
|
|
502
|
+
* session and supersedes it.
|
|
503
|
+
*/
|
|
504
|
+
export async function requeueDeadLetters(options: RequeueOptions): Promise<RequeueResult> {
|
|
505
|
+
const now = options.now ?? (() => new Date());
|
|
506
|
+
const wanted = options.ids?.length ? new Set(options.ids) : undefined;
|
|
507
|
+
const result: RequeueResult = { scanned: 0, requeued: 0, skippedLive: 0, unreadable: 0, entries: [] };
|
|
508
|
+
|
|
509
|
+
const all = await listDeadLetters(options.queueDir);
|
|
510
|
+
const selected = wanted
|
|
511
|
+
? all.filter((entry) => wanted.has(entry.id) || wanted.has(entry.file) || (entry.sessionId !== undefined && wanted.has(entry.sessionId)))
|
|
512
|
+
: all;
|
|
513
|
+
|
|
514
|
+
for (const entry of selected) {
|
|
515
|
+
if (options.limit !== undefined && result.requeued >= options.limit) break;
|
|
516
|
+
result.scanned += 1;
|
|
517
|
+
|
|
518
|
+
if (!entry.job) {
|
|
519
|
+
result.unreadable += 1;
|
|
520
|
+
continue;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
const live = jobPath(options.queueDir, entry.job.id);
|
|
524
|
+
try {
|
|
525
|
+
await stat(live);
|
|
526
|
+
result.skippedLive += 1;
|
|
527
|
+
continue;
|
|
528
|
+
} catch {
|
|
529
|
+
// Slot is free — the dead-letter is still the best copy of this session.
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
result.entries.push(entry);
|
|
533
|
+
result.requeued += 1;
|
|
534
|
+
if (options.dryRun) continue;
|
|
535
|
+
|
|
536
|
+
const job: MaintenanceJob = { ...entry.job, attempts: 0, requeuedAt: now().toISOString() };
|
|
537
|
+
delete job.lastError;
|
|
538
|
+
delete job.deadLetteredAt;
|
|
539
|
+
await atomicWrite(live, JSON.stringify(job));
|
|
540
|
+
await rm(join(options.queueDir, entry.file), { force: true });
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
return result;
|
|
544
|
+
}
|