humemory 0.2.7 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/AGENTS.md +14 -7
  2. package/CHANGELOG.md +23 -0
  3. package/README.md +66 -12
  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 -1
  9. package/dist/agent/maintenance-queue.js +36 -62
  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/memory-routes.js +1 -1
  22. package/dist/api/server.js +3 -2
  23. package/dist/cli/index.js +117 -6
  24. package/dist/core/cues.d.ts +1 -0
  25. package/dist/core/cues.js +19 -7
  26. package/dist/core/doctor.d.ts +28 -0
  27. package/dist/core/doctor.js +320 -0
  28. package/dist/core/embeddings.d.ts +0 -10
  29. package/dist/core/embeddings.js +2 -1
  30. package/dist/core/hybrid.d.ts +7 -3
  31. package/dist/core/hybrid.js +7 -3
  32. package/dist/core/llm-generator.d.ts +2 -10
  33. package/dist/core/paths.d.ts +12 -0
  34. package/dist/core/paths.js +36 -0
  35. package/dist/core/project-path.d.ts +3 -0
  36. package/dist/core/project-path.js +14 -0
  37. package/dist/core/search.d.ts +1 -1
  38. package/dist/core/search.js +7 -9
  39. package/dist/core/types.d.ts +13 -1
  40. package/dist/index.d.ts +5 -0
  41. package/dist/index.js +5 -0
  42. package/dist/store/sqlite.d.ts +37 -0
  43. package/dist/store/sqlite.js +94 -42
  44. package/docs/PORTABILITY.md +84 -0
  45. package/package.json +5 -3
  46. package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
  47. package/public/app/index.html +1 -1
  48. package/scripts/consolidate.js +4 -4
  49. package/scripts/hook-post-commit.ts +2 -1
  50. package/scripts/hook-session-start.ts +2 -1
  51. package/scripts/hook-session.ts +2 -1
  52. package/scripts/maintenance-worker.ts +7 -2
  53. package/src/agent/claude-hook.ts +126 -0
  54. package/src/agent/codex-import.ts +129 -0
  55. package/src/agent/codex-rollout-parser.ts +121 -0
  56. package/src/agent/commit-closer.ts +173 -0
  57. package/src/agent/kimi-import.ts +128 -0
  58. package/src/agent/kimi-session-parser.ts +127 -0
  59. package/src/agent/learning-extractor.ts +128 -0
  60. package/src/agent/maintenance-queue.ts +544 -0
  61. package/src/agent/maintenance-runner.ts +322 -0
  62. package/src/agent/maintenance-state.ts +168 -0
  63. package/src/agent/mcp-client-setup.ts +125 -0
  64. package/src/agent/opencode-import.ts +96 -0
  65. package/src/agent/opencode-session-parser.ts +53 -0
  66. package/src/agent/session-context.ts +302 -0
  67. package/src/agent/session-parser.ts +155 -0
  68. package/src/agent/source-registry.ts +135 -0
  69. package/src/api/cors.ts +42 -0
  70. package/src/api/dream-routes.ts +46 -0
  71. package/src/api/errors.ts +45 -0
  72. package/src/api/intentions-routes.ts +348 -0
  73. package/src/api/limits.ts +90 -0
  74. package/src/api/maintenance-routes.ts +73 -0
  75. package/src/api/memory-routes.ts +391 -0
  76. package/src/api/scripts-routes.ts +176 -0
  77. package/src/api/security-headers.ts +54 -0
  78. package/src/api/server.ts +292 -0
  79. package/src/cli/index.ts +1195 -0
  80. package/src/core/clock.ts +64 -0
  81. package/src/core/cue-arg.ts +79 -0
  82. package/src/core/cues.ts +511 -0
  83. package/src/core/decay.ts +198 -0
  84. package/src/core/doctor.ts +362 -0
  85. package/src/core/dreamer.ts +494 -0
  86. package/src/core/embeddings.ts +157 -0
  87. package/src/core/event-bus.ts +100 -0
  88. package/src/core/hybrid.ts +82 -0
  89. package/src/core/llm-cli-client.ts +118 -0
  90. package/src/core/llm-generator.ts +90 -0
  91. package/src/core/paths.ts +38 -0
  92. package/src/core/project-path.ts +14 -0
  93. package/src/core/sanitize.ts +116 -0
  94. package/src/core/scripts.ts +112 -0
  95. package/src/core/search.ts +189 -0
  96. package/src/core/trust.ts +67 -0
  97. package/src/core/types.ts +393 -0
  98. package/src/core/vector-clusterer.ts +131 -0
  99. package/src/index.ts +40 -0
  100. package/src/mcp/HTTP_TRANSPORT.md +359 -0
  101. package/src/mcp/server.ts +202 -0
  102. package/src/store/sqlite.ts +1958 -0
package/AGENTS.md CHANGED
@@ -24,7 +24,7 @@ On top of both: a **trust layer** (Phase 6) so several agents can write to one
24
24
  store without a wrong lesson becoming indestructible, a **dreamer** (6.1) that
25
25
  proposes cross-session/cross-agent patterns for human review, an **MCP server**
26
26
  (6.2) so Claude/Codex/Kimi/OpenCode share one memory, and **vector search**
27
- (Phase 7) as an opt-in second retrieval lane alongside BM25.
27
+ (Phase 7) as an opt-in second retrieval lane alongside the lexical one.
28
28
 
29
29
  The conceptual source for the prospective half is `SCRATCHPAD.md` (memoire
30
30
  prospective, scripts cognitifs, effet Zeigarnik).
@@ -61,16 +61,19 @@ src/
61
61
  ├── core/
62
62
  │ ├── types.ts # Memory, DecayLevel, SearchQuery, MemoryStore iface
63
63
  │ ├── decay.ts # degradation curve + thresholds
64
- │ ├── search.ts # inverse search (BM25, degraded-first)
64
+ │ ├── search.ts # inverse search (lexical, degraded-first)
65
65
  │ └── llm-generator.ts # deterministic L1/L2/L3; optional injected LLM
66
66
  ├── store/
67
67
  │ └── sqlite.ts # bun:sqlite store (WAL), findSimilar/merge/setPhotographic
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)
@@ -78,6 +81,8 @@ src/
78
81
  │ ├── clock.ts # Clock seam (systemClock / FakeClock)
79
82
  │ ├── event-bus.ts # AppEvent + InMemoryEventBus
80
83
  │ ├── cue-arg.ts # cue syntax, shared by the CLI and the React form
84
+ │ ├── paths.ts # single resolver for data/db/queue/model-cache/install root
85
+ │ ├── doctor.ts # install diagnostic behind `humemory doctor` (no content read)
81
86
  │ └── cues.ts # cue resolver, cron matcher, loop ids
82
87
  ├── api/server.ts # Hono HTTP API + serves public/ dashboard
83
88
  ├── cli/index.ts # commander CLI
@@ -86,8 +91,9 @@ web/ # React front (bun bundler → public/app, served at /
86
91
  scripts/hook-session.ts # Claude Code Stop hook → queue raw session only
87
92
  scripts/hook-session-start.ts # Claude Code SessionStart hook → inject context
88
93
  scripts/maintenance-worker.ts # async extraction/storage; deterministic by default
94
+ scripts/verify-package.ts # packs, installs outside the checkout, drives every entry point
89
95
  tests/ # bun test (hermetic; helpers/ + fixtures/)
90
- data/humemory.db # shared DB (created on first run)
96
+ data/humemory.db # legacy in-checkout DB; new installs use the OS data dir (core/paths.ts)
91
97
  ```
92
98
 
93
99
  ---
@@ -271,8 +277,9 @@ Claude, Codex, Kimi, OpenCode share one store with agent attribution on every
271
277
  write (`agent` arg or `$HUMEMORY_AGENT`; `HUMEMORY_DB` override for tests).
272
278
 
273
279
  **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:
280
+ scope, `HUMEMORY_AGENT=claude`). `pnpm cli sources setup` merge-registers the
281
+ same server in installed Kimi Code and OpenCode configs without removing other
282
+ MCP servers, using the identities below:
276
283
 
277
284
  | Agent | Config | `HUMEMORY_AGENT` |
278
285
  |-------|--------|------------------|
@@ -353,7 +360,7 @@ accepts a script id as the loser. API: `POST/GET /scripts`,
353
360
  [PHASE7_DIALOG.md](./PHASE7_DIALOG.md)
354
361
  - Multi-device sync of the shared store (the `device` column from 6.0.1 makes
355
362
  it migration-free; conflict policy TBD)
356
- - OpenCode / other-agent integration; export/import memories between projects
363
+ - Other-agent integration; export/import memories between projects
357
364
 
358
365
  ---
359
366
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.9] - 2026-09-07
4
+ **Features:**
5
+ - diagnose an installation, and prove the packaged one
6
+
7
+ **Bug Fixes:**
8
+ - make audit validation deterministic and isolated
9
+ - spawn the pnpm/npm shims through a shell on Windows
10
+ - pull fast-uri onto a patched 3.x
11
+
12
+ **Documentation:**
13
+ - record the remediation status in the portability audit
14
+
15
+ **Chores:**
16
+ - drop the dead lockStaleMs knob
17
+
18
+
19
+
20
+ ## [0.2.8] - 2026-09-06
21
+ **Other:**
22
+ - Add comprehensive tests for audit, maintenance, and import functionalities
23
+
24
+
25
+
3
26
  ## [0.2.7] - 2026-08-27
4
27
  **Bug Fixes:**
5
28
  - spend retries on bad jobs, not on outages (#2)
package/README.md CHANGED
@@ -28,7 +28,7 @@ Past learnings are **encoded**, then **degraded** over time on a human curve:
28
28
  | L0 | full detail | fresh (<24h) | complete content |
29
29
  | L1 | summary | days | LLM-generated résumé |
30
30
  | L2 | essential | weeks | the gist |
31
- | L3 | keywords | months | BM25 retrieval tokens |
31
+ | L3 | keywords | months | lexical retrieval tokens |
32
32
  | L4 | lost / merged | beyond | folded into a sibling trace |
33
33
 
34
34
  Recall resists decay. Saillance (mnemonic strength, 0–100) and recall count slow
@@ -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,13 +333,15 @@ 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
 
331
- TypeScript · `bun:sqlite` (WAL) · `flexsearch` (BM25) · `hono` (API) ·
343
+ TypeScript · `bun:sqlite` (WAL) · `flexsearch` (lexical index, heuristic
344
+ ranking — not a BM25 implementation) · `hono` (API) ·
332
345
  `commander` (CLI) · `@anthropic-ai/sdk` (optional maintenance adapter).
333
346
 
334
347
  ---
@@ -341,6 +354,22 @@ TypeScript · `bun:sqlite` (WAL) · `flexsearch` (BM25) · `hono` (API) ·
341
354
  pnpm install
342
355
  ```
343
356
 
357
+ New installations keep writable state in the user profile. Existing checkouts
358
+ with `data/humemory.db` keep that location; nothing is moved automatically.
359
+ `HUMEMORY_DATA_DIR` selects another data root, while `HUMEMORY_DB`,
360
+ `HUMEMORY_QUEUE` and `HUMEMORY_MODEL_CACHE` override individual locations.
361
+
362
+ To relocate a project's memory, preview the mapping before applying it:
363
+
364
+ ```bash
365
+ pnpm cli remap-project /old/project /new/project
366
+ pnpm cli remap-project /old/project /new/project --apply --backup /backups/before-remap.db
367
+ ```
368
+
369
+ The backup includes committed SQLite WAL contents. See
370
+ [portability and recovery guarantees](docs/PORTABILITY.md) for cron time zones,
371
+ model downloads, queue recovery and the limits of the platform checks.
372
+
344
373
  ### CLI Commands
345
374
 
346
375
  The CLI provides several commands to interact with humemory:
@@ -434,6 +463,18 @@ The CLI provides several commands to interact with humemory:
434
463
  - `-d, --directory <dir>`: Project mental space
435
464
  - `-n, --max <n>`: Max learnings to extract
436
465
 
466
+ - **Diagnose the installation**:
467
+ ```bash
468
+ pnpm cli doctor
469
+ ```
470
+ Prints the runtime, the resolved data/queue/model paths and whether they are
471
+ writable, the schema and journal mode, the state of both advisory locks, the
472
+ cached embedding models, and every auxiliary entry point (hooks, MCP server,
473
+ API, dashboard). Environment overrides are listed **by name only** — no value
474
+ is printed, and no memory content is read, so the output is safe to paste into
475
+ a bug report. `--json` for a machine-readable report; exit code 1 on a real
476
+ fault, 0 when everything that failed is merely "not set up yet".
477
+
437
478
  ### API
438
479
 
439
480
  Start the API server:
@@ -570,6 +611,19 @@ pnpm cli <command>
570
611
  pnpm consolidate
571
612
  ```
572
613
 
614
+ ### Verifying the published package
615
+
616
+ ```bash
617
+ pnpm verify:package
618
+ ```
619
+
620
+ Builds the archive, installs it into a temporary directory **outside** the
621
+ checkout — under a path containing a space and an accent — and drives the CLI,
622
+ the Stop hook, maintenance, the MCP server and the API from there against a
623
+ virgin profile. Nothing may reach back into the source tree, so a `files` list
624
+ that forgets a source an auxiliary entry point imports fails here rather than
625
+ days later on a user's machine. Runs on Linux, macOS and Windows in CI.
626
+
573
627
  ---
574
628
 
575
629
  ## Concepts
@@ -626,7 +680,7 @@ keywords >5. `photographic: true` disables decay entirely.
626
680
 
627
681
  ### 🛣️ Beyond
628
682
  - Shared multi-project DB with concurrency lock (WAL + advisory) — done (Sprint 5 / S5-00a)
629
- - OpenCode / other-agent integration; export/import memories between projects
683
+ - Other-agent import adapters; export/import memories between projects
630
684
 
631
685
  ---
632
686
 
@@ -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;
@@ -35,7 +36,6 @@ export interface WorkerOptions {
35
36
  client?: LLMClient;
36
37
  llmTimeoutMs?: number;
37
38
  maxJobs?: number;
38
- lockStaleMs?: number;
39
39
  maxAttempts?: number;
40
40
  /**
41
41
  * Consecutive job failures that trip the circuit breaker and end the pass.
@@ -79,6 +79,7 @@ export type FailureKind = 'job' | 'infrastructure';
79
79
  * machine is therefore treated as being about the transcript.
80
80
  */
81
81
  export declare function classifyMaintenanceFailure(error: unknown): FailureKind;
82
+ export declare function atomicWrite(path: string, content: string, replace?: typeof rename): Promise<void>;
82
83
  export declare function enqueueSession(rawTranscript: string, options: EnqueueOptions): Promise<QueueResult>;
83
84
  export declare function processMaintenanceQueue(options: WorkerOptions): Promise<WorkerResult>;
84
85
  export interface DeadLetter {
@@ -1,9 +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
- const DEFAULT_LOCK_STALE_MS = 5 * 60 * 1000;
6
+ import { AdvisoryLock } from '../store/sqlite.js';
7
7
  const DEFAULT_MAX_ATTEMPTS = 5;
8
8
  const DEFAULT_FAILURE_THRESHOLD = 3;
9
9
  const DEAD_LETTER_SUFFIX = '.dead.json';
@@ -83,17 +83,16 @@ async function readCheckpoint(queueDir, id) {
83
83
  return null;
84
84
  }
85
85
  }
86
- async function atomicWrite(path, content) {
87
- const temporary = `${path}.${process.pid}.tmp`;
86
+ export async function atomicWrite(path, content, replace = rename) {
87
+ const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
88
88
  await writeFile(temporary, content, { encoding: 'utf8', mode: 0o600 });
89
89
  try {
90
- await rename(temporary, path);
90
+ await replace(temporary, path);
91
91
  }
92
92
  catch (error) {
93
- if (error?.code !== 'EEXIST' && error?.code !== 'EPERM')
94
- throw error;
95
- await rm(path, { force: true });
96
- await rename(temporary, path);
93
+ // Leave the destination intact and the complete temporary recoverable.
94
+ // Never emulate replacement by deleting the only acknowledged version.
95
+ throw error;
97
96
  }
98
97
  }
99
98
  export async function enqueueSession(rawTranscript, options) {
@@ -123,55 +122,40 @@ export async function enqueueSession(rawTranscript, options) {
123
122
  attempts: 0,
124
123
  };
125
124
  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 };
125
+ return new AdvisoryLock(path + '.enqueue', 50).withLock(async () => {
126
+ let created = true;
127
+ try {
128
+ const previous = JSON.parse(await readFile(path, 'utf8'));
129
+ created = false;
130
+ const previousMessages = parseAgentSession(previous.rawTranscript, previous.directory).messages.length;
131
+ if (previousMessages > parsed.messages.length ||
132
+ (previousMessages === parsed.messages.length && previous.rawTranscript.length > rawTranscript.length)) {
133
+ return { job: previous, created: false, path };
134
+ }
135
+ }
136
+ catch (error) {
137
+ if (error?.code !== 'ENOENT')
138
+ throw error;
139
+ }
140
+ await atomicWrite(path, JSON.stringify(job));
141
+ return { job, created, path };
142
+ });
137
143
  }
138
144
  export async function processMaintenanceQueue(options) {
139
145
  await mkdir(options.queueDir, { recursive: true });
140
146
  await mkdir(join(options.queueDir, CHECKPOINT_DIR), { recursive: true });
141
147
  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
- }
148
+ // Ownership is an OS-backed SQLite lock, with no wall-clock expiry. A slow
149
+ // worker retains it; a killed worker releases it without a lease takeover race.
150
+ const lock = new AdvisoryLock(join(options.queueDir, '.worker-lock'), 1);
151
+ try {
152
+ await lock.acquire();
153
+ }
154
+ catch (error) {
155
+ if (error?.code === 'SQLITE_BUSY')
170
156
  return { ...emptyResult(), busy: true };
171
- }
157
+ throw error;
172
158
  }
173
- if (!lock)
174
- return { ...emptyResult(), busy: true };
175
159
  try {
176
160
  const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
177
161
  // We hold the exclusive lock, so any leftover `.processing` file belongs to
@@ -328,17 +312,7 @@ export async function processMaintenanceQueue(options) {
328
312
  return result;
329
313
  }
330
314
  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
- }
315
+ lock.release();
342
316
  }
343
317
  }
344
318
  function toDeadLetter(file, raw) {