claude-memory-layer 1.0.11 → 1.0.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +60 -0
- package/README.md +166 -2
- package/bootstrap-kb/decisions/decisions.md +244 -0
- package/bootstrap-kb/glossary/glossary.md +46 -0
- package/bootstrap-kb/modules/.claude-plugin.md +22 -0
- package/bootstrap-kb/modules/agents.md.md +15 -0
- package/bootstrap-kb/modules/claude.md.md +15 -0
- package/bootstrap-kb/modules/context.md.md +15 -0
- package/bootstrap-kb/modules/docs.md +18 -0
- package/bootstrap-kb/modules/handoff.md.md +15 -0
- package/bootstrap-kb/modules/package-lock.json.md +15 -0
- package/bootstrap-kb/modules/package.json.md +15 -0
- package/bootstrap-kb/modules/plan.md.md +15 -0
- package/bootstrap-kb/modules/readme.md.md +15 -0
- package/bootstrap-kb/modules/scripts.md +26 -0
- package/bootstrap-kb/modules/spec.md.md +15 -0
- package/bootstrap-kb/modules/specs.md +20 -0
- package/bootstrap-kb/modules/src.md +51 -0
- package/bootstrap-kb/modules/tests.md +42 -0
- package/bootstrap-kb/modules/tsconfig.json.md +15 -0
- package/bootstrap-kb/modules/vitest.config.ts.md +15 -0
- package/bootstrap-kb/overview/overview.md +40 -0
- package/bootstrap-kb/sources/manifest.json +950 -0
- package/bootstrap-kb/sources/manifest.md +227 -0
- package/bootstrap-kb/timeline/timeline.md +57 -0
- package/d.sh +3 -0
- package/deploy.sh +3 -0
- package/dist/cli/index.js +2389 -286
- package/dist/cli/index.js.map +4 -4
- package/dist/core/index.js +1017 -132
- package/dist/core/index.js.map +4 -4
- package/dist/hooks/post-tool-use.js +1347 -202
- package/dist/hooks/post-tool-use.js.map +4 -4
- package/dist/hooks/session-end.js +1339 -194
- package/dist/hooks/session-end.js.map +4 -4
- package/dist/hooks/session-start.js +1343 -198
- package/dist/hooks/session-start.js.map +4 -4
- package/dist/hooks/stop.js +1351 -206
- package/dist/hooks/stop.js.map +4 -4
- package/dist/hooks/user-prompt-submit.js +1347 -202
- package/dist/hooks/user-prompt-submit.js.map +4 -4
- package/dist/server/api/index.js +1436 -211
- package/dist/server/api/index.js.map +4 -4
- package/dist/server/index.js +1445 -220
- package/dist/server/index.js.map +4 -4
- package/dist/services/memory-service.js +1345 -199
- package/dist/services/memory-service.js.map +4 -4
- package/dist/ui/app.js +69 -2
- package/dist/ui/index.html +8 -0
- package/docs/MCP_MEMORY_SERVICE_COMPARATIVE_REVIEW.md +271 -0
- package/docs/MEMU_ADOPTION.md +40 -0
- package/memory/.claude-plugin/commands/2026-02-25.md +263 -0
- package/memory/_index.md +405 -0
- package/memory/default/uncategorized/2026-02-25.md +4839 -0
- package/memory/specs/20260207-dashboard-upgrade/2026-02-25.md +142 -0
- package/memory/specs/citations-system/2026-02-25.md +1121 -0
- package/memory/specs/endless-mode/2026-02-25.md +1392 -0
- package/memory/specs/entity-edge-model/2026-02-25.md +1263 -0
- package/memory/specs/evidence-aligner-v2/2026-02-25.md +1028 -0
- package/memory/specs/mcp-desktop-integration/2026-02-25.md +1334 -0
- package/memory/specs/post-tool-use-hook/2026-02-25.md +1164 -0
- package/memory/specs/private-tags/2026-02-25.md +1057 -0
- package/memory/specs/progressive-disclosure/2026-02-25.md +1436 -0
- package/memory/specs/task-entity-system/2026-02-25.md +924 -0
- package/memory/specs/vector-outbox-v2/2026-02-25.md +1510 -0
- package/memory/specs/web-viewer-ui/2026-02-25.md +1709 -0
- package/package.json +2 -1
- package/scripts/build.ts +6 -0
- package/scripts/bump-patch-version.sh +18 -0
- package/src/cli/index.ts +281 -2
- package/src/core/consolidated-store.ts +63 -1
- package/src/core/consolidation-worker.ts +115 -6
- package/src/core/event-store.ts +14 -0
- package/src/core/index.ts +1 -0
- package/src/core/ingest-interceptor.ts +80 -0
- package/src/core/markdown-mirror.ts +70 -0
- package/src/core/md-mirror.ts +92 -0
- package/src/core/mongo-sync-config.ts +165 -0
- package/src/core/mongo-sync-worker.ts +381 -0
- package/src/core/retriever.ts +540 -150
- package/src/core/sqlite-event-store.ts +350 -1
- package/src/core/tag-taxonomy.ts +51 -0
- package/src/core/types.ts +28 -0
- package/src/server/api/health.ts +53 -0
- package/src/server/api/index.ts +3 -1
- package/src/server/api/stats.ts +46 -1
- package/src/services/bootstrap-organizer.ts +443 -0
- package/src/services/codex-session-history-importer.ts +474 -0
- package/src/services/memory-service.ts +373 -68
- package/src/services/session-history-importer.ts +53 -25
- package/src/ui/app.js +69 -2
- package/src/ui/index.html +8 -0
- package/tests/bootstrap-organizer.test.ts +111 -0
- package/tests/consolidation-worker.test.ts +75 -0
- package/tests/ingest-interceptor.test.ts +38 -0
- package/tests/markdown-mirror.test.ts +85 -0
- package/tests/md-mirror.test.ts +50 -0
- package/tests/retriever-fallback-chain.test.ts +223 -0
- package/tests/retriever-strategy-scope.test.ts +97 -0
- package/tests/retriever.memu-adoption.test.ts +122 -0
- package/tests/sqlite-event-store-replication.test.ts +92 -0
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codex Session History Importer
|
|
3
|
+
* Imports existing Codex CLI conversation history into memory
|
|
4
|
+
*
|
|
5
|
+
* Codex stores session history in:
|
|
6
|
+
* ~/.codex/sessions/YYYY/MM/DD/rollout-<timestamp>-<session-id>.jsonl
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import * as fs from 'fs';
|
|
10
|
+
import * as path from 'path';
|
|
11
|
+
import * as os from 'os';
|
|
12
|
+
import * as readline from 'readline';
|
|
13
|
+
import { randomUUID } from 'crypto';
|
|
14
|
+
import { MemoryService, registerSession } from './memory-service.js';
|
|
15
|
+
import type { ImportOptions, ImportResult } from './session-history-importer.js';
|
|
16
|
+
|
|
17
|
+
type CodexLogLine = {
|
|
18
|
+
timestamp?: string;
|
|
19
|
+
type?: string;
|
|
20
|
+
payload?: unknown;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
type CodexSessionMetaPayload = {
|
|
24
|
+
id?: unknown;
|
|
25
|
+
cwd?: unknown;
|
|
26
|
+
timestamp?: unknown;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
type CodexResponseItemMessagePayload = {
|
|
30
|
+
type?: unknown;
|
|
31
|
+
role?: unknown;
|
|
32
|
+
content?: unknown;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
type CodexContentBlock = {
|
|
36
|
+
type?: unknown;
|
|
37
|
+
text?: unknown;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
41
|
+
return typeof value === 'object' && value !== null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function normalizeMaybeRealpath(p: string): string {
|
|
45
|
+
try {
|
|
46
|
+
return fs.realpathSync(p);
|
|
47
|
+
} catch {
|
|
48
|
+
return path.resolve(p);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function extractTextFromContent(content: unknown): string | null {
|
|
53
|
+
if (!Array.isArray(content)) return null;
|
|
54
|
+
const texts: string[] = [];
|
|
55
|
+
for (const block of content) {
|
|
56
|
+
if (!isRecord(block)) continue;
|
|
57
|
+
const b = block as CodexContentBlock;
|
|
58
|
+
const t = typeof b.type === 'string' ? b.type : '';
|
|
59
|
+
if (t !== 'input_text' && t !== 'output_text' && t !== 'text') continue;
|
|
60
|
+
if (typeof b.text === 'string' && b.text.length > 0) {
|
|
61
|
+
texts.push(b.text);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (texts.length === 0) return null;
|
|
65
|
+
return texts.join('\n');
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export class CodexSessionHistoryImporter {
|
|
69
|
+
private readonly memoryService: MemoryService;
|
|
70
|
+
private readonly codexDir: string;
|
|
71
|
+
|
|
72
|
+
constructor(memoryService: MemoryService) {
|
|
73
|
+
this.memoryService = memoryService;
|
|
74
|
+
this.codexDir = path.join(os.homedir(), '.codex');
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
private getSessionsRoot(): string {
|
|
78
|
+
return path.join(this.codexDir, 'sessions');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
private listSessionFilesRecursive(rootDir: string): string[] {
|
|
82
|
+
if (!fs.existsSync(rootDir)) return [];
|
|
83
|
+
const out: string[] = [];
|
|
84
|
+
const stack: string[] = [rootDir];
|
|
85
|
+
|
|
86
|
+
while (stack.length > 0) {
|
|
87
|
+
const dir = stack.pop()!;
|
|
88
|
+
let entries: fs.Dirent[];
|
|
89
|
+
try {
|
|
90
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
91
|
+
} catch {
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
for (const ent of entries) {
|
|
96
|
+
const fullPath = path.join(dir, ent.name);
|
|
97
|
+
if (ent.isDirectory()) {
|
|
98
|
+
stack.push(fullPath);
|
|
99
|
+
} else if (ent.isFile() && ent.name.endsWith('.jsonl')) {
|
|
100
|
+
out.push(fullPath);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
private async readSessionMeta(filePath: string): Promise<{ sessionId: string | null; cwd: string | null }> {
|
|
109
|
+
const fileStream = fs.createReadStream(filePath, { encoding: 'utf-8' });
|
|
110
|
+
const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity });
|
|
111
|
+
|
|
112
|
+
try {
|
|
113
|
+
let linesRead = 0;
|
|
114
|
+
for await (const line of rl) {
|
|
115
|
+
linesRead++;
|
|
116
|
+
if (!line.trim()) continue;
|
|
117
|
+
try {
|
|
118
|
+
const obj = JSON.parse(line) as CodexLogLine;
|
|
119
|
+
if (obj.type !== 'session_meta') continue;
|
|
120
|
+
if (!isRecord(obj.payload)) break;
|
|
121
|
+
const payload = obj.payload as CodexSessionMetaPayload;
|
|
122
|
+
const sessionId = typeof payload.id === 'string' ? payload.id : null;
|
|
123
|
+
const cwd = typeof payload.cwd === 'string' ? payload.cwd : null;
|
|
124
|
+
return { sessionId, cwd };
|
|
125
|
+
} catch {
|
|
126
|
+
// ignore parse errors; keep scanning initial lines
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// session_meta is expected at the top; don't scan entire file.
|
|
130
|
+
if (linesRead >= 25) break;
|
|
131
|
+
}
|
|
132
|
+
} finally {
|
|
133
|
+
rl.close();
|
|
134
|
+
fileStream.close();
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return { sessionId: null, cwd: null };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
private deriveSessionIdFromFileName(filePath: string): string | null {
|
|
141
|
+
const base = path.basename(filePath, '.jsonl');
|
|
142
|
+
// Common: rollout-<date>-<uuid>
|
|
143
|
+
const m = base.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i);
|
|
144
|
+
if (m?.[1]) return m[1];
|
|
145
|
+
return base.length > 0 ? base : null;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async importProject(projectPath: string, options: ImportOptions = {}): Promise<ImportResult> {
|
|
149
|
+
const result: ImportResult = {
|
|
150
|
+
totalSessions: 0,
|
|
151
|
+
totalMessages: 0,
|
|
152
|
+
importedPrompts: 0,
|
|
153
|
+
importedResponses: 0,
|
|
154
|
+
skippedDuplicates: 0,
|
|
155
|
+
errors: []
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
const onProgress = options.onProgress;
|
|
159
|
+
const sessionsRoot = this.getSessionsRoot();
|
|
160
|
+
if (!fs.existsSync(sessionsRoot)) {
|
|
161
|
+
result.errors.push(`Codex sessions directory not found: ${sessionsRoot}`);
|
|
162
|
+
return result;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const normalizedTarget = normalizeMaybeRealpath(projectPath);
|
|
166
|
+
onProgress?.({ phase: 'scan', message: 'Scanning Codex session files...' });
|
|
167
|
+
|
|
168
|
+
const sessionFiles = this.listSessionFilesRecursive(sessionsRoot);
|
|
169
|
+
const matchingFiles: string[] = [];
|
|
170
|
+
|
|
171
|
+
// Filter by original CWD stored in session_meta.payload.cwd
|
|
172
|
+
for (const filePath of sessionFiles) {
|
|
173
|
+
try {
|
|
174
|
+
const meta = await this.readSessionMeta(filePath);
|
|
175
|
+
if (!meta.cwd) continue;
|
|
176
|
+
if (normalizeMaybeRealpath(meta.cwd) === normalizedTarget) {
|
|
177
|
+
matchingFiles.push(filePath);
|
|
178
|
+
}
|
|
179
|
+
} catch {
|
|
180
|
+
// ignore
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
result.totalSessions = matchingFiles.length;
|
|
185
|
+
onProgress?.({ phase: 'scan', message: `Found ${matchingFiles.length} Codex session(s) for this project` });
|
|
186
|
+
|
|
187
|
+
const effectiveProjectPath = options.projectPath ?? projectPath;
|
|
188
|
+
|
|
189
|
+
for (let i = 0; i < matchingFiles.length; i++) {
|
|
190
|
+
const filePath = matchingFiles[i];
|
|
191
|
+
try {
|
|
192
|
+
onProgress?.({ phase: 'session-start', sessionIndex: i, totalSessions: matchingFiles.length, filePath });
|
|
193
|
+
const sessionResult = await this.importSessionFile(filePath, {
|
|
194
|
+
...options,
|
|
195
|
+
projectPath: effectiveProjectPath,
|
|
196
|
+
_sessionIndex: i,
|
|
197
|
+
} as ImportOptions & { _sessionIndex: number });
|
|
198
|
+
|
|
199
|
+
result.totalMessages += sessionResult.totalMessages;
|
|
200
|
+
result.importedPrompts += sessionResult.importedPrompts;
|
|
201
|
+
result.importedResponses += sessionResult.importedResponses;
|
|
202
|
+
result.skippedDuplicates += sessionResult.skippedDuplicates;
|
|
203
|
+
result.errors.push(...sessionResult.errors);
|
|
204
|
+
|
|
205
|
+
onProgress?.({
|
|
206
|
+
phase: 'session-done',
|
|
207
|
+
sessionIndex: i,
|
|
208
|
+
importedPrompts: sessionResult.importedPrompts,
|
|
209
|
+
importedResponses: sessionResult.importedResponses,
|
|
210
|
+
skipped: sessionResult.skippedDuplicates
|
|
211
|
+
});
|
|
212
|
+
} catch (error) {
|
|
213
|
+
result.errors.push(`Failed to import ${filePath}: ${error}`);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
return result;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async importAll(options: ImportOptions = {}): Promise<ImportResult> {
|
|
221
|
+
const result: ImportResult = {
|
|
222
|
+
totalSessions: 0,
|
|
223
|
+
totalMessages: 0,
|
|
224
|
+
importedPrompts: 0,
|
|
225
|
+
importedResponses: 0,
|
|
226
|
+
skippedDuplicates: 0,
|
|
227
|
+
errors: []
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
const onProgress = options.onProgress;
|
|
231
|
+
const sessionsRoot = this.getSessionsRoot();
|
|
232
|
+
if (!fs.existsSync(sessionsRoot)) {
|
|
233
|
+
result.errors.push(`Codex sessions directory not found: ${sessionsRoot}`);
|
|
234
|
+
return result;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
onProgress?.({ phase: 'scan', message: 'Scanning all Codex sessions...' });
|
|
238
|
+
const sessionFiles = this.listSessionFilesRecursive(sessionsRoot);
|
|
239
|
+
result.totalSessions = sessionFiles.length;
|
|
240
|
+
onProgress?.({ phase: 'scan', message: `Found ${sessionFiles.length} Codex session file(s)` });
|
|
241
|
+
|
|
242
|
+
for (let i = 0; i < sessionFiles.length; i++) {
|
|
243
|
+
const filePath = sessionFiles[i];
|
|
244
|
+
try {
|
|
245
|
+
onProgress?.({ phase: 'session-start', sessionIndex: i, totalSessions: sessionFiles.length, filePath });
|
|
246
|
+
const sessionResult = await this.importSessionFile(filePath, {
|
|
247
|
+
...options,
|
|
248
|
+
_sessionIndex: i,
|
|
249
|
+
} as ImportOptions & { _sessionIndex: number });
|
|
250
|
+
|
|
251
|
+
result.totalMessages += sessionResult.totalMessages;
|
|
252
|
+
result.importedPrompts += sessionResult.importedPrompts;
|
|
253
|
+
result.importedResponses += sessionResult.importedResponses;
|
|
254
|
+
result.skippedDuplicates += sessionResult.skippedDuplicates;
|
|
255
|
+
result.errors.push(...sessionResult.errors);
|
|
256
|
+
|
|
257
|
+
onProgress?.({
|
|
258
|
+
phase: 'session-done',
|
|
259
|
+
sessionIndex: i,
|
|
260
|
+
importedPrompts: sessionResult.importedPrompts,
|
|
261
|
+
importedResponses: sessionResult.importedResponses,
|
|
262
|
+
skipped: sessionResult.skippedDuplicates
|
|
263
|
+
});
|
|
264
|
+
} catch (error) {
|
|
265
|
+
result.errors.push(`Failed to process ${filePath}: ${error}`);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
return result;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
async importSessionFile(filePath: string, options: ImportOptions = {}): Promise<ImportResult> {
|
|
273
|
+
const result: ImportResult = {
|
|
274
|
+
totalSessions: 1,
|
|
275
|
+
totalMessages: 0,
|
|
276
|
+
importedPrompts: 0,
|
|
277
|
+
importedResponses: 0,
|
|
278
|
+
skippedDuplicates: 0,
|
|
279
|
+
errors: []
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
if (!fs.existsSync(filePath)) {
|
|
283
|
+
result.errors.push(`File not found: ${filePath}`);
|
|
284
|
+
return result;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const meta = await this.readSessionMeta(filePath);
|
|
288
|
+
const sessionId = meta.sessionId ?? this.deriveSessionIdFromFileName(filePath);
|
|
289
|
+
|
|
290
|
+
if (!sessionId) {
|
|
291
|
+
result.errors.push(`Could not determine session id for: ${filePath}`);
|
|
292
|
+
return result;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const effectiveProjectPath = options.projectPath ?? meta.cwd ?? undefined;
|
|
296
|
+
|
|
297
|
+
if (options.force) {
|
|
298
|
+
const deleted = await this.memoryService.deleteSessionEvents(sessionId);
|
|
299
|
+
if (options.verbose && deleted > 0) {
|
|
300
|
+
console.log(` Deleted ${deleted} existing events for session ${sessionId}`);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
await this.memoryService.startSession(sessionId, effectiveProjectPath);
|
|
305
|
+
|
|
306
|
+
const fileStream = fs.createReadStream(filePath, { encoding: 'utf-8' });
|
|
307
|
+
const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity });
|
|
308
|
+
|
|
309
|
+
const onProgress = options.onProgress;
|
|
310
|
+
const sessionIndex = (options as ImportOptions & { _sessionIndex?: number })._sessionIndex ?? 0;
|
|
311
|
+
let lastProgressAt = 0;
|
|
312
|
+
const limit = options.limit || Infinity;
|
|
313
|
+
let storedCount = 0;
|
|
314
|
+
|
|
315
|
+
let currentTurnId: string | null = null;
|
|
316
|
+
let textBuffer: string[] = [];
|
|
317
|
+
let lastTimestamp: string | undefined;
|
|
318
|
+
|
|
319
|
+
const flushTextBuffer = async () => {
|
|
320
|
+
if (storedCount >= limit) { textBuffer = []; return; }
|
|
321
|
+
if (textBuffer.length === 0 || !currentTurnId) return;
|
|
322
|
+
|
|
323
|
+
const substantive = textBuffer.filter(t => t.length >= 100);
|
|
324
|
+
const merged = substantive.length > 0
|
|
325
|
+
? substantive.join('\n\n')
|
|
326
|
+
: textBuffer.reduce((a, b) => a.length >= b.length ? a : b, '');
|
|
327
|
+
|
|
328
|
+
if (!merged) { textBuffer = []; return; }
|
|
329
|
+
|
|
330
|
+
const truncated = merged.length > 10000
|
|
331
|
+
? merged.slice(0, 10000) + '...[truncated]'
|
|
332
|
+
: merged;
|
|
333
|
+
|
|
334
|
+
const appendResult = await this.memoryService.storeAgentResponse(
|
|
335
|
+
sessionId,
|
|
336
|
+
truncated,
|
|
337
|
+
{ importedFrom: filePath, originalTimestamp: lastTimestamp, turnId: currentTurnId, source: 'codex' }
|
|
338
|
+
);
|
|
339
|
+
|
|
340
|
+
if (appendResult.isDuplicate) {
|
|
341
|
+
result.skippedDuplicates++;
|
|
342
|
+
} else {
|
|
343
|
+
result.importedResponses++;
|
|
344
|
+
}
|
|
345
|
+
storedCount++;
|
|
346
|
+
textBuffer = [];
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
try {
|
|
350
|
+
for await (const line of rl) {
|
|
351
|
+
if (storedCount >= limit) break;
|
|
352
|
+
try {
|
|
353
|
+
const entry = JSON.parse(line) as CodexLogLine;
|
|
354
|
+
result.totalMessages++;
|
|
355
|
+
|
|
356
|
+
if (entry.type === 'response_item' && isRecord(entry.payload)) {
|
|
357
|
+
const payload = entry.payload as CodexResponseItemMessagePayload;
|
|
358
|
+
if (payload.type !== 'message') continue;
|
|
359
|
+
|
|
360
|
+
const role = typeof payload.role === 'string' ? payload.role : null;
|
|
361
|
+
if (!role) continue;
|
|
362
|
+
|
|
363
|
+
if (role === 'user') {
|
|
364
|
+
await flushTextBuffer();
|
|
365
|
+
|
|
366
|
+
const content = extractTextFromContent(payload.content);
|
|
367
|
+
if (!content) continue;
|
|
368
|
+
|
|
369
|
+
currentTurnId = randomUUID();
|
|
370
|
+
|
|
371
|
+
const appendResult = await this.memoryService.storeUserPrompt(
|
|
372
|
+
sessionId,
|
|
373
|
+
content,
|
|
374
|
+
{ importedFrom: filePath, originalTimestamp: entry.timestamp, turnId: currentTurnId, source: 'codex' }
|
|
375
|
+
);
|
|
376
|
+
|
|
377
|
+
if (appendResult.isDuplicate) {
|
|
378
|
+
result.skippedDuplicates++;
|
|
379
|
+
} else {
|
|
380
|
+
result.importedPrompts++;
|
|
381
|
+
}
|
|
382
|
+
storedCount++;
|
|
383
|
+
} else if (role === 'assistant') {
|
|
384
|
+
const content = extractTextFromContent(payload.content);
|
|
385
|
+
if (content) {
|
|
386
|
+
textBuffer.push(content);
|
|
387
|
+
if (typeof entry.timestamp === 'string') {
|
|
388
|
+
lastTimestamp = entry.timestamp;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
} else {
|
|
392
|
+
// developer/system/tool messages are ignored by default
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
const now = Date.now();
|
|
397
|
+
if (now - lastProgressAt > 200) {
|
|
398
|
+
lastProgressAt = now;
|
|
399
|
+
onProgress?.({
|
|
400
|
+
phase: 'session-progress',
|
|
401
|
+
sessionIndex,
|
|
402
|
+
messagesProcessed: result.totalMessages,
|
|
403
|
+
imported: result.importedPrompts + result.importedResponses,
|
|
404
|
+
skipped: result.skippedDuplicates
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
} catch (parseError) {
|
|
408
|
+
result.errors.push(`Parse error: ${parseError}`);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
} finally {
|
|
412
|
+
await flushTextBuffer();
|
|
413
|
+
rl.close();
|
|
414
|
+
fileStream.close();
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
await this.memoryService.endSession(sessionId);
|
|
418
|
+
|
|
419
|
+
if (effectiveProjectPath) {
|
|
420
|
+
registerSession(sessionId, effectiveProjectPath);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
if (options.verbose) {
|
|
424
|
+
console.log(`Imported ${result.importedPrompts} prompts, ${result.importedResponses} responses from ${filePath}`);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
return result;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
async listAvailableSessions(projectPath?: string): Promise<Array<{
|
|
431
|
+
sessionId: string;
|
|
432
|
+
filePath: string;
|
|
433
|
+
size: number;
|
|
434
|
+
modifiedAt: Date;
|
|
435
|
+
}>> {
|
|
436
|
+
const sessionsRoot = this.getSessionsRoot();
|
|
437
|
+
if (!fs.existsSync(sessionsRoot)) return [];
|
|
438
|
+
|
|
439
|
+
const files = this.listSessionFilesRecursive(sessionsRoot);
|
|
440
|
+
const sessions: Array<{ sessionId: string; filePath: string; size: number; modifiedAt: Date }> = [];
|
|
441
|
+
|
|
442
|
+
const normalizedTarget = projectPath ? normalizeMaybeRealpath(projectPath) : null;
|
|
443
|
+
|
|
444
|
+
for (const filePath of files) {
|
|
445
|
+
try {
|
|
446
|
+
const stats = fs.statSync(filePath);
|
|
447
|
+
|
|
448
|
+
let sessionId = this.deriveSessionIdFromFileName(filePath) ?? path.basename(filePath, '.jsonl');
|
|
449
|
+
if (normalizedTarget) {
|
|
450
|
+
const meta = await this.readSessionMeta(filePath);
|
|
451
|
+
if (!meta.cwd) continue;
|
|
452
|
+
if (normalizeMaybeRealpath(meta.cwd) !== normalizedTarget) continue;
|
|
453
|
+
sessionId = meta.sessionId ?? sessionId;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
sessions.push({
|
|
457
|
+
sessionId,
|
|
458
|
+
filePath,
|
|
459
|
+
size: stats.size,
|
|
460
|
+
modifiedAt: stats.mtime
|
|
461
|
+
});
|
|
462
|
+
} catch {
|
|
463
|
+
// ignore
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
sessions.sort((a, b) => b.modifiedAt.getTime() - a.modifiedAt.getTime());
|
|
468
|
+
return sessions;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
export function createCodexSessionHistoryImporter(memoryService: MemoryService): CodexSessionHistoryImporter {
|
|
473
|
+
return new CodexSessionHistoryImporter(memoryService);
|
|
474
|
+
}
|