@reasontrail/cli 0.1.1 → 0.1.3
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/CHANGELOG.md +30 -0
- package/README.md +37 -3
- package/package.json +1 -1
- package/runtime/reasontrail-runtime.mjs +8241 -2282
- package/runtime/reasontrail-runtime.mjs.sha256 +1 -0
- package/skills/reasontrail/SKILL.md +153 -6
- package/src/build-info.json +1 -1
- package/src/cli.mjs +419 -125
- package/src/codex-sync.mjs +374 -34
- package/src/systemd-scope.mjs +3 -0
package/src/codex-sync.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
2
3
|
import { homedir } from "node:os";
|
|
3
4
|
import { basename, join, resolve } from "node:path";
|
|
4
5
|
import { spawnSync } from "node:child_process";
|
|
@@ -74,6 +75,12 @@ function isSystemOnlyText(text) {
|
|
|
74
75
|
return false;
|
|
75
76
|
}
|
|
76
77
|
|
|
78
|
+
// Suppress credential-bearing dialogue before managed capture makes an MCP call.
|
|
79
|
+
function containsCredential(text) {
|
|
80
|
+
return /-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----|\b(?:github_pat_|gh[pousr]_|sk-(?:proj-)?|sk_(?:live|test)_|rk_live_|xox[baprs]-)[A-Za-z0-9_-]{16,}|\bBearer\s+[A-Za-z0-9._~+/-]{20,}/i.test(text)
|
|
81
|
+
|| /\b(?:password|client_secret|api[_-]?key|access[_-]?token)\s*["']?\s*[:=]\s*["']?[A-Za-z0-9+/_.=-]{12,}/i.test(text);
|
|
82
|
+
}
|
|
83
|
+
|
|
77
84
|
function isVisibleAssistant(item) {
|
|
78
85
|
// Current rollouts use phase; legacy rollouts may omit both fields.
|
|
79
86
|
const visible = new Set(["commentary", "final", "final_answer"]);
|
|
@@ -143,6 +150,7 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
|
|
|
143
150
|
if (identity.error) return { ...identity, filePath };
|
|
144
151
|
const { threadId, parentThreadId, identitySource, historyStartLine } = identity;
|
|
145
152
|
let cwd = identity.cwd;
|
|
153
|
+
let turnCwd = cwd;
|
|
146
154
|
let excludedInheritedTurnCount = 0;
|
|
147
155
|
let startTs = null;
|
|
148
156
|
let endTs = null;
|
|
@@ -161,7 +169,10 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
|
|
|
161
169
|
}
|
|
162
170
|
if (!startTs && d.timestamp) startTs = d.timestamp;
|
|
163
171
|
if (d.timestamp) endTs = d.timestamp;
|
|
164
|
-
if (
|
|
172
|
+
if (d.type === "turn_context" && typeof d.payload?.cwd === "string") {
|
|
173
|
+
turnCwd = d.payload.cwd;
|
|
174
|
+
cwd ||= turnCwd;
|
|
175
|
+
}
|
|
165
176
|
|
|
166
177
|
// Only structured runtime error events establish a quota interruption.
|
|
167
178
|
// Messages and tool output may quote error names while discussing code.
|
|
@@ -187,9 +198,13 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
|
|
|
187
198
|
rawTurns.push({
|
|
188
199
|
id,
|
|
189
200
|
sourceLine: line,
|
|
201
|
+
cwd: turnCwd,
|
|
190
202
|
role,
|
|
191
203
|
content: cleaned,
|
|
192
|
-
|
|
204
|
+
// Missing source timestamps must stay missing. Substituting the
|
|
205
|
+
// current clock here makes the same native turn acquire a new
|
|
206
|
+
// fingerprint on every parse and defeats retry idempotency.
|
|
207
|
+
timestamp: d.timestamp || null,
|
|
193
208
|
});
|
|
194
209
|
}
|
|
195
210
|
}
|
|
@@ -214,9 +229,10 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
|
|
|
214
229
|
rawTurns.push({
|
|
215
230
|
id,
|
|
216
231
|
sourceLine: line,
|
|
232
|
+
cwd: turnCwd,
|
|
217
233
|
role,
|
|
218
234
|
content: cleaned,
|
|
219
|
-
timestamp: d.timestamp ||
|
|
235
|
+
timestamp: d.timestamp || null,
|
|
220
236
|
});
|
|
221
237
|
}
|
|
222
238
|
}
|
|
@@ -237,10 +253,14 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
|
|
|
237
253
|
continue;
|
|
238
254
|
}
|
|
239
255
|
}
|
|
256
|
+
const fingerprint = createHash("sha256").update(`${t.id}\0${t.timestamp ?? ""}\0${t.role}\0${t.content}`).digest("hex");
|
|
240
257
|
turns.push({
|
|
241
258
|
messageId: `codex:${threadId}:${turns.length}`,
|
|
259
|
+
stableMessageId: `codex:${threadId}:native:${fingerprint.slice(0, 32)}`,
|
|
260
|
+
fingerprint,
|
|
242
261
|
nativeMessageId: t.id,
|
|
243
262
|
sourceLine: t.sourceLine,
|
|
263
|
+
cwd: t.cwd,
|
|
244
264
|
role: t.role,
|
|
245
265
|
content: t.content,
|
|
246
266
|
sequence: turns.length,
|
|
@@ -262,6 +282,9 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
|
|
|
262
282
|
if (!title) {
|
|
263
283
|
title = `Codex session ${threadId.slice(0, 8)}`;
|
|
264
284
|
}
|
|
285
|
+
const sourceCheckpoint = `codex:${threadId}:${turns.length}:${createHash("sha256")
|
|
286
|
+
.update(turns.map((turn) => turn.fingerprint).join("\0"))
|
|
287
|
+
.digest("hex")}`;
|
|
265
288
|
|
|
266
289
|
return {
|
|
267
290
|
filePath,
|
|
@@ -278,6 +301,7 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
|
|
|
278
301
|
turnCount: turns.length,
|
|
279
302
|
userTurnCount: turns.filter((t) => t.role === "user").length,
|
|
280
303
|
assistantTurnCount: turns.filter((t) => t.role === "assistant").length,
|
|
304
|
+
sourceCheckpoint,
|
|
281
305
|
usageExceeded,
|
|
282
306
|
usageExceededMessage,
|
|
283
307
|
interrupted: usageExceeded,
|
|
@@ -295,7 +319,14 @@ export async function discoverAndMapCodexSessions(options = {}) {
|
|
|
295
319
|
const codexHome = options.codexHome || defaultCodexHome();
|
|
296
320
|
const sessionsDir = join(codexHome, "sessions");
|
|
297
321
|
const threadNames = await readSessionIndex(codexHome);
|
|
298
|
-
const
|
|
322
|
+
const discoveredFiles = await findJsonlFiles(sessionsDir);
|
|
323
|
+
// Exact-session recovery may inspect only the requested native transcript.
|
|
324
|
+
// Codex rollout filenames carry the native thread id, so filter paths before
|
|
325
|
+
// opening any JSONL content. If the file is absent, fail closed instead of
|
|
326
|
+
// scanning unrelated transcripts looking for a plausible identity.
|
|
327
|
+
const files = options.session
|
|
328
|
+
? discoveredFiles.filter((file) => basename(file).includes(String(options.session)))
|
|
329
|
+
: discoveredFiles;
|
|
299
330
|
|
|
300
331
|
const gitCache = {};
|
|
301
332
|
const resolveGit = (dir) => {
|
|
@@ -307,10 +338,32 @@ export async function discoverAndMapCodexSessions(options = {}) {
|
|
|
307
338
|
};
|
|
308
339
|
|
|
309
340
|
const bindings = options.bindings || {};
|
|
341
|
+
const gitCommon = new Map();
|
|
342
|
+
function commonDir(root) {
|
|
343
|
+
if (!root) return null;
|
|
344
|
+
if (!gitCommon.has(root)) {
|
|
345
|
+
const result = spawnSync("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd: root, encoding: "utf8" });
|
|
346
|
+
gitCommon.set(root, result.status === 0 ? result.stdout.trim() : null);
|
|
347
|
+
}
|
|
348
|
+
return gitCommon.get(root);
|
|
349
|
+
}
|
|
350
|
+
function bindingOf(cwd) {
|
|
351
|
+
const root = resolveGit(cwd);
|
|
352
|
+
if (!root) return null;
|
|
353
|
+
if (bindings[root]) return bindings[root];
|
|
354
|
+
const common = commonDir(root);
|
|
355
|
+
const siblings = common ? Object.entries(bindings).filter(([path]) => common === commonDir(path)).map(([, value]) => value) : [];
|
|
356
|
+
return new Set(siblings.map(binding => binding.projectSlug)).size === 1 ? siblings[0] : null;
|
|
357
|
+
}
|
|
358
|
+
const starts = Object.values(bindings).filter(b => !options.project || b.projectSlug === options.project)
|
|
359
|
+
.map(b => Date.parse(b.captureFrom ?? "")).filter(Number.isFinite);
|
|
360
|
+
const earliest = starts.length ? Math.min(...starts) : 0;
|
|
310
361
|
const sessions = [];
|
|
362
|
+
const observedProjects = new Map();
|
|
311
363
|
const parseFailures = [];
|
|
312
364
|
|
|
313
365
|
for (const file of files) {
|
|
366
|
+
if (options.managed && earliest && (await stat(file)).mtimeMs < earliest) continue;
|
|
314
367
|
const parsed = await parseCodexSessionFile(file, threadNames);
|
|
315
368
|
if (parsed.error) {
|
|
316
369
|
parseFailures.push({ filePath: file, reason: parsed.error });
|
|
@@ -329,17 +382,32 @@ export async function discoverAndMapCodexSessions(options = {}) {
|
|
|
329
382
|
|
|
330
383
|
// Filter by --session if requested
|
|
331
384
|
if (options.session && parsed.threadId !== options.session) {
|
|
385
|
+
parseFailures.push({ filePath: file, reason: "requested_session_identity_mismatch" });
|
|
332
386
|
continue;
|
|
333
387
|
}
|
|
334
388
|
|
|
335
389
|
const gitRoot = resolveGit(parsed.cwd);
|
|
336
|
-
const
|
|
337
|
-
const
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
390
|
+
const selected = parsed.turns.map(turn => ({ turn, binding: bindingOf(turn.cwd) }));
|
|
391
|
+
const slugs = new Set(selected.map(row => row.binding?.projectSlug).filter(Boolean));
|
|
392
|
+
const seen = observedProjects.get(parsed.threadId) ?? new Set();
|
|
393
|
+
for (const slug of slugs) seen.add(slug);
|
|
394
|
+
observedProjects.set(parsed.threadId, seen);
|
|
395
|
+
if (seen.size > 1) {
|
|
396
|
+
parseFailures.push({ filePath: file, reason: "multiple_bound_projects" });
|
|
341
397
|
continue;
|
|
342
398
|
}
|
|
399
|
+
const projectSlug = [...slugs][0] ?? bindingOf(parsed.cwd)?.projectSlug ?? null;
|
|
400
|
+
if (options.project && projectSlug !== options.project) continue;
|
|
401
|
+
if (projectSlug) {
|
|
402
|
+
const scoped = selected.filter(({ turn, binding }) => binding?.projectSlug === projectSlug
|
|
403
|
+
&& (!options.managed || !containsCredential(turn.content))
|
|
404
|
+
&& (!options.managed || !binding.captureFrom || Date.parse(turn.timestamp) >= Date.parse(binding.captureFrom)));
|
|
405
|
+
if (!scoped.length) continue;
|
|
406
|
+
if (scoped.length !== parsed.turns.length || options.managed) {
|
|
407
|
+
parsed.turns = scoped.map(({ turn }) => ({ ...turn, messageId: turn.stableMessageId }));
|
|
408
|
+
parsed.title = parsed.turns.find(turn => turn.role === "user")?.content.split("\n")[0].slice(0, 120) || "Codex project conversation";
|
|
409
|
+
}
|
|
410
|
+
}
|
|
343
411
|
|
|
344
412
|
const mapped = Boolean(projectSlug);
|
|
345
413
|
sessions.push({
|
|
@@ -358,13 +426,34 @@ export async function discoverAndMapCodexSessions(options = {}) {
|
|
|
358
426
|
if (!existing) {
|
|
359
427
|
byThread.set(s.threadId, s);
|
|
360
428
|
} else {
|
|
361
|
-
//
|
|
362
|
-
if (
|
|
363
|
-
|
|
429
|
+
// Desktop may rotate one native thread into several rollout files.
|
|
430
|
+
if (existing.projectSlug !== s.projectSlug) {
|
|
431
|
+
parseFailures.push({ filePath: s.filePath, reason: "rotated_project_mismatch" });
|
|
432
|
+
existing.ambiguous = true;
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
435
|
+
const known = new Map(existing.turns.map(turn => [turn.timestamp
|
|
436
|
+
? JSON.stringify([turn.timestamp, turn.role, turn.content]) : turn.fingerprint, turn]));
|
|
437
|
+
for (const turn of s.turns) {
|
|
438
|
+
const key = turn.timestamp ? JSON.stringify([turn.timestamp, turn.role, turn.content]) : turn.fingerprint;
|
|
439
|
+
if (!known.has(key)) known.set(key, turn);
|
|
440
|
+
}
|
|
441
|
+
existing.turns = [...known.values()].sort((a, b) => (a.timestamp ?? "").localeCompare(b.timestamp ?? ""))
|
|
442
|
+
.map(turn => ({ ...turn, messageId: turn.stableMessageId }));
|
|
443
|
+
if ((s.updatedAt ?? "") > (existing.updatedAt ?? "")) {
|
|
444
|
+
existing.updatedAt = s.updatedAt;
|
|
445
|
+
existing.interrupted = s.interrupted;
|
|
446
|
+
existing.interruptionReason = s.interruptionReason;
|
|
364
447
|
}
|
|
365
448
|
}
|
|
366
449
|
}
|
|
367
|
-
const resultSessions = Array.from(byThread.values());
|
|
450
|
+
const resultSessions = Array.from(byThread.values()).filter(s => !s.ambiguous && observedProjects.get(s.threadId)?.size <= 1);
|
|
451
|
+
for (const session of resultSessions) {
|
|
452
|
+
session.turnCount = session.turns.length;
|
|
453
|
+
session.userTurnCount = session.turns.filter(turn => turn.role === "user").length;
|
|
454
|
+
session.assistantTurnCount = session.turnCount - session.userTurnCount;
|
|
455
|
+
session.sourceCheckpoint = `codex:${session.threadId}:${session.turnCount}:${createHash("sha256").update(session.turns.map(t => t.fingerprint).join("\0")).digest("hex")}`;
|
|
456
|
+
}
|
|
368
457
|
|
|
369
458
|
// Sort chronologically
|
|
370
459
|
resultSessions.sort((a, b) => new Date(a.updatedAt || 0).getTime() - new Date(b.updatedAt || 0).getTime());
|
|
@@ -390,10 +479,61 @@ export async function saveSyncState(configDir, state) {
|
|
|
390
479
|
await writeFile(statePath, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
|
|
391
480
|
}
|
|
392
481
|
|
|
482
|
+
const MAX_RECONCILIATION_TURNS = 200;
|
|
483
|
+
|
|
484
|
+
function turnChunks(turns) {
|
|
485
|
+
if (turns.length === 0) return [[]];
|
|
486
|
+
const chunks = [];
|
|
487
|
+
for (let offset = 0; offset < turns.length; offset += MAX_RECONCILIATION_TURNS) {
|
|
488
|
+
chunks.push(turns.slice(offset, offset + MAX_RECONCILIATION_TURNS).map(
|
|
489
|
+
({ messageId, role, content, sequence, timestamp }) => ({ messageId, role, content, sequence, timestamp }),
|
|
490
|
+
));
|
|
491
|
+
}
|
|
492
|
+
return chunks;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
function combineReconciliations(results, session) {
|
|
496
|
+
const rank = {
|
|
497
|
+
SOURCE_EMPTY: 0,
|
|
498
|
+
NO_ACTION: 1,
|
|
499
|
+
SYNC_DELTA: 2,
|
|
500
|
+
RELINK_EXISTING: 3,
|
|
501
|
+
ERROR: 4,
|
|
502
|
+
MANUAL_REVIEW: 5,
|
|
503
|
+
};
|
|
504
|
+
const selected = results.reduce((best, result) =>
|
|
505
|
+
(rank[result?.recommendedAction] ?? 4) > (rank[best?.recommendedAction] ?? -1) ? result : best
|
|
506
|
+
, null) || {};
|
|
507
|
+
const sum = (key) => results.reduce((total, result) => total + Number(result?.[key] || 0), 0);
|
|
508
|
+
const unique = (key) => [...new Set(results.flatMap((result) =>
|
|
509
|
+
Array.isArray(result?.[key]) ? result[key] : []
|
|
510
|
+
))];
|
|
511
|
+
return {
|
|
512
|
+
...selected,
|
|
513
|
+
sourceSessionId: session.threadId,
|
|
514
|
+
sourceCheckpoint: session.sourceCheckpoint,
|
|
515
|
+
availableSourceTurns: session.turns.length,
|
|
516
|
+
duplicateSourceTurns: sum("duplicateSourceTurns"),
|
|
517
|
+
excludedTurns: sum("excludedTurns"),
|
|
518
|
+
newTurns: sum("newTurns"),
|
|
519
|
+
duplicates: sum("duplicates"),
|
|
520
|
+
persistedMatchingSourceMessages: sum("persistedMatchingSourceMessages"),
|
|
521
|
+
storedMessages: Math.max(0, ...results.map((result) => Number(result?.storedMessages || 0))),
|
|
522
|
+
totalConversationMessages: Math.max(0, ...results.map((result) => Number(result?.totalConversationMessages || 0))),
|
|
523
|
+
alreadyPersistedElsewhere: unique("alreadyPersistedElsewhere"),
|
|
524
|
+
conflictingMessageIds: unique("conflictingMessageIds"),
|
|
525
|
+
coverage: results.every((result) => result?.coverage === "COMPLETE_THROUGH_CHECKPOINT")
|
|
526
|
+
? "COMPLETE_THROUGH_CHECKPOINT"
|
|
527
|
+
: "PARTIAL",
|
|
528
|
+
chunkCount: results.length,
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
|
|
393
532
|
export async function syncCodex(client, tools, configDir, config, options = {}) {
|
|
394
533
|
const bindings = config.bindings || {};
|
|
395
534
|
const sessions = await discoverAndMapCodexSessions({
|
|
396
535
|
codexHome: options.codexHome || defaultCodexHome(),
|
|
536
|
+
managed: options.managed === true,
|
|
397
537
|
bindings,
|
|
398
538
|
since: options.since,
|
|
399
539
|
session: options.session,
|
|
@@ -410,6 +550,7 @@ export async function syncCodex(client, tools, configDir, config, options = {})
|
|
|
410
550
|
let skippedUnmapped = 0;
|
|
411
551
|
|
|
412
552
|
const eligibleSessions = [];
|
|
553
|
+
const mappedSessions = [];
|
|
413
554
|
|
|
414
555
|
for (const s of sessions) {
|
|
415
556
|
if (!s.mapped) {
|
|
@@ -419,22 +560,102 @@ export async function syncCodex(client, tools, configDir, config, options = {})
|
|
|
419
560
|
mapped++;
|
|
420
561
|
|
|
421
562
|
const prevSync = syncState[s.threadId];
|
|
422
|
-
const
|
|
563
|
+
const currentFingerprints = s.turns.map((turn) => turn.fingerprint);
|
|
564
|
+
const hasDurableFingerprintCursor = Array.isArray(prevSync?.turnFingerprints);
|
|
565
|
+
const prefixStillPresent = hasDurableFingerprintCursor
|
|
566
|
+
&& prevSync.turnFingerprints.every((fingerprint, index) => currentFingerprints[index] === fingerprint);
|
|
567
|
+
const priorFingerprints = new Set(hasDurableFingerprintCursor ? prevSync.turnFingerprints : []);
|
|
568
|
+
const deltaTurns = !prevSync
|
|
569
|
+
? s.turns
|
|
570
|
+
: hasDurableFingerprintCursor
|
|
571
|
+
? prefixStillPresent
|
|
572
|
+
? s.turns.slice(prevSync.turnFingerprints.length)
|
|
573
|
+
: s.turns
|
|
574
|
+
.filter((turn) => !priorFingerprints.has(turn.fingerprint))
|
|
575
|
+
.map((turn) => ({ ...turn, messageId: turn.stableMessageId }))
|
|
576
|
+
: s.turns.slice(prevSync.turnCount || 0);
|
|
577
|
+
const knownMessageIds = prevSync?.messageIdsByFingerprint && typeof prevSync.messageIdsByFingerprint === "object"
|
|
578
|
+
? prevSync.messageIdsByFingerprint
|
|
579
|
+
: {};
|
|
580
|
+
const deltaMessageIds = Object.fromEntries(deltaTurns.map((turn) => [turn.fingerprint, turn.messageId]));
|
|
581
|
+
const reconciliationTurns = s.turns.map((turn) => ({
|
|
582
|
+
...turn,
|
|
583
|
+
messageId: knownMessageIds[turn.fingerprint] || deltaMessageIds[turn.fingerprint] || turn.messageId,
|
|
584
|
+
}));
|
|
585
|
+
const session = { ...s, reconciliationTurns };
|
|
586
|
+
mappedSessions.push(session);
|
|
587
|
+
const isUpToDate = Boolean(prevSync)
|
|
588
|
+
&& deltaTurns.length === 0
|
|
589
|
+
&& prevSync.interrupted === s.interrupted;
|
|
423
590
|
if (isUpToDate && !options.force) {
|
|
424
591
|
alreadySynchronized++;
|
|
425
592
|
} else {
|
|
426
593
|
eligibleForImport++;
|
|
427
594
|
eligibleSessions.push({
|
|
428
|
-
session
|
|
595
|
+
session,
|
|
429
596
|
prevSync: prevSync || null,
|
|
430
|
-
deltaTurns
|
|
597
|
+
deltaTurns,
|
|
431
598
|
});
|
|
432
599
|
}
|
|
433
600
|
}
|
|
434
601
|
|
|
435
602
|
const dryRun = Boolean(options.dryRun || options.dry_run);
|
|
603
|
+
const previewAvailable = tools?.some((tool) => tool?.name === "preview_conversation_reconciliation");
|
|
604
|
+
const previewSession = async (session) => {
|
|
605
|
+
const results = [];
|
|
606
|
+
for (const turns of turnChunks(session.reconciliationTurns)) {
|
|
607
|
+
results.push(await client.call("preview_conversation_reconciliation", {
|
|
608
|
+
clientConversationId: `codex:${session.threadId}`,
|
|
609
|
+
sourceSessionId: session.threadId,
|
|
610
|
+
sourceCheckpoint: session.sourceCheckpoint,
|
|
611
|
+
turns,
|
|
612
|
+
projectSlug: session.projectSlug,
|
|
613
|
+
}));
|
|
614
|
+
}
|
|
615
|
+
return combineReconciliations(results, session);
|
|
616
|
+
};
|
|
617
|
+
|
|
618
|
+
if (options.session && mappedSessions.length === 0) {
|
|
619
|
+
return {
|
|
620
|
+
synchronized: false,
|
|
621
|
+
dry_run: dryRun,
|
|
622
|
+
requested_session: options.session,
|
|
623
|
+
source_status: "SOURCE_UNAVAILABLE",
|
|
624
|
+
source_reason: "The native Codex session was not found inside the selected authorized project binding.",
|
|
625
|
+
sessions_discovered: discovered,
|
|
626
|
+
sessions_mapped: mapped,
|
|
627
|
+
eligible_for_import: 0,
|
|
628
|
+
skipped_unmapped: skippedUnmapped,
|
|
629
|
+
parse_failures: sessions.parseFailures.length,
|
|
630
|
+
parse_failure_details: sessions.parseFailures.slice(0, 20),
|
|
631
|
+
reconciliations: [],
|
|
632
|
+
session_results: [],
|
|
633
|
+
};
|
|
634
|
+
}
|
|
436
635
|
|
|
437
636
|
if (dryRun) {
|
|
637
|
+
const reconciliations = [];
|
|
638
|
+
for (const session of mappedSessions) {
|
|
639
|
+
if (!client || !tools.some((tool) => tool?.name === "preview_conversation_reconciliation")) {
|
|
640
|
+
reconciliations.push({
|
|
641
|
+
conversationId: null,
|
|
642
|
+
organizationId: null,
|
|
643
|
+
projectId: null,
|
|
644
|
+
clientConversationId: `codex:${session.threadId}`,
|
|
645
|
+
sourceSessionId: session.threadId,
|
|
646
|
+
storedMessages: null,
|
|
647
|
+
availableSourceTurns: session.turns.length,
|
|
648
|
+
alreadyPersistedElsewhere: [],
|
|
649
|
+
newTurns: null,
|
|
650
|
+
duplicates: null,
|
|
651
|
+
cursorState: null,
|
|
652
|
+
recommendedAction: "ERROR",
|
|
653
|
+
reason: "The ReasonTrail server does not expose read-only conversation reconciliation. Update the CLI/server pair.",
|
|
654
|
+
});
|
|
655
|
+
continue;
|
|
656
|
+
}
|
|
657
|
+
reconciliations.push(await previewSession(session));
|
|
658
|
+
}
|
|
438
659
|
return {
|
|
439
660
|
dry_run: true,
|
|
440
661
|
sessions_discovered: discovered,
|
|
@@ -444,30 +665,74 @@ export async function syncCodex(client, tools, configDir, config, options = {})
|
|
|
444
665
|
skipped_unmapped: skippedUnmapped,
|
|
445
666
|
parse_failures: sessions.parseFailures.length,
|
|
446
667
|
parse_failure_details: sessions.parseFailures.slice(0, 20),
|
|
447
|
-
|
|
448
|
-
threadId: e.session.threadId,
|
|
449
|
-
title: e.session.title,
|
|
450
|
-
projectSlug: e.session.projectSlug,
|
|
451
|
-
turnCount: e.session.turnCount,
|
|
452
|
-
interrupted: e.session.interrupted,
|
|
453
|
-
interruptionReason: e.session.interruptionReason,
|
|
454
|
-
updatedAt: e.session.updatedAt,
|
|
455
|
-
})),
|
|
668
|
+
reconciliations,
|
|
456
669
|
};
|
|
457
670
|
}
|
|
458
671
|
|
|
459
672
|
// Live Sync
|
|
460
673
|
let importedCount = 0;
|
|
461
674
|
const now = new Date().toISOString();
|
|
675
|
+
let serverVerified = 0;
|
|
676
|
+
const reconciliationIssues = [];
|
|
677
|
+
const eligibleIds = new Set(eligibleSessions.map((item) => item.session.threadId));
|
|
678
|
+
for (const session of mappedSessions) {
|
|
679
|
+
if (eligibleIds.has(session.threadId) || !previewAvailable) continue;
|
|
680
|
+
const previous = syncState[session.threadId];
|
|
681
|
+
const verifiedAt = Date.parse(previous?.lastVerifiedAt || "");
|
|
682
|
+
const verificationDue = options.force || !Number.isFinite(verifiedAt) || Date.now() - verifiedAt >= 15 * 60 * 1000;
|
|
683
|
+
if (!verificationDue) continue;
|
|
684
|
+
const reconciliation = await previewSession(session);
|
|
685
|
+
serverVerified++;
|
|
686
|
+
if (["SYNC_DELTA", "RELINK_EXISTING"].includes(reconciliation?.recommendedAction)) {
|
|
687
|
+
eligibleSessions.push({ session, prevSync: previous || null, deltaTurns: session.reconciliationTurns, reconciliation });
|
|
688
|
+
eligibleIds.add(session.threadId);
|
|
689
|
+
eligibleForImport++;
|
|
690
|
+
alreadySynchronized = Math.max(0, alreadySynchronized - 1);
|
|
691
|
+
} else if (["MANUAL_REVIEW", "ERROR"].includes(reconciliation?.recommendedAction)) {
|
|
692
|
+
reconciliationIssues.push({ threadId: session.threadId, action: reconciliation.recommendedAction, reason: reconciliation.reason });
|
|
693
|
+
} else if (previous) {
|
|
694
|
+
syncState[session.threadId] = { ...previous, lastVerifiedAt: now };
|
|
695
|
+
}
|
|
696
|
+
}
|
|
462
697
|
|
|
698
|
+
const sessionResults = [];
|
|
463
699
|
for (const item of eligibleSessions) {
|
|
464
700
|
const s = item.session;
|
|
465
701
|
const clientConversationId = `codex:${s.threadId}`;
|
|
466
702
|
const project = { projectSlug: s.projectSlug };
|
|
467
703
|
|
|
704
|
+
// A historical source may have been reparsed differently from content
|
|
705
|
+
// already stored under the same stable message ids. Preflight before any
|
|
706
|
+
// write so one quarantined legacy Conversation cannot prevent unrelated
|
|
707
|
+
// sessions or repository Resources from being captured. The conflict stays
|
|
708
|
+
// visible for manual review and the local cursor is deliberately unchanged.
|
|
709
|
+
const preflight = previewAvailable
|
|
710
|
+
? item.reconciliation ?? await previewSession(s)
|
|
711
|
+
: null;
|
|
712
|
+
if (previewAvailable && !item.reconciliation) serverVerified++;
|
|
713
|
+
if (["MANUAL_REVIEW", "ERROR"].includes(preflight?.recommendedAction)) {
|
|
714
|
+
reconciliationIssues.push({
|
|
715
|
+
threadId: s.threadId,
|
|
716
|
+
action: preflight.recommendedAction,
|
|
717
|
+
reason: preflight.reason,
|
|
718
|
+
});
|
|
719
|
+
sessionResults.push({
|
|
720
|
+
sourceSessionId: s.threadId,
|
|
721
|
+
clientConversationId,
|
|
722
|
+
sourceCheckpoint: s.sourceCheckpoint,
|
|
723
|
+
sourceEligible: s.turns.length,
|
|
724
|
+
supplied: 0,
|
|
725
|
+
accepted: 0,
|
|
726
|
+
skippedForManualReview: true,
|
|
727
|
+
reconciliation: preflight,
|
|
728
|
+
transcript: null,
|
|
729
|
+
});
|
|
730
|
+
continue;
|
|
731
|
+
}
|
|
732
|
+
|
|
468
733
|
// 1. Begin task (idempotent: opens/reuses the conversation)
|
|
469
|
-
const firstUser = s.
|
|
470
|
-
await client.call("begin_task", {
|
|
734
|
+
const firstUser = s.reconciliationTurns.find((t) => t.role === "user");
|
|
735
|
+
const beginResult = await client.call("begin_task", {
|
|
471
736
|
clientConversationId,
|
|
472
737
|
taskTitle: s.title,
|
|
473
738
|
...(firstUser ? { userRequest: firstUser.content, messageId: firstUser.messageId } : {}),
|
|
@@ -476,14 +741,69 @@ export async function syncCodex(client, tools, configDir, config, options = {})
|
|
|
476
741
|
});
|
|
477
742
|
|
|
478
743
|
// 2. Sync turns delta
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
744
|
+
// The opening user turn was just handled by begin_task. Do not submit the
|
|
745
|
+
// same source message again in the delta merely to rely on deduplication.
|
|
746
|
+
const deltaTurns = firstUser
|
|
747
|
+
? item.deltaTurns.filter((turn) => turn.messageId !== firstUser.messageId)
|
|
748
|
+
: item.deltaTurns;
|
|
749
|
+
const syncResults = [];
|
|
750
|
+
if (item.deltaTurns.length > 0 || item.prevSync?.interrupted !== s.interrupted) {
|
|
751
|
+
for (const turns of turnChunks(deltaTurns)) {
|
|
752
|
+
syncResults.push(await client.call("sync_conversation_delta", {
|
|
753
|
+
clientConversationId,
|
|
754
|
+
sourceSessionId: s.threadId,
|
|
755
|
+
sourceCheckpoint: s.sourceCheckpoint,
|
|
756
|
+
sourceEligibleTurns: s.turns.length,
|
|
757
|
+
sourceAvailability: "AVAILABLE",
|
|
758
|
+
turns,
|
|
759
|
+
sourceStatus: s.interrupted ? "INTERRUPTED" : "ACTIVE",
|
|
760
|
+
sourceStatusReason: s.interruptionReason,
|
|
761
|
+
...project,
|
|
762
|
+
}));
|
|
763
|
+
}
|
|
485
764
|
}
|
|
486
765
|
|
|
766
|
+
const reconciliation = previewAvailable
|
|
767
|
+
? await previewSession(s)
|
|
768
|
+
: null;
|
|
769
|
+
if (reconciliation && (
|
|
770
|
+
!["NO_ACTION", "SOURCE_EMPTY"].includes(reconciliation.recommendedAction)
|
|
771
|
+
|| reconciliation.coverage !== "COMPLETE_THROUGH_CHECKPOINT"
|
|
772
|
+
)) {
|
|
773
|
+
throw new Error(
|
|
774
|
+
`Native session ${s.threadId} did not reconcile after synchronization (${reconciliation.recommendedAction || "UNKNOWN"}, ${reconciliation.coverage || "UNKNOWN"}). The local cursor was not advanced.`
|
|
775
|
+
);
|
|
776
|
+
}
|
|
777
|
+
const accepted = (beginResult?.turnsAccepted ?? 0) + syncResults.reduce((total, result) => total + (result?.turnsAccepted ?? 0), 0);
|
|
778
|
+
const duplicates = (beginResult?.duplicatesIgnored ?? 0) + syncResults.reduce((total, result) => total + (result?.duplicatesIgnored ?? 0), 0);
|
|
779
|
+
const rejected = (beginResult?.turnsRejected ?? 0) + syncResults.reduce((total, result) => total + (result?.turnsRejected ?? 0), 0);
|
|
780
|
+
sessionResults.push({
|
|
781
|
+
sourceSessionId: s.threadId,
|
|
782
|
+
clientConversationId,
|
|
783
|
+
sourceCheckpoint: s.sourceCheckpoint,
|
|
784
|
+
sourceEligible: s.turns.length,
|
|
785
|
+
supplied: item.deltaTurns.length,
|
|
786
|
+
accepted,
|
|
787
|
+
reconciliation,
|
|
788
|
+
transcript: reconciliation ? {
|
|
789
|
+
sourceSessionId: s.threadId,
|
|
790
|
+
sourceCheckpoint: s.sourceCheckpoint,
|
|
791
|
+
sourceEligible: s.turns.length,
|
|
792
|
+
supplied: item.deltaTurns.length,
|
|
793
|
+
accepted,
|
|
794
|
+
duplicates,
|
|
795
|
+
excluded: 0,
|
|
796
|
+
rejected,
|
|
797
|
+
persistedMatchingSourceMessages: reconciliation.persistedMatchingSourceMessages ?? null,
|
|
798
|
+
totalConversationMessages: reconciliation.totalConversationMessages ?? reconciliation.storedMessages ?? null,
|
|
799
|
+
lastAcknowledgedCursor: reconciliation.cursorState ? {
|
|
800
|
+
messageId: reconciliation.cursorState.lastSyncedMessageId ?? null,
|
|
801
|
+
sequence: reconciliation.cursorState.lastSyncedSequence ?? null,
|
|
802
|
+
} : null,
|
|
803
|
+
coverage: reconciliation.coverage ?? "UNKNOWN",
|
|
804
|
+
} : syncResults.at(-1)?.transcript ?? null,
|
|
805
|
+
});
|
|
806
|
+
|
|
487
807
|
// Interruption status is preserved on the synced conversation itself. Do
|
|
488
808
|
// not create a second generic Brain update: that produced noisy "Finding
|
|
489
809
|
// reported by reasontrail-cli" Inbox/review items for ordinary plan drift.
|
|
@@ -494,6 +814,20 @@ export async function syncCodex(client, tools, configDir, config, options = {})
|
|
|
494
814
|
interrupted: s.interrupted,
|
|
495
815
|
lastSyncAt: now,
|
|
496
816
|
updatedAt: s.updatedAt,
|
|
817
|
+
// A compacted source can temporarily omit its old prefix. Retain every
|
|
818
|
+
// fingerprint acknowledged by a successful server call so a later
|
|
819
|
+
// expanded/resumed source cannot resend old turns under fallback ids.
|
|
820
|
+
turnFingerprints: [...new Set([
|
|
821
|
+
...(Array.isArray(item.prevSync?.turnFingerprints) ? item.prevSync.turnFingerprints : []),
|
|
822
|
+
...s.turns.map((turn) => turn.fingerprint),
|
|
823
|
+
])],
|
|
824
|
+
messageIdsByFingerprint: {
|
|
825
|
+
...((item.prevSync?.messageIdsByFingerprint && typeof item.prevSync.messageIdsByFingerprint === "object")
|
|
826
|
+
? item.prevSync.messageIdsByFingerprint
|
|
827
|
+
: {}),
|
|
828
|
+
...Object.fromEntries(s.reconciliationTurns.map((turn) => [turn.fingerprint, turn.messageId])),
|
|
829
|
+
},
|
|
830
|
+
lastVerifiedAt: now,
|
|
497
831
|
};
|
|
498
832
|
state.sessions = syncState;
|
|
499
833
|
state.lastSyncAt = now;
|
|
@@ -503,6 +837,8 @@ export async function syncCodex(client, tools, configDir, config, options = {})
|
|
|
503
837
|
|
|
504
838
|
if (eligibleSessions.length === 0) {
|
|
505
839
|
state.sessions = syncState;
|
|
840
|
+
state.lastSyncAt = state.lastSyncAt || null;
|
|
841
|
+
await saveSyncState(configDir, state);
|
|
506
842
|
}
|
|
507
843
|
|
|
508
844
|
return {
|
|
@@ -515,6 +851,10 @@ export async function syncCodex(client, tools, configDir, config, options = {})
|
|
|
515
851
|
interrupted_sessions: eligibleSessions.filter((item) => item.session.interrupted).length,
|
|
516
852
|
parse_failures: sessions.parseFailures.length,
|
|
517
853
|
parse_failure_details: sessions.parseFailures.slice(0, 20),
|
|
854
|
+
server_verified: serverVerified,
|
|
855
|
+
reconciliation_issues: reconciliationIssues,
|
|
856
|
+
source_status: "AVAILABLE",
|
|
857
|
+
session_results: sessionResults,
|
|
518
858
|
last_sync_at: now,
|
|
519
859
|
};
|
|
520
860
|
}
|