@evomap/evolver-cli 2.0.0-beta.0

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 (91) hide show
  1. package/dist/antiGeneBenchmark.d.ts +9 -0
  2. package/dist/antiGeneBenchmark.js +173 -0
  3. package/dist/antiGeneRollout.d.ts +14 -0
  4. package/dist/antiGeneRollout.js +276 -0
  5. package/dist/atp.d.ts +122 -0
  6. package/dist/atp.js +413 -0
  7. package/dist/atpAutoDeliver.d.ts +53 -0
  8. package/dist/atpAutoDeliver.js +197 -0
  9. package/dist/atpAutobuyPrompt.d.ts +48 -0
  10. package/dist/atpAutobuyPrompt.js +109 -0
  11. package/dist/autoDistillAntiGene.d.ts +63 -0
  12. package/dist/autoDistillAntiGene.js +396 -0
  13. package/dist/autoDistillLlm.d.ts +94 -0
  14. package/dist/autoDistillLlm.js +510 -0
  15. package/dist/autoDistillTranscript.d.ts +87 -0
  16. package/dist/autoDistillTranscript.js +364 -0
  17. package/dist/autoRecall.d.ts +25 -0
  18. package/dist/autoRecall.js +80 -0
  19. package/dist/autoexec.d.ts +237 -0
  20. package/dist/autoexec.js +1041 -0
  21. package/dist/cli.d.ts +2 -0
  22. package/dist/cli.js +7 -0
  23. package/dist/cliContracts.d.ts +72 -0
  24. package/dist/cliContracts.js +815 -0
  25. package/dist/commands.d.ts +9 -0
  26. package/dist/commands.js +10 -0
  27. package/dist/cursorRewrite.d.ts +42 -0
  28. package/dist/cursorRewrite.js +65 -0
  29. package/dist/cycleConsumer.d.ts +42 -0
  30. package/dist/cycleConsumer.js +519 -0
  31. package/dist/daemonLoop.d.ts +33 -0
  32. package/dist/daemonLoop.js +72 -0
  33. package/dist/dispatch.d.ts +10 -0
  34. package/dist/dispatch.js +75 -0
  35. package/dist/distillObserver.d.ts +33 -0
  36. package/dist/distillObserver.js +146 -0
  37. package/dist/distillPrimitives.d.ts +48 -0
  38. package/dist/distillPrimitives.js +142 -0
  39. package/dist/doctor.d.ts +54 -0
  40. package/dist/doctor.js +931 -0
  41. package/dist/geneValue.d.ts +37 -0
  42. package/dist/geneValue.js +97 -0
  43. package/dist/index.d.ts +193 -0
  44. package/dist/index.js +1135 -0
  45. package/dist/lifecycle.d.ts +75 -0
  46. package/dist/lifecycle.js +859 -0
  47. package/dist/login.d.ts +10 -0
  48. package/dist/login.js +38 -0
  49. package/dist/migrate/divergenceAudit.d.ts +29 -0
  50. package/dist/migrate/divergenceAudit.js +37 -0
  51. package/dist/migrate/fieldMap.d.ts +18 -0
  52. package/dist/migrate/fieldMap.js +68 -0
  53. package/dist/migrate/v1Import.d.ts +16 -0
  54. package/dist/migrate/v1Import.js +118 -0
  55. package/dist/phub.d.ts +18 -0
  56. package/dist/phub.js +284 -0
  57. package/dist/recall.d.ts +26 -0
  58. package/dist/recall.js +162 -0
  59. package/dist/recipe.d.ts +61 -0
  60. package/dist/recipe.js +564 -0
  61. package/dist/reflectionObserver.d.ts +8 -0
  62. package/dist/reflectionObserver.js +6 -0
  63. package/dist/reuse.d.ts +48 -0
  64. package/dist/reuse.js +300 -0
  65. package/dist/reuseReport.d.ts +20 -0
  66. package/dist/reuseReport.js +255 -0
  67. package/dist/reviewFilter.d.ts +4 -0
  68. package/dist/reviewFilter.js +6 -0
  69. package/dist/runtimeSessionSource.d.ts +9 -0
  70. package/dist/runtimeSessionSource.js +29 -0
  71. package/dist/setupHooks.d.ts +2 -0
  72. package/dist/setupHooks.js +410 -0
  73. package/dist/skill2gep.d.ts +144 -0
  74. package/dist/skill2gep.js +321 -0
  75. package/dist/skillDistill.d.ts +75 -0
  76. package/dist/skillDistill.js +342 -0
  77. package/dist/solo/breaker.d.ts +14 -0
  78. package/dist/solo/breaker.js +21 -0
  79. package/dist/solo/gitGuard.d.ts +17 -0
  80. package/dist/solo/gitGuard.js +62 -0
  81. package/dist/solo/mode.d.ts +12 -0
  82. package/dist/solo/mode.js +55 -0
  83. package/dist/thesis.d.ts +43 -0
  84. package/dist/thesis.js +179 -0
  85. package/dist/trajectoryExport.d.ts +1 -0
  86. package/dist/trajectoryExport.js +895 -0
  87. package/dist/valueDigest.d.ts +33 -0
  88. package/dist/valueDigest.js +94 -0
  89. package/dist/version.d.ts +2 -0
  90. package/dist/version.js +14 -0
  91. package/package.json +38 -0
@@ -0,0 +1,895 @@
1
+ import { closeSync, existsSync, lstatSync, openSync, readSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeSync } from 'node:fs';
2
+ import { basename, delimiter, dirname, extname, join, resolve, sep } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ import { events, ops, trace } from '@evomap/evolver-core';
5
+ import { ADAPTERS, adapterForPath, genericChatAdapter, isCursorStateVscdbPath, parseCursorStateVscdb, parseJsonlLines, parseJsonlLinesWithStats, } from '@evomap/evolver-runtime-adapters';
6
+ const TRACE_FILE_RE = /(^|[/\\])llm-trace-[^/\\]*\.jsonl$/i;
7
+ const RUNTIME_SESSION_ENABLE_ENV = 'EVOLVER_TRAJECTORY_RUNTIME_SESSIONS';
8
+ const RUNTIME_SESSION_ENABLE_ENV_LEGACY = 'EVOLVER_TRAJECTORY_EXPORT_RUNTIME_SESSIONS';
9
+ const RUNTIME_SESSION_DIRS_ENV = 'EVOLVER_TRAJECTORY_RUNTIME_SESSION_DIRS';
10
+ const RUNTIME_SESSION_DIRS_ENV_LEGACY = 'EVOLVER_TRAJECTORY_EXPORT_RUNTIME_SESSION_DIRS';
11
+ const RUNTIME_DISCOVERY_AGENTS = new Set(['codex', 'claude-code', 'cursor', 'gemini', 'kimi']);
12
+ // Agents whose session files carry NO per-file cwd/workspace marker (Gemini chat: only sessionId+projectHash;
13
+ // Kimi wire.jsonl: raw wire log). The workspace-cwd gate (runtimeSessionBelongsToWorkspace) would reject every
14
+ // such file because transcriptCwd() returns undefined -> silently dropping ALL real sessions. For these agents
15
+ // we skip workspace scoping (the goal of this discovery is broad "采全" collection) and accept .json too, since
16
+ // Gemini's older/common session format is `.json`, not `.jsonl`.
17
+ const CWDLESS_DISCOVERY_AGENTS = new Set(['gemini', 'kimi']);
18
+ // Claude transcripts can carry several meta/preamble records before the first
19
+ // record that names the cwd; a 5-line / 4KB window dropped whole sessions when
20
+ // the preamble was one line longer than expected. Scan a wider window instead.
21
+ const TRANSCRIPT_CWD_HEAD_BYTES = 65536;
22
+ const TRANSCRIPT_CWD_MAX_LINES = 50;
23
+ // Marker gate (strict by default): the runtime-session discovery链路 only collects a session if evolver itself
24
+ // marked it. evolver's SessionStart hook (`evolver inject session-start --hook-stdin`) stamps the runtime
25
+ // `session_id` onto a `value.inject` root_event, so root_events.jsonl IS the registry of "sessions evolver
26
+ // actively touched". A discovered runtime session is collected only when its session_id ∈ that set. Sessions
27
+ // from tools with no hook installed (gemini/kimi), and history predating the hook install, carry no marker and
28
+ // are excluded — by design. `--include-unmarked` (or the env below) reopens the legacy "采全" behavior.
29
+ const INCLUDE_UNMARKED_ENV = 'EVOLVER_TRAJECTORY_INCLUDE_UNMARKED';
30
+ // Second gate (also strict by default): skip a discovered runtime session whose session_id the gateway already
31
+ // captured (in ~/.evomap/.../llm-trace-*.jsonl). The proxy extracts the SAME session_id the tool names its
32
+ // transcript with, so this de-dupes the two collection rails — the session链路 only fills gateway gaps.
33
+ // `--include-gateway-captured` (or the env below) disables this second gate.
34
+ const INCLUDE_GATEWAY_CAPTURED_ENV = 'EVOLVER_TRAJECTORY_INCLUDE_GATEWAY_CAPTURED';
35
+ function flagValue(arg, name) {
36
+ const prefix = `--${name}=`;
37
+ return arg.startsWith(prefix) ? arg.slice(prefix.length) : undefined;
38
+ }
39
+ function parseExportFlags(argv) {
40
+ const out = {};
41
+ for (let i = 0; i < argv.length; i++) {
42
+ const arg = argv[i] ?? '';
43
+ if (arg === '--help' || arg === '-h')
44
+ out.help = true;
45
+ if (arg === '--allow-partial')
46
+ out.allowPartial = true;
47
+ if (arg === '--include-unmarked')
48
+ out.includeUnmarked = true;
49
+ if (arg === '--include-gateway-captured')
50
+ out.includeGatewayCaptured = true;
51
+ if (arg === '--runtime-sessions') {
52
+ out.runtimeSessions = true;
53
+ continue;
54
+ }
55
+ for (const name of ['input', 'output', 'runtime-session-dir', 'node-secret', 'node-secret-file', 'node-secret-env', 'node-secret-keyring', 'hub-private-key']) {
56
+ const inline = flagValue(arg, name);
57
+ if (inline !== undefined) {
58
+ if (name === 'input')
59
+ out.input = inline;
60
+ else if (name === 'output')
61
+ out.output = inline;
62
+ else if (name === 'runtime-session-dir')
63
+ (out.runtimeSessionDirs ??= []).push(inline);
64
+ else if (name === 'node-secret')
65
+ out.nodeSecret = inline;
66
+ else if (name === 'node-secret-file')
67
+ out.nodeSecretFile = inline;
68
+ else if (name === 'node-secret-env')
69
+ out.nodeSecretEnv = inline;
70
+ else if (name === 'node-secret-keyring')
71
+ out.nodeSecretKeyring = inline;
72
+ else
73
+ out.hubPrivateKey = inline;
74
+ continue;
75
+ }
76
+ if (arg === `--${name}`) {
77
+ const value = argv[i + 1];
78
+ if (value === undefined || value.startsWith('--'))
79
+ throw new Error(`missing value for --${name}`);
80
+ if (name === 'input')
81
+ out.input = value;
82
+ else if (name === 'output')
83
+ out.output = value;
84
+ else if (name === 'runtime-session-dir')
85
+ (out.runtimeSessionDirs ??= []).push(value);
86
+ else if (name === 'node-secret')
87
+ out.nodeSecret = value;
88
+ else if (name === 'node-secret-file')
89
+ out.nodeSecretFile = value;
90
+ else if (name === 'node-secret-env')
91
+ out.nodeSecretEnv = value;
92
+ else if (name === 'node-secret-keyring')
93
+ out.nodeSecretKeyring = value;
94
+ else
95
+ out.hubPrivateKey = value;
96
+ i++;
97
+ }
98
+ }
99
+ }
100
+ return out;
101
+ }
102
+ function readSecretFile(path) {
103
+ if (path === undefined)
104
+ return undefined;
105
+ return readFileSync(resolve(path), 'utf8').trim();
106
+ }
107
+ function readNodeSecretEnv(name) {
108
+ if (name === undefined)
109
+ return undefined;
110
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))
111
+ throw new Error('invalid environment variable name for --node-secret-env');
112
+ const secret = String(process.env[name] ?? '').trim();
113
+ if (!secret)
114
+ throw new Error('node secret environment variable is empty or unset');
115
+ return secret;
116
+ }
117
+ function readNodeSecretKeyring(path) {
118
+ if (!path)
119
+ return undefined;
120
+ const parsed = JSON.parse(readFileSync(resolve(path), 'utf8'));
121
+ if ((parsed && typeof parsed === 'object' && !Array.isArray(parsed)) || Array.isArray(parsed)) {
122
+ return parsed;
123
+ }
124
+ throw new Error('node secret keyring must be a JSON object or array');
125
+ }
126
+ function defaultNodeSecret() {
127
+ const envSecret = process.env['EVOMAP_NODE_SECRET'] ?? process.env['A2A_NODE_SECRET'];
128
+ if (typeof envSecret === 'string' && envSecret.length > 0)
129
+ return envSecret;
130
+ const home = events.evomapHome();
131
+ for (const file of [join(home, 'node_secret')]) {
132
+ if (existsSync(file))
133
+ return readFileSync(file, 'utf8').trim();
134
+ }
135
+ return undefined;
136
+ }
137
+ function resolveNodeSecret(flags) {
138
+ const sources = [flags.nodeSecret, flags.nodeSecretFile, flags.nodeSecretEnv].filter((value) => value !== undefined).length;
139
+ if (sources > 1)
140
+ throw new Error('use only one node secret source');
141
+ if (flags.nodeSecretFile !== undefined)
142
+ return readSecretFile(flags.nodeSecretFile);
143
+ if (flags.nodeSecretEnv !== undefined)
144
+ return readNodeSecretEnv(flags.nodeSecretEnv);
145
+ if (flags.nodeSecret !== undefined)
146
+ return existsSync(flags.nodeSecret) ? readSecretFile(flags.nodeSecret) : flags.nodeSecret;
147
+ return defaultNodeSecret();
148
+ }
149
+ function isJsonCandidate(path) {
150
+ const ext = extname(path).toLowerCase();
151
+ const name = basename(path).toLowerCase();
152
+ return ext === '.json' || ext === '.jsonl' || name === '.json' || name === '.jsonl';
153
+ }
154
+ function isJsonlCandidate(path) {
155
+ const ext = extname(path).toLowerCase();
156
+ return ext === '.jsonl' || basename(path).toLowerCase() === '.jsonl';
157
+ }
158
+ function isTraceLikeRow(row) {
159
+ return row['event'] === 'llm_turn'
160
+ || row['prism_compatible'] === true
161
+ || row['encrypted'] === true
162
+ || row['event'] === 'llm_trace_envelope';
163
+ }
164
+ function traceLikeContent(chunk) {
165
+ return parseJsonlLines(chunk).some(isTraceLikeRow);
166
+ }
167
+ function adapterForContent(chunk) {
168
+ for (const adapter of [genericChatAdapter, ...ADAPTERS.filter((candidate) => candidate !== genericChatAdapter)]) {
169
+ if (adapter.parse(chunk).some((turn) => turn.isMeta !== true))
170
+ return adapter;
171
+ }
172
+ return undefined;
173
+ }
174
+ function adapterParsesRuntimeTurns(adapter, chunk) {
175
+ if (adapter.parseSessions)
176
+ return adapter.parseSessions(chunk).some((session) => session.turns.some((turn) => turn.isMeta !== true));
177
+ if (adapter.parseSession)
178
+ return adapter.parseSession(chunk).turns.some((turn) => turn.isMeta !== true);
179
+ return adapter.parse(chunk).some((turn) => turn.isMeta !== true);
180
+ }
181
+ function truthyEnv(value) {
182
+ if (value === undefined)
183
+ return false;
184
+ return ['1', 'true', 'yes', 'on'].includes(value.trim().toLowerCase());
185
+ }
186
+ function splitEnvDirs(value) {
187
+ if (!value)
188
+ return [];
189
+ return value.split(delimiter).flatMap((part) => part.split(',')).map((dir) => dir.trim()).filter(Boolean);
190
+ }
191
+ function cursorGlobalStorageDir(home) {
192
+ return join(home, 'Library', 'Application Support', 'Cursor', 'User', 'globalStorage');
193
+ }
194
+ function cursorGlobalStorageDirs(home) {
195
+ const dirs = [
196
+ cursorGlobalStorageDir(home),
197
+ join(home, '.config', 'Cursor', 'User', 'globalStorage'),
198
+ ];
199
+ const appData = process.env['APPDATA'];
200
+ if (appData)
201
+ dirs.push(join(appData, 'Cursor', 'User', 'globalStorage'));
202
+ return Array.from(new Set(dirs.map((dir) => resolve(dir))));
203
+ }
204
+ function runtimeHome() {
205
+ return process.env['HOME'] || homedir();
206
+ }
207
+ function defaultRuntimeSessionDirs() {
208
+ const home = runtimeHome();
209
+ // ~/.gemini/tmp holds per-project <hash>/chats/session-*.{json,jsonl}; the gemini
210
+ // adapter's detect() only matches those session files (never logs.json).
211
+ // Cursor's globalStorage holds state.vscdb (sqlite) — discovered via isCursorStateVscdbPath.
212
+ // ~/.kimi holds Kimi CLI wire.jsonl logs (no per-file cwd) — discovered as a cwd-less agent.
213
+ return [
214
+ join(home, '.codex', 'sessions'),
215
+ join(home, '.claude', 'projects'),
216
+ join(home, '.gemini', 'tmp'),
217
+ join(home, '.kimi'),
218
+ ...cursorGlobalStorageDirs(home),
219
+ ];
220
+ }
221
+ function runtimeSessionDirs(flags) {
222
+ const dirs = [];
223
+ for (const path of flags.runtimeSessionDirs ?? [])
224
+ dirs.push({ path, required: true });
225
+ for (const path of [
226
+ ...splitEnvDirs(process.env[RUNTIME_SESSION_DIRS_ENV]),
227
+ ...splitEnvDirs(process.env[RUNTIME_SESSION_DIRS_ENV_LEGACY]),
228
+ ...splitEnvDirs(process.env['EVOLVER_CURSOR_TRANSCRIPTS_DIR']),
229
+ ])
230
+ dirs.push({ path, required: true });
231
+ if (flags.runtimeSessions
232
+ || truthyEnv(process.env[RUNTIME_SESSION_ENABLE_ENV])
233
+ || truthyEnv(process.env[RUNTIME_SESSION_ENABLE_ENV_LEGACY])) {
234
+ for (const path of defaultRuntimeSessionDirs())
235
+ dirs.push({ path, required: false });
236
+ }
237
+ const seen = new Set();
238
+ return dirs.filter((dir) => {
239
+ const key = resolve(dir.path);
240
+ if (seen.has(key))
241
+ return false;
242
+ seen.add(key);
243
+ return true;
244
+ });
245
+ }
246
+ function assertRuntimeSessionDirBoundary(path) {
247
+ const resolved = resolve(path);
248
+ const home = resolve(runtimeHome());
249
+ const root = resolve(sep);
250
+ if (resolved === root || resolved === home || home.startsWith(`${resolved}${sep}`)) {
251
+ throw new Error(`runtime session directory is too broad: ${resolved}`);
252
+ }
253
+ if (resolved === join(home, '.codex') || resolved === join(home, '.claude') || resolved === join(home, '.gemini')) {
254
+ throw new Error(`runtime session directory must be a session subdirectory: ${resolved}`);
255
+ }
256
+ }
257
+ function runtimeSessionFileForPath(path) {
258
+ const adapter = adapterForPath(path);
259
+ if (!adapter || !RUNTIME_DISCOVERY_AGENTS.has(adapter.agent))
260
+ return null;
261
+ return { path, kind: 'session', adapter, fromRuntimeDiscovery: true };
262
+ }
263
+ function readFileHead(path, maxBytes) {
264
+ const fd = openSync(path, 'r');
265
+ try {
266
+ const buffer = Buffer.alloc(maxBytes);
267
+ const bytesRead = readSync(fd, buffer, 0, maxBytes, 0);
268
+ return buffer.slice(0, bytesRead).toString('utf8');
269
+ }
270
+ finally {
271
+ closeSync(fd);
272
+ }
273
+ }
274
+ function transcriptCwd(path) {
275
+ try {
276
+ const head = readFileHead(path, TRANSCRIPT_CWD_HEAD_BYTES);
277
+ for (const line of head.split('\n').slice(0, TRANSCRIPT_CWD_MAX_LINES)) {
278
+ if (!line.trim())
279
+ continue;
280
+ // Parse per line: a truncated final line (the head window may cut JSON
281
+ // mid-record) must not discard a cwd found on an earlier line.
282
+ let row;
283
+ try {
284
+ row = JSON.parse(line);
285
+ }
286
+ catch {
287
+ continue;
288
+ }
289
+ if (!row || typeof row !== 'object' || Array.isArray(row))
290
+ continue;
291
+ const record = row;
292
+ const payload = record['payload'];
293
+ if (record['type'] === 'session_meta' && payload && typeof payload === 'object' && !Array.isArray(payload)) {
294
+ const cwd = payload['cwd'];
295
+ if (typeof cwd === 'string' && cwd.trim())
296
+ return cwd;
297
+ }
298
+ const cwd = record['cwd'];
299
+ if (typeof cwd === 'string' && cwd.trim())
300
+ return cwd;
301
+ const data = record['data'];
302
+ if (data && typeof data === 'object' && !Array.isArray(data)) {
303
+ const nested = data['cwd'];
304
+ if (typeof nested === 'string' && nested.trim())
305
+ return nested;
306
+ }
307
+ }
308
+ }
309
+ catch {
310
+ return undefined;
311
+ }
312
+ return undefined;
313
+ }
314
+ function normalizeWorkspacePath(path) {
315
+ if (!path)
316
+ return undefined;
317
+ try {
318
+ const resolved = resolve(path).replace(/[\\/]+$/, '');
319
+ try {
320
+ return realpathSync.native(resolved).replace(/[\\/]+$/, '');
321
+ }
322
+ catch {
323
+ return realpathSync(resolved).replace(/[\\/]+$/, '');
324
+ }
325
+ }
326
+ catch {
327
+ try {
328
+ return resolve(path).replace(/[\\/]+$/, '');
329
+ }
330
+ catch {
331
+ return undefined;
332
+ }
333
+ }
334
+ }
335
+ function findGitRoot(start) {
336
+ let current = normalizeWorkspacePath(start);
337
+ while (current && current !== dirname(current)) {
338
+ if (existsSync(join(current, '.git')))
339
+ return current;
340
+ current = dirname(current);
341
+ }
342
+ return undefined;
343
+ }
344
+ function runtimeWorkspaceRoots() {
345
+ const roots = [
346
+ process.env['EVOLVER_REPO_ROOT'],
347
+ process.cwd(),
348
+ findGitRoot(process.cwd()),
349
+ ].map(normalizeWorkspacePath).filter((value) => Boolean(value));
350
+ return Array.from(new Set(roots));
351
+ }
352
+ function runtimeSessionBelongsToWorkspace(path, roots) {
353
+ const cwd = normalizeWorkspacePath(transcriptCwd(path));
354
+ if (!cwd)
355
+ return false;
356
+ return roots.some((root) => cwd === root || cwd.startsWith(`${root}${sep}`));
357
+ }
358
+ function inputFileForPath(path, explicit, strictUnknownJson = false) {
359
+ if (TRACE_FILE_RE.test(path))
360
+ return { path, kind: 'trace' };
361
+ // Cursor stores chat in a binary sqlite (state.vscdb), not a JSONL transcript — route it to the
362
+ // dedicated sqlite reader instead of trying to read it as a text chunk.
363
+ if (isCursorStateVscdbPath(path))
364
+ return { path, kind: 'cursor-vscdb' };
365
+ const adapter = adapterForPath(path);
366
+ if (adapter) {
367
+ if (explicit && strictUnknownJson && isJsonCandidate(path)) {
368
+ const chunk = readFileSync(path, 'utf8');
369
+ if (adapterParsesRuntimeTurns(adapter, chunk))
370
+ return { path, kind: 'session', adapter };
371
+ if (traceLikeContent(chunk))
372
+ return { path, kind: 'trace' };
373
+ const contentAdapter = adapterForContent(chunk);
374
+ if (contentAdapter)
375
+ return { path, kind: 'session', adapter: contentAdapter };
376
+ if (isJsonlCandidate(path))
377
+ throw new Error(`trajectory input format is not recognized: ${path}`);
378
+ return null;
379
+ }
380
+ return { path, kind: 'session', adapter };
381
+ }
382
+ if (!explicit || !isJsonCandidate(path))
383
+ return null;
384
+ const chunk = readFileSync(path, 'utf8');
385
+ if (traceLikeContent(chunk))
386
+ return { path, kind: 'trace' };
387
+ const contentAdapter = adapterForContent(chunk);
388
+ if (contentAdapter)
389
+ return { path, kind: 'session', adapter: contentAdapter };
390
+ if (!strictUnknownJson && !isJsonlCandidate(path))
391
+ return null;
392
+ throw new Error(`trajectory input format is not recognized: ${path}`);
393
+ }
394
+ function collectInputFiles(dir, explicit) {
395
+ const out = [];
396
+ const walk = (current) => {
397
+ for (const name of readdirSync(current).sort()) {
398
+ const path = join(current, name);
399
+ const st = lstatSync(path);
400
+ if (st.isSymbolicLink())
401
+ continue;
402
+ if (st.isDirectory()) {
403
+ walk(path);
404
+ continue;
405
+ }
406
+ if (!st.isFile())
407
+ continue;
408
+ const file = inputFileForPath(path, explicit, false);
409
+ if (file)
410
+ out.push(file);
411
+ }
412
+ };
413
+ walk(dir);
414
+ return out;
415
+ }
416
+ function collectRuntimeSessionInputFiles(dirs) {
417
+ const out = [];
418
+ const workspaceRoots = runtimeWorkspaceRoots();
419
+ const walk = (current) => {
420
+ let names;
421
+ try {
422
+ names = readdirSync(current).sort();
423
+ }
424
+ catch {
425
+ return;
426
+ }
427
+ for (const name of names) {
428
+ const path = join(current, name);
429
+ let st;
430
+ try {
431
+ st = lstatSync(path);
432
+ }
433
+ catch {
434
+ continue;
435
+ }
436
+ if (st.isSymbolicLink())
437
+ continue;
438
+ if (st.isDirectory()) {
439
+ walk(path);
440
+ continue;
441
+ }
442
+ if (!st.isFile())
443
+ continue;
444
+ // Cursor state.vscdb is a binary sqlite holding many cross-workspace composers; there is no per-file cwd to
445
+ // filter on, so discover it directly (workspace scoping is a no-op for a shared db).
446
+ if (isCursorStateVscdbPath(path)) {
447
+ out.push({ path, kind: 'cursor-vscdb', fromRuntimeDiscovery: true });
448
+ continue;
449
+ }
450
+ // Resolve the adapter first so cwd-less agents (gemini/kimi) can be accepted as .json and bypass the
451
+ // workspace-cwd gate that would otherwise silently drop every one of their files.
452
+ const adapter = adapterForPath(path);
453
+ const cwdless = adapter !== undefined && CWDLESS_DISCOVERY_AGENTS.has(adapter.agent);
454
+ // cwd-less agents may use .json (Gemini) or .jsonl; cwd-bearing agents stay .jsonl-only as before.
455
+ if (cwdless ? !isJsonCandidate(path) : !isJsonlCandidate(path))
456
+ continue;
457
+ // cwd-less agents have no per-file cwd to scope on -> include them broadly; others keep workspace scoping.
458
+ if (!cwdless && !runtimeSessionBelongsToWorkspace(path, workspaceRoots))
459
+ continue;
460
+ const file = runtimeSessionFileForPath(path);
461
+ if (file)
462
+ out.push(file);
463
+ }
464
+ };
465
+ for (const dir of dirs) {
466
+ const root = resolve(dir.path);
467
+ assertRuntimeSessionDirBoundary(root);
468
+ let st;
469
+ try {
470
+ st = lstatSync(root);
471
+ }
472
+ catch {
473
+ if (dir.required)
474
+ throw new Error(`runtime session directory is not readable: ${root}`);
475
+ continue;
476
+ }
477
+ if (st.isSymbolicLink() || !st.isDirectory()) {
478
+ if (dir.required)
479
+ throw new Error(`runtime session directory is not readable: ${root}`);
480
+ continue;
481
+ }
482
+ walk(root);
483
+ }
484
+ return out;
485
+ }
486
+ function dedupeInputFiles(files) {
487
+ const seen = new Set();
488
+ return files.filter((file) => {
489
+ const key = resolve(file.path);
490
+ if (seen.has(key))
491
+ return false;
492
+ seen.add(key);
493
+ return true;
494
+ });
495
+ }
496
+ function inputFiles(input, runtimeDirs) {
497
+ const target = input ? resolve(input) : events.tracesDir();
498
+ let files;
499
+ if (!existsSync(target)) {
500
+ if (input !== undefined)
501
+ throw new Error(`trace input is not readable: ${target}`);
502
+ files = [];
503
+ }
504
+ else {
505
+ const st = statSync(target);
506
+ if (st.isFile()) {
507
+ const file = inputFileForPath(target, true, true);
508
+ files = file ? [file] : [];
509
+ }
510
+ else if (st.isDirectory()) {
511
+ if (input === undefined) {
512
+ files = readdirSync(target)
513
+ .filter((name) => TRACE_FILE_RE.test(name))
514
+ .sort()
515
+ .flatMap((name) => {
516
+ const path = join(target, name);
517
+ try {
518
+ const item = lstatSync(path);
519
+ return item.isFile() ? [{ path, kind: 'trace' }] : [];
520
+ }
521
+ catch {
522
+ return [];
523
+ }
524
+ });
525
+ }
526
+ else {
527
+ files = collectInputFiles(target, true);
528
+ if (files.length === 0)
529
+ throw new Error(`trajectory input format is not recognized: ${target}`);
530
+ }
531
+ }
532
+ else {
533
+ if (input !== undefined)
534
+ throw new Error(`trace input is not readable: ${target}`);
535
+ files = [];
536
+ }
537
+ }
538
+ return dedupeInputFiles([...files, ...collectRuntimeSessionInputFiles(runtimeDirs)]);
539
+ }
540
+ // ── marker / gateway gates ───────────────────────────────────────────────────
541
+ /** Set of runtime session_ids evolver has marked, read from `value.inject` root_events (the SessionStart hook
542
+ * stamps the runtime session_id onto each). Mirrors recall.ts: a runtime session is "marked" iff its session_id
543
+ * appears here. Best-effort: a missing/unreadable root_events log yields an empty set (strict mode then collects
544
+ * nothing — the caller can still pass --include-unmarked to bypass the gate). */
545
+ function markedSessionIds() {
546
+ const out = new Set();
547
+ try {
548
+ for (const e of events.readEvents()) {
549
+ if (e.type !== ops.VALUE_INJECT_EVENT)
550
+ continue;
551
+ const sid = e.payload?.['sessionId'];
552
+ addSessionIdAliases(out, sid);
553
+ }
554
+ }
555
+ catch {
556
+ /* no root_events / unreadable → empty set */
557
+ }
558
+ return out;
559
+ }
560
+ const CLAUDE_USER_SESSION_MARKER = '__session_';
561
+ function sessionIdAliases(value) {
562
+ if (typeof value !== 'string')
563
+ return [];
564
+ const raw = value.trim();
565
+ if (!raw)
566
+ return [];
567
+ const aliases = [raw];
568
+ const marker = raw.indexOf(CLAUDE_USER_SESSION_MARKER);
569
+ if (marker >= 0) {
570
+ const sessionId = raw.slice(marker + CLAUDE_USER_SESSION_MARKER.length).trim();
571
+ if (sessionId)
572
+ aliases.push(sessionId);
573
+ }
574
+ return Array.from(new Set(aliases));
575
+ }
576
+ function addSessionIdAliases(out, value) {
577
+ for (const alias of sessionIdAliases(value))
578
+ out.add(alias);
579
+ }
580
+ /** Set of session_ids the gateway already captured, read from the proxy's llm-trace-*.jsonl day files. The proxy
581
+ * extracts the SAME session_id the tool names its transcript with (Claude metadata.user_id / cursor headers), so
582
+ * these align with runtime-session session_ids and can de-dupe the two rails. Decryption uses the same node-secret
583
+ * material the trace链路 already resolves; rows that stay encrypted simply contribute no session_id (they cannot
584
+ * collide with a plaintext runtime session_id anyway). */
585
+ function gatewayCapturedSessionIds(tracesDir, readOpts) {
586
+ const out = new Set();
587
+ try {
588
+ if (!existsSync(tracesDir))
589
+ return out;
590
+ const st = statSync(tracesDir);
591
+ if (!st.isDirectory())
592
+ return out;
593
+ for (const name of readdirSync(tracesDir).sort()) {
594
+ if (!TRACE_FILE_RE.test(name))
595
+ continue;
596
+ const path = join(tracesDir, name);
597
+ try {
598
+ if (lstatSync(path).isSymbolicLink())
599
+ continue;
600
+ const chunk = readFileSync(path, 'utf8');
601
+ const result = trace.readTraceRowsFromJsonl(chunk, readOpts);
602
+ for (const row of result.rows) {
603
+ const sid = row['session_id'] ?? row['sessionId'];
604
+ addSessionIdAliases(out, sid);
605
+ }
606
+ }
607
+ catch {
608
+ /* skip an unreadable / malformed trace file */
609
+ }
610
+ }
611
+ }
612
+ catch {
613
+ /* traces dir vanished mid-scan → whatever we collected */
614
+ }
615
+ return out;
616
+ }
617
+ /** Resolve the session_id a discovered runtime session file will be keyed on, WITHOUT a full parse — mirrors
618
+ * recall.ts/sessionMetadata: codex names the id inside session_meta.payload.id, every other transcript is named
619
+ * `<session_id>.<ext>` so the basename (minus extension) is the id. cursor-vscdb is special-cased by the caller
620
+ * (its session_id is per-composer, resolved at parse time), so it never reaches here. */
621
+ function runtimeSessionIdForFile(file) {
622
+ if (file.adapter?.agent === 'codex') {
623
+ try {
624
+ const head = readFileHead(file.path, TRANSCRIPT_CWD_HEAD_BYTES);
625
+ for (const line of head.split('\n').slice(0, TRANSCRIPT_CWD_MAX_LINES)) {
626
+ if (!line.trim())
627
+ continue;
628
+ let row;
629
+ try {
630
+ row = JSON.parse(line);
631
+ }
632
+ catch {
633
+ continue;
634
+ }
635
+ if (!row || typeof row !== 'object' || Array.isArray(row))
636
+ continue;
637
+ const record = row;
638
+ if (record['type'] === 'session_meta' && record['payload'] && typeof record['payload'] === 'object' && !Array.isArray(record['payload'])) {
639
+ const id = record['payload']['id'];
640
+ if (typeof id === 'string' && id.length > 0)
641
+ return id;
642
+ }
643
+ }
644
+ }
645
+ catch {
646
+ /* fall through to basename */
647
+ }
648
+ }
649
+ const base = basename(file.path).replace(/\.jsonl?$/i, '').replace(/\.json$/i, '');
650
+ return base.length > 0 ? base : undefined;
651
+ }
652
+ /** Decide whether a discovered runtime session (by its session_id) passes the marker + gateway gates. Files that
653
+ * did NOT come from runtime discovery (explicit --input) always pass — the gates are scoped to discovery only. */
654
+ function passesRuntimeGates(sessionId, marked, gatewayCaptured, flags) {
655
+ if (!flags.includeUnmarked) {
656
+ if (sessionId === undefined || !marked.has(sessionId))
657
+ return { collect: false, reason: 'unmarked' };
658
+ }
659
+ if (!flags.includeGatewayCaptured && sessionId !== undefined && gatewayCaptured.has(sessionId)) {
660
+ return { collect: false, reason: 'gateway_captured' };
661
+ }
662
+ return { collect: true };
663
+ }
664
+ function sessionMetadata(file, chunk, sourceAgent) {
665
+ const rows = parseJsonlLines(chunk);
666
+ const started = rows.find((row) => typeof row['timestamp'] === 'string')?.['timestamp'];
667
+ if (sourceAgent === 'codex') {
668
+ const meta = rows.find((row) => row['type'] === 'session_meta' && row['payload'] && typeof row['payload'] === 'object');
669
+ const payload = meta?.['payload'];
670
+ const id = payload && typeof payload['id'] === 'string' ? payload['id'] : undefined;
671
+ return { ...(id ? { sessionId: id } : {}), ...(typeof started === 'string' ? { startedAt: started } : {}) };
672
+ }
673
+ const fallback = basename(file).replace(/\.jsonl?$/i, '').replace(/\.json$/i, '');
674
+ return { ...(fallback ? { sessionId: fallback } : {}), ...(typeof started === 'string' ? { startedAt: started } : {}) };
675
+ }
676
+ function parseRuntimeSessions(adapter, chunk) {
677
+ if (adapter.parseSessions)
678
+ return adapter.parseSessions(chunk);
679
+ if (adapter.parseSession)
680
+ return [adapter.parseSession(chunk)];
681
+ return [{ turns: adapter.parse(chunk) }];
682
+ }
683
+ function usage() {
684
+ return [
685
+ '用法: evolver trajectory-export [--input <trace-or-session-file-or-dir>] [--output <jsonl>] [--allow-partial]',
686
+ ' --input <path> 支持 llm-trace JSONL,以及 Claude/Codex/Cursor session JSONL',
687
+ ' --runtime-sessions 同时扫描本机 ~/.codex/sessions、~/.claude/projects、~/.gemini/tmp、~/.kimi 与 Cursor state.vscdb(仅本地导出,不上传 Hub)',
688
+ ' --runtime-session-dir <dir> 额外扫描一个明确的本机 runtime session 目录;可重复',
689
+ ' --include-unmarked 关闭“标记闸门”:默认严格模式只采 evolver 主动标记过的会话(root_events.jsonl 的 value.inject 事件里有该 sessionId);',
690
+ ' 加此开关恢复旧的“采全”行为。等价 env EVOLVER_TRAJECTORY_INCLUDE_UNMARKED=1。仅作用于 runtime-session 发现链路。',
691
+ ' --include-gateway-captured 关闭“去重闸门”:默认跳过网关(llm-trace-*.jsonl)已采集的同 session_id 会话,只补网关漏的;',
692
+ ' 加此开关一并采集网关已采的会话。等价 env EVOLVER_TRAJECTORY_INCLUDE_GATEWAY_CAPTURED=1。仅作用于 runtime-session 发现链路。',
693
+ ' --node-secret <hex|file> 解密 node-secret trace envelope;默认读 env 或 ~/.evomap/node_secret',
694
+ ' --node-secret-file <file> 从文件读取 node secret(v1 兼容)',
695
+ ' --node-secret-env <name> 从环境变量读取 node secret(v1 兼容)',
696
+ ' --node-secret-keyring <json> 按 envelope.secret_version 选择 node secret;支持对象或数组格式',
697
+ ' --hub-private-key <file> 解密带 hub_key_envelope 的 trace envelope',
698
+ ].join('\n') + '\n';
699
+ }
700
+ function writeOutputAtomically(output, trajectories) {
701
+ try {
702
+ const st = lstatSync(output);
703
+ if (st.isDirectory())
704
+ throw new Error(`trajectory output path is a directory: ${output}`);
705
+ }
706
+ catch (err) {
707
+ const code = err.code;
708
+ if (code !== 'ENOENT')
709
+ throw err;
710
+ }
711
+ const tmp = `${output}.tmp-${process.pid}-${Date.now()}`;
712
+ const fd = openSync(tmp, 'wx', 0o600);
713
+ let closed = false;
714
+ try {
715
+ for (const trajectory of trajectories) {
716
+ writeSync(fd, `${JSON.stringify(trajectory)}\n`);
717
+ }
718
+ }
719
+ catch (err) {
720
+ closeSync(fd);
721
+ closed = true;
722
+ try {
723
+ unlinkSync(tmp);
724
+ }
725
+ catch { /* ignore cleanup failure */ }
726
+ throw err;
727
+ }
728
+ finally {
729
+ if (!closed)
730
+ closeSync(fd);
731
+ }
732
+ try {
733
+ renameSync(tmp, output);
734
+ }
735
+ catch (err) {
736
+ try {
737
+ unlinkSync(tmp);
738
+ }
739
+ catch { /* ignore cleanup failure */ }
740
+ throw err;
741
+ }
742
+ }
743
+ export async function runTrajectoryExport(argv) {
744
+ let flags;
745
+ try {
746
+ flags = parseExportFlags(argv);
747
+ }
748
+ catch (err) {
749
+ process.stderr.write(`trajectory-export failed: ${err instanceof Error ? err.message : String(err)}\n`);
750
+ return 1;
751
+ }
752
+ if (flags.help) {
753
+ process.stdout.write(usage());
754
+ return 0;
755
+ }
756
+ const output = resolve(flags.output ?? 'coding-trajectories.jsonl');
757
+ const allRows = [];
758
+ const sessionTrajectories = [];
759
+ const stats = {
760
+ rowsScanned: 0,
761
+ rowsRead: 0,
762
+ invalidJson: 0,
763
+ encryptedRows: 0,
764
+ skippedMissingSecret: 0,
765
+ decryptFailures: 0,
766
+ nonTraceSkipped: 0,
767
+ };
768
+ let files = [];
769
+ let sessionFileCount = 0;
770
+ let sessionTurnCount = 0;
771
+ let excludedUnmarked = 0;
772
+ let excludedGatewayCaptured = 0;
773
+ const discoveredRuntimeDirs = runtimeSessionDirs(flags);
774
+ try {
775
+ files = inputFiles(flags.input, discoveredRuntimeDirs);
776
+ const readOpts = {
777
+ allowPartial: flags.allowPartial,
778
+ nodeSecret: resolveNodeSecret(flags),
779
+ nodeSecretKeyring: readNodeSecretKeyring(flags.nodeSecretKeyring),
780
+ hubPrivateKey: readSecretFile(flags.hubPrivateKey),
781
+ };
782
+ // Strict by default: the marker + gateway gates apply to the runtime-session discovery链路 only. Build the
783
+ // gate sets once. Both sets stay empty (and the gates are skipped) when nothing is discovered, so an explicit
784
+ // single-file --input export never pays for reading root_events / the trace dir.
785
+ const hasRuntimeDiscovery = files.some((file) => file.fromRuntimeDiscovery);
786
+ const gateFlags = {
787
+ includeUnmarked: flags.includeUnmarked === true || truthyEnv(process.env[INCLUDE_UNMARKED_ENV]),
788
+ includeGatewayCaptured: flags.includeGatewayCaptured === true || truthyEnv(process.env[INCLUDE_GATEWAY_CAPTURED_ENV]),
789
+ };
790
+ const marked = hasRuntimeDiscovery && !gateFlags.includeUnmarked ? markedSessionIds() : new Set();
791
+ const gatewayCaptured = hasRuntimeDiscovery && !gateFlags.includeGatewayCaptured
792
+ ? gatewayCapturedSessionIds(events.tracesDir(), { ...readOpts, allowPartial: true })
793
+ : new Set();
794
+ for (const file of files) {
795
+ if (file.kind === 'cursor-vscdb') {
796
+ // Read Cursor chat out of the sqlite db (read-only) and convert each composer to a trajectory. The
797
+ // marker/gateway gates run PER COMPOSER here (each composerId is its own session_id), so a state.vscdb
798
+ // holding many composers contributes only the ones evolver marked (and not already gateway-captured).
799
+ for (const parsedSession of parseCursorStateVscdb(file.path)) {
800
+ const { turns, ...adapterMetadata } = parsedSession;
801
+ if (file.fromRuntimeDiscovery) {
802
+ const composerSessionId = typeof adapterMetadata.sessionId === 'string' ? adapterMetadata.sessionId : undefined;
803
+ const gate = passesRuntimeGates(composerSessionId, marked, gatewayCaptured, gateFlags);
804
+ if (!gate.collect) {
805
+ if (gate.reason === 'unmarked')
806
+ excludedUnmarked += 1;
807
+ else
808
+ excludedGatewayCaptured += 1;
809
+ continue;
810
+ }
811
+ }
812
+ sessionTurnCount += turns.length;
813
+ const trajectory = trace.buildCodingTrajectoryFromSessionLog({
814
+ sourceAgent: 'cursor',
815
+ sourcePath: file.path,
816
+ turns,
817
+ ...adapterMetadata,
818
+ });
819
+ if (trajectory) {
820
+ sessionFileCount += 1;
821
+ sessionTrajectories.push(trajectory);
822
+ }
823
+ }
824
+ continue;
825
+ }
826
+ // Marker/gateway gates for file-per-session runtime discovery (claude/codex/cursor-jsonl/gemini/kimi).
827
+ // Resolved from the session_id without a full parse (basename / codex session_meta.payload.id).
828
+ if (file.fromRuntimeDiscovery) {
829
+ const gate = passesRuntimeGates(runtimeSessionIdForFile(file), marked, gatewayCaptured, gateFlags);
830
+ if (!gate.collect) {
831
+ if (gate.reason === 'unmarked')
832
+ excludedUnmarked += 1;
833
+ else
834
+ excludedGatewayCaptured += 1;
835
+ continue;
836
+ }
837
+ }
838
+ const chunk = readFileSync(file.path, 'utf8');
839
+ if (file.kind === 'trace') {
840
+ const result = trace.readTraceRowsFromJsonl(chunk, readOpts);
841
+ allRows.push(...result.rows);
842
+ for (const key of Object.keys(stats))
843
+ stats[key] += result.stats[key];
844
+ continue;
845
+ }
846
+ const adapter = file.adapter ?? adapterForPath(file.path);
847
+ if (!adapter)
848
+ continue;
849
+ const parseStats = parseJsonlLinesWithStats(chunk).stats;
850
+ stats.rowsScanned += parseStats.rowsScanned;
851
+ stats.rowsRead += parseStats.rowsRead;
852
+ stats.invalidJson += parseStats.invalidJson;
853
+ const metadata = sessionMetadata(file.path, chunk, adapter.agent);
854
+ for (const parsedSession of parseRuntimeSessions(adapter, chunk)) {
855
+ const { turns, ...adapterMetadata } = parsedSession;
856
+ sessionTurnCount += turns.length;
857
+ const trajectory = trace.buildCodingTrajectoryFromSessionLog({
858
+ sourceAgent: adapter.agent,
859
+ sourcePath: file.path,
860
+ turns,
861
+ ...(parseStats.invalidJson > 0 ? { incompleteReasons: ['runtime_session_invalid_json'] } : {}),
862
+ ...metadata,
863
+ ...adapterMetadata,
864
+ });
865
+ if (trajectory) {
866
+ sessionFileCount += 1;
867
+ sessionTrajectories.push(trajectory);
868
+ }
869
+ }
870
+ }
871
+ }
872
+ catch (err) {
873
+ process.stderr.write(`trajectory-export failed: ${err instanceof Error ? err.message : String(err)}\n`);
874
+ return 1;
875
+ }
876
+ const trajectories = sessionTrajectories.concat(trace.buildCodingTrajectories(allRows));
877
+ try {
878
+ writeOutputAtomically(output, trajectories);
879
+ }
880
+ catch (err) {
881
+ process.stderr.write(`trajectory-export failed: ${err instanceof Error ? err.message : String(err)}\n`);
882
+ return 1;
883
+ }
884
+ process.stdout.write(`[trajectory-export] Wrote ${trajectories.length} trajector${trajectories.length === 1 ? 'y' : 'ies'} to ${output}\n`);
885
+ if (discoveredRuntimeDirs.length > 0)
886
+ process.stdout.write('[trajectory-export] Runtime session discovery is local-only; no Hub upload is performed.\n');
887
+ process.stdout.write(`[trajectory-export] Read ${allRows.length} trace row(s) and ${sessionTurnCount} session turn(s) from ${files.length} file(s).\n`);
888
+ if (sessionFileCount > 0)
889
+ process.stdout.write(`[trajectory-export] Converted ${sessionFileCount} runtime session file(s).\n`);
890
+ if (excludedUnmarked > 0 || excludedGatewayCaptured > 0) {
891
+ process.stdout.write(`[trajectory-export] Runtime session gate: excluded ${excludedUnmarked} unmarked (no evolver value.inject) and ${excludedGatewayCaptured} already-gateway-captured session(s). Pass --include-unmarked / --include-gateway-captured to collect them.\n`);
892
+ }
893
+ process.stdout.write(`[trajectory-export] Scanned ${stats.rowsScanned} row(s); encrypted=${stats.encryptedRows}, skipped_missing_secret=${stats.skippedMissingSecret}, decrypt_failures=${stats.decryptFailures}, invalid_json=${stats.invalidJson}, non_trace=${stats.nonTraceSkipped}.\n`);
894
+ return 0;
895
+ }