@reasontrail/cli 0.1.2 → 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.
@@ -1 +1 @@
1
- 990c844b8d89dbaea32e7af08775215cf7b437f7e5c01de72c9913f26d36a164 reasontrail-runtime.mjs
1
+ 3736d2e5fe29d9afc7e0abd87f601236c4176fde52eb9ccf7544a447a28e60e3 reasontrail-runtime.mjs
@@ -1 +1 @@
1
- {"sourceRevision":"e2dec2f9fa038f10880c700bba89035713baab29"}
1
+ {"sourceRevision":"d78c5c1833d960b45100d46f22e84c38887e6a24"}
package/src/cli.mjs CHANGED
@@ -836,18 +836,33 @@ async function updateCommand(argv) {
836
836
  if (Array.isArray(piped.turns) && piped.turns.length > 0) {
837
837
  throw new CliError("Conversation turns must come from the authorized Codex capture adapter. Pass --session <native-session-id>; do not reconstruct the transcript in update JSON.", 2);
838
838
  }
839
+ // Fields with an authoritative adapter-defined meaning remain execution
840
+ // history. They must not become Inbox proposals merely because the transport
841
+ // previously encoded their type as a prose prefix.
842
+ const operationalEvents = [
843
+ ...(piped.operationalEvents || []),
844
+ ...(piped.implementationFacts || piped.implementation_facts || []).map((value, index) => ({
845
+ eventType: "IMPLEMENTATION_FACT",
846
+ sourceEventId: `implementation-fact:${index}:${createHash("sha256").update(String(value)).digest("hex")}`,
847
+ summary: String(value),
848
+ })),
849
+ ...(piped.taskOutcomes || piped.task_outcomes || []).map((value, index) => ({
850
+ eventType: "TASK_OUTCOME",
851
+ sourceEventId: `task-outcome:${index}:${createHash("sha256").update(String(value)).digest("hex")}`,
852
+ summary: String(value),
853
+ })),
854
+ ];
839
855
  const labeledFindings = [
840
856
  ...(piped.findings || []),
841
857
  ...(piped.discoveries || []).map((value) => `[discovery] ${value}`),
842
- ...(piped.implementationFacts || piped.implementation_facts || []).map((value) => `[implementation fact] ${value}`),
843
858
  ...(piped.rejectedApproaches || piped.rejected_approaches || []).map((value) => `[rejected approach] ${value}`),
844
859
  ...(piped.constraints || []).map((value) => `[constraint] ${value}`),
845
860
  ...(piped.openQuestions || piped.open_questions || []).map((value) => `[open question] ${value}`),
846
- ...(piped.taskOutcomes || piped.task_outcomes || []).map((value) => `[task outcome] ${value}`),
847
861
  ];
848
862
  const args = {
849
863
  ...piped,
850
864
  ...(labeledFindings.length ? { findings: labeledFindings } : {}),
865
+ ...(operationalEvents.length ? { operationalEvents } : {}),
851
866
  ...(opts.summary ? { taskSummary: opts.summary } : {}),
852
867
  ...(opts.remaining_work ? { remainingWork: opts.remaining_work } : {}),
853
868
  turns: [],
@@ -973,7 +988,9 @@ async function bindCommand(argv) {
973
988
  const slug = repository.projectSlug;
974
989
  if (!slug) throw new CliError("ReasonTrail did not return a project for this repository. Nothing was bound.", 2);
975
990
  cfg.bindings ||= {};
976
- cfg.bindings[root] = { projectSlug: slug, projectId: opts.project_id || null, repositoryId: repository.repositoryId || null, repositoryUrl: repository.url, boundAt: new Date().toISOString() };
991
+ const priorBinding = cfg.bindings[root];
992
+ const captureFrom = priorBinding?.projectSlug === slug ? priorBinding.captureFrom : new Date().toISOString();
993
+ cfg.bindings[root] = { captureFrom, projectSlug: slug, projectId: opts.project_id || null, repositoryId: repository.repositoryId || null, repositoryUrl: repository.url, boundAt: new Date().toISOString() };
977
994
  await saveJson(target.paths.config, cfg);
978
995
  let automaticCapture;
979
996
  try {
@@ -1164,6 +1181,7 @@ async function syncCommand(argv) {
1164
1181
  if (sub === "managed") {
1165
1182
  const codex = await syncCodex(client, tools, target.paths.dir, target.cfg, {
1166
1183
  dryRun: !apply,
1184
+ managed: true,
1167
1185
  since: opts.since || null,
1168
1186
  project,
1169
1187
  session: opts.session || null,
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
2
+ import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import { basename, join, resolve } from "node:path";
5
5
  import { spawnSync } from "node:child_process";
@@ -75,6 +75,12 @@ function isSystemOnlyText(text) {
75
75
  return false;
76
76
  }
77
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
+
78
84
  function isVisibleAssistant(item) {
79
85
  // Current rollouts use phase; legacy rollouts may omit both fields.
80
86
  const visible = new Set(["commentary", "final", "final_answer"]);
@@ -144,6 +150,7 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
144
150
  if (identity.error) return { ...identity, filePath };
145
151
  const { threadId, parentThreadId, identitySource, historyStartLine } = identity;
146
152
  let cwd = identity.cwd;
153
+ let turnCwd = cwd;
147
154
  let excludedInheritedTurnCount = 0;
148
155
  let startTs = null;
149
156
  let endTs = null;
@@ -162,7 +169,10 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
162
169
  }
163
170
  if (!startTs && d.timestamp) startTs = d.timestamp;
164
171
  if (d.timestamp) endTs = d.timestamp;
165
- if (!cwd && d.type === "turn_context" && d.payload?.cwd) cwd = d.payload.cwd;
172
+ if (d.type === "turn_context" && typeof d.payload?.cwd === "string") {
173
+ turnCwd = d.payload.cwd;
174
+ cwd ||= turnCwd;
175
+ }
166
176
 
167
177
  // Only structured runtime error events establish a quota interruption.
168
178
  // Messages and tool output may quote error names while discussing code.
@@ -188,6 +198,7 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
188
198
  rawTurns.push({
189
199
  id,
190
200
  sourceLine: line,
201
+ cwd: turnCwd,
191
202
  role,
192
203
  content: cleaned,
193
204
  // Missing source timestamps must stay missing. Substituting the
@@ -218,6 +229,7 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
218
229
  rawTurns.push({
219
230
  id,
220
231
  sourceLine: line,
232
+ cwd: turnCwd,
221
233
  role,
222
234
  content: cleaned,
223
235
  timestamp: d.timestamp || null,
@@ -248,6 +260,7 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
248
260
  fingerprint,
249
261
  nativeMessageId: t.id,
250
262
  sourceLine: t.sourceLine,
263
+ cwd: t.cwd,
251
264
  role: t.role,
252
265
  content: t.content,
253
266
  sequence: turns.length,
@@ -325,10 +338,32 @@ export async function discoverAndMapCodexSessions(options = {}) {
325
338
  };
326
339
 
327
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;
328
361
  const sessions = [];
362
+ const observedProjects = new Map();
329
363
  const parseFailures = [];
330
364
 
331
365
  for (const file of files) {
366
+ if (options.managed && earliest && (await stat(file)).mtimeMs < earliest) continue;
332
367
  const parsed = await parseCodexSessionFile(file, threadNames);
333
368
  if (parsed.error) {
334
369
  parseFailures.push({ filePath: file, reason: parsed.error });
@@ -352,13 +387,27 @@ export async function discoverAndMapCodexSessions(options = {}) {
352
387
  }
353
388
 
354
389
  const gitRoot = resolveGit(parsed.cwd);
355
- const binding = gitRoot ? bindings[gitRoot] : null;
356
- const projectSlug = binding?.projectSlug || null;
357
-
358
- // Filter by --project if requested
359
- if (options.project && projectSlug !== options.project) {
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" });
360
397
  continue;
361
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
+ }
362
411
 
363
412
  const mapped = Boolean(projectSlug);
364
413
  sessions.push({
@@ -377,13 +426,34 @@ export async function discoverAndMapCodexSessions(options = {}) {
377
426
  if (!existing) {
378
427
  byThread.set(s.threadId, s);
379
428
  } else {
380
- // Choose the more complete session (more turns or newer update)
381
- if (s.turnCount > existing.turnCount || new Date(s.updatedAt || 0) > new Date(existing.updatedAt || 0)) {
382
- byThread.set(s.threadId, s);
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;
383
447
  }
384
448
  }
385
449
  }
386
- 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
+ }
387
457
 
388
458
  // Sort chronologically
389
459
  resultSessions.sort((a, b) => new Date(a.updatedAt || 0).getTime() - new Date(b.updatedAt || 0).getTime());
@@ -415,7 +485,9 @@ function turnChunks(turns) {
415
485
  if (turns.length === 0) return [[]];
416
486
  const chunks = [];
417
487
  for (let offset = 0; offset < turns.length; offset += MAX_RECONCILIATION_TURNS) {
418
- chunks.push(turns.slice(offset, 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
+ ));
419
491
  }
420
492
  return chunks;
421
493
  }
@@ -461,6 +533,7 @@ export async function syncCodex(client, tools, configDir, config, options = {})
461
533
  const bindings = config.bindings || {};
462
534
  const sessions = await discoverAndMapCodexSessions({
463
535
  codexHome: options.codexHome || defaultCodexHome(),
536
+ managed: options.managed === true,
464
537
  bindings,
465
538
  since: options.since,
466
539
  session: options.session,