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.
Files changed (95) hide show
  1. package/AGENTS.md +49 -4
  2. package/CHANGELOG.md +12 -0
  3. package/README.md +22 -10
  4. package/dist/agent/kimi-import.d.ts +19 -0
  5. package/dist/agent/kimi-import.js +111 -0
  6. package/dist/agent/kimi-session-parser.d.ts +3 -0
  7. package/dist/agent/kimi-session-parser.js +102 -0
  8. package/dist/agent/maintenance-queue.d.ts +89 -0
  9. package/dist/agent/maintenance-queue.js +245 -87
  10. package/dist/agent/maintenance-runner.d.ts +17 -4
  11. package/dist/agent/maintenance-runner.js +68 -17
  12. package/dist/agent/maintenance-state.d.ts +4 -0
  13. package/dist/agent/mcp-client-setup.d.ts +16 -0
  14. package/dist/agent/mcp-client-setup.js +108 -0
  15. package/dist/agent/opencode-import.d.ts +22 -0
  16. package/dist/agent/opencode-import.js +71 -0
  17. package/dist/agent/opencode-session-parser.d.ts +3 -0
  18. package/dist/agent/opencode-session-parser.js +35 -0
  19. package/dist/agent/session-parser.d.ts +8 -0
  20. package/dist/agent/session-parser.js +18 -0
  21. package/dist/agent/source-registry.js +1 -1
  22. package/dist/api/server.js +3 -2
  23. package/dist/cli/index.js +164 -4
  24. package/dist/core/cues.d.ts +1 -0
  25. package/dist/core/cues.js +19 -7
  26. package/dist/core/embeddings.d.ts +0 -10
  27. package/dist/core/embeddings.js +2 -1
  28. package/dist/core/llm-generator.d.ts +2 -10
  29. package/dist/core/paths.d.ts +5 -0
  30. package/dist/core/paths.js +27 -0
  31. package/dist/core/project-path.d.ts +3 -0
  32. package/dist/core/project-path.js +14 -0
  33. package/dist/core/search.d.ts +1 -1
  34. package/dist/core/search.js +7 -9
  35. package/dist/core/types.d.ts +13 -1
  36. package/dist/index.d.ts +5 -0
  37. package/dist/index.js +5 -0
  38. package/dist/store/sqlite.d.ts +37 -0
  39. package/dist/store/sqlite.js +94 -42
  40. package/package.json +4 -3
  41. package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
  42. package/public/app/index.html +1 -1
  43. package/scripts/consolidate.js +4 -4
  44. package/scripts/hook-post-commit.ts +2 -1
  45. package/scripts/hook-session-start.ts +2 -1
  46. package/scripts/hook-session.ts +2 -1
  47. package/src/agent/claude-hook.ts +126 -0
  48. package/src/agent/codex-import.ts +129 -0
  49. package/src/agent/codex-rollout-parser.ts +121 -0
  50. package/src/agent/commit-closer.ts +173 -0
  51. package/src/agent/kimi-import.ts +128 -0
  52. package/src/agent/kimi-session-parser.ts +127 -0
  53. package/src/agent/learning-extractor.ts +128 -0
  54. package/src/agent/maintenance-queue.ts +546 -0
  55. package/src/agent/maintenance-runner.ts +322 -0
  56. package/src/agent/maintenance-state.ts +168 -0
  57. package/src/agent/mcp-client-setup.ts +125 -0
  58. package/src/agent/opencode-import.ts +96 -0
  59. package/src/agent/opencode-session-parser.ts +53 -0
  60. package/src/agent/session-context.ts +302 -0
  61. package/src/agent/session-parser.ts +155 -0
  62. package/src/agent/source-registry.ts +135 -0
  63. package/src/api/cors.ts +42 -0
  64. package/src/api/dream-routes.ts +46 -0
  65. package/src/api/errors.ts +45 -0
  66. package/src/api/intentions-routes.ts +348 -0
  67. package/src/api/limits.ts +90 -0
  68. package/src/api/maintenance-routes.ts +73 -0
  69. package/src/api/memory-routes.ts +391 -0
  70. package/src/api/scripts-routes.ts +176 -0
  71. package/src/api/security-headers.ts +54 -0
  72. package/src/api/server.ts +292 -0
  73. package/src/cli/index.ts +1175 -0
  74. package/src/core/clock.ts +64 -0
  75. package/src/core/cue-arg.ts +79 -0
  76. package/src/core/cues.ts +511 -0
  77. package/src/core/decay.ts +198 -0
  78. package/src/core/dreamer.ts +494 -0
  79. package/src/core/embeddings.ts +157 -0
  80. package/src/core/event-bus.ts +100 -0
  81. package/src/core/hybrid.ts +78 -0
  82. package/src/core/llm-cli-client.ts +118 -0
  83. package/src/core/llm-generator.ts +90 -0
  84. package/src/core/paths.ts +28 -0
  85. package/src/core/project-path.ts +14 -0
  86. package/src/core/sanitize.ts +116 -0
  87. package/src/core/scripts.ts +112 -0
  88. package/src/core/search.ts +189 -0
  89. package/src/core/trust.ts +67 -0
  90. package/src/core/types.ts +393 -0
  91. package/src/core/vector-clusterer.ts +131 -0
  92. package/src/index.ts +40 -0
  93. package/src/mcp/HTTP_TRANSPORT.md +359 -0
  94. package/src/mcp/server.ts +202 -0
  95. package/src/store/sqlite.ts +1958 -0
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`
@@ -63,8 +68,13 @@ src/
63
68
  ├── agent/
64
69
  │ ├── session-parser.ts # parse Claude Code session transcripts
65
70
  │ ├── source-registry.ts # discover local AI runtimes without reading sessions
71
+ │ ├── kimi-session-parser.ts / kimi-import.ts # Kimi wire → maintenance queue
72
+ │ ├── opencode-session-parser.ts / opencode-import.ts # public OpenCode export → queue
73
+ │ ├── mcp-client-setup.ts # merge humemory into Kimi/OpenCode MCP configs
66
74
  │ ├── learning-extractor.ts # extract decisions/bugs/solutions
67
- │ ├── maintenance-queue.ts # durable async inbox, session checkpoints, dead-letter
75
+ │ ├── maintenance-queue.ts # durable async inbox, checkpoints, retry policy, dead-letter
76
+ │ ├── maintenance-runner.ts # one pass (Codex/Kimi/OpenCode import + drain), in-API loop
77
+ │ ├── maintenance-state.ts # durable health record of the loop (data/maintenance-state.json)
68
78
  │ ├── claude-hook.ts # worker-side session learning encoder
69
79
  │ └── session-context.ts # SessionStart → markdown block (open loops + traces)
70
80
  ├── core/
@@ -126,6 +136,40 @@ keywords >5. `photographic: true` disables decay entirely.
126
136
 
127
137
  ---
128
138
 
139
+ ## 🔁 Maintenance retry policy — an outage must not cost a session
140
+
141
+ The queue isolates jobs so one bad transcript cannot stop the others. That same
142
+ isolation once made an outage indistinguishable from a batch of bad sessions:
143
+ against an unopenable database every queued job simply failed, burned its five
144
+ attempts over five passes, and landed in a `.dead.json` file nothing ever read.
145
+ Three rules now separate "this transcript is bad" from "this machine is down":
146
+
147
+ 1. **Failures are classified** (`classifyMaintenanceFailure`). Anything that
148
+ names the machine — `unable to open database`, `database is locked`, `ENOSPC`,
149
+ `EROFS`, a `SQLITE_*` code that is not a constraint violation — is
150
+ *infrastructure* and costs no retry. Everything else is *job* and spends the
151
+ budget as before. The bias is deliberate: mislabelling a bad transcript wastes
152
+ a few passes, mislabelling an outage loses real sessions for good.
153
+ 2. **A circuit breaker ends the pass** after `failureThreshold` consecutive
154
+ failures (default 3, `false` disables it). The untouched jobs are never
155
+ claimed, so an outage costs one job's worth of damage instead of the queue's.
156
+ 3. **An aborted pass that encoded nothing refunds every retry it charged**, even
157
+ ones classified as job-level — a run of failures with zero successes is an
158
+ outage shape whatever the messages said. `processed > 0` proves the machine
159
+ works, and cancels the amnesty.
160
+
161
+ The verdict is therefore deferred: failures are held until the end of the pass,
162
+ because whether a retry is owed depends on how the pass finished.
163
+
164
+ A pass that discovers jobs and encodes none is still recorded as a **failure** in
165
+ `data/maintenance-state.json`, so `humemory maintenance status` shows it. Jobs
166
+ that genuinely exhaust their budget keep their raw transcript in `.dead.json` —
167
+ `humemory maintenance dead-letters` lists them and `humemory maintenance requeue`
168
+ puts them back with `attempts` reset. Requeuing never clobbers a live job for the
169
+ same session: that transcript is newer and supersedes the parked one.
170
+
171
+ ---
172
+
129
173
  ## 🧪 Autonomous test environment — REQUIRED
130
174
 
131
175
  **Non-negotiable design constraint** (set 2026-06-17). Every test run MUST be
@@ -230,8 +274,9 @@ Claude, Codex, Kimi, OpenCode share one store with agent attribution on every
230
274
  write (`agent` arg or `$HUMEMORY_AGENT`; `HUMEMORY_DB` override for tests).
231
275
 
232
276
  **Client registration** — the repo ships `.mcp.json` (Claude Code project
233
- scope, `HUMEMORY_AGENT=claude`). For other agents, register the same server
234
- with their own identity:
277
+ scope, `HUMEMORY_AGENT=claude`). `pnpm cli sources setup` merge-registers the
278
+ same server in installed Kimi Code and OpenCode configs without removing other
279
+ MCP servers, using the identities below:
235
280
 
236
281
  | Agent | Config | `HUMEMORY_AGENT` |
237
282
  |-------|--------|------------------|
@@ -312,7 +357,7 @@ accepts a script id as the loser. API: `POST/GET /scripts`,
312
357
  [PHASE7_DIALOG.md](./PHASE7_DIALOG.md)
313
358
  - Multi-device sync of the shared store (the `device` column from 6.0.1 makes
314
359
  it migration-free; conflict policy TBD)
315
- - OpenCode / other-agent integration; export/import memories between projects
360
+ - Other-agent integration; export/import memories between projects
316
361
 
317
362
  ---
318
363
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.8] - 2026-09-06
4
+ **Other:**
5
+ - Add comprehensive tests for audit, maintenance, and import functionalities
6
+
7
+
8
+
9
+ ## [0.2.7] - 2026-08-27
10
+ **Bug Fixes:**
11
+ - spend retries on bad jobs, not on outages (#2)
12
+
13
+
14
+
3
15
  ## [0.2.6] - 2026-08-27
4
16
  **Bug Fixes:**
5
17
  - stop the 15-min console flash, and make consolidation supervised (#1)
package/README.md CHANGED
@@ -84,7 +84,7 @@ The non-exhaustive catalog currently recognizes:
84
84
  | Codex | OpenAI | `codex`, `~/.codex` |
85
85
  | Kimi Code / Kimi Desktop | Moonshot AI | `kimi`, `~/.kimi-code`, desktop data roots |
86
86
  | Mistral Vibe | **Mistral AI** | `vibe`, `$VIBE_HOME`, `~/.vibe` |
87
- | OpenCode | SST | `opencode`, `~/.opencode` |
87
+ | OpenCode | SST | `opencode`, `~/.opencode`, `~/.local/share/opencode` |
88
88
  | Qwen Code | Alibaba Cloud | `qwen`, `$QWEN_RUNTIME_DIR`, `$QWEN_HOME`, `~/.qwen` |
89
89
  | Gemini CLI | Google | `gemini`, `$GEMINI_CLI_HOME`, `~/.gemini` |
90
90
  | GitHub Copilot CLI | GitHub | `copilot`, `~/.copilot` |
@@ -92,19 +92,30 @@ The non-exhaustive catalog currently recognizes:
92
92
  | Cursor | Anysphere | `cursor`, desktop data roots |
93
93
  | Windsurf | Cognition | `windsurf`, desktop data roots |
94
94
 
95
- An entry means **ready to be discovered**, not that its evolving private session
96
- format is already parsed. Run `pnpm cli sources discover --installed-only` for a
97
- local inventory without exposing conversation content.
95
+ An entry means **ready to be discovered**, not automatically importable. The
96
+ three parsed historical sources are named explicitly below; every other entry is
97
+ detection-only. Run `pnpm cli sources discover --installed-only` for a local
98
+ inventory without exposing conversation content.
98
99
 
99
- **Codex is parsed.** Its rollouts (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`,
100
- `$CODEX_HOME` honoured) import into the same queue the agent hooks write to:
100
+ **Codex, Kimi Code and OpenCode are parsed.** They all import into the same queue
101
+ the live hooks write to. Kimi uses its documented session index and wire under
102
+ `$KIMI_CODE_HOME`; OpenCode is read through its public `db` and `export` CLI
103
+ commands rather than coupling humemory to the SQLite schema:
101
104
 
102
105
  ```bash
103
106
  pnpm cli sources import-codex --dry-run # what would be queued, writes nothing
104
107
  pnpm cli sources import-codex --since 7 # the last week (default)
105
108
  pnpm cli sources import-codex --all # every rollout ever recorded
109
+ pnpm cli sources import-kimi --all
110
+ pnpm cli sources import-opencode --all
111
+ pnpm cli sources setup # register MCP in both installed clients
106
112
  ```
107
113
 
114
+ The resident maintenance loop sweeps new sessions from all three producers every
115
+ 15 minutes. `sources setup` merge-adds a `humemory` MCP entry without removing
116
+ existing servers and pins each client identity (`kimi` or `opencode`) plus the
117
+ absolute shared database path.
118
+
108
119
  Importing only *queues*; the worker still decides what becomes a trace. Jobs are
109
120
  keyed on session, so re-importing is idempotent and a thread that grew since the
110
121
  last pass contributes only its new messages. Threads codex spawned for itself
@@ -322,9 +333,10 @@ in sits outside the cognitive core.
322
333
  scripts begin as drafts, and contradictions stay inspectable. A model doesn't
323
334
  silently turn a guess into permanent memory.
324
335
 
325
- Historical absorption stays opt-in. `sources discover` checks commands and known
326
- paths without reading conversations. Each runtime still needs a parser before
327
- humemory can import its sessions, and discovery never pretends otherwise.
336
+ Historical bulk absorption stays opt-in. `sources discover` checks commands and
337
+ known paths without reading conversations. Codex, Kimi Code and OpenCode have
338
+ explicit import adapters; every other catalog entry remains detection-only, and
339
+ discovery never pretends otherwise.
328
340
 
329
341
  ## Stack
330
342
 
@@ -626,7 +638,7 @@ keywords >5. `photographic: true` disables decay entirely.
626
638
 
627
639
  ### 🛣️ Beyond
628
640
  - Shared multi-project DB with concurrency lock (WAL + advisory) — done (Sprint 5 / S5-00a)
629
- - OpenCode / other-agent integration; export/import memories between projects
641
+ - Other-agent import adapters; export/import memories between projects
630
642
 
631
643
  ---
632
644
 
@@ -0,0 +1,19 @@
1
+ export declare const KIMI_SOURCE = "kimi-code-session";
2
+ export interface KimiImportOptions {
3
+ queueDir: string;
4
+ kimiHome?: string;
5
+ since?: Date;
6
+ limit?: number;
7
+ dryRun?: boolean;
8
+ maxLearnings?: number;
9
+ }
10
+ export interface KimiImportResult {
11
+ scanned: number;
12
+ queued: number;
13
+ created: number;
14
+ skippedEmpty: number;
15
+ skippedOld: number;
16
+ unreadable: number;
17
+ }
18
+ export declare function defaultKimiHome(): string;
19
+ export declare function importKimiSessions(options: KimiImportOptions): Promise<KimiImportResult>;
@@ -0,0 +1,111 @@
1
+ /** Import Kimi Code sessions into the shared maintenance queue. */
2
+ import { isAbsolute, join, resolve } from 'path';
3
+ import { homedir } from 'os';
4
+ import { readdir, readFile, stat } from 'fs/promises';
5
+ import { enqueueSession } from './maintenance-queue.js';
6
+ import { parseKimiSession } from './kimi-session-parser.js';
7
+ import { serializeAgentSession } from './session-parser.js';
8
+ export const KIMI_SOURCE = 'kimi-code-session';
9
+ export function defaultKimiHome() {
10
+ return process.env.KIMI_CODE_HOME ?? join(homedir(), '.kimi-code');
11
+ }
12
+ async function discoverFromIndex(kimiHome) {
13
+ try {
14
+ const raw = await readFile(join(kimiHome, 'session_index.jsonl'), 'utf8');
15
+ const found = [];
16
+ for (const line of raw.split(/\r?\n/)) {
17
+ if (!line.trim())
18
+ continue;
19
+ try {
20
+ const entry = JSON.parse(line);
21
+ if (!entry.sessionDir)
22
+ continue;
23
+ found.push(isAbsolute(entry.sessionDir) ? entry.sessionDir : resolve(kimiHome, entry.sessionDir));
24
+ }
25
+ catch {
26
+ // One partially-written index line does not invalidate earlier sessions.
27
+ }
28
+ }
29
+ return found;
30
+ }
31
+ catch {
32
+ return [];
33
+ }
34
+ }
35
+ async function discoverByState(dir) {
36
+ let entries;
37
+ try {
38
+ entries = await readdir(dir, { withFileTypes: true });
39
+ }
40
+ catch {
41
+ return [];
42
+ }
43
+ if (entries.some((entry) => entry.isFile() && entry.name === 'state.json'))
44
+ return [dir];
45
+ const found = [];
46
+ for (const entry of entries) {
47
+ if (entry.isDirectory())
48
+ found.push(...await discoverByState(join(dir, entry.name)));
49
+ }
50
+ return found;
51
+ }
52
+ export async function importKimiSessions(options) {
53
+ const kimiHome = options.kimiHome ?? defaultKimiHome();
54
+ const indexed = await discoverFromIndex(kimiHome);
55
+ const sessionDirs = [...new Set(indexed.length ? indexed : await discoverByState(join(kimiHome, 'sessions')))];
56
+ const candidates = [];
57
+ const result = {
58
+ scanned: sessionDirs.length,
59
+ queued: 0,
60
+ created: 0,
61
+ skippedEmpty: 0,
62
+ skippedOld: 0,
63
+ unreadable: 0,
64
+ };
65
+ for (const dir of sessionDirs) {
66
+ try {
67
+ const modified = (await stat(join(dir, 'agents', 'main', 'wire.jsonl'))).mtime;
68
+ if (options.since && modified < options.since) {
69
+ result.skippedOld += 1;
70
+ continue;
71
+ }
72
+ candidates.push({ dir, modified });
73
+ }
74
+ catch {
75
+ result.unreadable += 1;
76
+ }
77
+ }
78
+ candidates.sort((a, b) => a.modified.getTime() - b.modified.getTime());
79
+ for (const candidate of candidates) {
80
+ if (options.limit !== undefined && result.queued >= options.limit)
81
+ break;
82
+ try {
83
+ const [wire, state] = await Promise.all([
84
+ readFile(join(candidate.dir, 'agents', 'main', 'wire.jsonl'), 'utf8'),
85
+ readFile(join(candidate.dir, 'state.json'), 'utf8'),
86
+ ]);
87
+ const parsed = parseKimiSession(wire, state, candidate.dir);
88
+ if (!parsed.messages.some((message) => message.role === 'user') ||
89
+ !parsed.messages.some((message) => message.role === 'assistant')) {
90
+ result.skippedEmpty += 1;
91
+ continue;
92
+ }
93
+ result.queued += 1;
94
+ if (options.dryRun)
95
+ continue;
96
+ const queued = await enqueueSession(serializeAgentSession(parsed), {
97
+ queueDir: options.queueDir,
98
+ directory: parsed.directory,
99
+ source: KIMI_SOURCE,
100
+ agent: 'kimi',
101
+ maxLearnings: options.maxLearnings,
102
+ });
103
+ if (queued.created)
104
+ result.created += 1;
105
+ }
106
+ catch {
107
+ result.unreadable += 1;
108
+ }
109
+ }
110
+ return result;
111
+ }
@@ -0,0 +1,3 @@
1
+ import type { ParsedSession } from './session-parser.js';
2
+ /** Parse Kimi Code's documented session wire into the common agent transcript. */
3
+ export declare function parseKimiSession(wire: string, stateRaw: string, fallbackDirectory: string): ParsedSession;
@@ -0,0 +1,102 @@
1
+ function timestamp(value) {
2
+ if (value === undefined)
3
+ return undefined;
4
+ const numeric = typeof value === 'number' ? value : Number(value);
5
+ const date = Number.isFinite(numeric)
6
+ ? new Date(numeric < 10_000_000_000 ? numeric * 1_000 : numeric)
7
+ : new Date(String(value));
8
+ return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
9
+ }
10
+ function textParts(value) {
11
+ if (typeof value === 'string')
12
+ return value;
13
+ if (!Array.isArray(value))
14
+ return '';
15
+ return value
16
+ .map((part) => {
17
+ if (typeof part === 'string')
18
+ return part;
19
+ if (!part || typeof part !== 'object')
20
+ return '';
21
+ const record = part;
22
+ return !record.type || record.type === 'text' ? (record.text ?? '') : '';
23
+ })
24
+ .filter(Boolean)
25
+ .join('\n');
26
+ }
27
+ /** Parse Kimi Code's documented session wire into the common agent transcript. */
28
+ export function parseKimiSession(wire, stateRaw, fallbackDirectory) {
29
+ let state = {};
30
+ try {
31
+ state = JSON.parse(stateRaw);
32
+ }
33
+ catch {
34
+ // A partially-written state file must not hide an otherwise valid wire.
35
+ }
36
+ const messages = [];
37
+ let assistantText = [];
38
+ let assistantTimestamp;
39
+ let activeTurn;
40
+ const flushAssistant = () => {
41
+ const content = assistantText.join('').trim();
42
+ if (content)
43
+ messages.push({ role: 'assistant', content, timestamp: assistantTimestamp });
44
+ assistantText = [];
45
+ assistantTimestamp = undefined;
46
+ activeTurn = undefined;
47
+ };
48
+ for (const line of wire.split(/\r?\n/)) {
49
+ if (!line.trim())
50
+ continue;
51
+ let record;
52
+ try {
53
+ record = JSON.parse(line);
54
+ }
55
+ catch {
56
+ continue;
57
+ }
58
+ if (record.type === 'context.append_message') {
59
+ if (record.message?.role !== 'user' || record.message.origin?.kind !== 'user')
60
+ continue;
61
+ flushAssistant();
62
+ const content = textParts(record.message.content).trim();
63
+ const previous = messages.at(-1);
64
+ if (content && !(previous?.role === 'user' && previous.content === content)) {
65
+ messages.push({ role: 'user', content, timestamp: timestamp(record.time) });
66
+ }
67
+ continue;
68
+ }
69
+ // Older wires may have the prompt event without the mirrored context event.
70
+ if (record.type === 'turn.prompt' && record.origin?.kind === 'user') {
71
+ const content = textParts(record.input).trim();
72
+ const previous = messages.at(-1);
73
+ if (content && !(previous?.role === 'user' && previous.content === content)) {
74
+ flushAssistant();
75
+ messages.push({ role: 'user', content, timestamp: timestamp(record.time) });
76
+ }
77
+ continue;
78
+ }
79
+ if (record.type !== 'context.append_loop_event')
80
+ continue;
81
+ const event = record.event;
82
+ if (event?.type !== 'content.part' || event.part?.type !== 'text' || !event.part.text)
83
+ continue;
84
+ if (activeTurn && event.turnId && event.turnId !== activeTurn)
85
+ flushAssistant();
86
+ activeTurn = event.turnId ?? activeTurn;
87
+ assistantTimestamp ??= timestamp(record.time);
88
+ assistantText.push(event.part.text);
89
+ }
90
+ flushAssistant();
91
+ const occurredAt = [...messages]
92
+ .reverse()
93
+ .map((message) => message.timestamp ? new Date(message.timestamp) : undefined)
94
+ .find((date) => date && !Number.isNaN(date.getTime()));
95
+ return {
96
+ sessionId: state.id ?? 'kimi-unknown-session',
97
+ directory: state.cwd ?? fallbackDirectory,
98
+ messages,
99
+ rawText: messages.map((message) => `${message.role}: ${message.content}`).join('\n\n'),
100
+ occurredAt,
101
+ };
102
+ }
@@ -1,3 +1,4 @@
1
+ import { rename } from 'fs/promises';
1
2
  import type { LLMClient } from '../core/llm-generator.js';
2
3
  export interface MaintenanceJob {
3
4
  version: 1;
@@ -11,6 +12,10 @@ export interface MaintenanceJob {
11
12
  queuedAt: string;
12
13
  attempts: number;
13
14
  lastError?: string;
15
+ /** Set when the job was moved to dead-letter; absent on a live job. */
16
+ deadLetteredAt?: string;
17
+ /** Set when a dead-letter was put back in the queue by hand. */
18
+ requeuedAt?: string;
14
19
  }
15
20
  export interface EnqueueOptions {
16
21
  queueDir: string;
@@ -33,6 +38,11 @@ export interface WorkerOptions {
33
38
  maxJobs?: number;
34
39
  lockStaleMs?: number;
35
40
  maxAttempts?: number;
41
+ /**
42
+ * Consecutive job failures that trip the circuit breaker and end the pass.
43
+ * `false` disables the breaker. See `processMaintenanceQueue`.
44
+ */
45
+ failureThreshold?: number | false;
36
46
  now?: () => Date;
37
47
  }
38
48
  export interface WorkerResult {
@@ -42,6 +52,85 @@ export interface WorkerResult {
42
52
  deadLettered: number;
43
53
  memoriesStored: number;
44
54
  busy: boolean;
55
+ /** Failures that look like the machine, not the transcript — these cost no retry. */
56
+ infrastructureFailures: number;
57
+ /** Retries handed back because the failure was an outage rather than a bad job. */
58
+ retriesRefunded: number;
59
+ /** True when the circuit breaker cut the pass short instead of working the queue. */
60
+ aborted: boolean;
45
61
  }
62
+ /**
63
+ * Why a job failed, as far as the retry budget is concerned.
64
+ *
65
+ * `job` — this transcript is the problem, and every future pass will fail on it
66
+ * the same way. Retrying a few times then dead-lettering is right.
67
+ *
68
+ * `infrastructure` — the machine is the problem (the database will not open,
69
+ * the disk is full, the file is locked). Every job in the queue would fail the
70
+ * same way right now and all of them would succeed once the machine is fixed,
71
+ * so burning a retry punishes the session for an outage it had no part in.
72
+ */
73
+ export type FailureKind = 'job' | 'infrastructure';
74
+ /**
75
+ * Classify a failure so an outage does not consume the queue's retry budget.
76
+ *
77
+ * Deliberately biased towards `job`: mislabelling a bad transcript as an outage
78
+ * only costs a few wasted passes, while mislabelling an outage as a bad job
79
+ * dead-letters real sessions permanently. Anything not recognisably about the
80
+ * machine is therefore treated as being about the transcript.
81
+ */
82
+ export declare function classifyMaintenanceFailure(error: unknown): FailureKind;
83
+ export declare function atomicWrite(path: string, content: string, replace?: typeof rename): Promise<void>;
46
84
  export declare function enqueueSession(rawTranscript: string, options: EnqueueOptions): Promise<QueueResult>;
47
85
  export declare function processMaintenanceQueue(options: WorkerOptions): Promise<WorkerResult>;
86
+ export interface DeadLetter {
87
+ /** Filename in the queue directory, so a caller can name one precisely. */
88
+ file: string;
89
+ id: string;
90
+ /** Absent when the file could not be parsed — the bytes are still there. */
91
+ job?: MaintenanceJob;
92
+ sessionId?: string;
93
+ source?: string;
94
+ attempts?: number;
95
+ lastError?: string;
96
+ deadLetteredAt?: string;
97
+ }
98
+ export interface RequeueOptions {
99
+ queueDir: string;
100
+ /**
101
+ * Restrict to these dead-letters. Each entry matches a job id, a session id,
102
+ * or a filename. Omitted means every dead-letter in the directory.
103
+ */
104
+ ids?: string[];
105
+ /** Report what would happen and write nothing. */
106
+ dryRun?: boolean;
107
+ limit?: number;
108
+ now?: () => Date;
109
+ }
110
+ export interface RequeueResult {
111
+ scanned: number;
112
+ requeued: number;
113
+ /** A live job already holds the slot — the newer transcript wins, so the dead-letter is left alone. */
114
+ skippedLive: number;
115
+ /** The file is not a usable job; requeuing it would only dead-letter it again. */
116
+ unreadable: number;
117
+ /** What was (or would be) put back. */
118
+ entries: DeadLetter[];
119
+ }
120
+ /** Everything currently parked in dead-letter, newest failure first. */
121
+ export declare function listDeadLetters(queueDir: string): Promise<DeadLetter[]>;
122
+ /**
123
+ * Put dead-lettered jobs back in the queue with a fresh retry budget.
124
+ *
125
+ * Dead-lettering is not always a verdict on the transcript: before the retry
126
+ * budget learned to tell an outage from a bad job, a single unopenable database
127
+ * could park an entire afternoon of sessions in `.dead.json` files that nothing
128
+ * would ever look at again. This is the way back, and the reason the raw
129
+ * transcript is kept on disk rather than deleted.
130
+ *
131
+ * Restoring resets `attempts` to 0 — the point is a clean chance now that
132
+ * whatever broke has been fixed. A dead-letter whose slot is already held by a
133
+ * live job is left alone: that job carries a newer transcript for the same
134
+ * session and supersedes it.
135
+ */
136
+ export declare function requeueDeadLetters(options: RequeueOptions): Promise<RequeueResult>;