@reasontrail/cli 0.1.0

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 ADDED
@@ -0,0 +1,1361 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { createHash } from "node:crypto";
4
+ import { chmod, copyFile, mkdir, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
5
+ import { homedir, hostname } from "node:os";
6
+ import { deviceLogin } from "./device-login.mjs";
7
+ import { dirname, join, resolve } from "node:path";
8
+ import { spawnSync } from "node:child_process";
9
+ import { stdin, stdout, stderr } from "node:process";
10
+ import {
11
+ defaultCodexHome,
12
+ discoverAndMapCodexSessions,
13
+ readSyncState,
14
+ syncCodex,
15
+ } from "./codex-sync.mjs";
16
+
17
+ const DEFAULT_ENDPOINT = "https://app.reasontrail.ai/api/mcp";
18
+ // The port `next dev` binds by default. A development instance on another
19
+ // port is set with `reasontrail config endpoint`, not by editing this.
20
+ const DEVELOPMENT_ENDPOINT = "http://127.0.0.1:3000/api/mcp";
21
+ const CONFIG_DIR = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "reasontrail");
22
+ const KEYCHAIN_SERVICE = "ai.reasontrail.cli";
23
+ const PACKAGE_ROOT = resolve(new URL("..", import.meta.url).pathname);
24
+ const PACKAGE_META = JSON.parse(await readFile(join(PACKAGE_ROOT, "package.json"), "utf8"));
25
+ const VERSION = PACKAGE_META.version;
26
+ const PROFILE_NAMES = new Set(["development", "production"]);
27
+
28
+ function profileDir(profile) {
29
+ return join(CONFIG_DIR, "profiles", profile);
30
+ }
31
+
32
+ function profilePaths(profile) {
33
+ const dir = profileDir(profile);
34
+ return {
35
+ dir,
36
+ config: join(dir, "config.json"),
37
+ credential: join(dir, "credentials.json"),
38
+ connectors: join(dir, "connectors"),
39
+ runtime: join(dir, "runtime.json"),
40
+ };
41
+ }
42
+
43
+ class CliError extends Error {
44
+ constructor(message, exitCode = 1, details = undefined) {
45
+ super(message);
46
+ this.exitCode = exitCode;
47
+ this.details = details;
48
+ }
49
+ }
50
+
51
+ async function readJson(path, fallback) {
52
+ try {
53
+ return JSON.parse(await readFile(path, "utf8"));
54
+ } catch (error) {
55
+ if (error?.code === "ENOENT") return fallback;
56
+ throw new CliError(`Could not read ${path}: ${error.message}`);
57
+ }
58
+ }
59
+
60
+ async function saveJson(path, value, mode = 0o600) {
61
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
62
+ await writeFile(path, `${JSON.stringify(value, null, 2)}\n`, { mode });
63
+ await chmod(path, mode);
64
+ }
65
+
66
+ function commandExists(name) {
67
+ return spawnSync("sh", ["-c", `command -v ${name}`], { stdio: "ignore" }).status === 0;
68
+ }
69
+
70
+ async function loadCredential(profile) {
71
+ const paths = profilePaths(profile);
72
+ if (process.platform === "darwin" && commandExists("security")) {
73
+ const found = spawnSync("security", ["find-generic-password", "-s", KEYCHAIN_SERVICE, "-a", profile, "-w"], { encoding: "utf8" });
74
+ if (found.status === 0 && found.stdout.trim()) return { token: found.stdout.trim(), source: "macOS Keychain" };
75
+ }
76
+ if (process.platform === "linux" && commandExists("secret-tool")) {
77
+ const found = spawnSync("secret-tool", ["lookup", "service", KEYCHAIN_SERVICE, "account", profile], { encoding: "utf8" });
78
+ if (found.status === 0 && found.stdout.trim()) return { token: found.stdout.trim(), source: "Secret Service" };
79
+ }
80
+ const stored = await readJson(paths.credential, null);
81
+ if (typeof stored?.token === "string" && stored.token) return { token: stored.token, source: paths.credential };
82
+ return null;
83
+ }
84
+
85
+ async function storeCredential(profile, token) {
86
+ const paths = profilePaths(profile);
87
+ if (!token.startsWith("rtmcp_")) throw new CliError("That is not a ReasonTrail MCP access token.", 2);
88
+ if (process.platform === "darwin" && commandExists("security")) {
89
+ const stored = spawnSync("security", ["add-generic-password", "-U", "-s", KEYCHAIN_SERVICE, "-a", profile, "-w", token], { encoding: "utf8" });
90
+ if (stored.status !== 0) throw new CliError(stored.stderr.trim() || "Could not store the credential in macOS Keychain.");
91
+ return "macOS Keychain";
92
+ }
93
+ if (process.platform === "linux" && commandExists("secret-tool")) {
94
+ const stored = spawnSync("secret-tool", ["store", "--label", `ReasonTrail CLI (${profile})`, "service", KEYCHAIN_SERVICE, "account", profile], { input: token, encoding: "utf8" });
95
+ if (stored.status !== 0) throw new CliError(stored.stderr.trim() || "Could not store the credential in Secret Service.");
96
+ return "Secret Service";
97
+ }
98
+ await saveJson(paths.credential, { token });
99
+ return paths.credential;
100
+ }
101
+
102
+ async function removeCredential(profile) {
103
+ const paths = profilePaths(profile);
104
+ const removed = [];
105
+ if (process.platform === "darwin" && commandExists("security")) {
106
+ const result = spawnSync("security", ["delete-generic-password", "-s", KEYCHAIN_SERVICE, "-a", profile], { encoding: "utf8" });
107
+ if (result.status === 0) removed.push("macOS Keychain");
108
+ }
109
+ if (process.platform === "linux" && commandExists("secret-tool")) {
110
+ const result = spawnSync("secret-tool", ["clear", "service", KEYCHAIN_SERVICE, "account", profile], { encoding: "utf8" });
111
+ if (result.status === 0) removed.push("Secret Service");
112
+ }
113
+ try {
114
+ await rm(paths.credential);
115
+ removed.push(paths.credential);
116
+ } catch (error) {
117
+ if (error?.code !== "ENOENT") throw error;
118
+ }
119
+ return removed;
120
+ }
121
+
122
+ async function promptToken() {
123
+ if (!stdin.isTTY) return (await readStdin()).trim();
124
+ return readTtyLine("ReasonTrail MCP access token: ", true);
125
+ }
126
+
127
+ function readTtyLine(prompt, hidden = false) {
128
+ stdout.write(prompt);
129
+ return new Promise((resolveLine, rejectLine) => {
130
+ let value = "";
131
+ const finish = (error = null) => {
132
+ stdin.off("data", onData);
133
+ stdin.setRawMode?.(false);
134
+ stdin.pause();
135
+ stdout.write("\n");
136
+ if (error) rejectLine(error);
137
+ else resolveLine(value);
138
+ };
139
+ const onData = (chunk) => {
140
+ for (const char of chunk.toString()) {
141
+ if (char === "\r" || char === "\n") return finish();
142
+ if (char === "\u0003") return finish(new CliError("Cancelled.", 130));
143
+ if (char === "\u007f") {
144
+ if (value) value = value.slice(0, -1);
145
+ } else {
146
+ value += char;
147
+ if (!hidden) stdout.write(char);
148
+ }
149
+ }
150
+ };
151
+ stdin.setRawMode?.(true);
152
+ stdin.resume();
153
+ stdin.on("data", onData);
154
+ });
155
+ }
156
+
157
+ async function repositoryRoot(cwd = process.cwd()) {
158
+ const git = spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf8" });
159
+ const candidate = git.status === 0 ? git.stdout.trim() : cwd;
160
+ try {
161
+ return await realpath(resolve(candidate));
162
+ } catch {
163
+ return resolve(candidate);
164
+ }
165
+ }
166
+
167
+ function gitRemote(cwd = process.cwd()) {
168
+ const result = spawnSync("git", ["remote", "get-url", "origin"], { cwd, encoding: "utf8" });
169
+ return result.status === 0 ? result.stdout.trim() : null;
170
+ }
171
+
172
+ function gitHead(cwd = process.cwd()) {
173
+ const result = spawnSync("git", ["rev-parse", "HEAD"], { cwd, encoding: "utf8" });
174
+ return result.status === 0 ? result.stdout.trim() : null;
175
+ }
176
+
177
+ function commitsAhead(cwd, indexedRevision) {
178
+ if (!indexedRevision) return null;
179
+ const result = spawnSync("git", ["rev-list", "--count", `${indexedRevision}..HEAD`], { cwd, encoding: "utf8" });
180
+ return result.status === 0 ? Number(result.stdout.trim()) : null;
181
+ }
182
+
183
+ async function repositoryFreshness(client, tools, binding, root) {
184
+ if (!binding?.projectSlug || !hasTool(tools, "get_repository_index_status")) return null;
185
+ const status = await client.call("get_repository_index_status", { projectSlug: binding.projectSlug });
186
+ const repositoryHead = gitHead(root);
187
+ const indexedRevision = status?.selectedRevision?.commitSha || status?.indexedRevision || null;
188
+ const staleByCommits = repositoryHead && indexedRevision && repositoryHead !== indexedRevision ? commitsAhead(root, indexedRevision) : 0;
189
+ const graphState = !repositoryHead || !indexedRevision
190
+ ? String(status?.state || "unknown").toLowerCase()
191
+ : repositoryHead === indexedRevision
192
+ ? "current"
193
+ : staleByCommits === null ? "stale" : `stale by ${staleByCommits} commit${staleByCommits === 1 ? "" : "s"}`;
194
+ return { repository_head: repositoryHead, indexed_revision: indexedRevision, graph_state: graphState, stale_by_commits: staleByCommits };
195
+ }
196
+
197
+ function normalizedRepositoryUrl(value) {
198
+ if (!value) return null;
199
+ return value
200
+ .trim()
201
+ .replace(/^git@([^:]+):/, "https://$1/")
202
+ .replace(/^ssh:\/\/git@/, "https://")
203
+ .replace(/\.git\/?$/, "")
204
+ .replace(/\/$/, "")
205
+ .toLowerCase();
206
+ }
207
+
208
+ async function config(profile, { allowMissing = false } = {}) {
209
+ const path = profilePaths(profile).config;
210
+ const cfg = await readJson(path, null);
211
+ if (!cfg && !allowMissing) {
212
+ throw new CliError(`Profile '${profile}' is not configured. Run \`reasontrail config endpoint <url> --profile ${profile}\`. Legacy unprofiled configuration is not used.`, 2, { kind: "configuration_missing" });
213
+ }
214
+ return cfg || { environment: profile, endpoint: profile === "development" ? DEVELOPMENT_ENDPOINT : DEFAULT_ENDPOINT, bindings: {}, hooksEnabled: false };
215
+ }
216
+
217
+ function validateEndpoint(endpoint, environment) {
218
+ let url;
219
+ try { url = new URL(endpoint); } catch { throw new CliError("The configured ReasonTrail endpoint is not a valid URL.", 2); }
220
+ if (!["http:", "https:"].includes(url.protocol)) throw new CliError("ReasonTrail endpoints must use HTTP or HTTPS.", 2);
221
+ if (url.username || url.password) throw new CliError("Credential-bearing endpoint URLs are prohibited. Store credentials with `auth login`.", 2);
222
+ if (url.search || url.hash) throw new CliError("ReasonTrail endpoint URLs may not contain query parameters or fragments.", 2);
223
+ if (environment === "production" && (url.protocol !== "https:" || url.origin !== "https://app.reasontrail.ai")) {
224
+ throw new CliError("Production ReasonTrail must use https://app.reasontrail.ai.", 2);
225
+ }
226
+ if (environment === "development" && !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) {
227
+ throw new CliError("The development profile accepts only loopback endpoints.", 2);
228
+ }
229
+ return url.toString();
230
+ }
231
+
232
+ function sanitizedEndpoint(endpoint) {
233
+ const url = new URL(endpoint);
234
+ url.username = "";
235
+ url.password = "";
236
+ url.search = "";
237
+ url.hash = "";
238
+ return url.toString();
239
+ }
240
+
241
+ function requiredProfile(opts) {
242
+ const profile = typeof opts.profile === "string" ? opts.profile : "";
243
+ if (!PROFILE_NAMES.has(profile)) {
244
+ throw new CliError("An explicit `--profile development` or `--profile production` is required. ReasonTrail never defaults to production.", 2, { kind: "profile_missing" });
245
+ }
246
+ return profile;
247
+ }
248
+
249
+ async function confirmProduction(opts) {
250
+ if (opts.profile !== "production") return;
251
+ if (!stdin.isTTY) {
252
+ if (opts.confirm_production !== true) {
253
+ throw new CliError("Noninteractive production access requires `--confirm-production` on this command.", 2, { kind: "production_confirmation_missing" });
254
+ }
255
+ return;
256
+ }
257
+ const answer = (await readTtyLine("Type PRODUCTION to connect: ")).trim();
258
+ if (answer !== "PRODUCTION") throw new CliError("Production connection cancelled.", 2);
259
+ }
260
+
261
+ async function resolveTarget(argv, { allowMissing = false, confirm = true } = {}) {
262
+ const opts = options(argv);
263
+ const profile = requiredProfile(opts);
264
+ const cfg = await config(profile, { allowMissing });
265
+ if (cfg.environment && cfg.environment !== profile) throw new CliError(`Profile '${profile}' contains mismatched environment '${cfg.environment}'.`, 2);
266
+ cfg.environment = profile;
267
+ cfg.endpoint = validateEndpoint(cfg.endpoint, profile);
268
+ cfg.bindings ||= {};
269
+ const endpoint = sanitizedEndpoint(cfg.endpoint);
270
+ process.stderr.write(`ReasonTrail target: profile=${profile} environment=${profile} endpoint=${endpoint}\n`);
271
+ if (confirm) await confirmProduction(opts);
272
+ return { opts, profile, cfg, endpoint, paths: profilePaths(profile) };
273
+ }
274
+
275
+ async function bindingFor(target, cwd = process.cwd()) {
276
+ const root = await repositoryRoot(cwd);
277
+ return { root, binding: target.cfg.bindings?.[root] || null, cfg: target.cfg };
278
+ }
279
+
280
+ class ReasonTrailClient {
281
+ constructor(endpoint, token) {
282
+ this.endpoint = endpoint;
283
+ this.token = token;
284
+ this.id = 0;
285
+ this.sessionId = null;
286
+ /** Set by a caller that knows which turn it is acting for; see request(). */
287
+ this.turnId = null;
288
+ }
289
+
290
+ async request(method, params = undefined, notification = false) {
291
+ const body = { jsonrpc: "2.0", method, ...(notification ? {} : { id: ++this.id }), ...(params ? { params } : {}) };
292
+ let response;
293
+ try {
294
+ response = await fetch(this.endpoint, {
295
+ method: "POST",
296
+ redirect: "manual",
297
+ headers: {
298
+ "Content-Type": "application/json",
299
+ Accept: "application/json, text/event-stream",
300
+ ...(this.token ? { Authorization: `Bearer ${this.token}` } : {}),
301
+ ...(this.sessionId ? { "Mcp-Session-Id": this.sessionId } : {}),
302
+ // MCP has no turn concept, so the client is the only thing that knows
303
+ // which conversation turn a call belongs to. Sent as a header rather
304
+ // than a tool argument so it applies to every tool without widening
305
+ // any tool's schema, and so a tool can never read it as input.
306
+ ...(this.turnId ? { "X-ReasonTrail-Turn-Id": this.turnId } : {}),
307
+ },
308
+ body: JSON.stringify(body),
309
+ });
310
+ } catch (error) {
311
+ throw new CliError(`ReasonTrail backend request failed: ${error.message}`, 3, { kind: "transport" });
312
+ }
313
+ if (response.status >= 300 && response.status < 400) {
314
+ throw new CliError(`ReasonTrail refused backend redirect (HTTP ${response.status}) to protect the Authorization header.`, 3, { kind: "transport", status: response.status });
315
+ }
316
+ const session = response.headers.get("mcp-session-id");
317
+ if (session) this.sessionId = session;
318
+ const text = await response.text();
319
+ let payload = null;
320
+ if (text) {
321
+ try { payload = JSON.parse(text); } catch { throw new CliError(`ReasonTrail returned HTTP ${response.status} with a non-JSON response.`, 3); }
322
+ }
323
+ if (!response.ok) {
324
+ const message = payload?.error?.message || `HTTP ${response.status}`;
325
+ throw new CliError(`ReasonTrail returned ${response.status}: ${message}`, response.status === 401 || response.status === 403 ? 4 : 3, { status: response.status, payload });
326
+ }
327
+ if (payload?.error) throw new CliError(`ReasonTrail RPC error ${payload.error.code}: ${payload.error.message}`, 3, { payload });
328
+ return payload?.result ?? null;
329
+ }
330
+
331
+ async initialize() {
332
+ const result = await this.request("initialize", {
333
+ protocolVersion: "2025-06-18",
334
+ capabilities: {},
335
+ clientInfo: { name: "reasontrail-cli", version: VERSION },
336
+ });
337
+ await this.request("notifications/initialized", undefined, true);
338
+ return result;
339
+ }
340
+
341
+ async tools() {
342
+ return (await this.request("tools/list"))?.tools || [];
343
+ }
344
+
345
+ async call(name, args = {}) {
346
+ const result = await this.request("tools/call", { name, arguments: args });
347
+ if (result?.isError) throw new CliError(result.content?.map((item) => item.text).filter(Boolean).join("\n") || `${name} failed.`, 3);
348
+ const text = result?.content?.find((item) => item.type === "text")?.text;
349
+ if (typeof text !== "string") return result;
350
+ try { return JSON.parse(text); } catch { return text; }
351
+ }
352
+ }
353
+
354
+ async function connected(target) {
355
+ const credential = await loadCredential(target.profile);
356
+ const client = new ReasonTrailClient(target.endpoint, credential?.token || null);
357
+ const server = await client.initialize();
358
+ const tools = await client.tools();
359
+ return { client, server, tools, credentialSource: credential?.source || null };
360
+ }
361
+
362
+ function hasTool(tools, name) {
363
+ return tools.some((tool) => tool.name === name);
364
+ }
365
+
366
+ function output(value) {
367
+ stdout.write(`${JSON.stringify(value, null, 2)}\n`);
368
+ }
369
+
370
+ function options(args) {
371
+ const values = { _: [] };
372
+ for (let i = 0; i < args.length; i += 1) {
373
+ const arg = args[i];
374
+ if (!arg.startsWith("--")) values._.push(arg);
375
+ else {
376
+ const key = arg.slice(2).replaceAll("-", "_");
377
+ const next = args[i + 1];
378
+ if (next && !next.startsWith("--")) { values[key] = next; i += 1; }
379
+ else values[key] = true;
380
+ }
381
+ }
382
+ return values;
383
+ }
384
+
385
+ async function getStatus(target) {
386
+ const { root, binding } = await bindingFor(target);
387
+ const credential = await loadCredential(target.profile);
388
+ const client = new ReasonTrailClient(target.endpoint, credential?.token || null);
389
+ let server;
390
+ let tools;
391
+ try {
392
+ server = await client.initialize();
393
+ tools = await client.tools();
394
+ } catch (error) {
395
+ if (error?.details?.status === 401 || error?.details?.status === 403) {
396
+ return {
397
+ available: true,
398
+ authenticated: false,
399
+ project_bound: false,
400
+ project_id: null,
401
+ tenant_id: null,
402
+ read_available: false,
403
+ write_available: false,
404
+ transport: "cli",
405
+ profile: target.profile,
406
+ environment: target.profile,
407
+ backend_endpoint: target.endpoint,
408
+ repository_root: root,
409
+ http_status: error.details.status,
410
+ error: error.message,
411
+ };
412
+ }
413
+ throw error;
414
+ }
415
+ const readTools = ["list_projects", "get_project_context", "search_brain", "context_for_task", "build_repository_context"];
416
+ const writeTools = ["update_reasontrail", "sync_conversation_delta", "capture_note", "save_conversation", "sync_docs"];
417
+ let projectBound = false;
418
+ let bindingError = null;
419
+ let freshness = null;
420
+ if (binding?.projectSlug && hasTool(tools, "get_project_context")) {
421
+ try {
422
+ const result = await client.call("get_project_context", { projectSlug: binding.projectSlug, budget: "TINY" });
423
+ projectBound = result?.ok !== false;
424
+ if (!projectBound) bindingError = result?.error || result?.note || "The backend did not resolve the bound project.";
425
+ if (projectBound) freshness = await repositoryFreshness(client, tools, binding, root);
426
+ } catch (error) {
427
+ bindingError = error.message;
428
+ }
429
+ }
430
+ const hooksInstalled = await claudeHooksInstalled(target.profile);
431
+ const codexSyncState = await readSyncState(target.paths.dir);
432
+ const codexSessions = await discoverAndMapCodexSessions({
433
+ codexHome: defaultCodexHome(),
434
+ bindings: target.cfg.bindings || {},
435
+ }).catch(() => []);
436
+ const codexMapped = codexSessions.filter((s) => s.mapped);
437
+ const codexPending = codexMapped.filter((s) => {
438
+ const prev = codexSyncState.sessions?.[s.threadId];
439
+ return !prev || prev.turnCount !== s.turnCount || prev.interrupted !== s.interrupted;
440
+ }).length;
441
+ const codexMcp = await codexMcpConfigured(target.profile);
442
+ const codexSkill = await (async () => {
443
+ try {
444
+ return (await stat(join(defaultCodexHome(), "skills", "reasontrail", "SKILL.md"))).isFile();
445
+ } catch { return false; }
446
+ })();
447
+
448
+ return {
449
+ available: tools.length > 0,
450
+ authenticated: true,
451
+ project_bound: projectBound,
452
+ project_id: projectBound ? binding.projectId || null : null,
453
+ project_slug: projectBound ? binding.projectSlug : null,
454
+ tenant_id: server?.tenantId || null,
455
+ read_available: readTools.some((name) => hasTool(tools, name)),
456
+ write_available: writeTools.some((name) => hasTool(tools, name)),
457
+ conversation_connector: projectBound
458
+ ? (hooksInstalled ? "Claude Code Hooks; Codex Local Session Sync" : "Codex Local Session Sync")
459
+ : "none",
460
+ automatic_transcript_sync: "disabled_explicit_sync_only",
461
+ codex_desktop: {
462
+ brain_access: codexMcp ? "connected" : "not_configured",
463
+ workspace: root,
464
+ repository: normalizedRepositoryUrl(gitRemote(root)),
465
+ project: projectBound ? binding.projectSlug : null,
466
+ capture_mechanism: "explicit `sync codex --apply` only",
467
+ session_store: join(defaultCodexHome(), "sessions"),
468
+ mcp_configured: codexMcp,
469
+ skill_installed: codexSkill,
470
+ last_sync_at: codexSyncState?.lastSyncAt || null,
471
+ discovered_sessions: codexSessions.length,
472
+ mapped_sessions: codexMapped.length,
473
+ pending_sessions: codexPending,
474
+ },
475
+ claude_code: { capture_mechanism: "explicitly enabled profile hooks", hooks_installed: hooksInstalled, retry_backlog: await claudeRetryBacklog(target.profile) },
476
+ transport: "cli",
477
+ profile: target.profile,
478
+ environment: target.profile,
479
+ backend_endpoint: target.endpoint,
480
+ repository_root: root,
481
+ ...(freshness || {}),
482
+ ...(bindingError ? { binding_error: bindingError } : {}),
483
+ };
484
+ }
485
+
486
+ async function statusCommand(argv) {
487
+ const target = await resolveTarget(argv);
488
+ output(await getStatus(target));
489
+ }
490
+
491
+ async function runtimeTool(target, name, args) {
492
+ const { client, tools } = await connected(target);
493
+ if (!hasTool(tools, name)) throw new CliError(`This ReasonTrail connection does not expose ${name}. Update the CLI/server pair.`, 3);
494
+ return client.call(name, args);
495
+ }
496
+
497
+ async function runCommand(argv) {
498
+ const target = await resolveTarget(argv);
499
+ const opts = target.opts;
500
+ const action = opts._[0];
501
+ if (["status", "stop", "resume"].includes(action)) {
502
+ const missionId = opts._[1];
503
+ if (!missionId) throw new CliError(`Usage: reasontrail run ${action} <run-or-mission-id>`, 2);
504
+ return output(await runtimeTool(target, `runtime_${action}`, { missionId }));
505
+ }
506
+ if (!opts.task && opts._.length === 0) return output(await runtimeTool(target, "runtime_list_runs", {}));
507
+ const { binding } = await bindingFor(target);
508
+ const request = opts.task ? undefined : opts._.join(" ").trim();
509
+ if (!opts.task && !request) throw new CliError('Usage: reasontrail run "<task>" | reasontrail run --task <task-id>', 2);
510
+ return output(await runtimeTool(target, "runtime_start", {
511
+ ...(opts.task ? { taskId: String(opts.task) } : { request }),
512
+ ...(opts.title ? { title: String(opts.title) } : {}),
513
+ ...(opts.workspace ? { workspaceId: String(opts.workspace) } : {}),
514
+ ...(opts.project || binding?.projectSlug ? { projectSlug: String(opts.project || binding.projectSlug) } : {}),
515
+ }));
516
+ }
517
+
518
+ async function decideCommand(argv) {
519
+ const target = await resolveTarget(argv);
520
+ const opts = target.opts;
521
+ const [missionId, gateId, answer] = opts._;
522
+ if (!missionId || !gateId || !answer) throw new CliError("Usage: reasontrail decide <mission-id> <gate-id> <answer> [--note <text>]", 2);
523
+ output(await runtimeTool(target, "runtime_decide", { missionId, gateId, answer, ...(opts.note ? { note: String(opts.note) } : {}) }));
524
+ }
525
+
526
+ async function contextCommand(argv) {
527
+ const target = await resolveTarget(argv);
528
+ const opts = target.opts;
529
+ const { root, binding } = await bindingFor(target);
530
+ const { client, tools } = await connected(target);
531
+ const request = String(opts.request || opts._.join(" ") || "Current repository context, active decisions, tasks, and shared project knowledge.").trim();
532
+ // Tell the server which checkout is asking.
533
+ //
534
+ // `reasontrail status` computed freshness from local Git and never sent it, so
535
+ // it could report "current" while the same repository's context pack said "no
536
+ // working copy has reported a HEAD". Both were right: one was describing this
537
+ // checkout, the other the canonical index. Sending the HEAD lets the server
538
+ // answer the question the caller actually has. It is request context only —
539
+ // the server never stores it and it cannot change canonical freshness.
540
+ const workingCopyRevision = root ? gitHead(root) : null;
541
+ const args = {
542
+ query: request,
543
+ tokenBudget: Number(opts.token_budget || 8000),
544
+ includeKnowledge: true,
545
+ ...(opts.project || binding?.projectSlug ? { projectSlug: opts.project || binding.projectSlug } : {}),
546
+ ...(workingCopyRevision ? { workingCopyRevision } : {}),
547
+ };
548
+ /**
549
+ * The ladder, in the order the ladder is meant to be climbed.
550
+ *
551
+ * `build_repository_context` used to be tried FIRST and returned
552
+ * unconditionally, which made `context_for_task` unreachable on any
553
+ * full-scope connection. Measured on real sessions, that made every single
554
+ * `reasontrail context` call a DEEP one: 4,138–13,644 response tokens,
555
+ * average 8,090, routinely truncated by the calling agent — while
556
+ * `context_for_task` answers the same request in ~1,200. DEEP is the
557
+ * fallback for when the graph has nothing to say, not the default.
558
+ */
559
+ const deepRequested = Boolean(opts.deep);
560
+
561
+ // A new repository has shared memory before it has a code index. Use the
562
+ // existing bounded project pack; never invent graph evidence or swallow errors.
563
+ if (!deepRequested && args.projectSlug && hasTool(tools, "get_repository_index_status")) {
564
+ const freshness = await repositoryFreshness(client, tools, { ...binding, projectSlug: args.projectSlug }, root);
565
+ if (freshness?.graph_state === "never_indexed") {
566
+ const memory = hasTool(tools, "get_project_context")
567
+ ? await client.call("get_project_context", { projectSlug: args.projectSlug, budget: "SMALL" })
568
+ : { candidates: [], recommendedNextAction: { operation: "explore_repository" } };
569
+ return output({ ...memory, warnings: [...(Array.isArray(memory?.warnings) ? memory.warnings : []), "This repository has never been indexed. This is shared project memory only; connect a repository companion and complete an initial index for code context."] });
570
+ }
571
+ }
572
+
573
+ if (!deepRequested && hasTool(tools, "context_for_task")) {
574
+ const ladder = await client.call("context_for_task", {
575
+ task: request,
576
+ ...(args.projectSlug ? { projectSlug: args.projectSlug } : {}),
577
+ });
578
+ // The server says so itself when the graph cannot answer: no candidates,
579
+ // and a recommendation to go and explore the repository instead. That —
580
+ // not a token count or a guess here — is the escalation signal.
581
+ const candidates = Array.isArray(ladder?.candidates) ? ladder.candidates : [];
582
+ const exhausted = candidates.length === 0
583
+ || ladder?.recommendedNextAction?.operation === "explore_repository";
584
+ if (!exhausted) return output(ladder);
585
+
586
+ }
587
+
588
+ if (hasTool(tools, "build_repository_context")) {
589
+ const result = await client.call("build_repository_context", args);
590
+ const freshness = await repositoryFreshness(client, tools, binding, root);
591
+ if (freshness && freshness.graph_state !== "current" && result && typeof result === "object") {
592
+ result.warnings = [...(Array.isArray(result.warnings) ? result.warnings : []), `Local repository HEAD is ${freshness.repository_head?.slice(0, 12)}, but the selected graph revision is ${freshness.indexed_revision?.slice(0, 12)} (${freshness.graph_state}).`];
593
+ }
594
+ return output(result);
595
+ }
596
+ if (hasTool(tools, "context_for_task")) {
597
+ return output(await client.call("context_for_task", { task: request, ...(args.projectSlug ? { projectSlug: args.projectSlug } : {}) }));
598
+ }
599
+ throw new CliError("The authenticated ReasonTrail connection exposes no context retrieval tool.", 3);
600
+ }
601
+
602
+ async function searchCommand(argv) {
603
+ const target = await resolveTarget(argv);
604
+ const opts = target.opts;
605
+ const query = String(opts.query || opts._.join(" ")).trim();
606
+ if (!query) throw new CliError("Usage: reasontrail search --query <text>", 2);
607
+ const { binding } = await bindingFor(target);
608
+ const { client, tools } = await connected(target);
609
+ if (!hasTool(tools, "search_brain")) throw new CliError("The authenticated ReasonTrail connection does not expose search_brain.", 3);
610
+ const projectSlug = opts.project || (!opts.all_projects ? binding?.projectSlug : null);
611
+ output(await client.call("search_brain", { query, limit: Number(opts.limit || 10), ...(projectSlug ? { projectSlug } : {}) }));
612
+ }
613
+
614
+ async function stdinJson() {
615
+ if (stdin.isTTY) return {};
616
+ const text = (await readStdin()).trim();
617
+ return text ? JSON.parse(text) : {};
618
+ }
619
+
620
+ async function readStdin() {
621
+ let text = "";
622
+ for await (const chunk of stdin) text += chunk.toString();
623
+ return text;
624
+ }
625
+
626
+ async function updateCommand(argv) {
627
+ const target = await resolveTarget(argv);
628
+ const opts = target.opts;
629
+ const piped = await stdinJson();
630
+ const { root, binding } = await bindingFor(target);
631
+ const { client, tools } = await connected(target);
632
+ 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);
634
+ const labeledFindings = [
635
+ ...(piped.findings || []),
636
+ ...(piped.discoveries || []).map((value) => `[discovery] ${value}`),
637
+ ...(piped.implementationFacts || piped.implementation_facts || []).map((value) => `[implementation fact] ${value}`),
638
+ ...(piped.rejectedApproaches || piped.rejected_approaches || []).map((value) => `[rejected approach] ${value}`),
639
+ ...(piped.constraints || []).map((value) => `[constraint] ${value}`),
640
+ ...(piped.ideas || []).map((value) => `[idea] ${value}`),
641
+ ...(piped.openQuestions || piped.open_questions || []).map((value) => `[open question] ${value}`),
642
+ ...(piped.taskOutcomes || piped.task_outcomes || []).map((value) => `[task outcome] ${value}`),
643
+ ];
644
+ const args = {
645
+ ...piped,
646
+ ...(labeledFindings.length ? { findings: labeledFindings } : {}),
647
+ ...(opts.summary ? { taskSummary: opts.summary } : {}),
648
+ ...(opts.remaining_work ? { remainingWork: opts.remaining_work } : {}),
649
+ clientConversationId: piped.clientConversationId || opts.conversation_id || `reasontrail-cli:${identity}`,
650
+ ...(opts.project || binding?.projectSlug ? { projectSlug: opts.project || binding.projectSlug } : {}),
651
+ };
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));
654
+ }
655
+
656
+ async function bindCommand(argv) {
657
+ const target = await resolveTarget(argv);
658
+ const opts = target.opts;
659
+ const { root, cfg } = await bindingFor(target);
660
+ const { client, tools } = await connected(target);
661
+ if (!hasTool(tools, "get_repository_index_status")) throw new CliError("The authenticated connection cannot resolve repository associations.", 3);
662
+ const origin = gitRemote(root);
663
+ if (!origin) throw new CliError("The current Git repository has no origin remote, so ReasonTrail will not guess a project association.", 2);
664
+ let repositories = [];
665
+ if (opts.project) {
666
+ repositories = [await client.call("get_repository_index_status", { projectSlug: opts.project })];
667
+ } else {
668
+ try {
669
+ repositories = [await client.call("get_repository_index_status", {})];
670
+ } catch (error) {
671
+ if (!hasTool(tools, "list_projects")) {
672
+ throw new CliError(`${error.message} Use \`reasontrail . --project <slug>\` only after confirming the project.`, 2);
673
+ }
674
+ const projects = await client.call("list_projects", {});
675
+ for (const project of Array.isArray(projects) ? projects : []) {
676
+ if (!project?.slug) continue;
677
+ try {
678
+ repositories.push(await client.call("get_repository_index_status", { projectSlug: project.slug }));
679
+ } catch {
680
+ // A project without an indexed repository is not a binding candidate.
681
+ }
682
+ }
683
+ }
684
+ }
685
+ const matches = repositories.filter((candidate) => normalizedRepositoryUrl(candidate?.url) === normalizedRepositoryUrl(origin));
686
+ if (matches.length > 1) {
687
+ throw new CliError(`More than one authorized ReasonTrail repository matches origin '${origin}'. Choose one with \`reasontrail . --project <slug>\`.`, 2, { projects: matches.map((match) => ({ slug: match.projectSlug, repositoryId: match.repositoryId })) });
688
+ }
689
+ const repository = matches[0];
690
+ if (!repository) {
691
+ const resolved = repositories.map((candidate) => candidate?.url).filter(Boolean);
692
+ throw new CliError(`No authorized ReasonTrail repository matches origin '${origin}'. Nothing was bound.`, 2, { repositories: resolved });
693
+ }
694
+ const slug = repository.projectSlug;
695
+ if (!slug) throw new CliError("ReasonTrail did not return a project for this repository. Nothing was bound.", 2);
696
+ cfg.bindings ||= {};
697
+ cfg.bindings[root] = { projectSlug: slug, projectId: opts.project_id || null, repositoryId: repository.repositoryId || null, repositoryUrl: repository.url, boundAt: new Date().toISOString() };
698
+ await saveJson(target.paths.config, cfg);
699
+ const runs = hasTool(tools, "runtime_list_runs") ? await client.call("runtime_list_runs", {}) : [];
700
+ 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" });
702
+ }
703
+
704
+ async function authCommand(argv) {
705
+ const action = argv[0];
706
+ if (action === "login") {
707
+ const target = await resolveTarget(argv.slice(1));
708
+ return output(await loginCredential(target, argv.includes("--device")));
709
+ }
710
+ if (action === "logout") {
711
+ const target = await resolveTarget(argv.slice(1), { confirm: false });
712
+ const removed = await removeCredential(target.profile);
713
+ return output({ profile: target.profile, authenticated: false, removed, note: removed.length ? "Stored CLI credentials removed." : "No stored CLI credential was present." });
714
+ }
715
+ if (action === "status") {
716
+ const target = await resolveTarget(argv.slice(1));
717
+ const credential = await loadCredential(target.profile);
718
+ const status = await getStatus(target);
719
+ return output({ credential_available: Boolean(credential), credential_store: credential?.source || null, ...status });
720
+ }
721
+ throw new CliError("Usage: reasontrail auth <login|logout|status>", 2);
722
+ }
723
+
724
+ async function loginCredential(target, device = false) {
725
+ async function install(token) {
726
+ const client = new ReasonTrailClient(target.endpoint, token);
727
+ const server = await client.initialize();
728
+ const tools = await client.tools();
729
+ const location = await storeCredential(target.profile, token);
730
+ return { profile: target.profile, authenticated: true, server: server?.serverInfo?.name || "reasontrail", tools: tools.length, credential_store: location };
731
+ }
732
+ if (!device) return install(await promptToken());
733
+ const previous = await loadCredential(target.profile);
734
+ return deviceLogin(target.endpoint, {
735
+ machineName: hostname(), version: VERSION,
736
+ announce: ({ verificationUri, userCode }) => stderr.write(`Open ${verificationUri} in your browser and approve code ${userCode}.\n`),
737
+ install,
738
+ rollback: async () => previous ? storeCredential(target.profile, previous.token) : removeCredential(target.profile),
739
+ });
740
+ }
741
+
742
+ async function installCommand(argv, uninstall = false) {
743
+ const opts = options(argv);
744
+ const platform = String(opts.platform || "").toLowerCase();
745
+ const source = join(PACKAGE_ROOT, "skills", "reasontrail", "SKILL.md");
746
+ const aliases = {
747
+ antigravity: "agy",
748
+ };
749
+ const normalizedPlatform = aliases[platform] || platform;
750
+ const destinations = {
751
+ codex: join(process.env.CODEX_HOME || join(homedir(), ".codex"), "skills", "reasontrail", "SKILL.md"),
752
+ claude: join(homedir(), ".claude", "skills", "reasontrail", "SKILL.md"),
753
+ agy: join(process.env.ANTIGRAVITY_CONFIG_DIR || join(homedir(), ".gemini", "config"), "skills", "reasontrail", "SKILL.md"),
754
+ };
755
+ if (!platform) throw new CliError("Choose `--platform codex`, `--platform claude`, or `--platform agy`.", 2);
756
+ if (platform === "cursor") {
757
+ throw new CliError(`${platform} installation is not yet supported by this release; no files were changed.`, 2);
758
+ }
759
+ const destination = destinations[normalizedPlatform];
760
+ if (!destination) throw new CliError(`Unsupported platform '${platform}'. Choose codex, claude, or agy.`, 2);
761
+ if (uninstall) {
762
+ await rm(dirname(destination), { recursive: true, force: true });
763
+ return output({ uninstalled: true, platform: normalizedPlatform, path: dirname(destination) });
764
+ }
765
+ await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
766
+ await copyFile(source, destination);
767
+ await chmod(destination, 0o600);
768
+ output({
769
+ installed: true,
770
+ platform: normalizedPlatform,
771
+ path: destination,
772
+ invocation: normalizedPlatform === "claude" ? "/reasontrail" : normalizedPlatform === "codex" ? "$reasontrail" : "ReasonTrail skill",
773
+ });
774
+ }
775
+
776
+ async function sourceRevision() {
777
+ const stamped = await readJson(join(PACKAGE_ROOT, "src", "build-info.json"), null);
778
+ if (typeof stamped?.sourceRevision === "string" && /^[0-9a-f]{40}$/.test(stamped.sourceRevision)) return stamped.sourceRevision;
779
+ return gitHead(PACKAGE_ROOT);
780
+ }
781
+
782
+ async function cliBuildIdentity(reviewRoot = null) {
783
+ const revision = await sourceRevision();
784
+ let reviewedRevision = null;
785
+ let sameVersionCheckout = false;
786
+ if (reviewRoot) {
787
+ const checkoutPackage = await readJson(join(reviewRoot, "packages", "reasontrail-cli", "package.json"), null);
788
+ sameVersionCheckout = checkoutPackage?.name === PACKAGE_META.name && checkoutPackage?.version === VERSION;
789
+ if (sameVersionCheckout) reviewedRevision = gitHead(reviewRoot);
790
+ }
791
+ const revisionsKnown = Boolean(revision && reviewedRevision);
792
+ const mismatch = Boolean(sameVersionCheckout && revisionsKnown && revision !== reviewedRevision);
793
+ const unverifiable = sameVersionCheckout && !revisionsKnown;
794
+ return {
795
+ installed: true,
796
+ version: VERSION,
797
+ source_revision: revision,
798
+ executable: process.argv[1],
799
+ reviewed_checkout_revision: reviewedRevision,
800
+ integrity: mismatch ? "mismatch" : unverifiable ? "unknown" : sameVersionCheckout ? "match" : "checkout_not_comparable",
801
+ ...(mismatch ? { warning: "Installed CLI source revision differs from this checkout while package versions match. Rebuild/reinstall from the reviewed checkout before use." } : {}),
802
+ ...(unverifiable ? { warning: "CLI integrity could not be verified: the installed source revision or reviewed checkout revision is unavailable." } : {}),
803
+ };
804
+ }
805
+
806
+ async function doctorCommand(argv) {
807
+ const target = await resolveTarget(argv);
808
+ const root = await repositoryRoot();
809
+ const origin = gitRemote(root);
810
+ const credential = await loadCredential(target.profile);
811
+ let backend;
812
+ try { backend = await getStatus(target); } catch (error) { backend = { available: false, authenticated: false, error: error.message }; }
813
+ const paths = {
814
+ codex: join(process.env.CODEX_HOME || join(homedir(), ".codex"), "skills", "reasontrail", "SKILL.md"),
815
+ claude: join(homedir(), ".claude", "skills", "reasontrail", "SKILL.md"),
816
+ agy: join(process.env.ANTIGRAVITY_CONFIG_DIR || join(homedir(), ".gemini", "config"), "skills", "reasontrail", "SKILL.md"),
817
+ };
818
+ const installed = {};
819
+ for (const [name, path] of Object.entries(paths)) {
820
+ try { installed[name] = (await stat(path)).isFile(); } catch { installed[name] = false; }
821
+ }
822
+ output({
823
+ cli: await cliBuildIdentity(root),
824
+ credential: { available: Boolean(credential), store: credential?.source || null },
825
+ backend,
826
+ repository: { root, origin, git: Boolean(origin) },
827
+ skills: installed,
828
+ native_mcp: { codex_configured: (await codexMcpConfigured(target.profile)), note: "MCP registration is profile-named and must obtain credentials independently; the CLI never generates inline Authorization headers." },
829
+ codex_sync: {
830
+ session_store: join(defaultCodexHome(), "sessions"),
831
+ discovered_sessions: backend?.codex_desktop?.discovered_sessions ?? 0,
832
+ mapped_sessions: backend?.codex_desktop?.mapped_sessions ?? 0,
833
+ pending_sessions: backend?.codex_desktop?.pending_sessions ?? 0,
834
+ last_sync_at: backend?.codex_desktop?.last_sync_at ?? null,
835
+ },
836
+ claude_mcp: await inspectClaudeMcp(target.profile),
837
+ cli_fallback: true,
838
+ });
839
+ }
840
+
841
+ async function syncCommand(argv) {
842
+ 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);
845
+ }
846
+ const target = await resolveTarget(argv.slice(1), { confirm: false });
847
+ const opts = target.opts;
848
+ const apply = opts.apply === true;
849
+ const watch = opts.watch === true;
850
+ if (opts.dry_run) throw new CliError("Preview is now the default. Remove `--dry-run`; add `--apply` only for an intentional synchronization.", 2);
851
+ if (watch && !apply) throw new CliError("Watch mode writes synchronized data. Add `--apply` when you intentionally want automatic upload.", 2);
852
+ const intervalSeconds = Math.max(10, Math.min(3600, Number(opts.interval || 60)));
853
+ if (!Number.isFinite(intervalSeconds)) throw new CliError("Sync interval must be a number of seconds.", 2);
854
+ let client = null;
855
+ let tools = [];
856
+ if (apply) {
857
+ await confirmProduction(opts);
858
+ ({ client, tools } = await connected(target));
859
+ }
860
+ const runOnce = async () => {
861
+ 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 } : {}) });
866
+ }
867
+ return syncCodex(client, tools, target.paths.dir, target.cfg, {
868
+ dryRun: !apply,
869
+ since: opts.since || null,
870
+ project: opts.project || null,
871
+ session: opts.session || null,
872
+ force: Boolean(opts.force),
873
+ });
874
+ };
875
+ if (!watch) return output(await runOnce());
876
+ for (;;) {
877
+ output({ watched_at: new Date().toISOString(), ...(await runOnce()) });
878
+ await new Promise((resolveSleep) => setTimeout(resolveSleep, intervalSeconds * 1000));
879
+ }
880
+ }
881
+
882
+ async function inspectClaudeMcp(profile) {
883
+ // Assistant-wide MCP diagnostics can probe registrations for other profiles.
884
+ // Keep doctor restricted to its own authenticated connection above.
885
+ return {
886
+ available: commandExists("claude"),
887
+ profile,
888
+ registrations: [],
889
+ issues: ["native_connectivity_not_checked"],
890
+ note: "Native assistant connections are not probed. Doctor checks only the selected ReasonTrail profile.",
891
+ };
892
+ }
893
+
894
+ async function codexMcpConfigured(profile) {
895
+ try {
896
+ const text = await readFile(join(process.env.CODEX_HOME || join(homedir(), ".codex"), "config.toml"), "utf8");
897
+ return new RegExp(`^\\[mcp_servers\\.reasontrail-${profile}\\]\\s*$`, "m").test(text);
898
+ } catch { return false; }
899
+ }
900
+
901
+ async function configCommand(argv) {
902
+ const opts = options(argv);
903
+ const profile = requiredProfile(opts);
904
+ const cfg = await config(profile, { allowMissing: true });
905
+ if (opts._[0] === "endpoint" && opts._[1] && opts._.length === 2) {
906
+ cfg.environment = profile;
907
+ cfg.endpoint = validateEndpoint(opts._[1], profile);
908
+ cfg.bindings ||= {};
909
+ await saveJson(profilePaths(profile).config, cfg);
910
+ return output({ profile, environment: profile, endpoint: sanitizedEndpoint(cfg.endpoint) });
911
+ }
912
+ if (opts._[0] === "environment" && opts._[1] === profile && opts._.length === 2) {
913
+ cfg.environment = profile;
914
+ cfg.endpoint = profile === "production" ? DEFAULT_ENDPOINT : DEVELOPMENT_ENDPOINT;
915
+ cfg.bindings ||= {};
916
+ await saveJson(profilePaths(profile).config, cfg);
917
+ return output({ profile, environment: profile, endpoint: cfg.endpoint });
918
+ }
919
+ throw new CliError("Usage: reasontrail config endpoint <url> --profile <development|production>", 2);
920
+ }
921
+
922
+ async function agyConfigured() {
923
+ try {
924
+ const dir = process.env.ANTIGRAVITY_CONFIG_DIR || join(homedir(), ".gemini");
925
+ return (await stat(dir)).isDirectory();
926
+ } catch { return false; }
927
+ }
928
+
929
+ async function setupCommand(argv) {
930
+ const target = await resolveTarget(argv, { allowMissing: true, confirm: false });
931
+ if (target.profile === "production" && target.opts.enable_hooks) {
932
+ throw new CliError("Production hooks are prohibited. Hooks may be explicitly enabled only for the development profile.", 2);
933
+ }
934
+ await saveJson(target.paths.config, target.cfg);
935
+ const detected = [];
936
+ if (commandExists("codex") || await codexMcpConfigured(target.profile)) detected.push("codex");
937
+ if (commandExists("claude")) detected.push("claude");
938
+ if (commandExists("agy") || commandExists("antigravity") || await agyConfigured()) detected.push("agy");
939
+ for (const platform of detected) await installCommand(["--platform", platform]);
940
+ let hooks = { enabled: false };
941
+ if (detected.includes("claude") && target.opts.enable_hooks === true) {
942
+ target.cfg.hooksEnabled = true;
943
+ await saveJson(target.paths.config, target.cfg);
944
+ hooks = await installClaudeHooks(target.profile);
945
+ await pruneClaudeRetryBacklog(target.profile);
946
+ }
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.` });
948
+ }
949
+
950
+ async function installClaudeHooks(profile) {
951
+ const current = await readJson(CLAUDE_SETTINGS, {});
952
+ const hooks = current.hooks && typeof current.hooks === "object" ? current.hooks : {};
953
+ const cli = resolve(process.argv[1]);
954
+ const marker = `${CLAUDE_HOOK_MARKER} --profile ${profile}`;
955
+ const command = `${cli} hook claude --reasontrail-hook --profile ${profile}`;
956
+ for (const event of ["SessionStart", "UserPromptSubmit", "Stop", "SessionEnd"]) {
957
+ const entries = Array.isArray(hooks[event]) ? hooks[event] : [];
958
+ const filtered = entries.filter((entry) => !JSON.stringify(entry).includes(marker));
959
+ filtered.push({ matcher: "", hooks: [{ type: "command", command, timeout: 10 }] });
960
+ hooks[event] = filtered;
961
+ }
962
+ const backup = `${CLAUDE_SETTINGS}.reasontrail-backup-${Date.now()}`;
963
+ try { await copyFile(CLAUDE_SETTINGS, backup); } catch (error) { if (error?.code !== "ENOENT") throw error; }
964
+ await saveJson(CLAUDE_SETTINGS, { ...current, hooks }, 0o600);
965
+ return { installed: true, path: CLAUDE_SETTINGS, backup, command };
966
+ }
967
+
968
+ const CLAUDE_SETTINGS = join(homedir(), ".claude", "settings.json");
969
+ const CLAUDE_HOOK_MARKER = "hook claude --reasontrail-hook";
970
+ async function claudeHooksInstalled(profile) {
971
+ const settings = await readJson(CLAUDE_SETTINGS, {});
972
+ return ["SessionStart", "UserPromptSubmit", "Stop", "SessionEnd"].every((event) =>
973
+ Array.isArray(settings.hooks?.[event]) && settings.hooks[event].some((entry) => JSON.stringify(entry).includes(`${CLAUDE_HOOK_MARKER} --profile ${profile}`))
974
+ );
975
+ }
976
+ async function claudeRetryBacklog(profile) {
977
+ const queue = await readJson(join(profilePaths(profile).connectors, "claude", "retry-queue.json"), []);
978
+ return Array.isArray(queue) ? queue.length : 0;
979
+ }
980
+ async function pruneClaudeRetryBacklog(profile) {
981
+ const path = join(profilePaths(profile).connectors, "claude", "retry-queue.json");
982
+ const queue = await readJson(path, []);
983
+ if (!Array.isArray(queue)) return 0;
984
+ // Legacy releases recorded non-retryable privacy decisions and malformed
985
+ // payloads here. Those entries contain no event body and can never be
986
+ // delivered; retaining them only reports a false degraded state.
987
+ const retryable = queue.filter((item) => !/WORKSPACE UNBOUND|did not include session_id|did not include cwd/i.test(String(item?.error || "")));
988
+ if (retryable.length !== queue.length) await saveJson(path, retryable);
989
+ return retryable.length;
990
+ }
991
+
992
+ /**
993
+ * Append one local probe record, bounded.
994
+ *
995
+ * The server records every call it actually receives, which is the authority
996
+ * for anything that got there. This file exists for what the server CANNOT
997
+ * see: a probe that never arrived because ReasonTrail was unreachable, timed
998
+ * out, or rejected the credential. Without it a turn where the check failed is
999
+ * indistinguishable from a turn where no check was attempted — the precise
1000
+ * ambiguity that made the original "is it consulted every turn?" question
1001
+ * unanswerable from telemetry.
1002
+ */
1003
+ async function recordProbe(profile, entry) {
1004
+ try {
1005
+ const path = join(profilePaths(profile).connectors, "claude", "probe-log.json");
1006
+ const log = await readJson(path, []);
1007
+ const list = Array.isArray(log) ? log : [];
1008
+ list.push(entry);
1009
+ await saveJson(path, list.slice(-500));
1010
+ } catch { /* diagnostics must never be what breaks a turn */ }
1011
+ }
1012
+
1013
+ /**
1014
+ * The lightweight per-turn context check.
1015
+ *
1016
+ * CHECK, not RETRIEVE: it asks `get_project_context` at TINY with the version
1017
+ * the last turn returned, and the common answer is `notModified` — measured at
1018
+ * 14 response tokens, against 8,090 for the DEEP pack this replaces as the
1019
+ * per-turn act. Only a changed version produces any output at all.
1020
+ *
1021
+ * Writing to stdout is deliberate and is the one thing this hook did not
1022
+ * previously do: Claude injects hook stdout into the model's context, which is
1023
+ * exactly the delivery mechanism a continuous context layer needs, and is why
1024
+ * silence on `notModified` matters so much — an unchanged turn must cost
1025
+ * nothing, not "a little".
1026
+ *
1027
+ * Fails open, always. ReasonTrail being down degrades a Claude session to what
1028
+ * it was before this existed; it never blocks or delays a turn.
1029
+ */
1030
+ async function probeProjectContext({ profile, client, tools, state, stateFile, project, turnId, at }) {
1031
+ if (!hasTool(tools, "get_project_context")) {
1032
+ await recordProbe(profile, { at, turnId, stage: "probe", ok: false, failure: "tool_unavailable" });
1033
+ return;
1034
+ }
1035
+ const previousVersion = typeof state.contextVersion === "string" ? state.contextVersion : null;
1036
+ let result;
1037
+ try {
1038
+ result = await client.call("get_project_context", {
1039
+ ...project,
1040
+ budget: "TINY",
1041
+ ...(previousVersion ? { sinceVersion: previousVersion } : {}),
1042
+ });
1043
+ } catch (error) {
1044
+ // Unreachable, timed out, unauthorized, project unresolvable — all the same
1045
+ // to the turn, and all recorded rather than swallowed.
1046
+ await recordProbe(profile, {
1047
+ at, turnId, stage: "probe", ok: false, previousVersion,
1048
+ failure: String(error?.details?.kind || error?.details?.status || error?.message || error).slice(0, 200),
1049
+ });
1050
+ return;
1051
+ }
1052
+
1053
+ if (result?.notModified) {
1054
+ await recordProbe(profile, {
1055
+ at, turnId, stage: "probe", ok: true, notModified: true,
1056
+ previousVersion, returnedVersion: result.version ?? previousVersion, emittedTokens: 0,
1057
+ });
1058
+ return; // The point of the whole exercise: nothing changed, so nothing is spent.
1059
+ }
1060
+
1061
+ const body = typeof result?.context === "string" ? result.context.trim() : "";
1062
+ if (!body) {
1063
+ await recordProbe(profile, { at, turnId, stage: "probe", ok: true, notModified: false, previousVersion, failure: "empty_context" });
1064
+ return;
1065
+ }
1066
+
1067
+ state.contextVersion = typeof result.version === "string" ? result.version : previousVersion;
1068
+ await saveJson(stateFile, state);
1069
+
1070
+ // Only the changed slice, labelled for what it is, so the model can tell
1071
+ // retrieved project state from the user's own words.
1072
+ stdout.write(`<reasontrail-context version="${state.contextVersion}">\n${body}\n</reasontrail-context>\n`);
1073
+
1074
+ await recordProbe(profile, {
1075
+ at, turnId, stage: previousVersion ? "retrieve" : "retrieve_initial", ok: true, notModified: false,
1076
+ previousVersion, returnedVersion: state.contextVersion,
1077
+ emittedTokens: result.estimatedTokens ?? null,
1078
+ });
1079
+ }
1080
+
1081
+ async function claudeHookCommandUnsafe(argv) {
1082
+ const target = await resolveTarget(argv, { confirm: false });
1083
+ if (target.profile === "production" || target.cfg.hooksEnabled !== true) {
1084
+ throw new CliError("Claude synchronization hooks are disabled for this profile.", 2, { kind: "hooks_disabled" });
1085
+ }
1086
+ const event = await stdinJson();
1087
+ const name = String(event.hook_event_name || event.event || event.type || "");
1088
+ const session = String(event.session_id || event.sessionId || "").trim();
1089
+ if (!session) throw new CliError("Claude hook payload did not include session_id.", 2);
1090
+ const eventCwd = typeof event.cwd === "string" ? event.cwd.trim() : "";
1091
+ if (!eventCwd) throw new CliError("WORKSPACE UNBOUND: Claude hook payload did not include cwd; automatic capture is disabled.", 2, { kind: "workspace_unbound" });
1092
+ const { root, binding } = await bindingFor(target, eventCwd);
1093
+ if (!binding?.projectSlug) throw new CliError(`WORKSPACE UNBOUND: ${root}`, 2, { kind: "workspace_unbound" });
1094
+ const stateDir = join(target.paths.connectors, "claude");
1095
+ const stateFile = join(stateDir, `${createHash("sha256").update(session).digest("hex")}.json`);
1096
+ const state = await readJson(stateFile, { session, clientConversationId: `claude:${session}`, turns: [], started: false, completed: false });
1097
+ const { client, tools } = await connected(target);
1098
+ const project = { projectSlug: binding.projectSlug };
1099
+ const now = new Date().toISOString();
1100
+ const text = (value) => typeof value === "string" ? value.trim() : "";
1101
+ const eventId = String(event.event_id || event.eventId || event.uuid || event.message_id || `${name}:${event.timestamp || now}`);
1102
+ // Every call this hook makes belongs to this turn, and says so to the server.
1103
+ client.turnId = eventId;
1104
+ async function sync(turns) {
1105
+ if (!turns.length || !hasTool(tools, "sync_conversation_delta")) return;
1106
+ const result = await client.call("sync_conversation_delta", { clientConversationId: state.clientConversationId, turns, ...project });
1107
+ state.lastSyncAt = now; state.cursor = result?.lastSyncedMessageId || result?.lastSyncedMessageId === null ? result.lastSyncedMessageId : state.cursor;
1108
+ await saveJson(stateFile, state);
1109
+ }
1110
+ if (name === "SessionStart" && !state.started) {
1111
+ await client.call("begin_task", { taskTitle: text(event.task_title || event.prompt || "Claude Code session") || "Claude Code session", userRequest: text(event.prompt), messageId: `${eventId}:start`, clientConversationId: state.clientConversationId, timestamp: now, ...project });
1112
+ state.started = true; await saveJson(stateFile, state);
1113
+ } else if (name === "UserPromptSubmit") {
1114
+ const content = text(event.prompt || event.user_prompt || event.message);
1115
+ if (content && !state.turns.includes(`${eventId}:user`)) { await sync([{ messageId: `${eventId}:user`, role: "user", content, timestamp: now }]); state.turns.push(`${eventId}:user`); await saveJson(stateFile, state); }
1116
+ // The per-turn check. Runs after the write-back so a probe failure can
1117
+ // never cost the turn its transcript.
1118
+ await probeProjectContext({ profile: target.profile, client, tools, state, stateFile, project, turnId: eventId, at: now });
1119
+ } else if (name === "Stop" || name === "SubagentStop") {
1120
+ const content = text(event.last_assistant_message || event.assistant_message || event.message);
1121
+ if (content && !state.turns.includes(`${eventId}:assistant`)) { await sync([{ messageId: `${eventId}:assistant`, role: "assistant", content, timestamp: now }]); state.turns.push(`${eventId}:assistant`); await saveJson(stateFile, state); }
1122
+ } else if (name === "SessionEnd" && !state.completed) {
1123
+ await client.call("complete_task", { clientConversationId: state.clientConversationId, outcome: "SUCCESS", resultSummary: "Claude Code session completed.", ...project });
1124
+ state.completed = true; state.lastSyncAt = now; await saveJson(stateFile, state);
1125
+ }
1126
+ // Claude injects hook stdout into model context. Every branch here is
1127
+ // write-back and stays silent for that reason. The ONE exception is the
1128
+ // per-turn probe in UserPromptSubmit, which writes only when the project
1129
+ // version actually moved — see probeProjectContext.
1130
+ }
1131
+
1132
+ // Claude hooks are observability, never policy gates. Any connector failure
1133
+ // is recorded locally and swallowed so UserPromptSubmit/Stop can never block
1134
+ // normal Claude operation. A successful hook emits stdout only when the
1135
+ // per-turn probe found changed context; an unchanged turn, and every failure,
1136
+ // emits nothing at all.
1137
+ async function claudeHookCommand(argv) {
1138
+ let profile = null;
1139
+ try {
1140
+ profile = requiredProfile(options(argv));
1141
+ await claudeHookCommandUnsafe(argv);
1142
+ } catch (error) {
1143
+ // An unbound workspace is an expected privacy decision, not a failed
1144
+ // delivery. Never queue it for replay after a later project binding.
1145
+ if (error?.details?.kind === "workspace_unbound" || error?.details?.kind === "hooks_disabled") return;
1146
+ try {
1147
+ if (!profile) return;
1148
+ const dir = join(profilePaths(profile).connectors, "claude");
1149
+ const path = join(dir, "retry-queue.json");
1150
+ const queue = await readJson(path, []);
1151
+ queue.push({ at: new Date().toISOString(), error: String(error?.message || error).slice(0, 240) });
1152
+ await saveJson(path, queue.slice(-100));
1153
+ } catch { /* fail-open even if local diagnostics cannot be written */ }
1154
+ }
1155
+ }
1156
+
1157
+ /* ── ReasonTrail Runtime ───────────────────────────────────────────────────
1158
+ *
1159
+ * The runtime is a separate program: a bundled, dependency-free build of the
1160
+ * Mission Runtime that ships inside this package. This CLI is its front door —
1161
+ * it stores the enrollment, resolves the bundle and execs it. It does not
1162
+ * reimplement any part of the runtime, and deliberately does not parse its
1163
+ * protocol: everything past `spawn` is the runtime's own business.
1164
+ *
1165
+ * WHY A SEPARATE CONFIG FILE from `credentials.json`. That file holds the MCP
1166
+ * token, which reads the Brain. `rtrt_` authorizes COMMAND EXECUTION on this
1167
+ * machine — the largest grant in the product — and the two should not share a
1168
+ * blast radius or a revocation. Same directory, same 0600, separate file.
1169
+ */
1170
+ const RUNTIME_BUNDLE = join(PACKAGE_ROOT, "runtime", "reasontrail-runtime.mjs");
1171
+
1172
+ async function runtimeConfig(profile) {
1173
+ return readJson(profilePaths(profile).runtime, null);
1174
+ }
1175
+
1176
+ function runtimeUsage() {
1177
+ return (
1178
+ `Usage: reasontrail runtime <command>\n\n` +
1179
+ ` enroll --url <origin> --token <rtrt_…> [--workspace <id>=<path>]…\n` +
1180
+ ` Store this machine's enrollment\n` +
1181
+ ` start [--once] Connect to ReasonTrail and take work\n` +
1182
+ ` status Show the stored enrollment\n` +
1183
+ ` logout Forget the stored enrollment\n`
1184
+ );
1185
+ }
1186
+
1187
+ async function runtimeCommand(argv) {
1188
+ const sub = argv[0];
1189
+
1190
+ if (!sub || sub === "help" || sub === "--help") return stdout.write(runtimeUsage());
1191
+ const target = await resolveTarget(argv.slice(1), { allowMissing: true, confirm: sub === "start" });
1192
+ const runtimeFile = target.paths.runtime;
1193
+
1194
+ if (sub === "enroll") {
1195
+ const value = (flag) => {
1196
+ const i = argv.indexOf(flag);
1197
+ return i > 0 && argv[i + 1] ? argv[i + 1] : null;
1198
+ };
1199
+ const url = value("--url");
1200
+ const token = value("--token");
1201
+ if (!url || !token) throw new CliError("Both --url and --token are required.\n\n" + runtimeUsage(), 2);
1202
+ if (!token.startsWith("rtrt_")) {
1203
+ throw new CliError("That does not look like a runtime credential (expected an rtrt_ prefix).", 2);
1204
+ }
1205
+ let origin;
1206
+ try {
1207
+ const parsed = new URL(url);
1208
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error("scheme");
1209
+ origin = parsed.origin;
1210
+ } catch {
1211
+ throw new CliError(`\`${url}\` is not a valid ReasonTrail origin.`, 2);
1212
+ }
1213
+
1214
+ // Repeated --workspace, matching the runtime's own argument shape.
1215
+ const workspaces = [];
1216
+ for (let i = 0; i < argv.length; i++) {
1217
+ if (argv[i] === "--workspace" && argv[i + 1]) workspaces.push(argv[++i]);
1218
+ }
1219
+
1220
+ // 0600, in a 0700 directory. The credential is the whole point of the file.
1221
+ if (target.profile === "production" && origin !== "https://app.reasontrail.ai") throw new CliError("Production runtime enrollment must use https://app.reasontrail.ai.", 2);
1222
+ 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);
1224
+ stdout.write(
1225
+ `Enrolled against ${origin}.\n` +
1226
+ `${workspaces.length} workspace${workspaces.length === 1 ? "" : "s"} configured.\n` +
1227
+ `Stored in ${runtimeFile} (owner-only).\n\n` +
1228
+ `Start it with: reasontrail runtime start --profile ${target.profile}\n`
1229
+ );
1230
+ return;
1231
+ }
1232
+
1233
+ if (sub === "status") {
1234
+ const cfg = await runtimeConfig(target.profile);
1235
+ if (!cfg) return stdout.write("No runtime enrollment on this machine.\nRun `reasontrail runtime enroll …`.\n");
1236
+ // The PREFIX only. The credential is never redisplayed after enrollment.
1237
+ const prefix = String(cfg.token || "").slice(0, 11);
1238
+ stdout.write(
1239
+ `ReasonTrail Runtime\n` +
1240
+ ` Instance ${cfg.origin}\n` +
1241
+ ` Credential ${prefix}… (stored, not shown)\n` +
1242
+ ` Workspaces ${cfg.workspaces?.length ? cfg.workspaces.join(", ") : "none — map them in ReasonTrail after connecting"}\n` +
1243
+ ` Bundle ${RUNTIME_BUNDLE}\n\n` +
1244
+ `Live status — protocol, workers, readiness — is shown by ReasonTrail itself,\n` +
1245
+ `which is the authority on all three. This command reports local setup only.\n`
1246
+ );
1247
+ return;
1248
+ }
1249
+
1250
+ if (sub === "logout") {
1251
+ await rm(runtimeFile, { force: true });
1252
+ stdout.write("Local runtime enrollment removed. Revoke the credential in ReasonTrail to disable it server-side.\n");
1253
+ return;
1254
+ }
1255
+
1256
+ if (sub === "start") {
1257
+ const cfg = await runtimeConfig(target.profile);
1258
+ if (!cfg?.origin || !cfg?.token) {
1259
+ throw new CliError("This machine is not enrolled. Run `reasontrail runtime enroll --url … --token …` first.", 2);
1260
+ }
1261
+ // Re-prove a possibly copied enrollment before handing its token to a child.
1262
+ 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.`);
1267
+ }
1268
+
1269
+ const args = [RUNTIME_BUNDLE, "run"];
1270
+ for (const workspace of cfg.workspaces ?? []) args.push("--workspace", workspace);
1271
+ if (argv.includes("--once")) args.push("--once");
1272
+
1273
+ // The credential is passed through the environment of the child and never
1274
+ // written to a log or an argv anybody can read from `ps`.
1275
+ const result = spawnSync(process.execPath, args, {
1276
+ stdio: "inherit",
1277
+ env: { ...process.env, REASONTRAIL_URL: cfg.origin, REASONTRAIL_RUNTIME_TOKEN: cfg.token },
1278
+ });
1279
+ if (result.error) throw new CliError(`Could not start the runtime: ${result.error.message}`);
1280
+ process.exitCode = result.status ?? 0;
1281
+ return;
1282
+ }
1283
+
1284
+ throw new CliError(`Unknown runtime command '${sub}'.\n\n` + runtimeUsage(), 2);
1285
+ }
1286
+
1287
+ function helpCommand() {
1288
+ stdout.write(`ReasonTrail CLI ${VERSION}\n\n` +
1289
+ `Usage: reasontrail <command> --profile <development|production>\n\n` +
1290
+ ` status Real backend and project status\n` +
1291
+ ` doctor Safe installation diagnostics\n` +
1292
+ ` login Persistent authentication\n` +
1293
+ ` auth login --device Browser-authorized device login\n` +
1294
+ ` auth login|logout|status Authentication management\n` +
1295
+ ` context --request <request> Bounded context (ladder first; --deep for the full pack)\n` +
1296
+ ` search --query <text> Bound-project Brain search (use --all-projects intentionally)\n` +
1297
+ ` update Submit structured JSON on stdin\n` +
1298
+ ` run "<task>" | --task <id> Start a Mission on the shared Runtime\n` +
1299
+ ` run status|stop|resume <id> Control one Runtime Mission\n` +
1300
+ ` decide <mission> <gate> <key> Answer an existing Mission gate\n` +
1301
+ ` . [--project <slug>] Bind the current Git repository\n` +
1302
+ ` install --platform <name> Install the assistant skill\n` +
1303
+ ` uninstall --platform <name> Remove the assistant skill\n` +
1304
+ ` 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` +
1307
+ ` hook claude Receive a Claude Code lifecycle hook event\n` +
1308
+ ` config endpoint <url> --profile <profile> Configure an isolated named profile\n` +
1309
+ ` runtime enroll|start|status|logout ReasonTrail Runtime on this machine\n` +
1310
+ ` upgrade Reserved until signed releases exist\n`);
1311
+ }
1312
+
1313
+ async function main() {
1314
+ const [command, ...argv] = process.argv.slice(2);
1315
+ if (command === "--version" || command === "-v" || argv.includes("--version") || argv.includes("-v")) {
1316
+ const build = await cliBuildIdentity();
1317
+ return stdout.write(`${VERSION} revision ${build.source_revision || "unknown"}\n`);
1318
+ }
1319
+ if (!command || command === "help" || command === "--help" || command === "-h") return helpCommand();
1320
+ if (argv.includes("--help") || argv.includes("-h") || argv[0] === "help") return helpCommand();
1321
+ if (command === "status") return statusCommand(argv);
1322
+ if (command === "doctor") return doctorCommand(argv);
1323
+ if (command === "context") return contextCommand(argv);
1324
+ if (command === "search") return searchCommand(argv);
1325
+ if (command === "update") return updateCommand(argv);
1326
+ if (command === "run") return runCommand(argv);
1327
+ if (command === "decide") return decideCommand(argv);
1328
+ if (command === ".") return bindCommand(argv);
1329
+ if (command === "auth") return authCommand(argv);
1330
+ if (command === "login") return authCommand(["login", ...argv]);
1331
+ if (command === "install") return installCommand(argv);
1332
+ if (command === "uninstall") return installCommand(argv, true);
1333
+ if (command === "setup") return setupCommand(argv);
1334
+ if (command === "sync") return syncCommand(argv);
1335
+ if (command === "hook" && argv[0] === "claude") return claudeHookCommand(argv.slice(1));
1336
+ if (command === "config") return configCommand(argv);
1337
+ if (command === "runtime") return runtimeCommand(argv);
1338
+ if (command === "upgrade") throw new CliError("Automatic upgrade is unavailable until versioned signed artifacts are published. No changes were made.", 2);
1339
+ throw new CliError(`Unknown command '${command}'. Run \`reasontrail help\`.`, 2);
1340
+ }
1341
+
1342
+ main().catch((error) => {
1343
+ const isStatus = process.argv[2] === "status";
1344
+ const payload = {
1345
+ available: isStatus ? false : error?.details?.kind === "transport" ? false : undefined,
1346
+ authenticated: error?.details?.status === 401 || error?.details?.status === 403 || error?.details?.kind === "credential_missing" ? false : undefined,
1347
+ ...(isStatus ? {
1348
+ project_bound: false,
1349
+ project_id: null,
1350
+ tenant_id: null,
1351
+ read_available: false,
1352
+ write_available: false,
1353
+ } : {}),
1354
+ transport: "cli",
1355
+ error: error instanceof Error ? error.message : String(error),
1356
+ ...(error?.details?.status ? { http_status: error.details.status } : {}),
1357
+ ...(error?.details?.projects ? { projects: error.details.projects } : {}),
1358
+ };
1359
+ output(Object.fromEntries(Object.entries(payload).filter(([, value]) => value !== undefined)));
1360
+ process.exitCode = error?.exitCode || 1;
1361
+ });