humemory 0.2.6 → 0.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +49 -4
- package/CHANGELOG.md +12 -0
- package/README.md +22 -10
- 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 +89 -0
- package/dist/agent/maintenance-queue.js +245 -87
- package/dist/agent/maintenance-runner.d.ts +17 -4
- package/dist/agent/maintenance-runner.js +68 -17
- package/dist/agent/maintenance-state.d.ts +4 -0
- 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/server.js +3 -2
- package/dist/cli/index.js +164 -4
- package/dist/core/cues.d.ts +1 -0
- package/dist/core/cues.js +19 -7
- package/dist/core/embeddings.d.ts +0 -10
- package/dist/core/embeddings.js +2 -1
- package/dist/core/llm-generator.d.ts +2 -10
- package/dist/core/paths.d.ts +5 -0
- package/dist/core/paths.js +27 -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/package.json +4 -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/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 +546 -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 +1175 -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/dreamer.ts +494 -0
- package/src/core/embeddings.ts +157 -0
- package/src/core/event-bus.ts +100 -0
- package/src/core/hybrid.ts +78 -0
- package/src/core/llm-cli-client.ts +118 -0
- package/src/core/llm-generator.ts +90 -0
- package/src/core/paths.ts +28 -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
|
@@ -1,13 +1,75 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'crypto';
|
|
2
|
-
import { mkdir,
|
|
2
|
+
import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'fs/promises';
|
|
3
3
|
import { join } from 'path';
|
|
4
4
|
import { processSession } from './claude-hook.js';
|
|
5
5
|
import { parseAgentSession } from './session-parser.js';
|
|
6
|
+
import { AdvisoryLock } from '../store/sqlite.js';
|
|
6
7
|
const DEFAULT_LOCK_STALE_MS = 5 * 60 * 1000;
|
|
7
8
|
const DEFAULT_MAX_ATTEMPTS = 5;
|
|
9
|
+
const DEFAULT_FAILURE_THRESHOLD = 3;
|
|
8
10
|
const DEAD_LETTER_SUFFIX = '.dead.json';
|
|
9
11
|
const PROCESSING_SUFFIX = '.processing';
|
|
10
12
|
const CHECKPOINT_DIR = 'checkpoints';
|
|
13
|
+
/** errno values that mean "the machine", never "this transcript". */
|
|
14
|
+
const INFRASTRUCTURE_CODES = new Set([
|
|
15
|
+
'EACCES', 'EAGAIN', 'EBUSY', 'EDQUOT', 'EIO', 'EISDIR', 'EMFILE',
|
|
16
|
+
'ENFILE', 'ENOMEM', 'ENOSPC', 'EPERM', 'EROFS', 'ETIMEDOUT',
|
|
17
|
+
]);
|
|
18
|
+
const INFRASTRUCTURE_PATTERNS = [
|
|
19
|
+
/unable to open database/i,
|
|
20
|
+
/database is locked/i,
|
|
21
|
+
/database disk image is malformed/i,
|
|
22
|
+
/attempt to write a readonly database/i,
|
|
23
|
+
/disk i\/o error/i,
|
|
24
|
+
/no space left/i,
|
|
25
|
+
/out of memory/i,
|
|
26
|
+
/too many open files/i,
|
|
27
|
+
/read-?only file system/i,
|
|
28
|
+
];
|
|
29
|
+
/**
|
|
30
|
+
* Classify a failure so an outage does not consume the queue's retry budget.
|
|
31
|
+
*
|
|
32
|
+
* Deliberately biased towards `job`: mislabelling a bad transcript as an outage
|
|
33
|
+
* only costs a few wasted passes, while mislabelling an outage as a bad job
|
|
34
|
+
* dead-letters real sessions permanently. Anything not recognisably about the
|
|
35
|
+
* machine is therefore treated as being about the transcript.
|
|
36
|
+
*/
|
|
37
|
+
export function classifyMaintenanceFailure(error) {
|
|
38
|
+
const err = error;
|
|
39
|
+
if (!err || typeof err !== 'object')
|
|
40
|
+
return 'job';
|
|
41
|
+
const message = typeof err.message === 'string' ? err.message : String(error);
|
|
42
|
+
if (INFRASTRUCTURE_PATTERNS.some((pattern) => pattern.test(message)))
|
|
43
|
+
return 'infrastructure';
|
|
44
|
+
if (typeof err.code === 'string') {
|
|
45
|
+
if (INFRASTRUCTURE_CODES.has(err.code))
|
|
46
|
+
return 'infrastructure';
|
|
47
|
+
// bun:sqlite reports the extended result code, e.g. SQLITE_CANTOPEN_ISDIR.
|
|
48
|
+
if (err.code.startsWith('SQLITE_') && !err.code.startsWith('SQLITE_CONSTRAINT'))
|
|
49
|
+
return 'infrastructure';
|
|
50
|
+
}
|
|
51
|
+
// A constraint violation is a schema bug, not an outage — retrying cannot fix
|
|
52
|
+
// it, so it stays on the job's own budget. Every other SQLite error is the
|
|
53
|
+
// storage layer refusing to work at all.
|
|
54
|
+
if (err.name === 'SQLiteError' && !/constraint/i.test(message))
|
|
55
|
+
return 'infrastructure';
|
|
56
|
+
if (err.cause !== undefined && err.cause !== err)
|
|
57
|
+
return classifyMaintenanceFailure(err.cause);
|
|
58
|
+
return 'job';
|
|
59
|
+
}
|
|
60
|
+
function emptyResult() {
|
|
61
|
+
return {
|
|
62
|
+
discovered: 0,
|
|
63
|
+
processed: 0,
|
|
64
|
+
failed: 0,
|
|
65
|
+
deadLettered: 0,
|
|
66
|
+
memoriesStored: 0,
|
|
67
|
+
busy: false,
|
|
68
|
+
infrastructureFailures: 0,
|
|
69
|
+
retriesRefunded: 0,
|
|
70
|
+
aborted: false,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
11
73
|
function jobPath(queueDir, id) {
|
|
12
74
|
return join(queueDir, `${id}.json`);
|
|
13
75
|
}
|
|
@@ -22,17 +84,16 @@ async function readCheckpoint(queueDir, id) {
|
|
|
22
84
|
return null;
|
|
23
85
|
}
|
|
24
86
|
}
|
|
25
|
-
async function atomicWrite(path, content) {
|
|
26
|
-
const temporary = `${path}.${process.pid}.tmp`;
|
|
87
|
+
export async function atomicWrite(path, content, replace = rename) {
|
|
88
|
+
const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
27
89
|
await writeFile(temporary, content, { encoding: 'utf8', mode: 0o600 });
|
|
28
90
|
try {
|
|
29
|
-
await
|
|
91
|
+
await replace(temporary, path);
|
|
30
92
|
}
|
|
31
93
|
catch (error) {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
await rename(temporary, path);
|
|
94
|
+
// Leave the destination intact and the complete temporary recoverable.
|
|
95
|
+
// Never emulate replacement by deleting the only acknowledged version.
|
|
96
|
+
throw error;
|
|
36
97
|
}
|
|
37
98
|
}
|
|
38
99
|
export async function enqueueSession(rawTranscript, options) {
|
|
@@ -62,55 +123,40 @@ export async function enqueueSession(rawTranscript, options) {
|
|
|
62
123
|
attempts: 0,
|
|
63
124
|
};
|
|
64
125
|
await mkdir(options.queueDir, { recursive: true });
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
await readFile(path, 'utf8');
|
|
68
|
-
created = false;
|
|
69
|
-
}
|
|
70
|
-
catch (error) {
|
|
71
|
-
if (error?.code !== 'ENOENT')
|
|
72
|
-
throw error;
|
|
73
|
-
}
|
|
74
|
-
await atomicWrite(path, JSON.stringify(job));
|
|
75
|
-
return { job, created, path };
|
|
76
|
-
}
|
|
77
|
-
export async function processMaintenanceQueue(options) {
|
|
78
|
-
await mkdir(options.queueDir, { recursive: true });
|
|
79
|
-
await mkdir(join(options.queueDir, CHECKPOINT_DIR), { recursive: true });
|
|
80
|
-
const now = options.now ?? (() => new Date());
|
|
81
|
-
const lockPath = join(options.queueDir, '.worker.lock');
|
|
82
|
-
const token = `${process.pid}-${randomUUID()}`;
|
|
83
|
-
let lock;
|
|
84
|
-
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
126
|
+
return new AdvisoryLock(path + '.enqueue', 50).withLock(async () => {
|
|
127
|
+
let created = true;
|
|
85
128
|
try {
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
129
|
+
const previous = JSON.parse(await readFile(path, 'utf8'));
|
|
130
|
+
created = false;
|
|
131
|
+
const previousMessages = parseAgentSession(previous.rawTranscript, previous.directory).messages.length;
|
|
132
|
+
if (previousMessages > parsed.messages.length ||
|
|
133
|
+
(previousMessages === parsed.messages.length && previous.rawTranscript.length > rawTranscript.length)) {
|
|
134
|
+
return { job: previous, created: false, path };
|
|
135
|
+
}
|
|
89
136
|
}
|
|
90
137
|
catch (error) {
|
|
91
|
-
if (error?.code !== '
|
|
138
|
+
if (error?.code !== 'ENOENT')
|
|
92
139
|
throw error;
|
|
93
|
-
const age = now().getTime() - (await stat(lockPath)).mtimeMs;
|
|
94
|
-
if (attempt === 0 && age > (options.lockStaleMs ?? DEFAULT_LOCK_STALE_MS)) {
|
|
95
|
-
// Atomic takeover: renaming the stale lock away can only succeed once,
|
|
96
|
-
// so two workers seeing the same stale lock cannot both reclaim it. A
|
|
97
|
-
// plain unlink would instead delete a lock the winner just acquired.
|
|
98
|
-
try {
|
|
99
|
-
await rename(lockPath, `${lockPath}.stale.${token}`);
|
|
100
|
-
await rm(`${lockPath}.stale.${token}`, { force: true });
|
|
101
|
-
}
|
|
102
|
-
catch (renameError) {
|
|
103
|
-
if (renameError?.code !== 'ENOENT')
|
|
104
|
-
throw renameError;
|
|
105
|
-
// Another worker won the takeover; the retry below will see its lock.
|
|
106
|
-
}
|
|
107
|
-
continue;
|
|
108
|
-
}
|
|
109
|
-
return { discovered: 0, processed: 0, failed: 0, deadLettered: 0, memoriesStored: 0, busy: true };
|
|
110
140
|
}
|
|
141
|
+
await atomicWrite(path, JSON.stringify(job));
|
|
142
|
+
return { job, created, path };
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
export async function processMaintenanceQueue(options) {
|
|
146
|
+
await mkdir(options.queueDir, { recursive: true });
|
|
147
|
+
await mkdir(join(options.queueDir, CHECKPOINT_DIR), { recursive: true });
|
|
148
|
+
const now = options.now ?? (() => new Date());
|
|
149
|
+
// Ownership is an OS-backed SQLite lock, with no wall-clock expiry. A slow
|
|
150
|
+
// worker retains it; a killed worker releases it without a lease takeover race.
|
|
151
|
+
const lock = new AdvisoryLock(join(options.queueDir, '.worker-lock'), 1);
|
|
152
|
+
try {
|
|
153
|
+
await lock.acquire();
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
if (error?.code === 'SQLITE_BUSY')
|
|
157
|
+
return { ...emptyResult(), busy: true };
|
|
158
|
+
throw error;
|
|
111
159
|
}
|
|
112
|
-
if (!lock)
|
|
113
|
-
return { discovered: 0, processed: 0, failed: 0, deadLettered: 0, memoriesStored: 0, busy: true };
|
|
114
160
|
try {
|
|
115
161
|
const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
116
162
|
// We hold the exclusive lock, so any leftover `.processing` file belongs to
|
|
@@ -144,14 +190,15 @@ export async function processMaintenanceQueue(options) {
|
|
|
144
190
|
.sort((a, b) => a.queuedAt.localeCompare(b.queuedAt))
|
|
145
191
|
.slice(0, options.maxJobs ?? 20)
|
|
146
192
|
.map((entry) => entry.file);
|
|
147
|
-
const result = {
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
193
|
+
const result = { ...emptyResult(), discovered: files.length };
|
|
194
|
+
const failureThreshold = options.failureThreshold === false
|
|
195
|
+
? Number.POSITIVE_INFINITY
|
|
196
|
+
: options.failureThreshold ?? DEFAULT_FAILURE_THRESHOLD;
|
|
197
|
+
// Failures are held rather than settled on the spot: whether a retry should
|
|
198
|
+
// be charged depends on how the *pass* ended, which is not known until the
|
|
199
|
+
// loop is over. See the finalisation block below.
|
|
200
|
+
const pending = [];
|
|
201
|
+
let consecutiveFailures = 0;
|
|
155
202
|
for (const file of files) {
|
|
156
203
|
const path = join(options.queueDir, file);
|
|
157
204
|
// Claim the job by moving it aside. The hook may enqueue a newer, longer
|
|
@@ -186,10 +233,15 @@ export async function processMaintenanceQueue(options) {
|
|
|
186
233
|
await rm(claimed, { force: true });
|
|
187
234
|
result.processed += 1;
|
|
188
235
|
result.memoriesStored += processed.memoriesStored;
|
|
236
|
+
consecutiveFailures = 0;
|
|
189
237
|
}
|
|
190
238
|
catch (error) {
|
|
191
239
|
result.failed += 1;
|
|
240
|
+
consecutiveFailures += 1;
|
|
192
241
|
const lastError = error instanceof Error ? error.message.slice(0, 500) : String(error).slice(0, 500);
|
|
242
|
+
const kind = classifyMaintenanceFailure(error);
|
|
243
|
+
if (kind === 'infrastructure')
|
|
244
|
+
result.infrastructureFailures += 1;
|
|
193
245
|
try {
|
|
194
246
|
if (!job) {
|
|
195
247
|
// Unparseable on disk: no attempt counter can live in it, so retrying
|
|
@@ -197,50 +249,156 @@ export async function processMaintenanceQueue(options) {
|
|
|
197
249
|
// failing this file on every future pass.
|
|
198
250
|
await rename(claimed, join(options.queueDir, `${file.replace(/\.json$/, '')}${DEAD_LETTER_SUFFIX}`));
|
|
199
251
|
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
252
|
}
|
|
212
253
|
else {
|
|
213
|
-
|
|
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
|
-
}
|
|
254
|
+
pending.push({ path, claimed, job, lastError, kind });
|
|
223
255
|
}
|
|
224
256
|
}
|
|
225
257
|
catch {
|
|
226
258
|
// Never erase evidence: the claimed file stays for manual inspection
|
|
227
259
|
// and the orphan sweep restores it on the next pass.
|
|
228
260
|
}
|
|
261
|
+
// Circuit breaker. Working through the rest of the queue during an
|
|
262
|
+
// outage is how every queued session used to burn its retries in a
|
|
263
|
+
// single afternoon; a run of failures this long is far more likely to
|
|
264
|
+
// be the machine than a coincidence of bad transcripts, so stop and
|
|
265
|
+
// leave the untouched jobs for the next pass.
|
|
266
|
+
if (consecutiveFailures >= failureThreshold) {
|
|
267
|
+
result.aborted = true;
|
|
268
|
+
break;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
// A pass that aborted without encoding anything is an outage by definition,
|
|
273
|
+
// whatever the individual error messages happened to look like: refund those
|
|
274
|
+
// retries too, so an unrecognised failure mode cannot drain the queue either.
|
|
275
|
+
const wholesaleFailure = result.aborted && result.processed === 0;
|
|
276
|
+
for (const entry of pending) {
|
|
277
|
+
const refund = entry.kind === 'infrastructure' || wholesaleFailure;
|
|
278
|
+
try {
|
|
279
|
+
entry.job.lastError = entry.lastError;
|
|
280
|
+
if (refund) {
|
|
281
|
+
result.retriesRefunded += 1;
|
|
282
|
+
}
|
|
283
|
+
else {
|
|
284
|
+
entry.job.attempts = (entry.job.attempts ?? 0) + 1;
|
|
285
|
+
}
|
|
286
|
+
if (!refund && entry.job.attempts >= maxAttempts) {
|
|
287
|
+
// Exhausted retries: move out of the active queue so it stops being
|
|
288
|
+
// picked up and stops inflating `failed` on every future pass, but
|
|
289
|
+
// keep the raw transcript on disk for manual inspection.
|
|
290
|
+
entry.job.deadLetteredAt = now().toISOString();
|
|
291
|
+
await atomicWrite(join(options.queueDir, `${entry.job.id}${DEAD_LETTER_SUFFIX}`), JSON.stringify(entry.job));
|
|
292
|
+
await rm(entry.claimed, { force: true });
|
|
293
|
+
result.deadLettered += 1;
|
|
294
|
+
}
|
|
295
|
+
else {
|
|
296
|
+
// Restore for a later pass — unless a newer transcript already took
|
|
297
|
+
// the slot, which supersedes this one.
|
|
298
|
+
try {
|
|
299
|
+
await stat(entry.path);
|
|
300
|
+
await rm(entry.claimed, { force: true });
|
|
301
|
+
}
|
|
302
|
+
catch {
|
|
303
|
+
await atomicWrite(entry.path, JSON.stringify(entry.job));
|
|
304
|
+
await rm(entry.claimed, { force: true });
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
catch {
|
|
309
|
+
// Never erase evidence: the claimed file stays for manual inspection
|
|
310
|
+
// and the orphan sweep restores it on the next pass.
|
|
229
311
|
}
|
|
230
312
|
}
|
|
231
313
|
return result;
|
|
232
314
|
}
|
|
233
315
|
finally {
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
316
|
+
lock.release();
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
function toDeadLetter(file, raw) {
|
|
320
|
+
const id = file.slice(0, -DEAD_LETTER_SUFFIX.length);
|
|
321
|
+
try {
|
|
322
|
+
const job = JSON.parse(raw);
|
|
323
|
+
if (job?.version !== 1 || !job.rawTranscript || typeof job.id !== 'string')
|
|
324
|
+
return { file, id };
|
|
325
|
+
return {
|
|
326
|
+
file,
|
|
327
|
+
id: job.id,
|
|
328
|
+
job,
|
|
329
|
+
sessionId: job.sessionId,
|
|
330
|
+
source: job.source,
|
|
331
|
+
attempts: job.attempts,
|
|
332
|
+
lastError: job.lastError,
|
|
333
|
+
deadLetteredAt: job.deadLetteredAt,
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
catch {
|
|
337
|
+
return { file, id };
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
/** Everything currently parked in dead-letter, newest failure first. */
|
|
341
|
+
export async function listDeadLetters(queueDir) {
|
|
342
|
+
let files;
|
|
343
|
+
try {
|
|
344
|
+
files = (await readdir(queueDir)).filter((file) => file.endsWith(DEAD_LETTER_SUFFIX));
|
|
345
|
+
}
|
|
346
|
+
catch (error) {
|
|
347
|
+
if (error?.code === 'ENOENT')
|
|
348
|
+
return [];
|
|
349
|
+
throw error;
|
|
350
|
+
}
|
|
351
|
+
const entries = await Promise.all(files.map(async (file) => toDeadLetter(file, await readFile(join(queueDir, file), 'utf8').catch(() => ''))));
|
|
352
|
+
return entries.sort((a, b) => (b.deadLetteredAt ?? '').localeCompare(a.deadLetteredAt ?? ''));
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Put dead-lettered jobs back in the queue with a fresh retry budget.
|
|
356
|
+
*
|
|
357
|
+
* Dead-lettering is not always a verdict on the transcript: before the retry
|
|
358
|
+
* budget learned to tell an outage from a bad job, a single unopenable database
|
|
359
|
+
* could park an entire afternoon of sessions in `.dead.json` files that nothing
|
|
360
|
+
* would ever look at again. This is the way back, and the reason the raw
|
|
361
|
+
* transcript is kept on disk rather than deleted.
|
|
362
|
+
*
|
|
363
|
+
* Restoring resets `attempts` to 0 — the point is a clean chance now that
|
|
364
|
+
* whatever broke has been fixed. A dead-letter whose slot is already held by a
|
|
365
|
+
* live job is left alone: that job carries a newer transcript for the same
|
|
366
|
+
* session and supersedes it.
|
|
367
|
+
*/
|
|
368
|
+
export async function requeueDeadLetters(options) {
|
|
369
|
+
const now = options.now ?? (() => new Date());
|
|
370
|
+
const wanted = options.ids?.length ? new Set(options.ids) : undefined;
|
|
371
|
+
const result = { scanned: 0, requeued: 0, skippedLive: 0, unreadable: 0, entries: [] };
|
|
372
|
+
const all = await listDeadLetters(options.queueDir);
|
|
373
|
+
const selected = wanted
|
|
374
|
+
? all.filter((entry) => wanted.has(entry.id) || wanted.has(entry.file) || (entry.sessionId !== undefined && wanted.has(entry.sessionId)))
|
|
375
|
+
: all;
|
|
376
|
+
for (const entry of selected) {
|
|
377
|
+
if (options.limit !== undefined && result.requeued >= options.limit)
|
|
378
|
+
break;
|
|
379
|
+
result.scanned += 1;
|
|
380
|
+
if (!entry.job) {
|
|
381
|
+
result.unreadable += 1;
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
const live = jobPath(options.queueDir, entry.job.id);
|
|
237
385
|
try {
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
386
|
+
await stat(live);
|
|
387
|
+
result.skippedLive += 1;
|
|
388
|
+
continue;
|
|
241
389
|
}
|
|
242
390
|
catch {
|
|
243
|
-
//
|
|
391
|
+
// Slot is free — the dead-letter is still the best copy of this session.
|
|
244
392
|
}
|
|
393
|
+
result.entries.push(entry);
|
|
394
|
+
result.requeued += 1;
|
|
395
|
+
if (options.dryRun)
|
|
396
|
+
continue;
|
|
397
|
+
const job = { ...entry.job, attempts: 0, requeuedAt: now().toISOString() };
|
|
398
|
+
delete job.lastError;
|
|
399
|
+
delete job.deadLetteredAt;
|
|
400
|
+
await atomicWrite(live, JSON.stringify(job));
|
|
401
|
+
await rm(join(options.queueDir, entry.file), { force: true });
|
|
245
402
|
}
|
|
403
|
+
return result;
|
|
246
404
|
}
|
|
@@ -17,6 +17,8 @@ import type { LLMClient } from '../core/llm-generator.js';
|
|
|
17
17
|
import type { Clock } from '../core/clock.js';
|
|
18
18
|
import { type WorkerResult } from './maintenance-queue.js';
|
|
19
19
|
import { type CodexImportResult } from './codex-import.js';
|
|
20
|
+
import { type KimiImportResult } from './kimi-import.js';
|
|
21
|
+
import { type OpenCodeCommandRunner, type OpenCodeImportResult } from './opencode-import.js';
|
|
20
22
|
export declare const DEFAULT_INTERVAL_MS: number;
|
|
21
23
|
export interface MaintenancePassOptions {
|
|
22
24
|
queueDir?: string;
|
|
@@ -26,6 +28,15 @@ export interface MaintenancePassOptions {
|
|
|
26
28
|
codexSinceDays?: number | false;
|
|
27
29
|
/** Overrides `$CODEX_HOME/sessions`; mainly a test seam. */
|
|
28
30
|
codexSessionsDir?: string;
|
|
31
|
+
/** Days of Kimi Code sessions to sweep in. `false` skips Kimi. */
|
|
32
|
+
kimiSinceDays?: number | false;
|
|
33
|
+
/** Overrides `$KIMI_CODE_HOME`; mainly a test seam. */
|
|
34
|
+
kimiHome?: string;
|
|
35
|
+
/** Days of OpenCode sessions to sweep in. `false` skips OpenCode. */
|
|
36
|
+
opencodeSinceDays?: number | false;
|
|
37
|
+
/** Test seam for the otherwise local, logged-in OpenCode CLI. */
|
|
38
|
+
opencodeRun?: OpenCodeCommandRunner;
|
|
39
|
+
opencodeCommand?: string;
|
|
29
40
|
client?: LLMClient;
|
|
30
41
|
llmTimeoutMs?: number;
|
|
31
42
|
maxJobs?: number;
|
|
@@ -35,8 +46,11 @@ export interface MaintenancePassOptions {
|
|
|
35
46
|
}
|
|
36
47
|
export interface MaintenancePassResult {
|
|
37
48
|
codex?: CodexImportResult;
|
|
38
|
-
/** Set when the codex import failed; the queue is still drained regardless. */
|
|
39
49
|
codexError?: string;
|
|
50
|
+
kimi?: KimiImportResult;
|
|
51
|
+
kimiError?: string;
|
|
52
|
+
opencode?: OpenCodeImportResult;
|
|
53
|
+
opencodeError?: string;
|
|
40
54
|
worker: WorkerResult;
|
|
41
55
|
}
|
|
42
56
|
export declare function defaultQueueDir(): string;
|
|
@@ -50,9 +64,8 @@ export declare function configuredIntervalMs(): number;
|
|
|
50
64
|
*/
|
|
51
65
|
export declare function resolveMaintenanceClient(timeoutMs?: number): Promise<LLMClient | undefined>;
|
|
52
66
|
/**
|
|
53
|
-
* Import, then drain, then record.
|
|
54
|
-
*
|
|
55
|
-
* from every other source.
|
|
67
|
+
* Import, then drain, then record. Every producer is isolated: a missing or
|
|
68
|
+
* unreadable runtime must never stall the queue or another producer.
|
|
56
69
|
*
|
|
57
70
|
* Throws only if the queue itself could not be drained — the caller records
|
|
58
71
|
* that failure and stays alive.
|
|
@@ -13,20 +13,23 @@
|
|
|
13
13
|
* it succeeds or fails, so a loop that has silently stopped is detectable from
|
|
14
14
|
* the CLI and the API instead of being noticed weeks later.
|
|
15
15
|
*/
|
|
16
|
-
import { dirname
|
|
16
|
+
import { dirname } from 'path';
|
|
17
17
|
import { fileURLToPath } from 'url';
|
|
18
18
|
import { systemClock } from '../core/clock.js';
|
|
19
|
+
import { databasePath, queueDirectory } from '../core/paths.js';
|
|
19
20
|
import { createCodexClient } from '../core/llm-cli-client.js';
|
|
20
21
|
import { processMaintenanceQueue } from './maintenance-queue.js';
|
|
21
22
|
import { importCodexRollouts, defaultCodexSessionsDir } from './codex-import.js';
|
|
23
|
+
import { importKimiSessions, defaultKimiHome } from './kimi-import.js';
|
|
24
|
+
import { importOpenCodeSessions, } from './opencode-import.js';
|
|
22
25
|
import { defaultStatePath, recordMaintenanceRun } from './maintenance-state.js';
|
|
23
26
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
24
27
|
export const DEFAULT_INTERVAL_MS = 15 * 60 * 1000;
|
|
25
28
|
export function defaultQueueDir() {
|
|
26
|
-
return
|
|
29
|
+
return queueDirectory();
|
|
27
30
|
}
|
|
28
31
|
export function defaultDbPath() {
|
|
29
|
-
return
|
|
32
|
+
return databasePath();
|
|
30
33
|
}
|
|
31
34
|
export function defaultLlmTimeoutMs() {
|
|
32
35
|
return Number(process.env.HUMEMORY_MAINTENANCE_TIMEOUT_MS ?? 8_000);
|
|
@@ -54,9 +57,8 @@ export async function resolveMaintenanceClient(timeoutMs = defaultLlmTimeoutMs()
|
|
|
54
57
|
return undefined;
|
|
55
58
|
}
|
|
56
59
|
/**
|
|
57
|
-
* Import, then drain, then record.
|
|
58
|
-
*
|
|
59
|
-
* from every other source.
|
|
60
|
+
* Import, then drain, then record. Every producer is isolated: a missing or
|
|
61
|
+
* unreadable runtime must never stall the queue or another producer.
|
|
60
62
|
*
|
|
61
63
|
* Throws only if the queue itself could not be drained — the caller records
|
|
62
64
|
* that failure and stays alive.
|
|
@@ -67,16 +69,18 @@ export async function runMaintenancePass(options = {}) {
|
|
|
67
69
|
const dbPath = options.dbPath ?? defaultDbPath();
|
|
68
70
|
const statePath = options.statePath ?? defaultStatePath(queueDir);
|
|
69
71
|
const llmTimeoutMs = options.llmTimeoutMs ?? defaultLlmTimeoutMs();
|
|
70
|
-
const
|
|
72
|
+
const codexSinceDays = options.codexSinceDays ?? 1;
|
|
73
|
+
const kimiSinceDays = options.kimiSinceDays ?? 1;
|
|
74
|
+
const opencodeSinceDays = options.opencodeSinceDays ?? 1;
|
|
71
75
|
const startedAt = clock.now();
|
|
72
76
|
let codex;
|
|
73
77
|
let codexError;
|
|
74
|
-
if (
|
|
78
|
+
if (codexSinceDays !== false) {
|
|
75
79
|
try {
|
|
76
80
|
codex = await importCodexRollouts({
|
|
77
81
|
queueDir,
|
|
78
82
|
sessionsDir: options.codexSessionsDir ?? defaultCodexSessionsDir(),
|
|
79
|
-
since: new Date(startedAt.getTime() -
|
|
83
|
+
since: new Date(startedAt.getTime() - codexSinceDays * 24 * 60 * 60 * 1000),
|
|
80
84
|
});
|
|
81
85
|
}
|
|
82
86
|
catch (error) {
|
|
@@ -84,6 +88,37 @@ export async function runMaintenancePass(options = {}) {
|
|
|
84
88
|
console.error('[humemory] maintenance: codex import failed —', codexError);
|
|
85
89
|
}
|
|
86
90
|
}
|
|
91
|
+
let kimi;
|
|
92
|
+
let kimiError;
|
|
93
|
+
if (kimiSinceDays !== false) {
|
|
94
|
+
try {
|
|
95
|
+
kimi = await importKimiSessions({
|
|
96
|
+
queueDir,
|
|
97
|
+
kimiHome: options.kimiHome ?? defaultKimiHome(),
|
|
98
|
+
since: new Date(startedAt.getTime() - kimiSinceDays * 24 * 60 * 60 * 1000),
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
kimiError = error.message;
|
|
103
|
+
console.error('[humemory] maintenance: Kimi import failed —', kimiError);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
let opencode;
|
|
107
|
+
let opencodeError;
|
|
108
|
+
if (opencodeSinceDays !== false) {
|
|
109
|
+
try {
|
|
110
|
+
opencode = await importOpenCodeSessions({
|
|
111
|
+
queueDir,
|
|
112
|
+
since: new Date(startedAt.getTime() - opencodeSinceDays * 24 * 60 * 60 * 1000),
|
|
113
|
+
run: options.opencodeRun,
|
|
114
|
+
command: options.opencodeCommand,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
opencodeError = error.message;
|
|
119
|
+
console.error('[humemory] maintenance: OpenCode import failed —', opencodeError);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
87
122
|
try {
|
|
88
123
|
const worker = await processMaintenanceQueue({
|
|
89
124
|
queueDir,
|
|
@@ -96,18 +131,18 @@ export async function runMaintenancePass(options = {}) {
|
|
|
96
131
|
// A pass where every job failed is not a healthy pass. The queue isolates
|
|
97
132
|
// jobs on purpose — a bad transcript must not stop the others — but that
|
|
98
133
|
// isolation also makes an infrastructure failure (unopenable database, full
|
|
99
|
-
// disk) look exactly like a batch of bad sessions
|
|
100
|
-
//
|
|
101
|
-
//
|
|
134
|
+
// disk) look exactly like a batch of bad sessions. The queue no longer
|
|
135
|
+
// dead-letters its way through an outage (retries are refunded and the
|
|
136
|
+
// circuit breaker cuts the pass short), but silence would still leave the
|
|
137
|
+
// machine broken and nothing consolidated, so the pass is recorded as a
|
|
138
|
+
// failure and `maintenance status` says so.
|
|
102
139
|
const wholesaleFailure = worker.discovered > 0 && worker.processed === 0 && worker.failed > 0;
|
|
103
140
|
await recordMaintenanceRun({
|
|
104
141
|
path: statePath,
|
|
105
142
|
startedAt,
|
|
106
143
|
clock,
|
|
107
144
|
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,
|
|
145
|
+
error: wholesaleFailure ? new Error(wholesaleFailureMessage(worker)) : undefined,
|
|
111
146
|
result: {
|
|
112
147
|
discovered: worker.discovered,
|
|
113
148
|
processed: worker.processed,
|
|
@@ -115,15 +150,30 @@ export async function runMaintenancePass(options = {}) {
|
|
|
115
150
|
deadLettered: worker.deadLettered,
|
|
116
151
|
memoriesStored: worker.memoriesStored,
|
|
117
152
|
busy: worker.busy,
|
|
153
|
+
retriesRefunded: worker.retriesRefunded,
|
|
154
|
+
aborted: worker.aborted,
|
|
118
155
|
},
|
|
119
156
|
});
|
|
120
|
-
return { codex, codexError, worker };
|
|
157
|
+
return { codex, codexError, kimi, kimiError, opencode, opencodeError, worker };
|
|
121
158
|
}
|
|
122
159
|
catch (error) {
|
|
123
160
|
await recordMaintenanceRun({ path: statePath, startedAt, clock, runner: options.runner, error });
|
|
124
161
|
throw error;
|
|
125
162
|
}
|
|
126
163
|
}
|
|
164
|
+
/**
|
|
165
|
+
* One line naming what the pass looked like, so `maintenance status` can be
|
|
166
|
+
* read without opening the queue directory.
|
|
167
|
+
*/
|
|
168
|
+
function wholesaleFailureMessage(worker) {
|
|
169
|
+
const scope = worker.aborted
|
|
170
|
+
? `pass aborted after ${worker.failed} consecutive failures`
|
|
171
|
+
: `every job failed this pass (${worker.failed}/${worker.discovered})`;
|
|
172
|
+
const budget = worker.retriesRefunded > 0
|
|
173
|
+
? `; ${worker.retriesRefunded} retry(ies) refunded, nothing dead-lettered`
|
|
174
|
+
: '';
|
|
175
|
+
return `${scope} — suspect the database or the disk, not the sessions${budget}`;
|
|
176
|
+
}
|
|
127
177
|
const REAL_TIMERS = {
|
|
128
178
|
setInterval: (handler, ms) => {
|
|
129
179
|
const handle = setInterval(handler, ms);
|
|
@@ -160,7 +210,8 @@ export function startMaintenanceLoop(options = {}) {
|
|
|
160
210
|
const { worker } = await runMaintenancePass({ ...options, client, runner: options.runner ?? 'api-loop' });
|
|
161
211
|
if (process.env.HUMEMORY_VERBOSE === '1' || worker.failed > 0) {
|
|
162
212
|
console.error(`[humemory] maintenance: ${worker.processed}/${worker.discovered} jobs, ` +
|
|
163
|
-
`${worker.memoriesStored} memories, ${worker.failed} failed, ${worker.deadLettered} dead-lettered`
|
|
213
|
+
`${worker.memoriesStored} memories, ${worker.failed} failed, ${worker.deadLettered} dead-lettered` +
|
|
214
|
+
(worker.aborted ? ' (pass aborted — suspected outage)' : ''));
|
|
164
215
|
}
|
|
165
216
|
}
|
|
166
217
|
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;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export type HumemoryMcpClient = 'kimi' | 'opencode';
|
|
2
|
+
export interface McpClientSetupOptions {
|
|
3
|
+
clients: HumemoryMcpClient[];
|
|
4
|
+
projectRoot: string;
|
|
5
|
+
dbPath?: string;
|
|
6
|
+
bunPath?: string;
|
|
7
|
+
kimiHome?: string;
|
|
8
|
+
openCodeConfig?: string;
|
|
9
|
+
dryRun?: boolean;
|
|
10
|
+
}
|
|
11
|
+
export interface McpClientSetupEntry {
|
|
12
|
+
client: HumemoryMcpClient;
|
|
13
|
+
path: string;
|
|
14
|
+
changed: boolean;
|
|
15
|
+
}
|
|
16
|
+
export declare function setupHumemoryMcpClients(options: McpClientSetupOptions): Promise<McpClientSetupEntry[]>;
|