@reasontrail/cli 0.1.0 → 0.1.2

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.
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
2
3
  import { homedir } from "node:os";
3
4
  import { basename, join, resolve } from "node:path";
@@ -189,7 +190,10 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
189
190
  sourceLine: line,
190
191
  role,
191
192
  content: cleaned,
192
- timestamp: d.timestamp || endTs || new Date().toISOString(),
193
+ // Missing source timestamps must stay missing. Substituting the
194
+ // current clock here makes the same native turn acquire a new
195
+ // fingerprint on every parse and defeats retry idempotency.
196
+ timestamp: d.timestamp || null,
193
197
  });
194
198
  }
195
199
  }
@@ -216,7 +220,7 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
216
220
  sourceLine: line,
217
221
  role,
218
222
  content: cleaned,
219
- timestamp: d.timestamp || endTs || new Date().toISOString(),
223
+ timestamp: d.timestamp || null,
220
224
  });
221
225
  }
222
226
  }
@@ -237,8 +241,11 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
237
241
  continue;
238
242
  }
239
243
  }
244
+ const fingerprint = createHash("sha256").update(`${t.id}\0${t.timestamp ?? ""}\0${t.role}\0${t.content}`).digest("hex");
240
245
  turns.push({
241
246
  messageId: `codex:${threadId}:${turns.length}`,
247
+ stableMessageId: `codex:${threadId}:native:${fingerprint.slice(0, 32)}`,
248
+ fingerprint,
242
249
  nativeMessageId: t.id,
243
250
  sourceLine: t.sourceLine,
244
251
  role: t.role,
@@ -262,6 +269,9 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
262
269
  if (!title) {
263
270
  title = `Codex session ${threadId.slice(0, 8)}`;
264
271
  }
272
+ const sourceCheckpoint = `codex:${threadId}:${turns.length}:${createHash("sha256")
273
+ .update(turns.map((turn) => turn.fingerprint).join("\0"))
274
+ .digest("hex")}`;
265
275
 
266
276
  return {
267
277
  filePath,
@@ -278,6 +288,7 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
278
288
  turnCount: turns.length,
279
289
  userTurnCount: turns.filter((t) => t.role === "user").length,
280
290
  assistantTurnCount: turns.filter((t) => t.role === "assistant").length,
291
+ sourceCheckpoint,
281
292
  usageExceeded,
282
293
  usageExceededMessage,
283
294
  interrupted: usageExceeded,
@@ -295,7 +306,14 @@ export async function discoverAndMapCodexSessions(options = {}) {
295
306
  const codexHome = options.codexHome || defaultCodexHome();
296
307
  const sessionsDir = join(codexHome, "sessions");
297
308
  const threadNames = await readSessionIndex(codexHome);
298
- const files = await findJsonlFiles(sessionsDir);
309
+ const discoveredFiles = await findJsonlFiles(sessionsDir);
310
+ // Exact-session recovery may inspect only the requested native transcript.
311
+ // Codex rollout filenames carry the native thread id, so filter paths before
312
+ // opening any JSONL content. If the file is absent, fail closed instead of
313
+ // scanning unrelated transcripts looking for a plausible identity.
314
+ const files = options.session
315
+ ? discoveredFiles.filter((file) => basename(file).includes(String(options.session)))
316
+ : discoveredFiles;
299
317
 
300
318
  const gitCache = {};
301
319
  const resolveGit = (dir) => {
@@ -329,6 +347,7 @@ export async function discoverAndMapCodexSessions(options = {}) {
329
347
 
330
348
  // Filter by --session if requested
331
349
  if (options.session && parsed.threadId !== options.session) {
350
+ parseFailures.push({ filePath: file, reason: "requested_session_identity_mismatch" });
332
351
  continue;
333
352
  }
334
353
 
@@ -390,6 +409,54 @@ export async function saveSyncState(configDir, state) {
390
409
  await writeFile(statePath, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
391
410
  }
392
411
 
412
+ const MAX_RECONCILIATION_TURNS = 200;
413
+
414
+ function turnChunks(turns) {
415
+ if (turns.length === 0) return [[]];
416
+ const chunks = [];
417
+ for (let offset = 0; offset < turns.length; offset += MAX_RECONCILIATION_TURNS) {
418
+ chunks.push(turns.slice(offset, offset + MAX_RECONCILIATION_TURNS));
419
+ }
420
+ return chunks;
421
+ }
422
+
423
+ function combineReconciliations(results, session) {
424
+ const rank = {
425
+ SOURCE_EMPTY: 0,
426
+ NO_ACTION: 1,
427
+ SYNC_DELTA: 2,
428
+ RELINK_EXISTING: 3,
429
+ ERROR: 4,
430
+ MANUAL_REVIEW: 5,
431
+ };
432
+ const selected = results.reduce((best, result) =>
433
+ (rank[result?.recommendedAction] ?? 4) > (rank[best?.recommendedAction] ?? -1) ? result : best
434
+ , null) || {};
435
+ const sum = (key) => results.reduce((total, result) => total + Number(result?.[key] || 0), 0);
436
+ const unique = (key) => [...new Set(results.flatMap((result) =>
437
+ Array.isArray(result?.[key]) ? result[key] : []
438
+ ))];
439
+ return {
440
+ ...selected,
441
+ sourceSessionId: session.threadId,
442
+ sourceCheckpoint: session.sourceCheckpoint,
443
+ availableSourceTurns: session.turns.length,
444
+ duplicateSourceTurns: sum("duplicateSourceTurns"),
445
+ excludedTurns: sum("excludedTurns"),
446
+ newTurns: sum("newTurns"),
447
+ duplicates: sum("duplicates"),
448
+ persistedMatchingSourceMessages: sum("persistedMatchingSourceMessages"),
449
+ storedMessages: Math.max(0, ...results.map((result) => Number(result?.storedMessages || 0))),
450
+ totalConversationMessages: Math.max(0, ...results.map((result) => Number(result?.totalConversationMessages || 0))),
451
+ alreadyPersistedElsewhere: unique("alreadyPersistedElsewhere"),
452
+ conflictingMessageIds: unique("conflictingMessageIds"),
453
+ coverage: results.every((result) => result?.coverage === "COMPLETE_THROUGH_CHECKPOINT")
454
+ ? "COMPLETE_THROUGH_CHECKPOINT"
455
+ : "PARTIAL",
456
+ chunkCount: results.length,
457
+ };
458
+ }
459
+
393
460
  export async function syncCodex(client, tools, configDir, config, options = {}) {
394
461
  const bindings = config.bindings || {};
395
462
  const sessions = await discoverAndMapCodexSessions({
@@ -410,6 +477,7 @@ export async function syncCodex(client, tools, configDir, config, options = {})
410
477
  let skippedUnmapped = 0;
411
478
 
412
479
  const eligibleSessions = [];
480
+ const mappedSessions = [];
413
481
 
414
482
  for (const s of sessions) {
415
483
  if (!s.mapped) {
@@ -419,22 +487,102 @@ export async function syncCodex(client, tools, configDir, config, options = {})
419
487
  mapped++;
420
488
 
421
489
  const prevSync = syncState[s.threadId];
422
- const isUpToDate = prevSync && prevSync.turnCount === s.turnCount && prevSync.interrupted === s.interrupted;
490
+ const currentFingerprints = s.turns.map((turn) => turn.fingerprint);
491
+ const hasDurableFingerprintCursor = Array.isArray(prevSync?.turnFingerprints);
492
+ const prefixStillPresent = hasDurableFingerprintCursor
493
+ && prevSync.turnFingerprints.every((fingerprint, index) => currentFingerprints[index] === fingerprint);
494
+ const priorFingerprints = new Set(hasDurableFingerprintCursor ? prevSync.turnFingerprints : []);
495
+ const deltaTurns = !prevSync
496
+ ? s.turns
497
+ : hasDurableFingerprintCursor
498
+ ? prefixStillPresent
499
+ ? s.turns.slice(prevSync.turnFingerprints.length)
500
+ : s.turns
501
+ .filter((turn) => !priorFingerprints.has(turn.fingerprint))
502
+ .map((turn) => ({ ...turn, messageId: turn.stableMessageId }))
503
+ : s.turns.slice(prevSync.turnCount || 0);
504
+ const knownMessageIds = prevSync?.messageIdsByFingerprint && typeof prevSync.messageIdsByFingerprint === "object"
505
+ ? prevSync.messageIdsByFingerprint
506
+ : {};
507
+ const deltaMessageIds = Object.fromEntries(deltaTurns.map((turn) => [turn.fingerprint, turn.messageId]));
508
+ const reconciliationTurns = s.turns.map((turn) => ({
509
+ ...turn,
510
+ messageId: knownMessageIds[turn.fingerprint] || deltaMessageIds[turn.fingerprint] || turn.messageId,
511
+ }));
512
+ const session = { ...s, reconciliationTurns };
513
+ mappedSessions.push(session);
514
+ const isUpToDate = Boolean(prevSync)
515
+ && deltaTurns.length === 0
516
+ && prevSync.interrupted === s.interrupted;
423
517
  if (isUpToDate && !options.force) {
424
518
  alreadySynchronized++;
425
519
  } else {
426
520
  eligibleForImport++;
427
521
  eligibleSessions.push({
428
- session: s,
522
+ session,
429
523
  prevSync: prevSync || null,
430
- deltaTurns: prevSync ? s.turns.slice(prevSync.turnCount || 0) : s.turns,
524
+ deltaTurns,
431
525
  });
432
526
  }
433
527
  }
434
528
 
435
529
  const dryRun = Boolean(options.dryRun || options.dry_run);
530
+ const previewAvailable = tools?.some((tool) => tool?.name === "preview_conversation_reconciliation");
531
+ const previewSession = async (session) => {
532
+ const results = [];
533
+ for (const turns of turnChunks(session.reconciliationTurns)) {
534
+ results.push(await client.call("preview_conversation_reconciliation", {
535
+ clientConversationId: `codex:${session.threadId}`,
536
+ sourceSessionId: session.threadId,
537
+ sourceCheckpoint: session.sourceCheckpoint,
538
+ turns,
539
+ projectSlug: session.projectSlug,
540
+ }));
541
+ }
542
+ return combineReconciliations(results, session);
543
+ };
544
+
545
+ if (options.session && mappedSessions.length === 0) {
546
+ return {
547
+ synchronized: false,
548
+ dry_run: dryRun,
549
+ requested_session: options.session,
550
+ source_status: "SOURCE_UNAVAILABLE",
551
+ source_reason: "The native Codex session was not found inside the selected authorized project binding.",
552
+ sessions_discovered: discovered,
553
+ sessions_mapped: mapped,
554
+ eligible_for_import: 0,
555
+ skipped_unmapped: skippedUnmapped,
556
+ parse_failures: sessions.parseFailures.length,
557
+ parse_failure_details: sessions.parseFailures.slice(0, 20),
558
+ reconciliations: [],
559
+ session_results: [],
560
+ };
561
+ }
436
562
 
437
563
  if (dryRun) {
564
+ const reconciliations = [];
565
+ for (const session of mappedSessions) {
566
+ if (!client || !tools.some((tool) => tool?.name === "preview_conversation_reconciliation")) {
567
+ reconciliations.push({
568
+ conversationId: null,
569
+ organizationId: null,
570
+ projectId: null,
571
+ clientConversationId: `codex:${session.threadId}`,
572
+ sourceSessionId: session.threadId,
573
+ storedMessages: null,
574
+ availableSourceTurns: session.turns.length,
575
+ alreadyPersistedElsewhere: [],
576
+ newTurns: null,
577
+ duplicates: null,
578
+ cursorState: null,
579
+ recommendedAction: "ERROR",
580
+ reason: "The ReasonTrail server does not expose read-only conversation reconciliation. Update the CLI/server pair.",
581
+ });
582
+ continue;
583
+ }
584
+ reconciliations.push(await previewSession(session));
585
+ }
438
586
  return {
439
587
  dry_run: true,
440
588
  sessions_discovered: discovered,
@@ -444,30 +592,74 @@ export async function syncCodex(client, tools, configDir, config, options = {})
444
592
  skipped_unmapped: skippedUnmapped,
445
593
  parse_failures: sessions.parseFailures.length,
446
594
  parse_failure_details: sessions.parseFailures.slice(0, 20),
447
- eligible_sessions: eligibleSessions.map((e) => ({
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
- })),
595
+ reconciliations,
456
596
  };
457
597
  }
458
598
 
459
599
  // Live Sync
460
600
  let importedCount = 0;
461
601
  const now = new Date().toISOString();
602
+ let serverVerified = 0;
603
+ const reconciliationIssues = [];
604
+ const eligibleIds = new Set(eligibleSessions.map((item) => item.session.threadId));
605
+ for (const session of mappedSessions) {
606
+ if (eligibleIds.has(session.threadId) || !previewAvailable) continue;
607
+ const previous = syncState[session.threadId];
608
+ const verifiedAt = Date.parse(previous?.lastVerifiedAt || "");
609
+ const verificationDue = options.force || !Number.isFinite(verifiedAt) || Date.now() - verifiedAt >= 15 * 60 * 1000;
610
+ if (!verificationDue) continue;
611
+ const reconciliation = await previewSession(session);
612
+ serverVerified++;
613
+ if (["SYNC_DELTA", "RELINK_EXISTING"].includes(reconciliation?.recommendedAction)) {
614
+ eligibleSessions.push({ session, prevSync: previous || null, deltaTurns: session.reconciliationTurns, reconciliation });
615
+ eligibleIds.add(session.threadId);
616
+ eligibleForImport++;
617
+ alreadySynchronized = Math.max(0, alreadySynchronized - 1);
618
+ } else if (["MANUAL_REVIEW", "ERROR"].includes(reconciliation?.recommendedAction)) {
619
+ reconciliationIssues.push({ threadId: session.threadId, action: reconciliation.recommendedAction, reason: reconciliation.reason });
620
+ } else if (previous) {
621
+ syncState[session.threadId] = { ...previous, lastVerifiedAt: now };
622
+ }
623
+ }
462
624
 
625
+ const sessionResults = [];
463
626
  for (const item of eligibleSessions) {
464
627
  const s = item.session;
465
628
  const clientConversationId = `codex:${s.threadId}`;
466
629
  const project = { projectSlug: s.projectSlug };
467
630
 
631
+ // A historical source may have been reparsed differently from content
632
+ // already stored under the same stable message ids. Preflight before any
633
+ // write so one quarantined legacy Conversation cannot prevent unrelated
634
+ // sessions or repository Resources from being captured. The conflict stays
635
+ // visible for manual review and the local cursor is deliberately unchanged.
636
+ const preflight = previewAvailable
637
+ ? item.reconciliation ?? await previewSession(s)
638
+ : null;
639
+ if (previewAvailable && !item.reconciliation) serverVerified++;
640
+ if (["MANUAL_REVIEW", "ERROR"].includes(preflight?.recommendedAction)) {
641
+ reconciliationIssues.push({
642
+ threadId: s.threadId,
643
+ action: preflight.recommendedAction,
644
+ reason: preflight.reason,
645
+ });
646
+ sessionResults.push({
647
+ sourceSessionId: s.threadId,
648
+ clientConversationId,
649
+ sourceCheckpoint: s.sourceCheckpoint,
650
+ sourceEligible: s.turns.length,
651
+ supplied: 0,
652
+ accepted: 0,
653
+ skippedForManualReview: true,
654
+ reconciliation: preflight,
655
+ transcript: null,
656
+ });
657
+ continue;
658
+ }
659
+
468
660
  // 1. Begin task (idempotent: opens/reuses the conversation)
469
- const firstUser = s.turns.find((t) => t.role === "user");
470
- await client.call("begin_task", {
661
+ const firstUser = s.reconciliationTurns.find((t) => t.role === "user");
662
+ const beginResult = await client.call("begin_task", {
471
663
  clientConversationId,
472
664
  taskTitle: s.title,
473
665
  ...(firstUser ? { userRequest: firstUser.content, messageId: firstUser.messageId } : {}),
@@ -476,13 +668,68 @@ export async function syncCodex(client, tools, configDir, config, options = {})
476
668
  });
477
669
 
478
670
  // 2. Sync turns delta
479
- if (item.deltaTurns.length > 0) {
480
- await client.call("sync_conversation_delta", {
481
- clientConversationId,
482
- turns: item.deltaTurns,
483
- ...project,
484
- });
671
+ // The opening user turn was just handled by begin_task. Do not submit the
672
+ // same source message again in the delta merely to rely on deduplication.
673
+ const deltaTurns = firstUser
674
+ ? item.deltaTurns.filter((turn) => turn.messageId !== firstUser.messageId)
675
+ : item.deltaTurns;
676
+ const syncResults = [];
677
+ if (item.deltaTurns.length > 0 || item.prevSync?.interrupted !== s.interrupted) {
678
+ for (const turns of turnChunks(deltaTurns)) {
679
+ syncResults.push(await client.call("sync_conversation_delta", {
680
+ clientConversationId,
681
+ sourceSessionId: s.threadId,
682
+ sourceCheckpoint: s.sourceCheckpoint,
683
+ sourceEligibleTurns: s.turns.length,
684
+ sourceAvailability: "AVAILABLE",
685
+ turns,
686
+ sourceStatus: s.interrupted ? "INTERRUPTED" : "ACTIVE",
687
+ sourceStatusReason: s.interruptionReason,
688
+ ...project,
689
+ }));
690
+ }
691
+ }
692
+
693
+ const reconciliation = previewAvailable
694
+ ? await previewSession(s)
695
+ : null;
696
+ if (reconciliation && (
697
+ !["NO_ACTION", "SOURCE_EMPTY"].includes(reconciliation.recommendedAction)
698
+ || reconciliation.coverage !== "COMPLETE_THROUGH_CHECKPOINT"
699
+ )) {
700
+ throw new Error(
701
+ `Native session ${s.threadId} did not reconcile after synchronization (${reconciliation.recommendedAction || "UNKNOWN"}, ${reconciliation.coverage || "UNKNOWN"}). The local cursor was not advanced.`
702
+ );
485
703
  }
704
+ const accepted = (beginResult?.turnsAccepted ?? 0) + syncResults.reduce((total, result) => total + (result?.turnsAccepted ?? 0), 0);
705
+ const duplicates = (beginResult?.duplicatesIgnored ?? 0) + syncResults.reduce((total, result) => total + (result?.duplicatesIgnored ?? 0), 0);
706
+ const rejected = (beginResult?.turnsRejected ?? 0) + syncResults.reduce((total, result) => total + (result?.turnsRejected ?? 0), 0);
707
+ sessionResults.push({
708
+ sourceSessionId: s.threadId,
709
+ clientConversationId,
710
+ sourceCheckpoint: s.sourceCheckpoint,
711
+ sourceEligible: s.turns.length,
712
+ supplied: item.deltaTurns.length,
713
+ accepted,
714
+ reconciliation,
715
+ transcript: reconciliation ? {
716
+ sourceSessionId: s.threadId,
717
+ sourceCheckpoint: s.sourceCheckpoint,
718
+ sourceEligible: s.turns.length,
719
+ supplied: item.deltaTurns.length,
720
+ accepted,
721
+ duplicates,
722
+ excluded: 0,
723
+ rejected,
724
+ persistedMatchingSourceMessages: reconciliation.persistedMatchingSourceMessages ?? null,
725
+ totalConversationMessages: reconciliation.totalConversationMessages ?? reconciliation.storedMessages ?? null,
726
+ lastAcknowledgedCursor: reconciliation.cursorState ? {
727
+ messageId: reconciliation.cursorState.lastSyncedMessageId ?? null,
728
+ sequence: reconciliation.cursorState.lastSyncedSequence ?? null,
729
+ } : null,
730
+ coverage: reconciliation.coverage ?? "UNKNOWN",
731
+ } : syncResults.at(-1)?.transcript ?? null,
732
+ });
486
733
 
487
734
  // Interruption status is preserved on the synced conversation itself. Do
488
735
  // not create a second generic Brain update: that produced noisy "Finding
@@ -494,6 +741,20 @@ export async function syncCodex(client, tools, configDir, config, options = {})
494
741
  interrupted: s.interrupted,
495
742
  lastSyncAt: now,
496
743
  updatedAt: s.updatedAt,
744
+ // A compacted source can temporarily omit its old prefix. Retain every
745
+ // fingerprint acknowledged by a successful server call so a later
746
+ // expanded/resumed source cannot resend old turns under fallback ids.
747
+ turnFingerprints: [...new Set([
748
+ ...(Array.isArray(item.prevSync?.turnFingerprints) ? item.prevSync.turnFingerprints : []),
749
+ ...s.turns.map((turn) => turn.fingerprint),
750
+ ])],
751
+ messageIdsByFingerprint: {
752
+ ...((item.prevSync?.messageIdsByFingerprint && typeof item.prevSync.messageIdsByFingerprint === "object")
753
+ ? item.prevSync.messageIdsByFingerprint
754
+ : {}),
755
+ ...Object.fromEntries(s.reconciliationTurns.map((turn) => [turn.fingerprint, turn.messageId])),
756
+ },
757
+ lastVerifiedAt: now,
497
758
  };
498
759
  state.sessions = syncState;
499
760
  state.lastSyncAt = now;
@@ -503,6 +764,8 @@ export async function syncCodex(client, tools, configDir, config, options = {})
503
764
 
504
765
  if (eligibleSessions.length === 0) {
505
766
  state.sessions = syncState;
767
+ state.lastSyncAt = state.lastSyncAt || null;
768
+ await saveSyncState(configDir, state);
506
769
  }
507
770
 
508
771
  return {
@@ -515,6 +778,10 @@ export async function syncCodex(client, tools, configDir, config, options = {})
515
778
  interrupted_sessions: eligibleSessions.filter((item) => item.session.interrupted).length,
516
779
  parse_failures: sessions.parseFailures.length,
517
780
  parse_failure_details: sessions.parseFailures.slice(0, 20),
781
+ server_verified: serverVerified,
782
+ reconciliation_issues: reconciliationIssues,
783
+ source_status: "AVAILABLE",
784
+ session_results: sessionResults,
518
785
  last_sync_at: now,
519
786
  };
520
787
  }
@@ -0,0 +1,3 @@
1
+ export function selectSystemdScope({ systemRequested = false, systemUnitExists = false } = {}) {
2
+ return systemRequested || systemUnitExists ? "system" : "user";
3
+ }