@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/src/cli.mjs CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  readSyncState,
14
14
  syncCodex,
15
15
  } from "./codex-sync.mjs";
16
+ import { selectSystemdScope } from "./systemd-scope.mjs";
16
17
 
17
18
  const DEFAULT_ENDPOINT = "https://app.reasontrail.ai/api/mcp";
18
19
  // The port `next dev` binds by default. A development instance on another
@@ -389,6 +390,175 @@ function systemdQuote(value) {
389
390
  return `"${String(value).replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
390
391
  }
391
392
 
393
+ function managedServiceIdentity(target, project) {
394
+ const service = `${SERVICE_NAME_PREFIX}-${serviceSafeName(target.profile)}${project ? `-${serviceSafeName(project)}` : ""}`;
395
+ return {
396
+ service,
397
+ heartbeatPath: join(target.paths.dir, "connectors", "managed", `${service}.json`),
398
+ };
399
+ }
400
+
401
+ function managedHeartbeatHealth(active, heartbeat) {
402
+ if (!active) return { healthy: false, heartbeatStatus: "inactive" };
403
+ if (!heartbeat?.lastAttemptAt) return { healthy: false, heartbeatStatus: "starting" };
404
+ if (heartbeat.lastError) return { healthy: false, heartbeatStatus: "failed" };
405
+ if (!heartbeat.lastSuccessAt) return { healthy: false, heartbeatStatus: "no_success" };
406
+ const ageMs = Date.now() - Date.parse(heartbeat.lastSuccessAt);
407
+ const staleAfterMs = Math.max(120, Number(heartbeat.intervalSeconds || 60) * 3) * 1000;
408
+ if (!Number.isFinite(ageMs) || ageMs > staleAfterMs) return { healthy: false, heartbeatStatus: "stale" };
409
+ return { healthy: true, heartbeatStatus: "healthy" };
410
+ }
411
+
412
+ async function resolveSystemdScope(identity, systemRequested = false) {
413
+ const systemPath = `/etc/systemd/system/${identity.service}.service`;
414
+ const systemUnitExists = Boolean(await stat(systemPath).catch(() => null));
415
+ return selectSystemdScope({ systemRequested, systemUnitExists });
416
+ }
417
+
418
+ async function inspectManagedCaptureService(target, project, { system = false } = {}) {
419
+ if (!project) return { installed: false, enabled: false, active: false, status: "unbound", heartbeat: null };
420
+ const identity = managedServiceIdentity(target, project);
421
+ const heartbeat = await readJson(identity.heartbeatPath, null).catch((error) => ({ lastError: error.message }));
422
+ if (process.platform === "linux") {
423
+ const scope = await resolveSystemdScope(identity, system);
424
+ const systemScope = scope === "system";
425
+ const path = systemScope
426
+ ? `/etc/systemd/system/${identity.service}.service`
427
+ : join(homedir(), ".config", "systemd", "user", `${identity.service}.service`);
428
+ const installed = Boolean(await stat(path).catch(() => null));
429
+ const ctl = systemScope ? [] : ["--user"];
430
+ const enabledResult = spawnSync("systemctl", [...ctl, "is-enabled", `${identity.service}.service`], { encoding: "utf8" });
431
+ const activeResult = spawnSync("systemctl", [...ctl, "is-active", `${identity.service}.service`], { encoding: "utf8" });
432
+ const enabled = enabledResult.status === 0 && enabledResult.stdout.trim() === "enabled";
433
+ const active = activeResult.status === 0 && activeResult.stdout.trim() === "active";
434
+ const health = managedHeartbeatHealth(active, heartbeat);
435
+ return {
436
+ installed,
437
+ enabled,
438
+ active,
439
+ status: active ? `active_${health.heartbeatStatus}` : installed ? "inactive" : "not_installed",
440
+ ...health,
441
+ manager: systemScope ? "systemd-system" : "systemd-user",
442
+ service: identity.service,
443
+ path,
444
+ heartbeat,
445
+ ...(!active && activeResult.stderr.trim() ? { managerError: activeResult.stderr.trim() } : {}),
446
+ };
447
+ }
448
+ if (process.platform === "darwin") {
449
+ const label = `ai.reasontrail.${identity.service}`;
450
+ const path = join(homedir(), "Library", "LaunchAgents", `${label}.plist`);
451
+ const installed = Boolean(await stat(path).catch(() => null));
452
+ const result = spawnSync("launchctl", ["print", `gui/${process.getuid?.() ?? 0}/${label}`], { encoding: "utf8" });
453
+ const active = result.status === 0;
454
+ const health = managedHeartbeatHealth(active, heartbeat);
455
+ return {
456
+ installed,
457
+ enabled: installed,
458
+ active,
459
+ status: active ? `active_${health.heartbeatStatus}` : installed ? "inactive" : "not_installed",
460
+ ...health,
461
+ manager: "launchd",
462
+ service: label,
463
+ path,
464
+ heartbeat,
465
+ ...(!active && result.stderr.trim() ? { managerError: result.stderr.trim() } : {}),
466
+ };
467
+ }
468
+ return { installed: false, enabled: false, active: false, status: "unsupported", heartbeat };
469
+ }
470
+
471
+ async function recordManagedHeartbeat(target, project, value) {
472
+ if (!project) return;
473
+ const { heartbeatPath } = managedServiceIdentity(target, project);
474
+ await saveJson(heartbeatPath, value);
475
+ }
476
+
477
+ async function installManagedCaptureService(target, root, project, intervalSeconds, { system = false } = {}) {
478
+ if (!project) throw new CliError("Install requires a project binding.", 2);
479
+ const identity = managedServiceIdentity(target, project);
480
+ const script = resolve(process.argv[1]);
481
+ const args = [
482
+ script, "sync", "managed", "--profile", target.profile, "--apply", "--watch",
483
+ "--interval", String(intervalSeconds), "--project", project,
484
+ ...(target.profile === "production" ? ["--confirm-production"] : []),
485
+ ];
486
+ if (process.platform === "linux") {
487
+ const scope = await resolveSystemdScope(identity, system);
488
+ const systemScope = scope === "system";
489
+ const servicePath = systemScope
490
+ ? `/etc/systemd/system/${identity.service}.service`
491
+ : join(homedir(), ".config", "systemd", "user", `${identity.service}.service`);
492
+ const unit = [
493
+ "[Unit]",
494
+ `Description=ReasonTrail managed capture (${target.profile}/${project})`,
495
+ "After=network-online.target",
496
+ "Wants=network-online.target",
497
+ "",
498
+ "[Service]",
499
+ "Type=simple",
500
+ `Environment=${systemdQuote(`HOME=${homedir()}`)}`,
501
+ `Environment=${systemdQuote(`XDG_CONFIG_HOME=${process.env.XDG_CONFIG_HOME || join(homedir(), ".config")}`)}`,
502
+ `Environment=${systemdQuote(`CODEX_HOME=${process.env.CODEX_HOME || join(homedir(), ".codex")}`)}`,
503
+ `WorkingDirectory=${root}`,
504
+ `ExecStart=${systemdQuote(process.execPath)} ${args.map(systemdQuote).join(" ")}`,
505
+ "Restart=always",
506
+ "RestartSec=15",
507
+ "",
508
+ "[Install]",
509
+ "WantedBy=default.target",
510
+ "",
511
+ ].join("\n");
512
+ await mkdir(dirname(servicePath), { recursive: true, mode: 0o755 });
513
+ await writeFile(servicePath, unit, { mode: 0o644 });
514
+ const ctl = systemScope ? ["systemctl"] : ["systemctl", "--user"];
515
+ for (const command of [["daemon-reload"], ["enable", "--now", `${identity.service}.service`]]) {
516
+ const result = spawnSync(ctl[0], [...ctl.slice(1), ...command], { encoding: "utf8" });
517
+ if (result.status !== 0) throw new CliError(result.stderr.trim() || `${ctl.join(" ")} ${command.join(" ")} failed`, 3);
518
+ }
519
+ const active = spawnSync(ctl[0], [...ctl.slice(1), "is-active", `${identity.service}.service`], { encoding: "utf8" });
520
+ if (active.status !== 0 || active.stdout.trim() !== "active") {
521
+ throw new CliError(active.stderr.trim() || `${identity.service}.service did not become active`, 3);
522
+ }
523
+ return {
524
+ ...(await inspectManagedCaptureService(target, project, { system: systemScope })),
525
+ platform: "linux",
526
+ projectSlug: project,
527
+ };
528
+ }
529
+ if (process.platform === "darwin") {
530
+ const label = `ai.reasontrail.${identity.service}`;
531
+ const plistPath = join(homedir(), "Library", "LaunchAgents", `${label}.plist`);
532
+ const programArguments = [process.execPath, ...args].map((arg) => ` <string>${plistEscape(arg)}</string>`);
533
+ const plist = [
534
+ `<?xml version="1.0" encoding="UTF-8"?>`,
535
+ `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
536
+ `<plist version="1.0">`, `<dict>`,
537
+ ` <key>Label</key><string>${plistEscape(label)}</string>`,
538
+ ` <key>WorkingDirectory</key><string>${plistEscape(root)}</string>`,
539
+ ` <key>ProgramArguments</key>`, ` <array>`, ...programArguments, ` </array>`,
540
+ ` <key>KeepAlive</key><true/>`, ` <key>RunAtLoad</key><true/>`,
541
+ ` <key>StandardOutPath</key><string>${plistEscape(join(CONFIG_DIR, `${identity.service}.out.log`))}</string>`,
542
+ ` <key>StandardErrorPath</key><string>${plistEscape(join(CONFIG_DIR, `${identity.service}.err.log`))}</string>`,
543
+ `</dict>`, `</plist>`, ``,
544
+ ].join("\n");
545
+ await mkdir(dirname(plistPath), { recursive: true, mode: 0o755 });
546
+ await writeFile(plistPath, plist, { mode: 0o644 });
547
+ const gui = `gui/${process.getuid?.() ?? 0}`;
548
+ spawnSync("launchctl", ["bootout", `${gui}/${label}`], { encoding: "utf8" });
549
+ const activated = spawnSync("launchctl", ["bootstrap", gui, plistPath], { encoding: "utf8" });
550
+ if (activated.status !== 0) throw new CliError(activated.stderr.trim() || `Could not activate ${label}`, 3);
551
+ const active = spawnSync("launchctl", ["print", `${gui}/${label}`], { encoding: "utf8" });
552
+ if (active.status !== 0) throw new CliError(active.stderr.trim() || `${label} did not become active`, 3);
553
+ return {
554
+ ...(await inspectManagedCaptureService(target, project)),
555
+ platform: "darwin",
556
+ projectSlug: project,
557
+ };
558
+ }
559
+ throw new CliError(`Managed sync service install is not implemented for ${process.platform}.`, 2);
560
+ }
561
+
392
562
  function options(args) {
393
563
  const values = { _: [] };
394
564
  for (let i = 0; i < args.length; i += 1) {
@@ -458,7 +628,10 @@ async function getStatus(target) {
458
628
  const codexMapped = codexSessions.filter((s) => s.mapped);
459
629
  const codexPending = codexMapped.filter((s) => {
460
630
  const prev = codexSyncState.sessions?.[s.threadId];
461
- return !prev || prev.turnCount !== s.turnCount || prev.interrupted !== s.interrupted;
631
+ if (!prev || prev.interrupted !== s.interrupted) return true;
632
+ if (!Array.isArray(prev.turnFingerprints)) return prev.turnCount !== s.turnCount;
633
+ const acknowledged = new Set(prev.turnFingerprints);
634
+ return s.turns.some((turn) => !acknowledged.has(turn.fingerprint));
462
635
  }).length;
463
636
  const codexMcp = await codexMcpConfigured(target.profile);
464
637
  const codexSkill = await (async () => {
@@ -466,6 +639,7 @@ async function getStatus(target) {
466
639
  return (await stat(join(defaultCodexHome(), "skills", "reasontrail", "SKILL.md"))).isFile();
467
640
  } catch { return false; }
468
641
  })();
642
+ const managedCapture = await inspectManagedCaptureService(target, projectBound ? binding?.projectSlug : null);
469
643
 
470
644
  return {
471
645
  available: tools.length > 0,
@@ -479,13 +653,14 @@ async function getStatus(target) {
479
653
  conversation_connector: projectBound
480
654
  ? (hooksInstalled ? "Claude Code Hooks; Codex Local Session Sync" : "Codex Local Session Sync")
481
655
  : "none",
482
- automatic_transcript_sync: "disabled_explicit_sync_only",
656
+ automatic_transcript_sync: managedCapture.active ? "active_managed_capture" : "inactive",
657
+ managed_capture_service: managedCapture,
483
658
  codex_desktop: {
484
659
  brain_access: codexMcp ? "connected" : "not_configured",
485
660
  workspace: root,
486
661
  repository: normalizedRepositoryUrl(gitRemote(root)),
487
662
  project: projectBound ? binding.projectSlug : null,
488
- capture_mechanism: "explicit `sync codex --apply` only",
663
+ capture_mechanism: managedCapture.active ? "managed capture service" : "inactive; explicit sync remains available",
489
664
  session_store: join(defaultCodexHome(), "sessions"),
490
665
  mcp_configured: codexMcp,
491
666
  skill_installed: codexSkill,
@@ -654,30 +829,122 @@ async function updateCommand(argv) {
654
829
  const target = await resolveTarget(argv);
655
830
  const opts = target.opts;
656
831
  const piped = await stdinJson();
657
- const { root, binding } = await bindingFor(target);
832
+ const { binding } = await bindingFor(target);
658
833
  const { client, tools } = await connected(target);
659
834
  if (!hasTool(tools, "update_reasontrail")) throw new CliError("The authenticated ReasonTrail connection does not expose update_reasontrail.", 3);
660
- const identity = createHash("sha256").update(root).digest("hex").slice(0, 20);
835
+ const sourceSessionId = String(opts.session || piped.sourceSessionId || "").trim() || null;
836
+ if (Array.isArray(piped.turns) && piped.turns.length > 0) {
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
+ }
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
+ ];
661
855
  const labeledFindings = [
662
856
  ...(piped.findings || []),
663
857
  ...(piped.discoveries || []).map((value) => `[discovery] ${value}`),
664
- ...(piped.implementationFacts || piped.implementation_facts || []).map((value) => `[implementation fact] ${value}`),
665
858
  ...(piped.rejectedApproaches || piped.rejected_approaches || []).map((value) => `[rejected approach] ${value}`),
666
859
  ...(piped.constraints || []).map((value) => `[constraint] ${value}`),
667
- ...(piped.ideas || []).map((value) => `[idea] ${value}`),
668
860
  ...(piped.openQuestions || piped.open_questions || []).map((value) => `[open question] ${value}`),
669
- ...(piped.taskOutcomes || piped.task_outcomes || []).map((value) => `[task outcome] ${value}`),
670
861
  ];
671
862
  const args = {
672
863
  ...piped,
673
864
  ...(labeledFindings.length ? { findings: labeledFindings } : {}),
865
+ ...(operationalEvents.length ? { operationalEvents } : {}),
674
866
  ...(opts.summary ? { taskSummary: opts.summary } : {}),
675
867
  ...(opts.remaining_work ? { remainingWork: opts.remaining_work } : {}),
676
- clientConversationId: piped.clientConversationId || opts.conversation_id || `reasontrail-cli:${identity}`,
868
+ turns: [],
677
869
  ...(opts.project || binding?.projectSlug ? { projectSlug: opts.project || binding.projectSlug } : {}),
678
870
  };
679
- for (const key of ["discoveries", "implementationFacts", "implementation_facts", "rejectedApproaches", "rejected_approaches", "constraints", "ideas", "openQuestions", "open_questions", "taskOutcomes", "task_outcomes"]) delete args[key];
680
- output(await client.call("update_reasontrail", args));
871
+ for (const key of [
872
+ "discoveries", "implementationFacts", "implementation_facts", "rejectedApproaches", "rejected_approaches",
873
+ "constraints", "openQuestions", "open_questions", "taskOutcomes", "task_outcomes", "clientConversationId",
874
+ "sourceSessionId", "sourceCheckpoint", "sourceEligibleTurns", "sourceAvailability",
875
+ ]) delete args[key];
876
+ if (sourceSessionId) {
877
+ args.sourceSessionId = sourceSessionId;
878
+ args.clientConversationId = `codex:${sourceSessionId}`;
879
+ } else {
880
+ args.sourceAvailability = "SOURCE_UNAVAILABLE";
881
+ }
882
+ if (!sourceSessionId) {
883
+ const projectUpdate = await client.call("update_reasontrail", args);
884
+ return output({
885
+ ...(projectUpdate && typeof projectUpdate === "object" ? projectUpdate : {}),
886
+ transcript: projectUpdate?.transcript ?? {
887
+ sourceSessionId: null,
888
+ sourceCheckpoint: null,
889
+ sourceEligible: null,
890
+ supplied: 0,
891
+ accepted: 0,
892
+ duplicates: 0,
893
+ excluded: 0,
894
+ rejected: 0,
895
+ persistedMatchingSourceMessages: 0,
896
+ totalConversationMessages: 0,
897
+ lastAcknowledgedCursor: { messageId: null, sequence: null },
898
+ coverage: "SOURCE_UNAVAILABLE",
899
+ },
900
+ projectUpdate: projectUpdate?.projectUpdate ?? null,
901
+ summaryOnly: true,
902
+ note: "Project update processed without transcript synchronization because no authorized native session identity was available.",
903
+ });
904
+ }
905
+
906
+ for (const tool of ["begin_task", "sync_conversation_delta", "preview_conversation_reconciliation"]) {
907
+ if (!hasTool(tools, tool)) throw new CliError("The ReasonTrail server does not support verified native-session flushing. Update the CLI/server pair before retrying.", 3);
908
+ }
909
+ const synchronized = await syncCodex(client, tools, target.paths.dir, target.cfg, {
910
+ codexHome: defaultCodexHome(),
911
+ session: sourceSessionId,
912
+ project: opts.project || binding?.projectSlug || null,
913
+ force: true,
914
+ });
915
+ const source = synchronized.session_results?.find((item) => item.sourceSessionId === sourceSessionId) ?? null;
916
+ const available = synchronized.source_status === "AVAILABLE" && source;
917
+ const projectUpdate = await client.call("update_reasontrail", {
918
+ ...args,
919
+ sourceAvailability: available ? "AVAILABLE" : "SOURCE_UNAVAILABLE",
920
+ ...(available ? {
921
+ sourceCheckpoint: source.sourceCheckpoint,
922
+ sourceEligibleTurns: source.sourceEligible,
923
+ } : {}),
924
+ });
925
+ return output({
926
+ ...(projectUpdate && typeof projectUpdate === "object" ? projectUpdate : {}),
927
+ transcript: source?.transcript ?? projectUpdate?.transcript ?? {
928
+ sourceSessionId,
929
+ sourceCheckpoint: null,
930
+ sourceEligible: null,
931
+ supplied: 0,
932
+ accepted: 0,
933
+ duplicates: 0,
934
+ excluded: 0,
935
+ rejected: 0,
936
+ persistedMatchingSourceMessages: 0,
937
+ totalConversationMessages: 0,
938
+ lastAcknowledgedCursor: { messageId: null, sequence: null },
939
+ coverage: "SOURCE_UNAVAILABLE",
940
+ },
941
+ projectUpdate: projectUpdate?.projectUpdate ?? null,
942
+ summaryOnly: !available,
943
+ note: available
944
+ ? "The native Codex session was synchronized through the capture adapter; the project update is reported separately."
945
+ : "The native session was unavailable or outside the authorized project binding. No synthetic Conversation was created; the project update is summary-only.",
946
+ capture: synchronized,
947
+ });
681
948
  }
682
949
 
683
950
  async function bindCommand(argv) {
@@ -721,11 +988,27 @@ async function bindCommand(argv) {
721
988
  const slug = repository.projectSlug;
722
989
  if (!slug) throw new CliError("ReasonTrail did not return a project for this repository. Nothing was bound.", 2);
723
990
  cfg.bindings ||= {};
724
- 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() };
725
994
  await saveJson(target.paths.config, cfg);
995
+ let automaticCapture;
996
+ try {
997
+ automaticCapture = await installManagedCaptureService(target, root, slug, 60);
998
+ } catch (error) {
999
+ // The binding is still durable and truthful. Surface activation failure as
1000
+ // a first-class state instead of claiming that writing a unit was enough.
1001
+ automaticCapture = {
1002
+ installed: Boolean(await inspectManagedCaptureService(target, slug).then((status) => status.installed).catch(() => false)),
1003
+ enabled: false,
1004
+ active: false,
1005
+ status: "activation_failed",
1006
+ error: error instanceof Error ? error.message : "managed capture activation failed",
1007
+ };
1008
+ }
726
1009
  const runs = hasTool(tools, "runtime_list_runs") ? await client.call("runtime_list_runs", {}) : [];
727
1010
  const runtime = Array.isArray(runs) ? runs.find((run) => run?.project?.slug === slug && run?.workspace?.runtime) : null;
728
- output({ bound: true, repository_root: root, repository: repository.url, repository_id: repository.repositoryId || null, project_slug: slug, project_id: opts.project_id || null, graph: repository.state || null, runtime: runtime?.workspace?.runtime || null, transport: "cli" });
1011
+ output({ bound: true, repository_root: root, repository: repository.url, repository_id: repository.repositoryId || null, project_slug: slug, project_id: opts.project_id || null, graph: repository.state || null, runtime: runtime?.workspace?.runtime || null, automatic_capture: automaticCapture, transport: "cli" });
729
1012
  }
730
1013
 
731
1014
  async function authCommand(argv) {
@@ -881,34 +1164,57 @@ async function syncCommand(argv) {
881
1164
  if (watch && !apply) throw new CliError("Watch mode writes synchronized data. Add `--apply` when you intentionally want automatic upload.", 2);
882
1165
  const intervalSeconds = Math.max(10, Math.min(3600, Number(opts.interval || 60)));
883
1166
  if (!Number.isFinite(intervalSeconds)) throw new CliError("Sync interval must be a number of seconds.", 2);
884
- let client = null;
885
- let tools = [];
1167
+ let client;
1168
+ let tools;
886
1169
  if (apply) {
887
1170
  await confirmProduction(opts);
888
- ({ client, tools } = await connected(target));
889
1171
  }
1172
+ ({ client, tools } = await connected(target));
1173
+ const { binding } = await bindingFor(target);
1174
+ const project = opts.project || binding?.projectSlug || null;
890
1175
  const runOnce = async () => {
891
1176
  if (sub === "docs") {
892
- if (!apply) throw new CliError("Repository docs sync writes versioned Markdown into ReasonTrail. Add `--apply` when you intentionally want to sync docs.", 2);
893
- if (!hasTool(tools, "sync_docs")) throw new CliError("The authenticated ReasonTrail connection does not expose sync_docs. Update the CLI/server pair.", 3);
894
- const { binding } = await bindingFor(target);
895
- return client.call("sync_docs", { ...(opts.project || binding?.projectSlug ? { projectSlug: opts.project || binding.projectSlug } : {}) });
1177
+ const tool = apply ? "sync_docs" : "preview_docs_reconciliation";
1178
+ if (!hasTool(tools, tool)) throw new CliError(`The authenticated ReasonTrail connection does not expose ${tool}. Update the CLI/server pair.`, 3);
1179
+ return client.call(tool, { ...(project ? { projectSlug: project } : {}), syncMode: "MANUAL" });
896
1180
  }
897
1181
  if (sub === "managed") {
898
- if (!apply) throw new CliError("Managed sync writes conversation and documentation updates into ReasonTrail. Add `--apply` when you intentionally want background capture.", 2);
899
1182
  const codex = await syncCodex(client, tools, target.paths.dir, target.cfg, {
900
- dryRun: false,
1183
+ dryRun: !apply,
1184
+ managed: true,
901
1185
  since: opts.since || null,
902
- project: opts.project || null,
1186
+ project,
903
1187
  session: opts.session || null,
904
1188
  force: Boolean(opts.force),
905
1189
  });
906
1190
  let docs = null;
907
- if (hasTool(tools, "sync_docs")) {
908
- const { binding } = await bindingFor(target);
909
- docs = await client.call("sync_docs", { ...(opts.project || binding?.projectSlug ? { projectSlug: opts.project || binding.projectSlug } : {}) });
1191
+ const docsTool = apply ? "sync_docs" : "preview_docs_reconciliation";
1192
+ if (hasTool(tools, docsTool)) {
1193
+ docs = await client.call(docsTool, { ...(project ? { projectSlug: project } : {}), syncMode: "AUTOMATIC" });
1194
+ }
1195
+ if (apply) {
1196
+ const failedDocs = Array.isArray(docs?.synced)
1197
+ ? docs.synced.filter((entry) => entry?.error || Number(entry?.failed || 0) > 0)
1198
+ : [];
1199
+ if (failedDocs.length > 0) {
1200
+ const detail = failedDocs.map((entry) => entry.error || `${entry.project ?? "project"}: ${entry.failed} document failures`).join("; ");
1201
+ throw new Error(`Repository Resource synchronization was partial: ${detail}`);
1202
+ }
910
1203
  }
911
- return { synchronized: true, codex, docs };
1204
+ const result = { synchronized: apply, dry_run: !apply, codex, docs };
1205
+ if (apply) {
1206
+ await recordManagedHeartbeat(target, project, {
1207
+ service: managedServiceIdentity(target, project).service,
1208
+ projectSlug: project,
1209
+ intervalSeconds,
1210
+ lastAttemptAt: new Date().toISOString(),
1211
+ lastSuccessAt: new Date().toISOString(),
1212
+ lastError: null,
1213
+ codex,
1214
+ docs,
1215
+ });
1216
+ }
1217
+ return result;
912
1218
  }
913
1219
  return syncCodex(client, tools, target.paths.dir, target.cfg, {
914
1220
  dryRun: !apply,
@@ -918,9 +1224,40 @@ async function syncCommand(argv) {
918
1224
  force: Boolean(opts.force),
919
1225
  });
920
1226
  };
921
- if (!watch) return output(await runOnce());
1227
+ if (!watch) {
1228
+ try {
1229
+ return output(await runOnce());
1230
+ } catch (error) {
1231
+ if (sub === "managed" && apply) {
1232
+ const attemptedAt = new Date().toISOString();
1233
+ const prior = await readJson(managedServiceIdentity(target, project).heartbeatPath, null);
1234
+ await recordManagedHeartbeat(target, project, {
1235
+ service: managedServiceIdentity(target, project).service,
1236
+ projectSlug: project,
1237
+ intervalSeconds,
1238
+ lastAttemptAt: attemptedAt,
1239
+ lastSuccessAt: prior?.lastSuccessAt ?? null,
1240
+ lastError: error instanceof Error ? error.message : "managed capture failed",
1241
+ });
1242
+ }
1243
+ throw error;
1244
+ }
1245
+ }
922
1246
  for (;;) {
923
- output({ watched_at: new Date().toISOString(), ...(await runOnce()) });
1247
+ try {
1248
+ output({ watched_at: new Date().toISOString(), ...(await runOnce()) });
1249
+ } catch (error) {
1250
+ const attemptedAt = new Date().toISOString();
1251
+ await recordManagedHeartbeat(target, project, {
1252
+ service: managedServiceIdentity(target, project).service,
1253
+ projectSlug: project,
1254
+ intervalSeconds,
1255
+ lastAttemptAt: attemptedAt,
1256
+ lastSuccessAt: (await readJson(managedServiceIdentity(target, project).heartbeatPath, null))?.lastSuccessAt ?? null,
1257
+ lastError: error instanceof Error ? error.message : "managed capture failed",
1258
+ });
1259
+ output({ watched_at: attemptedAt, synchronized: false, error: error instanceof Error ? error.message : "managed capture failed", retry_in_seconds: intervalSeconds });
1260
+ }
924
1261
  await new Promise((resolveSleep) => setTimeout(resolveSleep, intervalSeconds * 1000));
925
1262
  }
926
1263
  }
@@ -936,105 +1273,36 @@ async function syncServiceCommand(argv) {
936
1273
  const project = opts.project || binding?.projectSlug;
937
1274
  const intervalSeconds = Math.max(10, Math.min(3600, Number(opts.interval || 60)));
938
1275
  if (!Number.isFinite(intervalSeconds)) throw new CliError("Sync interval must be a number of seconds.", 2);
939
- const serviceName = `${SERVICE_NAME_PREFIX}-${serviceSafeName(target.profile)}${project ? `-${serviceSafeName(project)}` : ""}`;
940
- const script = resolve(process.argv[1]);
941
- const args = [
942
- script,
943
- "sync",
944
- "managed",
945
- "--profile",
946
- target.profile,
947
- "--apply",
948
- "--watch",
949
- "--interval",
950
- String(intervalSeconds),
951
- ...(project ? ["--project", project] : []),
952
- ...(target.profile === "production" ? ["--confirm-production"] : []),
953
- ];
1276
+ const serviceName = managedServiceIdentity(target, project).service;
1277
+ if (target.profile === "production" && action !== "status") await confirmProduction(opts);
954
1278
 
955
1279
  if (action === "install") {
956
1280
  if (!project) throw new CliError("Install requires a project. Bind this repository first with `reasontrail . --project <slug>` or pass `--project <slug>`.", 2);
957
- if (process.platform === "linux") {
958
- const system = opts.system === true;
959
- const servicePath = system
960
- ? `/etc/systemd/system/${serviceName}.service`
961
- : join(homedir(), ".config", "systemd", "user", `${serviceName}.service`);
962
- const unit = [
963
- "[Unit]",
964
- `Description=ReasonTrail managed capture (${target.profile}/${project})`,
965
- "After=network-online.target",
966
- "Wants=network-online.target",
967
- "",
968
- "[Service]",
969
- "Type=simple",
970
- `Environment=${systemdQuote(`HOME=${homedir()}`)}`,
971
- `Environment=${systemdQuote(`XDG_CONFIG_HOME=${process.env.XDG_CONFIG_HOME || join(homedir(), ".config")}`)}`,
972
- `Environment=${systemdQuote(`CODEX_HOME=${process.env.CODEX_HOME || join(homedir(), ".codex")}`)}`,
973
- `WorkingDirectory=${root}`,
974
- `ExecStart=${systemdQuote(process.execPath)} ${args.map(systemdQuote).join(" ")}`,
975
- "Restart=always",
976
- "RestartSec=15",
977
- "",
978
- "[Install]",
979
- "WantedBy=default.target",
980
- "",
981
- ].join("\n");
982
- await mkdir(dirname(servicePath), { recursive: true, mode: 0o755 });
983
- await writeFile(servicePath, unit, { mode: 0o644 });
984
- return output({
985
- installed: true,
986
- platform: "linux",
987
- manager: system ? "systemd-system" : "systemd-user",
988
- service: serviceName,
989
- path: servicePath,
990
- projectSlug: project,
991
- next: system
992
- ? [`systemctl daemon-reload`, `systemctl enable --now ${serviceName}.service`, `systemctl status ${serviceName}.service`]
993
- : [`systemctl --user daemon-reload`, `systemctl --user enable --now ${serviceName}.service`, `systemctl --user status ${serviceName}.service`],
994
- });
995
- }
996
- if (process.platform === "darwin") {
997
- const label = `ai.reasontrail.${serviceName}`;
998
- const plistPath = join(homedir(), "Library", "LaunchAgents", `${label}.plist`);
999
- const programArguments = [process.execPath, ...args].map((arg) => ` <string>${plistEscape(arg)}</string>`);
1000
- const plist = [
1001
- `<?xml version="1.0" encoding="UTF-8"?>`,
1002
- `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
1003
- `<plist version="1.0">`,
1004
- `<dict>`,
1005
- ` <key>Label</key><string>${plistEscape(label)}</string>`,
1006
- ` <key>WorkingDirectory</key><string>${plistEscape(root)}</string>`,
1007
- ` <key>ProgramArguments</key>`,
1008
- ` <array>`,
1009
- ...programArguments,
1010
- ` </array>`,
1011
- ` <key>KeepAlive</key><true/>`,
1012
- ` <key>RunAtLoad</key><true/>`,
1013
- ` <key>StandardOutPath</key><string>${plistEscape(join(CONFIG_DIR, `${serviceName}.out.log`))}</string>`,
1014
- ` <key>StandardErrorPath</key><string>${plistEscape(join(CONFIG_DIR, `${serviceName}.err.log`))}</string>`,
1015
- `</dict>`,
1016
- `</plist>`,
1017
- ``,
1018
- ].join("\n");
1019
- await mkdir(dirname(plistPath), { recursive: true, mode: 0o755 });
1020
- await writeFile(plistPath, plist, { mode: 0o644 });
1021
- return output({ installed: true, platform: "darwin", manager: "launchd", service: label, path: plistPath, projectSlug: project, next: [`launchctl bootstrap gui/$(id -u) ${plistPath}`, `launchctl print gui/$(id -u)/${label}`] });
1022
- }
1023
- throw new CliError(`Managed sync service install is not implemented for ${process.platform}. Use \`reasontrail sync managed --apply --watch\` under your OS service manager.`, 2);
1281
+ return output(await installManagedCaptureService(target, root, project, intervalSeconds, { system: opts.system === true }));
1024
1282
  }
1025
1283
 
1284
+ if (action === "status") return output(await inspectManagedCaptureService(target, project, { system: opts.system === true }));
1285
+
1026
1286
  if (process.platform === "linux") {
1027
- const system = opts.system === true;
1287
+ const system = (await resolveSystemdScope(managedServiceIdentity(target, project), opts.system === true)) === "system";
1028
1288
  const ctl = system ? ["systemctl"] : ["systemctl", "--user"];
1029
1289
  const verb = action === "uninstall" ? "disable" : action;
1030
1290
  if (action === "uninstall") {
1031
1291
  const result = spawnSync(ctl[0], [...ctl.slice(1), "disable", "--now", `${serviceName}.service`], { encoding: "utf8" });
1032
1292
  if (result.status !== 0) throw new CliError(result.stderr.trim() || `Could not disable ${serviceName}.service`, 3);
1033
- return output({ removed: false, disabled: true, service: serviceName, note: "The unit file was left in place; remove it manually if you no longer need it." });
1293
+ return output({
1294
+ removed: false,
1295
+ disabled: true,
1296
+ ...(await inspectManagedCaptureService(target, project, { system })),
1297
+ note: "The unit file was left in place; remove it manually if you no longer need it.",
1298
+ });
1034
1299
  }
1035
1300
  const result = spawnSync(ctl[0], [...ctl.slice(1), verb, `${serviceName}.service`], { encoding: "utf8" });
1036
1301
  if (result.status !== 0) throw new CliError(result.stderr.trim() || `systemctl ${verb} failed`, 3);
1037
- return output({ ok: true, manager: system ? "systemd-system" : "systemd-user", action, service: serviceName, output: result.stdout.trim() });
1302
+ const inspected = await inspectManagedCaptureService(target, project, { system });
1303
+ if (action === "start" && !inspected.active) throw new CliError(`${serviceName}.service did not become active`, 3);
1304
+ if (action === "stop" && inspected.active) throw new CliError(`${serviceName}.service remained active after stop`, 3);
1305
+ return output({ ok: true, action, ...inspected, managerOutput: result.stdout.trim() });
1038
1306
  }
1039
1307
  if (process.platform === "darwin") {
1040
1308
  const label = `ai.reasontrail.${serviceName}`;
@@ -1045,7 +1313,10 @@ async function syncServiceCommand(argv) {
1045
1313
  : ["bootout", `${gui}/${label}`];
1046
1314
  const result = spawnSync("launchctl", command, { encoding: "utf8" });
1047
1315
  if (result.status !== 0) throw new CliError(result.stderr.trim() || `launchctl ${action} failed`, 3);
1048
- return output({ ok: true, manager: "launchd", action, service: label, output: result.stdout.trim() });
1316
+ const inspected = await inspectManagedCaptureService(target, project);
1317
+ if (action === "start" && !inspected.active) throw new CliError(`${label} did not become active`, 3);
1318
+ if (action === "stop" && inspected.active) throw new CliError(`${label} remained active after stop`, 3);
1319
+ return output({ ok: true, action, ...inspected, managerOutput: result.stdout.trim() });
1049
1320
  }
1050
1321
  throw new CliError(`Managed sync service ${action} is not implemented for ${process.platform}.`, 2);
1051
1322
  }
@@ -1115,7 +1386,7 @@ async function setupCommand(argv) {
1115
1386
  hooks = await installClaudeHooks(target.profile);
1116
1387
  await pruneClaudeRetryBacklog(target.profile);
1117
1388
  }
1118
- output({ configured: true, profile: target.profile, environment: target.profile, endpoint: target.endpoint, detected_platforms: detected, hooks, mcp_configuration: "not_generated", next: `Run \`reasontrail auth login --profile ${target.profile}\`, then configure MCP credentials through the assistant's secure credential mechanism.` });
1389
+ output({ configured: true, profile: target.profile, environment: target.profile, endpoint: target.endpoint, detected_platforms: detected, hooks, mcp_configuration: "not_generated", next: `Run \`reasontrail auth login --profile ${target.profile}\`, configure MCP credentials through the assistant's secure credential mechanism, then run \`reasontrail . --profile ${target.profile}\` in the repository. The explicit repository binding activates managed Codex and repository-document capture and reports any activation failure.` });
1119
1390
  }
1120
1391
 
1121
1392
  async function installClaudeHooks(profile) {
@@ -1339,6 +1610,25 @@ async function claudeHookCommand(argv) {
1339
1610
  * blast radius or a revocation. Same directory, same 0600, separate file.
1340
1611
  */
1341
1612
  const RUNTIME_BUNDLE = join(PACKAGE_ROOT, "runtime", "reasontrail-runtime.mjs");
1613
+ const RUNTIME_CHECKSUM = `${RUNTIME_BUNDLE}.sha256`;
1614
+
1615
+ async function runtimeBundleIntegrity() {
1616
+ let bundle;
1617
+ let checksum;
1618
+ try {
1619
+ [bundle, checksum] = await Promise.all([
1620
+ readFile(RUNTIME_BUNDLE),
1621
+ readFile(RUNTIME_CHECKSUM, "utf8"),
1622
+ ]);
1623
+ } catch (error) {
1624
+ if (error?.code === "ENOENT") return { state: "missing" };
1625
+ throw new CliError(`Could not verify the Runtime bundle: ${error.message}`);
1626
+ }
1627
+ const expected = checksum.trim().split(/\s+/)[0]?.toLowerCase();
1628
+ if (!/^[0-9a-f]{64}$/.test(expected || "")) return { state: "invalid-checksum" };
1629
+ const actual = createHash("sha256").update(bundle).digest("hex");
1630
+ return { state: actual === expected ? "verified" : "mismatch", expected, actual };
1631
+ }
1342
1632
 
1343
1633
  async function runtimeConfig(profile) {
1344
1634
  return readJson(profilePaths(profile).runtime, null);
@@ -1418,6 +1708,7 @@ async function runtimeCommand(argv) {
1418
1708
  if (sub === "status") {
1419
1709
  const cfg = await runtimeConfig(target.profile);
1420
1710
  if (!cfg) return stdout.write("No runtime enrollment on this machine.\nRun `reasontrail runtime enroll …`.\n");
1711
+ const bundleIntegrity = await runtimeBundleIntegrity();
1421
1712
  // The PREFIX only. The credential is never redisplayed after enrollment.
1422
1713
  const prefix = String(cfg.token || "").slice(0, 11);
1423
1714
  stdout.write(
@@ -1427,7 +1718,8 @@ async function runtimeCommand(argv) {
1427
1718
  ` Workspaces ${cfg.workspaces?.length ? cfg.workspaces.join(", ") : "none — map them in ReasonTrail after connecting"}\n` +
1428
1719
  ` Exec root ${cfg.executionRoot || "not configured — provider execution disabled"}\n` +
1429
1720
  ` Dep network ${cfg.dependencyNetwork || "disabled"}\n` +
1430
- ` Bundle ${RUNTIME_BUNDLE}\n\n` +
1721
+ ` Bundle ${RUNTIME_BUNDLE}\n` +
1722
+ ` Integrity ${bundleIntegrity.state}\n\n` +
1431
1723
  `Live status — protocol, workers, readiness — is shown by ReasonTrail itself,\n` +
1432
1724
  `which is the authority on all three. This command reports local setup only.\n`
1433
1725
  );
@@ -1447,10 +1739,12 @@ async function runtimeCommand(argv) {
1447
1739
  }
1448
1740
  // Re-prove a possibly copied enrollment before handing its token to a child.
1449
1741
  validateEndpoint(cfg.origin, target.profile);
1450
- try {
1451
- await stat(RUNTIME_BUNDLE);
1452
- } catch {
1453
- throw new CliError(`The runtime bundle is missing from this installation (${RUNTIME_BUNDLE}). Reinstall the CLI.`);
1742
+ const bundleIntegrity = await runtimeBundleIntegrity();
1743
+ if (bundleIntegrity.state === "missing") {
1744
+ throw new CliError(`The Runtime bundle or checksum is missing from this installation (${RUNTIME_BUNDLE}). Reinstall the CLI.`);
1745
+ }
1746
+ if (bundleIntegrity.state !== "verified") {
1747
+ throw new CliError(`The Runtime bundle failed its integrity check (${bundleIntegrity.state}). Reinstall the CLI before starting it.`);
1454
1748
  }
1455
1749
 
1456
1750
  const args = [RUNTIME_BUNDLE, "run"];
@@ -1488,7 +1782,7 @@ function helpCommand() {
1488
1782
  ` auth login|logout|status Authentication management\n` +
1489
1783
  ` context --request <request> Bounded context (ladder first; --deep for the full pack)\n` +
1490
1784
  ` search --query <text> Bound-project Brain search (use --all-projects intentionally)\n` +
1491
- ` update Submit structured JSON on stdin\n` +
1785
+ ` update [--session <native-id>] Submit governed project JSON and verify the native Codex transcript when identified\n` +
1492
1786
  ` run "<task>" | --task <id> Start a Mission on the shared Runtime\n` +
1493
1787
  ` run status|stop|resume <id> Control one Runtime Mission\n` +
1494
1788
  ` decide <mission> <gate> <key> Answer an existing Mission gate\n` +
@@ -1496,9 +1790,9 @@ function helpCommand() {
1496
1790
  ` install --platform <name> Install the assistant skill\n` +
1497
1791
  ` uninstall --platform <name> Remove the assistant skill\n` +
1498
1792
  ` setup --profile <profile> Configure detected assistants (hooks require --enable-hooks in development)\n` +
1499
- ` sync codex --profile <profile> Preview local Codex sessions; add --apply and optionally --watch\n` +
1500
- ` sync docs --profile <profile> Synchronize repository Markdown docs; requires --apply; optionally --watch\n` +
1501
- ` sync managed --profile <profile> Sync eligible Codex sessions and Markdown docs together\n` +
1793
+ ` sync codex --profile <profile> Read-only source/server preview; add --apply and optionally --watch\n` +
1794
+ ` sync docs --profile <profile> Preview repository docs; add --apply and optionally --watch\n` +
1795
+ ` sync managed --profile <profile> Preview both capture paths; add --apply to synchronize\n` +
1502
1796
  ` sync service install|status Manage OS background capture for one profile/project\n` +
1503
1797
  ` hook claude Receive a Claude Code lifecycle hook event\n` +
1504
1798
  ` config endpoint <url> --profile <profile> Configure an isolated named profile\n` +