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
@@ -0,0 +1,128 @@
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
+
9
+ export const KIMI_SOURCE = 'kimi-code-session';
10
+
11
+ export interface KimiImportOptions {
12
+ queueDir: string;
13
+ kimiHome?: string;
14
+ since?: Date;
15
+ limit?: number;
16
+ dryRun?: boolean;
17
+ maxLearnings?: number;
18
+ }
19
+
20
+ export interface KimiImportResult {
21
+ scanned: number;
22
+ queued: number;
23
+ created: number;
24
+ skippedEmpty: number;
25
+ skippedOld: number;
26
+ unreadable: number;
27
+ }
28
+
29
+ interface KimiIndexEntry {
30
+ sessionDir?: string;
31
+ }
32
+
33
+ export function defaultKimiHome(): string {
34
+ return process.env.KIMI_CODE_HOME ?? join(homedir(), '.kimi-code');
35
+ }
36
+
37
+ async function discoverFromIndex(kimiHome: string): Promise<string[]> {
38
+ try {
39
+ const raw = await readFile(join(kimiHome, 'session_index.jsonl'), 'utf8');
40
+ const found: string[] = [];
41
+ for (const line of raw.split(/\r?\n/)) {
42
+ if (!line.trim()) continue;
43
+ try {
44
+ const entry = JSON.parse(line) as KimiIndexEntry;
45
+ if (!entry.sessionDir) continue;
46
+ found.push(isAbsolute(entry.sessionDir) ? entry.sessionDir : resolve(kimiHome, entry.sessionDir));
47
+ } catch {
48
+ // One partially-written index line does not invalidate earlier sessions.
49
+ }
50
+ }
51
+ return found;
52
+ } catch {
53
+ return [];
54
+ }
55
+ }
56
+
57
+ async function discoverByState(dir: string): Promise<string[]> {
58
+ let entries;
59
+ try {
60
+ entries = await readdir(dir, { withFileTypes: true });
61
+ } catch {
62
+ return [];
63
+ }
64
+ if (entries.some((entry) => entry.isFile() && entry.name === 'state.json')) return [dir];
65
+ const found: string[] = [];
66
+ for (const entry of entries) {
67
+ if (entry.isDirectory()) found.push(...await discoverByState(join(dir, entry.name)));
68
+ }
69
+ return found;
70
+ }
71
+
72
+ export async function importKimiSessions(options: KimiImportOptions): Promise<KimiImportResult> {
73
+ const kimiHome = options.kimiHome ?? defaultKimiHome();
74
+ const indexed = await discoverFromIndex(kimiHome);
75
+ const sessionDirs = [...new Set(indexed.length ? indexed : await discoverByState(join(kimiHome, 'sessions')))];
76
+ const candidates: Array<{ dir: string; modified: Date }> = [];
77
+ const result: KimiImportResult = {
78
+ scanned: sessionDirs.length,
79
+ queued: 0,
80
+ created: 0,
81
+ skippedEmpty: 0,
82
+ skippedOld: 0,
83
+ unreadable: 0,
84
+ };
85
+
86
+ for (const dir of sessionDirs) {
87
+ try {
88
+ const modified = (await stat(join(dir, 'agents', 'main', 'wire.jsonl'))).mtime;
89
+ if (options.since && modified < options.since) {
90
+ result.skippedOld += 1;
91
+ continue;
92
+ }
93
+ candidates.push({ dir, modified });
94
+ } catch {
95
+ result.unreadable += 1;
96
+ }
97
+ }
98
+
99
+ candidates.sort((a, b) => a.modified.getTime() - b.modified.getTime());
100
+ for (const candidate of candidates) {
101
+ if (options.limit !== undefined && result.queued >= options.limit) break;
102
+ try {
103
+ const [wire, state] = await Promise.all([
104
+ readFile(join(candidate.dir, 'agents', 'main', 'wire.jsonl'), 'utf8'),
105
+ readFile(join(candidate.dir, 'state.json'), 'utf8'),
106
+ ]);
107
+ const parsed = parseKimiSession(wire, state, candidate.dir);
108
+ if (!parsed.messages.some((message) => message.role === 'user') ||
109
+ !parsed.messages.some((message) => message.role === 'assistant')) {
110
+ result.skippedEmpty += 1;
111
+ continue;
112
+ }
113
+ result.queued += 1;
114
+ if (options.dryRun) continue;
115
+ const queued = await enqueueSession(serializeAgentSession(parsed), {
116
+ queueDir: options.queueDir,
117
+ directory: parsed.directory,
118
+ source: KIMI_SOURCE,
119
+ agent: 'kimi',
120
+ maxLearnings: options.maxLearnings,
121
+ });
122
+ if (queued.created) result.created += 1;
123
+ } catch {
124
+ result.unreadable += 1;
125
+ }
126
+ }
127
+ return result;
128
+ }
@@ -0,0 +1,127 @@
1
+ import type { ParsedSession, SessionMessage } from './session-parser.js';
2
+
3
+ interface KimiWireRecord {
4
+ type?: string;
5
+ time?: number | string;
6
+ input?: unknown;
7
+ origin?: { kind?: string };
8
+ message?: {
9
+ role?: string;
10
+ origin?: { kind?: string };
11
+ content?: unknown;
12
+ };
13
+ event?: {
14
+ type?: string;
15
+ turnId?: string;
16
+ part?: { type?: string; text?: string };
17
+ };
18
+ }
19
+
20
+ interface KimiState {
21
+ id?: string;
22
+ cwd?: string;
23
+ }
24
+
25
+ function timestamp(value: number | string | undefined): string | undefined {
26
+ if (value === undefined) return undefined;
27
+ const numeric = typeof value === 'number' ? value : Number(value);
28
+ const date = Number.isFinite(numeric)
29
+ ? new Date(numeric < 10_000_000_000 ? numeric * 1_000 : numeric)
30
+ : new Date(String(value));
31
+ return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
32
+ }
33
+
34
+ function textParts(value: unknown): string {
35
+ if (typeof value === 'string') return value;
36
+ if (!Array.isArray(value)) return '';
37
+ return value
38
+ .map((part) => {
39
+ if (typeof part === 'string') return part;
40
+ if (!part || typeof part !== 'object') return '';
41
+ const record = part as { type?: string; text?: string };
42
+ return !record.type || record.type === 'text' ? (record.text ?? '') : '';
43
+ })
44
+ .filter(Boolean)
45
+ .join('\n');
46
+ }
47
+
48
+ /** Parse Kimi Code's documented session wire into the common agent transcript. */
49
+ export function parseKimiSession(
50
+ wire: string,
51
+ stateRaw: string,
52
+ fallbackDirectory: string,
53
+ ): ParsedSession {
54
+ let state: KimiState = {};
55
+ try {
56
+ state = JSON.parse(stateRaw) as KimiState;
57
+ } catch {
58
+ // A partially-written state file must not hide an otherwise valid wire.
59
+ }
60
+
61
+ const messages: SessionMessage[] = [];
62
+ let assistantText: string[] = [];
63
+ let assistantTimestamp: string | undefined;
64
+ let activeTurn: string | undefined;
65
+
66
+ const flushAssistant = () => {
67
+ const content = assistantText.join('').trim();
68
+ if (content) messages.push({ role: 'assistant', content, timestamp: assistantTimestamp });
69
+ assistantText = [];
70
+ assistantTimestamp = undefined;
71
+ activeTurn = undefined;
72
+ };
73
+
74
+ for (const line of wire.split(/\r?\n/)) {
75
+ if (!line.trim()) continue;
76
+ let record: KimiWireRecord;
77
+ try {
78
+ record = JSON.parse(line) as KimiWireRecord;
79
+ } catch {
80
+ continue;
81
+ }
82
+
83
+ if (record.type === 'context.append_message') {
84
+ if (record.message?.role !== 'user' || record.message.origin?.kind !== 'user') continue;
85
+ flushAssistant();
86
+ const content = textParts(record.message.content).trim();
87
+ const previous = messages.at(-1);
88
+ if (content && !(previous?.role === 'user' && previous.content === content)) {
89
+ messages.push({ role: 'user', content, timestamp: timestamp(record.time) });
90
+ }
91
+ continue;
92
+ }
93
+
94
+ // Older wires may have the prompt event without the mirrored context event.
95
+ if (record.type === 'turn.prompt' && record.origin?.kind === 'user') {
96
+ const content = textParts(record.input).trim();
97
+ const previous = messages.at(-1);
98
+ if (content && !(previous?.role === 'user' && previous.content === content)) {
99
+ flushAssistant();
100
+ messages.push({ role: 'user', content, timestamp: timestamp(record.time) });
101
+ }
102
+ continue;
103
+ }
104
+
105
+ if (record.type !== 'context.append_loop_event') continue;
106
+ const event = record.event;
107
+ if (event?.type !== 'content.part' || event.part?.type !== 'text' || !event.part.text) continue;
108
+ if (activeTurn && event.turnId && event.turnId !== activeTurn) flushAssistant();
109
+ activeTurn = event.turnId ?? activeTurn;
110
+ assistantTimestamp ??= timestamp(record.time);
111
+ assistantText.push(event.part.text);
112
+ }
113
+ flushAssistant();
114
+
115
+ const occurredAt = [...messages]
116
+ .reverse()
117
+ .map((message) => message.timestamp ? new Date(message.timestamp) : undefined)
118
+ .find((date) => date && !Number.isNaN(date.getTime()));
119
+
120
+ return {
121
+ sessionId: state.id ?? 'kimi-unknown-session',
122
+ directory: state.cwd ?? fallbackDirectory,
123
+ messages,
124
+ rawText: messages.map((message) => `${message.role}: ${message.content}`).join('\n\n'),
125
+ occurredAt,
126
+ };
127
+ }
@@ -0,0 +1,128 @@
1
+ import type { LLMClient } from '../core/llm-generator.js';
2
+ import type { MemoryType } from '../core/types.js';
3
+ import type { ParsedSession } from './session-parser.js';
4
+
5
+ export interface ExtractedLearning {
6
+ content: string;
7
+ memoryType: MemoryType;
8
+ keywords: string[];
9
+ level3Keywords: string;
10
+ }
11
+
12
+ const STOP_WORDS = new Set([
13
+ 'about', 'after', 'again', 'avec', 'cette', 'dans', 'elle', 'from', 'have', 'mais',
14
+ 'pour', 'that', 'this', 'tout', 'une', 'with', 'your', 'être', 'plus', 'then', 'when',
15
+ ]);
16
+
17
+ function deterministicKeywords(content: string): string[] {
18
+ const words = content
19
+ .toLocaleLowerCase()
20
+ .normalize('NFD')
21
+ .replace(/[\u0300-\u036f]/g, '')
22
+ .match(/[a-z0-9_-]{4,}/g) ?? [];
23
+ return [...new Set(words.filter((word) => !STOP_WORDS.has(word)))].slice(0, 8);
24
+ }
25
+
26
+ /** Fast, network-free baseline used whenever no maintenance model is available. */
27
+ export function extractLearningsDeterministic(
28
+ session: ParsedSession,
29
+ maxLearnings = 5,
30
+ ): ExtractedLearning[] {
31
+ const unique = new Set<string>();
32
+ const candidates = session.messages
33
+ .filter((message) => message.role === 'assistant')
34
+ .map((message) => message.content.trim())
35
+ .filter((content) => content.length >= 40)
36
+ .filter((content) => {
37
+ const key = content.replace(/\s+/g, ' ').toLocaleLowerCase();
38
+ if (unique.has(key)) return false;
39
+ unique.add(key);
40
+ return true;
41
+ })
42
+ .slice(-maxLearnings);
43
+
44
+ return candidates.map((content) => {
45
+ const clipped = content.slice(0, 1_000);
46
+ const keywords = deterministicKeywords(clipped);
47
+ const procedural = /\b(fix(?:ed)?|implement(?:ed)?|add(?:ed)?|use|run|step|corrig|ajout|remplac|configur)/i.test(clipped);
48
+ return {
49
+ content: clipped,
50
+ memoryType: procedural ? 'procedural' : 'episodic',
51
+ keywords,
52
+ level3Keywords: keywords.join(' '),
53
+ };
54
+ });
55
+ }
56
+
57
+ const SYSTEM_PROMPT = `You are a system that extracts mnemonic learnings.
58
+ Analyse the session and extract the key learnings worth remembering.
59
+ Write them in the same language as the session itself.
60
+ Answer with a JSON array ONLY — no markdown.`;
61
+
62
+ export async function extractLearnings(
63
+ session: ParsedSession,
64
+ client: LLMClient,
65
+ maxLearnings = 5
66
+ ): Promise<ExtractedLearning[]> {
67
+ // Truncate to avoid token limits — keep last ~3000 chars which has recent context
68
+ const transcript = session.rawText.slice(-3000);
69
+
70
+ const response = await client.messages.create({
71
+ model: 'claude-haiku-4-5-20251001',
72
+ max_tokens: 1024,
73
+ system: [
74
+ {
75
+ type: 'text',
76
+ text: SYSTEM_PROMPT,
77
+ cache_control: { type: 'ephemeral' },
78
+ },
79
+ ],
80
+ messages: [
81
+ {
82
+ role: 'user',
83
+ content: `Projet: ${session.directory}
84
+ Session: ${session.sessionId}
85
+
86
+ Transcript:
87
+ """
88
+ ${transcript}
89
+ """
90
+
91
+ Extract up to ${maxLearnings} key learnings (technical decisions, bugs solved, patterns discovered, important facts).
92
+ Skip trivial exchanges and repetitions.
93
+
94
+ Format JSON requis:
95
+ [
96
+ {
97
+ "content": "full description of the learning",
98
+ "memoryType": "episodic|semantic|procedural",
99
+ "keywords": ["mot1", "mot2"],
100
+ "level3Keywords": "BM25 keywords separated by spaces"
101
+ }
102
+ ]`,
103
+ },
104
+ ],
105
+ });
106
+
107
+ const text = response.content[0]?.type === 'text' ? (response.content[0].text ?? '') : '';
108
+
109
+ try {
110
+ const parsed = JSON.parse(text.trim());
111
+ if (!Array.isArray(parsed)) throw new Error('Expected array');
112
+
113
+ return parsed
114
+ .filter((item: any) => item.content && item.memoryType)
115
+ .map((item: any) => ({
116
+ content: String(item.content),
117
+ memoryType: (['episodic', 'semantic', 'procedural'].includes(item.memoryType)
118
+ ? item.memoryType
119
+ : 'semantic') as MemoryType,
120
+ keywords: Array.isArray(item.keywords) ? item.keywords.map(String) : [],
121
+ level3Keywords: String(item.level3Keywords || item.keywords?.join(' ') || ''),
122
+ }))
123
+ .slice(0, maxLearnings);
124
+ } catch {
125
+ return extractLearningsDeterministic(session, 1)
126
+ .map((learning) => ({ ...learning, memoryType: 'episodic' }));
127
+ }
128
+ }