humemory 0.2.7 → 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 (94) hide show
  1. package/AGENTS.md +8 -4
  2. package/CHANGELOG.md +6 -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 +2 -0
  9. package/dist/agent/maintenance-queue.js +36 -61
  10. package/dist/agent/maintenance-runner.d.ts +17 -4
  11. package/dist/agent/maintenance-runner.js +45 -10
  12. package/dist/agent/mcp-client-setup.d.ts +16 -0
  13. package/dist/agent/mcp-client-setup.js +108 -0
  14. package/dist/agent/opencode-import.d.ts +22 -0
  15. package/dist/agent/opencode-import.js +71 -0
  16. package/dist/agent/opencode-session-parser.d.ts +3 -0
  17. package/dist/agent/opencode-session-parser.js +35 -0
  18. package/dist/agent/session-parser.d.ts +8 -0
  19. package/dist/agent/session-parser.js +18 -0
  20. package/dist/agent/source-registry.js +1 -1
  21. package/dist/api/server.js +3 -2
  22. package/dist/cli/index.js +96 -4
  23. package/dist/core/cues.d.ts +1 -0
  24. package/dist/core/cues.js +19 -7
  25. package/dist/core/embeddings.d.ts +0 -10
  26. package/dist/core/embeddings.js +2 -1
  27. package/dist/core/llm-generator.d.ts +2 -10
  28. package/dist/core/paths.d.ts +5 -0
  29. package/dist/core/paths.js +27 -0
  30. package/dist/core/project-path.d.ts +3 -0
  31. package/dist/core/project-path.js +14 -0
  32. package/dist/core/search.d.ts +1 -1
  33. package/dist/core/search.js +7 -9
  34. package/dist/core/types.d.ts +13 -1
  35. package/dist/index.d.ts +5 -0
  36. package/dist/index.js +5 -0
  37. package/dist/store/sqlite.d.ts +37 -0
  38. package/dist/store/sqlite.js +94 -42
  39. package/package.json +4 -3
  40. package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
  41. package/public/app/index.html +1 -1
  42. package/scripts/consolidate.js +4 -4
  43. package/scripts/hook-post-commit.ts +2 -1
  44. package/scripts/hook-session-start.ts +2 -1
  45. package/scripts/hook-session.ts +2 -1
  46. package/src/agent/claude-hook.ts +126 -0
  47. package/src/agent/codex-import.ts +129 -0
  48. package/src/agent/codex-rollout-parser.ts +121 -0
  49. package/src/agent/commit-closer.ts +173 -0
  50. package/src/agent/kimi-import.ts +128 -0
  51. package/src/agent/kimi-session-parser.ts +127 -0
  52. package/src/agent/learning-extractor.ts +128 -0
  53. package/src/agent/maintenance-queue.ts +546 -0
  54. package/src/agent/maintenance-runner.ts +322 -0
  55. package/src/agent/maintenance-state.ts +168 -0
  56. package/src/agent/mcp-client-setup.ts +125 -0
  57. package/src/agent/opencode-import.ts +96 -0
  58. package/src/agent/opencode-session-parser.ts +53 -0
  59. package/src/agent/session-context.ts +302 -0
  60. package/src/agent/session-parser.ts +155 -0
  61. package/src/agent/source-registry.ts +135 -0
  62. package/src/api/cors.ts +42 -0
  63. package/src/api/dream-routes.ts +46 -0
  64. package/src/api/errors.ts +45 -0
  65. package/src/api/intentions-routes.ts +348 -0
  66. package/src/api/limits.ts +90 -0
  67. package/src/api/maintenance-routes.ts +73 -0
  68. package/src/api/memory-routes.ts +391 -0
  69. package/src/api/scripts-routes.ts +176 -0
  70. package/src/api/security-headers.ts +54 -0
  71. package/src/api/server.ts +292 -0
  72. package/src/cli/index.ts +1175 -0
  73. package/src/core/clock.ts +64 -0
  74. package/src/core/cue-arg.ts +79 -0
  75. package/src/core/cues.ts +511 -0
  76. package/src/core/decay.ts +198 -0
  77. package/src/core/dreamer.ts +494 -0
  78. package/src/core/embeddings.ts +157 -0
  79. package/src/core/event-bus.ts +100 -0
  80. package/src/core/hybrid.ts +78 -0
  81. package/src/core/llm-cli-client.ts +118 -0
  82. package/src/core/llm-generator.ts +90 -0
  83. package/src/core/paths.ts +28 -0
  84. package/src/core/project-path.ts +14 -0
  85. package/src/core/sanitize.ts +116 -0
  86. package/src/core/scripts.ts +112 -0
  87. package/src/core/search.ts +189 -0
  88. package/src/core/trust.ts +67 -0
  89. package/src/core/types.ts +393 -0
  90. package/src/core/vector-clusterer.ts +131 -0
  91. package/src/index.ts +40 -0
  92. package/src/mcp/HTTP_TRANSPORT.md +359 -0
  93. package/src/mcp/server.ts +202 -0
  94. package/src/store/sqlite.ts +1958 -0
package/AGENTS.md CHANGED
@@ -68,9 +68,12 @@ src/
68
68
  ├── agent/
69
69
  │ ├── session-parser.ts # parse Claude Code session transcripts
70
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
71
74
  │ ├── learning-extractor.ts # extract decisions/bugs/solutions
72
75
  │ ├── maintenance-queue.ts # durable async inbox, checkpoints, retry policy, dead-letter
73
- │ ├── maintenance-runner.ts # one pass (codex import + drain), and the in-API loop
76
+ │ ├── maintenance-runner.ts # one pass (Codex/Kimi/OpenCode import + drain), in-API loop
74
77
  │ ├── maintenance-state.ts # durable health record of the loop (data/maintenance-state.json)
75
78
  │ ├── claude-hook.ts # worker-side session learning encoder
76
79
  │ └── session-context.ts # SessionStart → markdown block (open loops + traces)
@@ -271,8 +274,9 @@ Claude, Codex, Kimi, OpenCode share one store with agent attribution on every
271
274
  write (`agent` arg or `$HUMEMORY_AGENT`; `HUMEMORY_DB` override for tests).
272
275
 
273
276
  **Client registration** — the repo ships `.mcp.json` (Claude Code project
274
- scope, `HUMEMORY_AGENT=claude`). For other agents, register the same server
275
- 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:
276
280
 
277
281
  | Agent | Config | `HUMEMORY_AGENT` |
278
282
  |-------|--------|------------------|
@@ -353,7 +357,7 @@ accepts a script id as the loser. API: `POST/GET /scripts`,
353
357
  [PHASE7_DIALOG.md](./PHASE7_DIALOG.md)
354
358
  - Multi-device sync of the shared store (the `device` column from 6.0.1 makes
355
359
  it migration-free; conflict policy TBD)
356
- - OpenCode / other-agent integration; export/import memories between projects
360
+ - Other-agent integration; export/import memories between projects
357
361
 
358
362
  ---
359
363
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
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
+
3
9
  ## [0.2.7] - 2026-08-27
4
10
  **Bug Fixes:**
5
11
  - spend retries on bad jobs, not on outages (#2)
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;
@@ -79,6 +80,7 @@ export type FailureKind = 'job' | 'infrastructure';
79
80
  * machine is therefore treated as being about the transcript.
80
81
  */
81
82
  export declare function classifyMaintenanceFailure(error: unknown): FailureKind;
83
+ export declare function atomicWrite(path: string, content: string, replace?: typeof rename): Promise<void>;
82
84
  export declare function enqueueSession(rawTranscript: string, options: EnqueueOptions): Promise<QueueResult>;
83
85
  export declare function processMaintenanceQueue(options: WorkerOptions): Promise<WorkerResult>;
84
86
  export interface DeadLetter {
@@ -1,8 +1,9 @@
1
1
  import { createHash, randomUUID } from 'crypto';
2
- import { mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from 'fs/promises';
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;
8
9
  const DEFAULT_FAILURE_THRESHOLD = 3;
@@ -83,17 +84,16 @@ async function readCheckpoint(queueDir, id) {
83
84
  return null;
84
85
  }
85
86
  }
86
- async function atomicWrite(path, content) {
87
- const temporary = `${path}.${process.pid}.tmp`;
87
+ export async function atomicWrite(path, content, replace = rename) {
88
+ const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
88
89
  await writeFile(temporary, content, { encoding: 'utf8', mode: 0o600 });
89
90
  try {
90
- await rename(temporary, path);
91
+ await replace(temporary, path);
91
92
  }
92
93
  catch (error) {
93
- if (error?.code !== 'EEXIST' && error?.code !== 'EPERM')
94
- throw error;
95
- await rm(path, { force: true });
96
- 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;
97
97
  }
98
98
  }
99
99
  export async function enqueueSession(rawTranscript, options) {
@@ -123,55 +123,40 @@ export async function enqueueSession(rawTranscript, options) {
123
123
  attempts: 0,
124
124
  };
125
125
  await mkdir(options.queueDir, { recursive: true });
126
- let created = true;
127
- try {
128
- await readFile(path, 'utf8');
129
- created = false;
130
- }
131
- catch (error) {
132
- if (error?.code !== 'ENOENT')
133
- throw error;
134
- }
135
- await atomicWrite(path, JSON.stringify(job));
136
- return { job, created, path };
126
+ return new AdvisoryLock(path + '.enqueue', 50).withLock(async () => {
127
+ let created = true;
128
+ try {
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
+ }
136
+ }
137
+ catch (error) {
138
+ if (error?.code !== 'ENOENT')
139
+ throw error;
140
+ }
141
+ await atomicWrite(path, JSON.stringify(job));
142
+ return { job, created, path };
143
+ });
137
144
  }
138
145
  export async function processMaintenanceQueue(options) {
139
146
  await mkdir(options.queueDir, { recursive: true });
140
147
  await mkdir(join(options.queueDir, CHECKPOINT_DIR), { recursive: true });
141
148
  const now = options.now ?? (() => new Date());
142
- const lockPath = join(options.queueDir, '.worker.lock');
143
- const token = `${process.pid}-${randomUUID()}`;
144
- let lock;
145
- for (let attempt = 0; attempt < 2; attempt += 1) {
146
- try {
147
- lock = await open(lockPath, 'wx', 0o600);
148
- await lock.writeFile(JSON.stringify({ pid: process.pid, token, startedAt: now().toISOString() }));
149
- break;
150
- }
151
- catch (error) {
152
- if (error?.code !== 'EEXIST')
153
- throw error;
154
- const age = now().getTime() - (await stat(lockPath)).mtimeMs;
155
- if (attempt === 0 && age > (options.lockStaleMs ?? DEFAULT_LOCK_STALE_MS)) {
156
- // Atomic takeover: renaming the stale lock away can only succeed once,
157
- // so two workers seeing the same stale lock cannot both reclaim it. A
158
- // plain unlink would instead delete a lock the winner just acquired.
159
- try {
160
- await rename(lockPath, `${lockPath}.stale.${token}`);
161
- await rm(`${lockPath}.stale.${token}`, { force: true });
162
- }
163
- catch (renameError) {
164
- if (renameError?.code !== 'ENOENT')
165
- throw renameError;
166
- // Another worker won the takeover; the retry below will see its lock.
167
- }
168
- continue;
169
- }
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')
170
157
  return { ...emptyResult(), busy: true };
171
- }
158
+ throw error;
172
159
  }
173
- if (!lock)
174
- return { ...emptyResult(), busy: true };
175
160
  try {
176
161
  const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
177
162
  // We hold the exclusive lock, so any leftover `.processing` file belongs to
@@ -328,17 +313,7 @@ export async function processMaintenanceQueue(options) {
328
313
  return result;
329
314
  }
330
315
  finally {
331
- await lock.close();
332
- // Only release a lock still held by this worker: if ours went stale and was
333
- // reclaimed, the file now belongs to whoever took over.
334
- try {
335
- const held = JSON.parse(await readFile(lockPath, 'utf8'));
336
- if (held?.token === token)
337
- await rm(lockPath, { force: true });
338
- }
339
- catch {
340
- // Already gone or unreadable — nothing of ours left to release.
341
- }
316
+ lock.release();
342
317
  }
343
318
  }
344
319
  function toDeadLetter(file, raw) {
@@ -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. A failing codex import is contained: a
54
- * missing or unreadable codex must never stall the queue, which holds sessions
55
- * from every other source.
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, join } from 'path';
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 process.env.HUMEMORY_QUEUE ?? join(__dirname, '../../data/maintenance-queue');
29
+ return queueDirectory();
27
30
  }
28
31
  export function defaultDbPath() {
29
- return process.env.HUMEMORY_DB ?? join(__dirname, '../../data/humemory.db');
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. A failing codex import is contained: a
58
- * missing or unreadable codex must never stall the queue, which holds sessions
59
- * from every other source.
60
+ * 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 sinceDays = options.codexSinceDays ?? 1;
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 (sinceDays !== false) {
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() - sinceDays * 24 * 60 * 60 * 1000),
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,
@@ -119,7 +154,7 @@ export async function runMaintenancePass(options = {}) {
119
154
  aborted: worker.aborted,
120
155
  },
121
156
  });
122
- return { codex, codexError, worker };
157
+ return { codex, codexError, kimi, kimiError, opencode, opencodeError, worker };
123
158
  }
124
159
  catch (error) {
125
160
  await recordMaintenanceRun({ path: statePath, startedAt, clock, runner: options.runner, error });