@reasontrail/cli 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { createHash } from "node:crypto";
3
+ import { createHash, randomUUID } from "node:crypto";
4
4
  import { chmod, copyFile, mkdir, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
5
5
  import { homedir, hostname } from "node:os";
6
6
  import { deviceLogin } from "./device-login.mjs";
@@ -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
@@ -24,6 +25,7 @@ const PACKAGE_ROOT = resolve(new URL("..", import.meta.url).pathname);
24
25
  const PACKAGE_META = JSON.parse(await readFile(join(PACKAGE_ROOT, "package.json"), "utf8"));
25
26
  const VERSION = PACKAGE_META.version;
26
27
  const PROFILE_NAMES = new Set(["development", "production"]);
28
+ const SERVICE_NAME_PREFIX = "reasontrail-sync";
27
29
 
28
30
  function profileDir(profile) {
29
31
  return join(CONFIG_DIR, "profiles", profile);
@@ -367,6 +369,196 @@ function output(value) {
367
369
  stdout.write(`${JSON.stringify(value, null, 2)}\n`);
368
370
  }
369
371
 
372
+ function serviceSafeName(value) {
373
+ return String(value || "")
374
+ .toLowerCase()
375
+ .replace(/[^a-z0-9_.-]+/g, "-")
376
+ .replace(/^-+|-+$/g, "")
377
+ .slice(0, 80) || "default";
378
+ }
379
+
380
+ function plistEscape(value) {
381
+ return String(value)
382
+ .replaceAll("&", "&")
383
+ .replaceAll("<", "&lt;")
384
+ .replaceAll(">", "&gt;")
385
+ .replaceAll('"', "&quot;")
386
+ .replaceAll("'", "&apos;");
387
+ }
388
+
389
+ function systemdQuote(value) {
390
+ return `"${String(value).replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
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
+
370
562
  function options(args) {
371
563
  const values = { _: [] };
372
564
  for (let i = 0; i < args.length; i += 1) {
@@ -436,7 +628,10 @@ async function getStatus(target) {
436
628
  const codexMapped = codexSessions.filter((s) => s.mapped);
437
629
  const codexPending = codexMapped.filter((s) => {
438
630
  const prev = codexSyncState.sessions?.[s.threadId];
439
- 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));
440
635
  }).length;
441
636
  const codexMcp = await codexMcpConfigured(target.profile);
442
637
  const codexSkill = await (async () => {
@@ -444,6 +639,7 @@ async function getStatus(target) {
444
639
  return (await stat(join(defaultCodexHome(), "skills", "reasontrail", "SKILL.md"))).isFile();
445
640
  } catch { return false; }
446
641
  })();
642
+ const managedCapture = await inspectManagedCaptureService(target, projectBound ? binding?.projectSlug : null);
447
643
 
448
644
  return {
449
645
  available: tools.length > 0,
@@ -457,13 +653,14 @@ async function getStatus(target) {
457
653
  conversation_connector: projectBound
458
654
  ? (hooksInstalled ? "Claude Code Hooks; Codex Local Session Sync" : "Codex Local Session Sync")
459
655
  : "none",
460
- automatic_transcript_sync: "disabled_explicit_sync_only",
656
+ automatic_transcript_sync: managedCapture.active ? "active_managed_capture" : "inactive",
657
+ managed_capture_service: managedCapture,
461
658
  codex_desktop: {
462
659
  brain_access: codexMcp ? "connected" : "not_configured",
463
660
  workspace: root,
464
661
  repository: normalizedRepositoryUrl(gitRemote(root)),
465
662
  project: projectBound ? binding.projectSlug : null,
466
- capture_mechanism: "explicit `sync codex --apply` only",
663
+ capture_mechanism: managedCapture.active ? "managed capture service" : "inactive; explicit sync remains available",
467
664
  session_store: join(defaultCodexHome(), "sessions"),
468
665
  mcp_configured: codexMcp,
469
666
  skill_installed: codexSkill,
@@ -507,10 +704,15 @@ async function runCommand(argv) {
507
704
  const { binding } = await bindingFor(target);
508
705
  const request = opts.task ? undefined : opts._.join(" ").trim();
509
706
  if (!opts.task && !request) throw new CliError('Usage: reasontrail run "<task>" | reasontrail run --task <task-id>', 2);
707
+ const requestId = opts["request-id"] ? String(opts["request-id"]) : randomUUID();
510
708
  return output(await runtimeTool(target, "runtime_start", {
511
709
  ...(opts.task ? { taskId: String(opts.task) } : { request }),
512
710
  ...(opts.title ? { title: String(opts.title) } : {}),
513
711
  ...(opts.workspace ? { workspaceId: String(opts.workspace) } : {}),
712
+ ...(opts.task ? {
713
+ workerKey: String(opts.worker || "codex-cli"),
714
+ idempotencyKey: `work-cli:${String(opts.task)}:${requestId}`,
715
+ } : {}),
514
716
  ...(opts.project || binding?.projectSlug ? { projectSlug: String(opts.project || binding.projectSlug) } : {}),
515
717
  }));
516
718
  }
@@ -627,17 +829,19 @@ async function updateCommand(argv) {
627
829
  const target = await resolveTarget(argv);
628
830
  const opts = target.opts;
629
831
  const piped = await stdinJson();
630
- const { root, binding } = await bindingFor(target);
832
+ const { binding } = await bindingFor(target);
631
833
  const { client, tools } = await connected(target);
632
834
  if (!hasTool(tools, "update_reasontrail")) throw new CliError("The authenticated ReasonTrail connection does not expose update_reasontrail.", 3);
633
- 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
+ }
634
839
  const labeledFindings = [
635
840
  ...(piped.findings || []),
636
841
  ...(piped.discoveries || []).map((value) => `[discovery] ${value}`),
637
842
  ...(piped.implementationFacts || piped.implementation_facts || []).map((value) => `[implementation fact] ${value}`),
638
843
  ...(piped.rejectedApproaches || piped.rejected_approaches || []).map((value) => `[rejected approach] ${value}`),
639
844
  ...(piped.constraints || []).map((value) => `[constraint] ${value}`),
640
- ...(piped.ideas || []).map((value) => `[idea] ${value}`),
641
845
  ...(piped.openQuestions || piped.open_questions || []).map((value) => `[open question] ${value}`),
642
846
  ...(piped.taskOutcomes || piped.task_outcomes || []).map((value) => `[task outcome] ${value}`),
643
847
  ];
@@ -646,11 +850,86 @@ async function updateCommand(argv) {
646
850
  ...(labeledFindings.length ? { findings: labeledFindings } : {}),
647
851
  ...(opts.summary ? { taskSummary: opts.summary } : {}),
648
852
  ...(opts.remaining_work ? { remainingWork: opts.remaining_work } : {}),
649
- clientConversationId: piped.clientConversationId || opts.conversation_id || `reasontrail-cli:${identity}`,
853
+ turns: [],
650
854
  ...(opts.project || binding?.projectSlug ? { projectSlug: opts.project || binding.projectSlug } : {}),
651
855
  };
652
- for (const key of ["discoveries", "implementationFacts", "implementation_facts", "rejectedApproaches", "rejected_approaches", "constraints", "ideas", "openQuestions", "open_questions", "taskOutcomes", "task_outcomes"]) delete args[key];
653
- 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
+ });
654
933
  }
655
934
 
656
935
  async function bindCommand(argv) {
@@ -696,9 +975,23 @@ async function bindCommand(argv) {
696
975
  cfg.bindings ||= {};
697
976
  cfg.bindings[root] = { projectSlug: slug, projectId: opts.project_id || null, repositoryId: repository.repositoryId || null, repositoryUrl: repository.url, boundAt: new Date().toISOString() };
698
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
+ }
699
992
  const runs = hasTool(tools, "runtime_list_runs") ? await client.call("runtime_list_runs", {}) : [];
700
993
  const runtime = Array.isArray(runs) ? runs.find((run) => run?.project?.slug === slug && run?.workspace?.runtime) : null;
701
- 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" });
702
995
  }
703
996
 
704
997
  async function authCommand(argv) {
@@ -840,8 +1133,11 @@ async function doctorCommand(argv) {
840
1133
 
841
1134
  async function syncCommand(argv) {
842
1135
  const sub = argv[0];
843
- if (!["codex", "docs"].includes(sub)) {
844
- throw new CliError("Usage: reasontrail sync codex|docs --profile <profile> [--apply] [--watch] [--interval <seconds>] [--since <time>] [--project <slug>] [--session <id>]", 2);
1136
+ if (!["codex", "docs", "managed", "service"].includes(sub)) {
1137
+ throw new CliError("Usage: reasontrail sync codex|docs|managed|service --profile <profile> [--apply] [--watch] [--interval <seconds>] [--project <slug>]", 2);
1138
+ }
1139
+ if (sub === "service") {
1140
+ return syncServiceCommand(argv.slice(1));
845
1141
  }
846
1142
  const target = await resolveTarget(argv.slice(1), { confirm: false });
847
1143
  const opts = target.opts;
@@ -851,18 +1147,56 @@ async function syncCommand(argv) {
851
1147
  if (watch && !apply) throw new CliError("Watch mode writes synchronized data. Add `--apply` when you intentionally want automatic upload.", 2);
852
1148
  const intervalSeconds = Math.max(10, Math.min(3600, Number(opts.interval || 60)));
853
1149
  if (!Number.isFinite(intervalSeconds)) throw new CliError("Sync interval must be a number of seconds.", 2);
854
- let client = null;
855
- let tools = [];
1150
+ let client;
1151
+ let tools;
856
1152
  if (apply) {
857
1153
  await confirmProduction(opts);
858
- ({ client, tools } = await connected(target));
859
1154
  }
1155
+ ({ client, tools } = await connected(target));
1156
+ const { binding } = await bindingFor(target);
1157
+ const project = opts.project || binding?.projectSlug || null;
860
1158
  const runOnce = async () => {
861
1159
  if (sub === "docs") {
862
- if (!apply) throw new CliError("Repository docs sync writes versioned Markdown into ReasonTrail. Add `--apply` when you intentionally want to sync docs.", 2);
863
- if (!hasTool(tools, "sync_docs")) throw new CliError("The authenticated ReasonTrail connection does not expose sync_docs. Update the CLI/server pair.", 3);
864
- const { binding } = await bindingFor(target);
865
- 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" });
1163
+ }
1164
+ if (sub === "managed") {
1165
+ const codex = await syncCodex(client, tools, target.paths.dir, target.cfg, {
1166
+ dryRun: !apply,
1167
+ since: opts.since || null,
1168
+ project,
1169
+ session: opts.session || null,
1170
+ force: Boolean(opts.force),
1171
+ });
1172
+ let docs = null;
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
+ }
1185
+ }
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;
866
1200
  }
867
1201
  return syncCodex(client, tools, target.paths.dir, target.cfg, {
868
1202
  dryRun: !apply,
@@ -872,13 +1206,103 @@ async function syncCommand(argv) {
872
1206
  force: Boolean(opts.force),
873
1207
  });
874
1208
  };
875
- 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
+ }
876
1228
  for (;;) {
877
- 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
+ }
878
1243
  await new Promise((resolveSleep) => setTimeout(resolveSleep, intervalSeconds * 1000));
879
1244
  }
880
1245
  }
881
1246
 
1247
+ async function syncServiceCommand(argv) {
1248
+ const action = argv[0];
1249
+ if (!["install", "status", "start", "stop", "uninstall"].includes(action)) {
1250
+ throw new CliError("Usage: reasontrail sync service install|status|start|stop|uninstall --profile <profile> [--project <slug>] [--interval <seconds>] [--system]", 2);
1251
+ }
1252
+ const target = await resolveTarget(argv.slice(1), { confirm: false });
1253
+ const opts = target.opts;
1254
+ const { root, binding } = await bindingFor(target);
1255
+ const project = opts.project || binding?.projectSlug;
1256
+ const intervalSeconds = Math.max(10, Math.min(3600, Number(opts.interval || 60)));
1257
+ if (!Number.isFinite(intervalSeconds)) throw new CliError("Sync interval must be a number of seconds.", 2);
1258
+ const serviceName = managedServiceIdentity(target, project).service;
1259
+ if (target.profile === "production" && action !== "status") await confirmProduction(opts);
1260
+
1261
+ if (action === "install") {
1262
+ if (!project) throw new CliError("Install requires a project. Bind this repository first with `reasontrail . --project <slug>` or pass `--project <slug>`.", 2);
1263
+ return output(await installManagedCaptureService(target, root, project, intervalSeconds, { system: opts.system === true }));
1264
+ }
1265
+
1266
+ if (action === "status") return output(await inspectManagedCaptureService(target, project, { system: opts.system === true }));
1267
+
1268
+ if (process.platform === "linux") {
1269
+ const system = (await resolveSystemdScope(managedServiceIdentity(target, project), opts.system === true)) === "system";
1270
+ const ctl = system ? ["systemctl"] : ["systemctl", "--user"];
1271
+ const verb = action === "uninstall" ? "disable" : action;
1272
+ if (action === "uninstall") {
1273
+ const result = spawnSync(ctl[0], [...ctl.slice(1), "disable", "--now", `${serviceName}.service`], { encoding: "utf8" });
1274
+ if (result.status !== 0) throw new CliError(result.stderr.trim() || `Could not disable ${serviceName}.service`, 3);
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
+ });
1281
+ }
1282
+ const result = spawnSync(ctl[0], [...ctl.slice(1), verb, `${serviceName}.service`], { encoding: "utf8" });
1283
+ if (result.status !== 0) throw new CliError(result.stderr.trim() || `systemctl ${verb} failed`, 3);
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() });
1288
+ }
1289
+ if (process.platform === "darwin") {
1290
+ const label = `ai.reasontrail.${serviceName}`;
1291
+ const gui = `gui/${process.getuid?.() ?? "$(id -u)"}`;
1292
+ const command = action === "status" ? ["print", `${gui}/${label}`]
1293
+ : action === "start" ? ["kickstart", "-k", `${gui}/${label}`]
1294
+ : action === "stop" ? ["bootout", `${gui}/${label}`]
1295
+ : ["bootout", `${gui}/${label}`];
1296
+ const result = spawnSync("launchctl", command, { encoding: "utf8" });
1297
+ if (result.status !== 0) throw new CliError(result.stderr.trim() || `launchctl ${action} failed`, 3);
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() });
1302
+ }
1303
+ throw new CliError(`Managed sync service ${action} is not implemented for ${process.platform}.`, 2);
1304
+ }
1305
+
882
1306
  async function inspectClaudeMcp(profile) {
883
1307
  // Assistant-wide MCP diagnostics can probe registrations for other profiles.
884
1308
  // Keep doctor restricted to its own authenticated connection above.
@@ -944,7 +1368,7 @@ async function setupCommand(argv) {
944
1368
  hooks = await installClaudeHooks(target.profile);
945
1369
  await pruneClaudeRetryBacklog(target.profile);
946
1370
  }
947
- 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.` });
948
1372
  }
949
1373
 
950
1374
  async function installClaudeHooks(profile) {
@@ -1168,6 +1592,25 @@ async function claudeHookCommand(argv) {
1168
1592
  * blast radius or a revocation. Same directory, same 0600, separate file.
1169
1593
  */
1170
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
+ }
1171
1614
 
1172
1615
  async function runtimeConfig(profile) {
1173
1616
  return readJson(profilePaths(profile).runtime, null);
@@ -1176,9 +1619,10 @@ async function runtimeConfig(profile) {
1176
1619
  function runtimeUsage() {
1177
1620
  return (
1178
1621
  `Usage: reasontrail runtime <command>\n\n` +
1179
- ` enroll --url <origin> --token <rtrt_…> [--workspace <id>=<path>]…\n` +
1622
+ ` enroll --url <origin> --token <rtrt_…> --execution-root <path> [--dependency-network disabled|public] [--workspace <id>=<path>]…\n` +
1180
1623
  ` Store this machine's enrollment\n` +
1181
- ` start [--once] Connect to ReasonTrail and take work\n` +
1624
+ ` start [--once] [--dependency-network disabled|public]\n` +
1625
+ ` Connect to ReasonTrail and take work\n` +
1182
1626
  ` status Show the stored enrollment\n` +
1183
1627
  ` logout Forget the stored enrollment\n`
1184
1628
  );
@@ -1198,7 +1642,12 @@ async function runtimeCommand(argv) {
1198
1642
  };
1199
1643
  const url = value("--url");
1200
1644
  const token = value("--token");
1201
- if (!url || !token) throw new CliError("Both --url and --token are required.\n\n" + runtimeUsage(), 2);
1645
+ const executionRoot = value("--execution-root");
1646
+ const dependencyNetwork = value("--dependency-network") || "disabled";
1647
+ if (!url || !token || !executionRoot) throw new CliError("--url, --token and --execution-root are required.\n\n" + runtimeUsage(), 2);
1648
+ if (!["disabled", "public"].includes(dependencyNetwork)) {
1649
+ throw new CliError("--dependency-network must be 'disabled' or 'public'.", 2);
1650
+ }
1202
1651
  if (!token.startsWith("rtrt_")) {
1203
1652
  throw new CliError("That does not look like a runtime credential (expected an rtrt_ prefix).", 2);
1204
1653
  }
@@ -1220,10 +1669,18 @@ async function runtimeCommand(argv) {
1220
1669
  // 0600, in a 0700 directory. The credential is the whole point of the file.
1221
1670
  if (target.profile === "production" && origin !== "https://app.reasontrail.ai") throw new CliError("Production runtime enrollment must use https://app.reasontrail.ai.", 2);
1222
1671
  if (target.profile === "development" && !["localhost", "127.0.0.1", "[::1]"].includes(new URL(origin).hostname)) throw new CliError("Development runtime enrollment accepts only a loopback origin.", 2);
1223
- await saveJson(runtimeFile, { origin, token, workspaces }, 0o600);
1672
+ await saveJson(runtimeFile, {
1673
+ origin,
1674
+ token,
1675
+ workspaces,
1676
+ executionRoot: resolve(executionRoot),
1677
+ dependencyNetwork,
1678
+ }, 0o600);
1224
1679
  stdout.write(
1225
1680
  `Enrolled against ${origin}.\n` +
1226
1681
  `${workspaces.length} workspace${workspaces.length === 1 ? "" : "s"} configured.\n` +
1682
+ `Disposable execution root: ${resolve(executionRoot)}\n` +
1683
+ `Dependency network: ${dependencyNetwork}\n` +
1227
1684
  `Stored in ${runtimeFile} (owner-only).\n\n` +
1228
1685
  `Start it with: reasontrail runtime start --profile ${target.profile}\n`
1229
1686
  );
@@ -1233,6 +1690,7 @@ async function runtimeCommand(argv) {
1233
1690
  if (sub === "status") {
1234
1691
  const cfg = await runtimeConfig(target.profile);
1235
1692
  if (!cfg) return stdout.write("No runtime enrollment on this machine.\nRun `reasontrail runtime enroll …`.\n");
1693
+ const bundleIntegrity = await runtimeBundleIntegrity();
1236
1694
  // The PREFIX only. The credential is never redisplayed after enrollment.
1237
1695
  const prefix = String(cfg.token || "").slice(0, 11);
1238
1696
  stdout.write(
@@ -1240,7 +1698,10 @@ async function runtimeCommand(argv) {
1240
1698
  ` Instance ${cfg.origin}\n` +
1241
1699
  ` Credential ${prefix}… (stored, not shown)\n` +
1242
1700
  ` Workspaces ${cfg.workspaces?.length ? cfg.workspaces.join(", ") : "none — map them in ReasonTrail after connecting"}\n` +
1243
- ` Bundle ${RUNTIME_BUNDLE}\n\n` +
1701
+ ` Exec root ${cfg.executionRoot || "not configured — provider execution disabled"}\n` +
1702
+ ` Dep network ${cfg.dependencyNetwork || "disabled"}\n` +
1703
+ ` Bundle ${RUNTIME_BUNDLE}\n` +
1704
+ ` Integrity ${bundleIntegrity.state}\n\n` +
1244
1705
  `Live status — protocol, workers, readiness — is shown by ReasonTrail itself,\n` +
1245
1706
  `which is the authority on all three. This command reports local setup only.\n`
1246
1707
  );
@@ -1260,14 +1721,23 @@ async function runtimeCommand(argv) {
1260
1721
  }
1261
1722
  // Re-prove a possibly copied enrollment before handing its token to a child.
1262
1723
  validateEndpoint(cfg.origin, target.profile);
1263
- try {
1264
- await stat(RUNTIME_BUNDLE);
1265
- } catch {
1266
- 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.`);
1267
1730
  }
1268
1731
 
1269
1732
  const args = [RUNTIME_BUNDLE, "run"];
1270
1733
  for (const workspace of cfg.workspaces ?? []) args.push("--workspace", workspace);
1734
+ if (cfg.executionRoot) args.push("--execution-root", cfg.executionRoot);
1735
+ const networkFlagIndex = argv.indexOf("--dependency-network");
1736
+ const dependencyNetwork = networkFlagIndex >= 0 ? argv[networkFlagIndex + 1] : (cfg.dependencyNetwork || "disabled");
1737
+ if (!["disabled", "public"].includes(dependencyNetwork)) {
1738
+ throw new CliError("--dependency-network must be 'disabled' or 'public'.", 2);
1739
+ }
1740
+ args.push("--dependency-network", dependencyNetwork);
1271
1741
  if (argv.includes("--once")) args.push("--once");
1272
1742
 
1273
1743
  // The credential is passed through the environment of the child and never
@@ -1294,7 +1764,7 @@ function helpCommand() {
1294
1764
  ` auth login|logout|status Authentication management\n` +
1295
1765
  ` context --request <request> Bounded context (ladder first; --deep for the full pack)\n` +
1296
1766
  ` search --query <text> Bound-project Brain search (use --all-projects intentionally)\n` +
1297
- ` 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` +
1298
1768
  ` run "<task>" | --task <id> Start a Mission on the shared Runtime\n` +
1299
1769
  ` run status|stop|resume <id> Control one Runtime Mission\n` +
1300
1770
  ` decide <mission> <gate> <key> Answer an existing Mission gate\n` +
@@ -1302,8 +1772,10 @@ function helpCommand() {
1302
1772
  ` install --platform <name> Install the assistant skill\n` +
1303
1773
  ` uninstall --platform <name> Remove the assistant skill\n` +
1304
1774
  ` setup --profile <profile> Configure detected assistants (hooks require --enable-hooks in development)\n` +
1305
- ` sync codex --profile <profile> Preview local Codex sessions; add --apply and optionally --watch\n` +
1306
- ` sync docs --profile <profile> Synchronize repository Markdown docs; requires --apply; optionally --watch\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` +
1778
+ ` sync service install|status Manage OS background capture for one profile/project\n` +
1307
1779
  ` hook claude Receive a Claude Code lifecycle hook event\n` +
1308
1780
  ` config endpoint <url> --profile <profile> Configure an isolated named profile\n` +
1309
1781
  ` runtime enroll|start|status|logout ReasonTrail Runtime on this machine\n` +