@reasontrail/cli 0.1.1 → 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.
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,17 +829,19 @@ 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
+ }
661
839
  const labeledFindings = [
662
840
  ...(piped.findings || []),
663
841
  ...(piped.discoveries || []).map((value) => `[discovery] ${value}`),
664
842
  ...(piped.implementationFacts || piped.implementation_facts || []).map((value) => `[implementation fact] ${value}`),
665
843
  ...(piped.rejectedApproaches || piped.rejected_approaches || []).map((value) => `[rejected approach] ${value}`),
666
844
  ...(piped.constraints || []).map((value) => `[constraint] ${value}`),
667
- ...(piped.ideas || []).map((value) => `[idea] ${value}`),
668
845
  ...(piped.openQuestions || piped.open_questions || []).map((value) => `[open question] ${value}`),
669
846
  ...(piped.taskOutcomes || piped.task_outcomes || []).map((value) => `[task outcome] ${value}`),
670
847
  ];
@@ -673,11 +850,86 @@ async function updateCommand(argv) {
673
850
  ...(labeledFindings.length ? { findings: labeledFindings } : {}),
674
851
  ...(opts.summary ? { taskSummary: opts.summary } : {}),
675
852
  ...(opts.remaining_work ? { remainingWork: opts.remaining_work } : {}),
676
- clientConversationId: piped.clientConversationId || opts.conversation_id || `reasontrail-cli:${identity}`,
853
+ turns: [],
677
854
  ...(opts.project || binding?.projectSlug ? { projectSlug: opts.project || binding.projectSlug } : {}),
678
855
  };
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));
856
+ for (const key of [
857
+ "discoveries", "implementationFacts", "implementation_facts", "rejectedApproaches", "rejected_approaches",
858
+ "constraints", "openQuestions", "open_questions", "taskOutcomes", "task_outcomes", "clientConversationId",
859
+ "sourceSessionId", "sourceCheckpoint", "sourceEligibleTurns", "sourceAvailability",
860
+ ]) delete args[key];
861
+ if (sourceSessionId) {
862
+ args.sourceSessionId = sourceSessionId;
863
+ args.clientConversationId = `codex:${sourceSessionId}`;
864
+ } else {
865
+ args.sourceAvailability = "SOURCE_UNAVAILABLE";
866
+ }
867
+ if (!sourceSessionId) {
868
+ const projectUpdate = await client.call("update_reasontrail", args);
869
+ return output({
870
+ ...(projectUpdate && typeof projectUpdate === "object" ? projectUpdate : {}),
871
+ transcript: projectUpdate?.transcript ?? {
872
+ sourceSessionId: null,
873
+ sourceCheckpoint: null,
874
+ sourceEligible: null,
875
+ supplied: 0,
876
+ accepted: 0,
877
+ duplicates: 0,
878
+ excluded: 0,
879
+ rejected: 0,
880
+ persistedMatchingSourceMessages: 0,
881
+ totalConversationMessages: 0,
882
+ lastAcknowledgedCursor: { messageId: null, sequence: null },
883
+ coverage: "SOURCE_UNAVAILABLE",
884
+ },
885
+ projectUpdate: projectUpdate?.projectUpdate ?? null,
886
+ summaryOnly: true,
887
+ note: "Project update processed without transcript synchronization because no authorized native session identity was available.",
888
+ });
889
+ }
890
+
891
+ for (const tool of ["begin_task", "sync_conversation_delta", "preview_conversation_reconciliation"]) {
892
+ 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);
893
+ }
894
+ const synchronized = await syncCodex(client, tools, target.paths.dir, target.cfg, {
895
+ codexHome: defaultCodexHome(),
896
+ session: sourceSessionId,
897
+ project: opts.project || binding?.projectSlug || null,
898
+ force: true,
899
+ });
900
+ const source = synchronized.session_results?.find((item) => item.sourceSessionId === sourceSessionId) ?? null;
901
+ const available = synchronized.source_status === "AVAILABLE" && source;
902
+ const projectUpdate = await client.call("update_reasontrail", {
903
+ ...args,
904
+ sourceAvailability: available ? "AVAILABLE" : "SOURCE_UNAVAILABLE",
905
+ ...(available ? {
906
+ sourceCheckpoint: source.sourceCheckpoint,
907
+ sourceEligibleTurns: source.sourceEligible,
908
+ } : {}),
909
+ });
910
+ return output({
911
+ ...(projectUpdate && typeof projectUpdate === "object" ? projectUpdate : {}),
912
+ transcript: source?.transcript ?? projectUpdate?.transcript ?? {
913
+ sourceSessionId,
914
+ sourceCheckpoint: null,
915
+ sourceEligible: null,
916
+ supplied: 0,
917
+ accepted: 0,
918
+ duplicates: 0,
919
+ excluded: 0,
920
+ rejected: 0,
921
+ persistedMatchingSourceMessages: 0,
922
+ totalConversationMessages: 0,
923
+ lastAcknowledgedCursor: { messageId: null, sequence: null },
924
+ coverage: "SOURCE_UNAVAILABLE",
925
+ },
926
+ projectUpdate: projectUpdate?.projectUpdate ?? null,
927
+ summaryOnly: !available,
928
+ note: available
929
+ ? "The native Codex session was synchronized through the capture adapter; the project update is reported separately."
930
+ : "The native session was unavailable or outside the authorized project binding. No synthetic Conversation was created; the project update is summary-only.",
931
+ capture: synchronized,
932
+ });
681
933
  }
682
934
 
683
935
  async function bindCommand(argv) {
@@ -723,9 +975,23 @@ async function bindCommand(argv) {
723
975
  cfg.bindings ||= {};
724
976
  cfg.bindings[root] = { projectSlug: slug, projectId: opts.project_id || null, repositoryId: repository.repositoryId || null, repositoryUrl: repository.url, boundAt: new Date().toISOString() };
725
977
  await saveJson(target.paths.config, cfg);
978
+ let automaticCapture;
979
+ try {
980
+ automaticCapture = await installManagedCaptureService(target, root, slug, 60);
981
+ } catch (error) {
982
+ // The binding is still durable and truthful. Surface activation failure as
983
+ // a first-class state instead of claiming that writing a unit was enough.
984
+ automaticCapture = {
985
+ installed: Boolean(await inspectManagedCaptureService(target, slug).then((status) => status.installed).catch(() => false)),
986
+ enabled: false,
987
+ active: false,
988
+ status: "activation_failed",
989
+ error: error instanceof Error ? error.message : "managed capture activation failed",
990
+ };
991
+ }
726
992
  const runs = hasTool(tools, "runtime_list_runs") ? await client.call("runtime_list_runs", {}) : [];
727
993
  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" });
994
+ 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
995
  }
730
996
 
731
997
  async function authCommand(argv) {
@@ -881,34 +1147,56 @@ async function syncCommand(argv) {
881
1147
  if (watch && !apply) throw new CliError("Watch mode writes synchronized data. Add `--apply` when you intentionally want automatic upload.", 2);
882
1148
  const intervalSeconds = Math.max(10, Math.min(3600, Number(opts.interval || 60)));
883
1149
  if (!Number.isFinite(intervalSeconds)) throw new CliError("Sync interval must be a number of seconds.", 2);
884
- let client = null;
885
- let tools = [];
1150
+ let client;
1151
+ let tools;
886
1152
  if (apply) {
887
1153
  await confirmProduction(opts);
888
- ({ client, tools } = await connected(target));
889
1154
  }
1155
+ ({ client, tools } = await connected(target));
1156
+ const { binding } = await bindingFor(target);
1157
+ const project = opts.project || binding?.projectSlug || null;
890
1158
  const runOnce = async () => {
891
1159
  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 } : {}) });
1160
+ const tool = apply ? "sync_docs" : "preview_docs_reconciliation";
1161
+ if (!hasTool(tools, tool)) throw new CliError(`The authenticated ReasonTrail connection does not expose ${tool}. Update the CLI/server pair.`, 3);
1162
+ return client.call(tool, { ...(project ? { projectSlug: project } : {}), syncMode: "MANUAL" });
896
1163
  }
897
1164
  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
1165
  const codex = await syncCodex(client, tools, target.paths.dir, target.cfg, {
900
- dryRun: false,
1166
+ dryRun: !apply,
901
1167
  since: opts.since || null,
902
- project: opts.project || null,
1168
+ project,
903
1169
  session: opts.session || null,
904
1170
  force: Boolean(opts.force),
905
1171
  });
906
1172
  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 } : {}) });
1173
+ const docsTool = apply ? "sync_docs" : "preview_docs_reconciliation";
1174
+ if (hasTool(tools, docsTool)) {
1175
+ docs = await client.call(docsTool, { ...(project ? { projectSlug: project } : {}), syncMode: "AUTOMATIC" });
1176
+ }
1177
+ if (apply) {
1178
+ const failedDocs = Array.isArray(docs?.synced)
1179
+ ? docs.synced.filter((entry) => entry?.error || Number(entry?.failed || 0) > 0)
1180
+ : [];
1181
+ if (failedDocs.length > 0) {
1182
+ const detail = failedDocs.map((entry) => entry.error || `${entry.project ?? "project"}: ${entry.failed} document failures`).join("; ");
1183
+ throw new Error(`Repository Resource synchronization was partial: ${detail}`);
1184
+ }
910
1185
  }
911
- return { synchronized: true, codex, docs };
1186
+ const result = { synchronized: apply, dry_run: !apply, codex, docs };
1187
+ if (apply) {
1188
+ await recordManagedHeartbeat(target, project, {
1189
+ service: managedServiceIdentity(target, project).service,
1190
+ projectSlug: project,
1191
+ intervalSeconds,
1192
+ lastAttemptAt: new Date().toISOString(),
1193
+ lastSuccessAt: new Date().toISOString(),
1194
+ lastError: null,
1195
+ codex,
1196
+ docs,
1197
+ });
1198
+ }
1199
+ return result;
912
1200
  }
913
1201
  return syncCodex(client, tools, target.paths.dir, target.cfg, {
914
1202
  dryRun: !apply,
@@ -918,9 +1206,40 @@ async function syncCommand(argv) {
918
1206
  force: Boolean(opts.force),
919
1207
  });
920
1208
  };
921
- if (!watch) return output(await runOnce());
1209
+ if (!watch) {
1210
+ try {
1211
+ return output(await runOnce());
1212
+ } catch (error) {
1213
+ if (sub === "managed" && apply) {
1214
+ const attemptedAt = new Date().toISOString();
1215
+ const prior = await readJson(managedServiceIdentity(target, project).heartbeatPath, null);
1216
+ await recordManagedHeartbeat(target, project, {
1217
+ service: managedServiceIdentity(target, project).service,
1218
+ projectSlug: project,
1219
+ intervalSeconds,
1220
+ lastAttemptAt: attemptedAt,
1221
+ lastSuccessAt: prior?.lastSuccessAt ?? null,
1222
+ lastError: error instanceof Error ? error.message : "managed capture failed",
1223
+ });
1224
+ }
1225
+ throw error;
1226
+ }
1227
+ }
922
1228
  for (;;) {
923
- output({ watched_at: new Date().toISOString(), ...(await runOnce()) });
1229
+ try {
1230
+ output({ watched_at: new Date().toISOString(), ...(await runOnce()) });
1231
+ } catch (error) {
1232
+ const attemptedAt = new Date().toISOString();
1233
+ await recordManagedHeartbeat(target, project, {
1234
+ service: managedServiceIdentity(target, project).service,
1235
+ projectSlug: project,
1236
+ intervalSeconds,
1237
+ lastAttemptAt: attemptedAt,
1238
+ lastSuccessAt: (await readJson(managedServiceIdentity(target, project).heartbeatPath, null))?.lastSuccessAt ?? null,
1239
+ lastError: error instanceof Error ? error.message : "managed capture failed",
1240
+ });
1241
+ output({ watched_at: attemptedAt, synchronized: false, error: error instanceof Error ? error.message : "managed capture failed", retry_in_seconds: intervalSeconds });
1242
+ }
924
1243
  await new Promise((resolveSleep) => setTimeout(resolveSleep, intervalSeconds * 1000));
925
1244
  }
926
1245
  }
@@ -936,105 +1255,36 @@ async function syncServiceCommand(argv) {
936
1255
  const project = opts.project || binding?.projectSlug;
937
1256
  const intervalSeconds = Math.max(10, Math.min(3600, Number(opts.interval || 60)));
938
1257
  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
- ];
1258
+ const serviceName = managedServiceIdentity(target, project).service;
1259
+ if (target.profile === "production" && action !== "status") await confirmProduction(opts);
954
1260
 
955
1261
  if (action === "install") {
956
1262
  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);
1263
+ return output(await installManagedCaptureService(target, root, project, intervalSeconds, { system: opts.system === true }));
1024
1264
  }
1025
1265
 
1266
+ if (action === "status") return output(await inspectManagedCaptureService(target, project, { system: opts.system === true }));
1267
+
1026
1268
  if (process.platform === "linux") {
1027
- const system = opts.system === true;
1269
+ const system = (await resolveSystemdScope(managedServiceIdentity(target, project), opts.system === true)) === "system";
1028
1270
  const ctl = system ? ["systemctl"] : ["systemctl", "--user"];
1029
1271
  const verb = action === "uninstall" ? "disable" : action;
1030
1272
  if (action === "uninstall") {
1031
1273
  const result = spawnSync(ctl[0], [...ctl.slice(1), "disable", "--now", `${serviceName}.service`], { encoding: "utf8" });
1032
1274
  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." });
1275
+ return output({
1276
+ removed: false,
1277
+ disabled: true,
1278
+ ...(await inspectManagedCaptureService(target, project, { system })),
1279
+ note: "The unit file was left in place; remove it manually if you no longer need it.",
1280
+ });
1034
1281
  }
1035
1282
  const result = spawnSync(ctl[0], [...ctl.slice(1), verb, `${serviceName}.service`], { encoding: "utf8" });
1036
1283
  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() });
1284
+ const inspected = await inspectManagedCaptureService(target, project, { system });
1285
+ if (action === "start" && !inspected.active) throw new CliError(`${serviceName}.service did not become active`, 3);
1286
+ if (action === "stop" && inspected.active) throw new CliError(`${serviceName}.service remained active after stop`, 3);
1287
+ return output({ ok: true, action, ...inspected, managerOutput: result.stdout.trim() });
1038
1288
  }
1039
1289
  if (process.platform === "darwin") {
1040
1290
  const label = `ai.reasontrail.${serviceName}`;
@@ -1045,7 +1295,10 @@ async function syncServiceCommand(argv) {
1045
1295
  : ["bootout", `${gui}/${label}`];
1046
1296
  const result = spawnSync("launchctl", command, { encoding: "utf8" });
1047
1297
  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() });
1298
+ const inspected = await inspectManagedCaptureService(target, project);
1299
+ if (action === "start" && !inspected.active) throw new CliError(`${label} did not become active`, 3);
1300
+ if (action === "stop" && inspected.active) throw new CliError(`${label} remained active after stop`, 3);
1301
+ return output({ ok: true, action, ...inspected, managerOutput: result.stdout.trim() });
1049
1302
  }
1050
1303
  throw new CliError(`Managed sync service ${action} is not implemented for ${process.platform}.`, 2);
1051
1304
  }
@@ -1115,7 +1368,7 @@ async function setupCommand(argv) {
1115
1368
  hooks = await installClaudeHooks(target.profile);
1116
1369
  await pruneClaudeRetryBacklog(target.profile);
1117
1370
  }
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.` });
1371
+ 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
1372
  }
1120
1373
 
1121
1374
  async function installClaudeHooks(profile) {
@@ -1339,6 +1592,25 @@ async function claudeHookCommand(argv) {
1339
1592
  * blast radius or a revocation. Same directory, same 0600, separate file.
1340
1593
  */
1341
1594
  const RUNTIME_BUNDLE = join(PACKAGE_ROOT, "runtime", "reasontrail-runtime.mjs");
1595
+ const RUNTIME_CHECKSUM = `${RUNTIME_BUNDLE}.sha256`;
1596
+
1597
+ async function runtimeBundleIntegrity() {
1598
+ let bundle;
1599
+ let checksum;
1600
+ try {
1601
+ [bundle, checksum] = await Promise.all([
1602
+ readFile(RUNTIME_BUNDLE),
1603
+ readFile(RUNTIME_CHECKSUM, "utf8"),
1604
+ ]);
1605
+ } catch (error) {
1606
+ if (error?.code === "ENOENT") return { state: "missing" };
1607
+ throw new CliError(`Could not verify the Runtime bundle: ${error.message}`);
1608
+ }
1609
+ const expected = checksum.trim().split(/\s+/)[0]?.toLowerCase();
1610
+ if (!/^[0-9a-f]{64}$/.test(expected || "")) return { state: "invalid-checksum" };
1611
+ const actual = createHash("sha256").update(bundle).digest("hex");
1612
+ return { state: actual === expected ? "verified" : "mismatch", expected, actual };
1613
+ }
1342
1614
 
1343
1615
  async function runtimeConfig(profile) {
1344
1616
  return readJson(profilePaths(profile).runtime, null);
@@ -1418,6 +1690,7 @@ async function runtimeCommand(argv) {
1418
1690
  if (sub === "status") {
1419
1691
  const cfg = await runtimeConfig(target.profile);
1420
1692
  if (!cfg) return stdout.write("No runtime enrollment on this machine.\nRun `reasontrail runtime enroll …`.\n");
1693
+ const bundleIntegrity = await runtimeBundleIntegrity();
1421
1694
  // The PREFIX only. The credential is never redisplayed after enrollment.
1422
1695
  const prefix = String(cfg.token || "").slice(0, 11);
1423
1696
  stdout.write(
@@ -1427,7 +1700,8 @@ async function runtimeCommand(argv) {
1427
1700
  ` Workspaces ${cfg.workspaces?.length ? cfg.workspaces.join(", ") : "none — map them in ReasonTrail after connecting"}\n` +
1428
1701
  ` Exec root ${cfg.executionRoot || "not configured — provider execution disabled"}\n` +
1429
1702
  ` Dep network ${cfg.dependencyNetwork || "disabled"}\n` +
1430
- ` Bundle ${RUNTIME_BUNDLE}\n\n` +
1703
+ ` Bundle ${RUNTIME_BUNDLE}\n` +
1704
+ ` Integrity ${bundleIntegrity.state}\n\n` +
1431
1705
  `Live status — protocol, workers, readiness — is shown by ReasonTrail itself,\n` +
1432
1706
  `which is the authority on all three. This command reports local setup only.\n`
1433
1707
  );
@@ -1447,10 +1721,12 @@ async function runtimeCommand(argv) {
1447
1721
  }
1448
1722
  // Re-prove a possibly copied enrollment before handing its token to a child.
1449
1723
  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.`);
1724
+ const bundleIntegrity = await runtimeBundleIntegrity();
1725
+ if (bundleIntegrity.state === "missing") {
1726
+ throw new CliError(`The Runtime bundle or checksum is missing from this installation (${RUNTIME_BUNDLE}). Reinstall the CLI.`);
1727
+ }
1728
+ if (bundleIntegrity.state !== "verified") {
1729
+ throw new CliError(`The Runtime bundle failed its integrity check (${bundleIntegrity.state}). Reinstall the CLI before starting it.`);
1454
1730
  }
1455
1731
 
1456
1732
  const args = [RUNTIME_BUNDLE, "run"];
@@ -1488,7 +1764,7 @@ function helpCommand() {
1488
1764
  ` auth login|logout|status Authentication management\n` +
1489
1765
  ` context --request <request> Bounded context (ladder first; --deep for the full pack)\n` +
1490
1766
  ` search --query <text> Bound-project Brain search (use --all-projects intentionally)\n` +
1491
- ` update Submit structured JSON on stdin\n` +
1767
+ ` update [--session <native-id>] Submit governed project JSON and verify the native Codex transcript when identified\n` +
1492
1768
  ` run "<task>" | --task <id> Start a Mission on the shared Runtime\n` +
1493
1769
  ` run status|stop|resume <id> Control one Runtime Mission\n` +
1494
1770
  ` decide <mission> <gate> <key> Answer an existing Mission gate\n` +
@@ -1496,9 +1772,9 @@ function helpCommand() {
1496
1772
  ` install --platform <name> Install the assistant skill\n` +
1497
1773
  ` uninstall --platform <name> Remove the assistant skill\n` +
1498
1774
  ` 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` +
1775
+ ` sync codex --profile <profile> Read-only source/server preview; add --apply and optionally --watch\n` +
1776
+ ` sync docs --profile <profile> Preview repository docs; add --apply and optionally --watch\n` +
1777
+ ` sync managed --profile <profile> Preview both capture paths; add --apply to synchronize\n` +
1502
1778
  ` sync service install|status Manage OS background capture for one profile/project\n` +
1503
1779
  ` hook claude Receive a Claude Code lifecycle hook event\n` +
1504
1780
  ` config endpoint <url> --profile <profile> Configure an isolated named profile\n` +