The best way to control Claude Code, Codex and more from any computer or phone

main
ts 214 lines 8.55 KB
Raw
1 import { DATABASE_COMPACTION_RECOMMENDED_BYTES } from "@t3tools/contracts";
2 import * as Clock from "effect/Clock";
3 import * as Console from "effect/Console";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 import * as Option from "effect/Option";
7 import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
8
9 import * as BootService from "../cloud/bootService.ts";
10 import * as DatabaseMaintenance from "../persistence/DatabaseMaintenance.ts";
11 import * as ServerOwnership from "../serverOwnership.ts";
12 import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
13 import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
14 import * as CliService from "./service.ts";
15
16 const formatBytes = (bytes: number) =>
17 bytes >= 1024 ** 3
18 ? `${(bytes / 1024 ** 3).toFixed(2)} GiB`
19 : bytes >= 1024 ** 2
20 ? `${(bytes / 1024 ** 2).toFixed(1)} MiB`
21 : `${Math.ceil(bytes / 1024)} KiB`;
22
23 const formatElapsed = (nanos: bigint) => {
24 const seconds = Number(nanos / 1_000_000_000n);
25 return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
26 };
27
28 const COMPACT_STEP_LABELS: Record<DatabaseMaintenance.DatabaseCompactStep, string> = {
29 "prune-events": "Removing superseded events",
30 vacuum: "Rewriting the database file",
31 "rebuild-search": "Rebuilding the search index",
32 checkpoint: "Flushing the write-ahead log",
33 };
34
35 // Holding the server lock refuses a server launched mid-repair, such as one started over SSH.
36 // Lock only: acquireServerOwnership would also refuse the older service doctor just stopped.
37 const lockServerHome = Effect.fn("runDoctor.lockServerHome")(function* (paths: {
38 readonly dbPath: string;
39 readonly serverRuntimeStatePath: string;
40 }) {
41 yield* ServerOwnership.holdServerOwnershipLock(paths.serverRuntimeStatePath).pipe(
42 Effect.catchTags({
43 ServerAlreadyRunningError: Effect.fn("runDoctor.nameServerHolder")(function* (cause) {
44 const owner = yield* readPersistedServerRuntimeState(paths.serverRuntimeStatePath).pipe(
45 Effect.map(Option.filter((state) => isProcessAlive(state.pid))),
46 Effect.orElseSucceed(() => Option.none()),
47 );
48 return yield* new DatabaseMaintenance.DatabaseInUseError({
49 path: paths.dbPath,
50 cause,
51 ...(Option.isSome(owner) && {
52 pid: owner.value.pid,
53 serviceManaged: owner.value.serviceManaged === true,
54 }),
55 });
56 }),
57 }),
58 );
59 });
60
61 export const runDoctor = Effect.fn("runDoctor")(function* (
62 paths: { readonly dbPath: string; readonly serverRuntimeStatePath: string },
63 options: { readonly fix: boolean; readonly dryRun: boolean; readonly interactive?: boolean },
64 ) {
65 const databasePath = paths.dbPath;
66 const maintenance = yield* DatabaseMaintenance.DatabaseMaintenance;
67 const status = yield* maintenance.inspect(databasePath);
68 yield* Console.log(
69 `Database: ${formatBytes(status.databaseBytes)}, ${formatBytes(status.reclaimableBytes)} reclaimable.`,
70 );
71 const legacyRecords = status.legacyOnlyRecords;
72 if (status.legacyDatabaseBytes !== null) {
73 yield* Console.log(
74 `Database from before 0.1.0: ${formatBytes(status.legacyDatabaseBytes)}, kept for rolling back.`,
75 );
76 if (legacyRecords === null) {
77 yield* Console.log(
78 " Could not check for missing projects or threads. Keep the old database.",
79 );
80 } else if (legacyRecords.projects > 0 || legacyRecords.threads > 0) {
81 yield* Console.log(
82 ` The current database is missing legacy records. Projects missing: ${legacyRecords.projects}. Threads missing: ${legacyRecords.threads}. Keep the old database for recovery.`,
83 );
84 }
85 }
86 const repairs = [
87 ...(status.incrementalVacuumEnabled && status.reclaimableBytes === 0
88 ? []
89 : [
90 {
91 id: "database" as const,
92 title: "Reclaim database space",
93 description: `${
94 status.incrementalVacuumEnabled
95 ? "Returns unused space to disk."
96 : "Returns unused space to disk and turns on automatic shrinking."
97 }\n Rewrites the whole ${formatBytes(status.databaseBytes)} database, which can take more than an hour on a large database or slow disk.\n Pauses the background service, if installed, while it runs and may need temporary disk space.`,
98 recommended:
99 !status.incrementalVacuumEnabled ||
100 status.reclaimableBytes >= DATABASE_COMPACTION_RECOMMENDED_BYTES,
101 },
102 ]),
103 ...(status.legacyDatabaseBytes === null ||
104 legacyRecords === null ||
105 legacyRecords.projects > 0 ||
106 legacyRecords.threads > 0
107 ? []
108 : [
109 {
110 id: "legacy" as const,
111 title: "Delete the database from before 0.1.0",
112 description: `Frees ${formatBytes(status.legacyDatabaseBytes)}.\n Warning: after this, a T3 Code version before 0.1.0 starts with no threads or settings, so you can no longer roll back.`,
113 recommended: false,
114 },
115 ]),
116 ];
117 if (repairs.length === 0) {
118 yield* Console.log("Nothing to repair.");
119 return;
120 }
121 for (const repair of repairs) {
122 yield* Console.log(
123 `\n${repair.title}${repair.recommended ? " (recommended)" : ""}\n ${repair.description}`,
124 );
125 }
126 if (options.dryRun) {
127 yield* Console.log("\nDry run: nothing changed.");
128 return;
129 }
130 const interactive = options.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
131 if (!options.fix && !interactive) {
132 yield* Console.log(
133 "\nRun in a terminal to choose repairs, or pass --fix for the recommended ones.",
134 );
135 return;
136 }
137 const selected = options.fix
138 ? repairs.filter((repair) => repair.recommended).map((repair) => repair.id)
139 : yield* Prompt.run(
140 Prompt.MultiSelect({
141 message: "Choose repairs to run",
142 choices: repairs.map((repair) => ({
143 title: repair.title + (repair.recommended ? " (recommended)" : ""),
144 value: repair.id,
145 selected: repair.recommended,
146 })),
147 }),
148 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed([]) }));
149 if (selected.length === 0) {
150 yield* Console.log(
151 options.fix
152 ? "No recommended repairs; nothing changed."
153 : "No repairs selected; nothing changed.",
154 );
155 return;
156 }
157 if (selected.includes("database")) {
158 const service = yield* BootService.BootService;
159 yield* Console.log("\nReclaiming database space. Each step is shown as it starts.");
160 const startedAt = yield* Clock.monotonicTimeNanos;
161 const reportStep = (step: DatabaseMaintenance.DatabaseCompactStep) =>
162 Clock.monotonicTimeNanos.pipe(
163 Effect.flatMap((now) =>
164 Console.log(` [${formatElapsed(now - startedAt)}] ${COMPACT_STEP_LABELS[step]}`),
165 ),
166 );
167 // Report the repair before restarting, which can fail independently.
168 yield* service.withStopped(
169 lockServerHome(paths).pipe(
170 Effect.andThen(maintenance.compact(databasePath, reportStep)),
171 Effect.tap((result) =>
172 Clock.monotonicTimeNanos.pipe(
173 Effect.flatMap((now) =>
174 Console.log(
175 `Done in ${formatElapsed(now - startedAt)}: ${formatBytes(result.beforeBytes)} -> ${formatBytes(result.afterBytes)}, ${result.deletedEventCount} superseded events removed.`,
176 ),
177 ),
178 ),
179 ),
180 Effect.scoped,
181 ),
182 );
183 }
184 if (selected.includes("legacy")) {
185 // Only pre-0.1.0 servers use this file; removal refuses while they hold it open.
186 yield* maintenance.removeLegacyDatabase(databasePath);
187 yield* Console.log("\nDeleted the database from before 0.1.0.");
188 }
189 });
190
191 export const doctorCommand = Command.make("doctor", {
192 ...projectLocationFlags,
193 fix: Flag.Boolean("fix").pipe(
194 Flag.withDescription("Apply the recommended repairs without prompting."),
195 Flag.withDefault(false),
196 ),
197 dryRun: Flag.Boolean("dry-run").pipe(
198 Flag.withDescription("Show the repairs without changing anything, even with --fix."),
199 Flag.withDefault(false),
200 ),
201 }).pipe(
202 Command.withDescription(
203 "Inspect this T3 Code data directory and repair it. Pauses and restarts the background service as needed.",
204 ),
205 Command.withHandler((flags) =>
206 Effect.gen(function* () {
207 const logLevel = yield* GlobalFlag.LogLevel;
208 const config = yield* resolveCliAuthConfig(flags, logLevel);
209 yield* runDoctor(config, { fix: flags.fix, dryRun: flags.dryRun }).pipe(
210 Effect.provide(Layer.merge(DatabaseMaintenance.layer, CliService.layer(config))),
211 );
212 }),
213 ),
214 );