The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 02:00 UTC
feat: Settings reclaims freed database space in one click (#32941)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Nov 8, 2026 at 16:38 UTC
8969e1d8d0433be9e598d122431c54c69e0aa83c
15 files changed
+607
-64
apps/server/src/cli/server.ts
+10
-1
@@ -8,6 +8,7 @@ import * as CliError from "effect/cli/CliError";
8
9
import * as ServerConfig from "../config.ts";
10
import { awaitLauncherLoss } from "../launcherWatch.ts";
11
+import * as DatabaseMaintenance from "../persistence/DatabaseMaintenance.ts";
12
import * as ProcessRunner from "../processRunner.ts";
13
import * as AutomaticPort from "./automaticPort.ts";
14
import { type CliServerFlags, resolveServerConfig, sharedServerCommandFlags } from "./config.ts";
@@ -34,7 +35,15 @@ const runServerCommand = Effect.fn("server.runServerCommand")(function* (
35
const logLevel = yield* GlobalFlag.LogLevel;
36
const selectAutomaticPort = yield* AutomaticPort.make.pipe(Effect.provide(ProcessRunner.layer));
37
const config = yield* resolveServerConfig(flags, logLevel, { ...options, selectAutomaticPort });
37
- const run = runServer.pipe(Effect.provideService(ServerConfig.ServerConfig, config));
38
+ const run = runServer.pipe(
39
+ Effect.provideService(ServerConfig.ServerConfig, config),
40
+ // Settings' Reclaim stops the server; repair once the database is closed, before the restart.
41
+ Effect.ensuring(
42
+ DatabaseMaintenance.runRequestedReclaim(config.dbPath).pipe(
43
+ Effect.provide(DatabaseMaintenance.layer),
44
+ ),
45
+ ),
46
+ );
47
if (config.mode !== "desktop" || config.desktopBootstrapToken === undefined) return yield* run;
48
yield* Effect.sync(() => {
49
process.stdout.on("error", ignoreClosedLauncherPipe);
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -62,6 +62,7 @@ const RPC_AGGREGATES = {
62
[WS_METHODS.serverRunStorageCleanup]: "server",
63
[WS_METHODS.serverGetStorageCleanupReport]: "server",
64
[WS_METHODS.serverGetDatabaseStorage]: "server",
65
+ [WS_METHODS.serverReclaimDatabaseSpace]: "server",
66
[WS_METHODS.peerLinksList]: "peerLinks",
67
[WS_METHODS.peerLinksLink]: "peerLinks",
68
[WS_METHODS.peerLinksUnlink]: "peerLinks",
apps/server/src/persistence/DatabaseMaintenance.test.ts
+71
@@ -101,6 +101,77 @@ it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer)))
101
}).pipe(Effect.scoped),
102
);
103
104
+ it.effect("runs a repair requested from Settings once and keeps its failure for Settings", () =>
105
+ Effect.gen(function* () {
106
+ const fs = yield* FileSystem.FileSystem;
107
+ const path = yield* Path.Path;
108
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-requested-reclaim-" });
109
+ const dbPath = path.join(baseDir, "userdata", "statev2.sqlite");
110
+ const files = DatabaseMaintenance.reclaimFiles(path, dbPath);
111
+ yield* Effect.void.pipe(Effect.provide(Sqlite.layerFromPath(dbPath)));
112
+ const autoVacuum = Effect.flatMap(
113
+ SqlClient.SqlClient,
114
+ (sql) => sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`,
115
+ ).pipe(
116
+ Effect.map((rows) => rows[0]?.auto_vacuum),
117
+ Effect.provide(NodeSqliteClient.layer({ filename: dbPath, readonly: true })),
118
+ );
119
+ yield* Effect.gen(function* () {
120
+ const sql = yield* SqlClient.SqlClient;
121
+ yield* sql`PRAGMA auto_vacuum = NONE`;
122
+ yield* sql`VACUUM`;
123
+ yield* sql`CREATE TABLE retained_data (value TEXT)`;
124
+ yield* sql`INSERT INTO retained_data VALUES ('keep')`;
125
+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath })));
126
+
127
+ // Every server exit runs this; without a request it must leave the database alone.
128
+ yield* DatabaseMaintenance.runRequestedReclaim(dbPath);
129
+ assert.equal(yield* autoVacuum, 0);
130
+
131
+ yield* fs.writeFileString(files.request, "");
132
+ yield* fs.writeFileString(files.failure, "an earlier failure");
133
+ yield* DatabaseMaintenance.runRequestedReclaim(dbPath);
134
+ assert.isFalse(yield* fs.exists(files.request));
135
+ assert.isFalse(yield* fs.exists(files.failure));
136
+ assert.equal(yield* autoVacuum, 2);
137
+ yield* Effect.gen(function* () {
138
+ const sql = yield* SqlClient.SqlClient;
139
+ assert.deepEqual(yield* sql`SELECT value FROM retained_data`, [{ value: "keep" }]);
140
+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath, readonly: true })));
141
+
142
+ const brokenPath = path.join(baseDir, "broken", "statev2.sqlite");
143
+ const broken = DatabaseMaintenance.reclaimFiles(path, brokenPath);
144
+ yield* fs.makeDirectory(path.dirname(brokenPath));
145
+ yield* fs.writeFileString(brokenPath, "not a database");
146
+ yield* fs.writeFileString(broken.request, "");
147
+ yield* DatabaseMaintenance.runRequestedReclaim(brokenPath);
148
+ assert.isFalse(
149
+ yield* fs.exists(broken.request),
150
+ "a failed repair must not rerun on every exit",
151
+ );
152
+ assert.equal(
153
+ yield* fs.readFileString(broken.failure),
154
+ new DatabaseMaintenance.DatabaseCompactError({ path: brokenPath, cause: null }).message,
155
+ );
156
+ }).pipe(Effect.scoped),
157
+ );
158
+
159
+ it.effect("refuses a repair whose copies would not fit on disk", () =>
160
+ Effect.gen(function* () {
161
+ const fs = yield* FileSystem.FileSystem;
162
+ const path = yield* Path.Path;
163
+ const dbPath = path.join(
164
+ yield* fs.makeTempDirectoryScoped({ prefix: "t3-reclaim-space-" }),
165
+ "statev2.sqlite",
166
+ );
167
+ assert.isNull(yield* DatabaseMaintenance.reclaimSpaceShortfall(dbPath, 1024));
168
+ const huge = 2 ** 60;
169
+ const shortfall = yield* DatabaseMaintenance.reclaimSpaceShortfall(dbPath, huge);
170
+ assert.isAtLeast(shortfall?.neededBytes ?? 0, huge);
171
+ assert.isBelow(shortfall?.freeBytes ?? Infinity, huge);
172
+ }).pipe(Effect.scoped),
173
+ );
174
+
175
it.effect("compacts an existing database offline only once its server has stopped", () =>
176
Effect.gen(function* () {
177
const fs = yield* FileSystem.FileSystem;
apps/server/src/persistence/DatabaseMaintenance.ts
+114
@@ -4,8 +4,13 @@ import * as Context from "effect/Context";
4
import * as Effect from "effect/Effect";
5
import * as FileSystem from "effect/FileSystem";
6
import * as Layer from "effect/Layer";
7
+import * as Option from "effect/Option";
8
import * as Path from "effect/Path";
9
+import * as Schedule from "effect/Schedule";
10
import * as Schema from "effect/Schema";
11
+// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect has no free-space query.
12
+import * as NodeFSP from "node:fs/promises";
13
+import * as NodeOS from "node:os";
14
import * as SqlClient from "effect/sql/SqlClient";
15
import { isSqlError } from "effect/sql/SqlError";
16
@@ -57,6 +62,15 @@ export class LegacyDatabaseRemoveError extends Schema.TaggedError<LegacyDatabase
62
}
63
}
64
65
+export class DiskSpaceCheckError extends Schema.TaggedError<DiskSpaceCheckError>()(
66
+ "DiskSpaceCheckError",
67
+ { path: Schema.String, cause: Schema.Defect() },
68
+) {
69
+ override get message() {
70
+ return "Could not check free disk space.";
71
+ }
72
+}
73
+
74
export class DatabaseMaintenance extends Context.Service<
75
DatabaseMaintenance,
76
{
@@ -230,3 +244,103 @@ const make = Effect.gen(function* () {
244
});
245
246
export const layer = Layer.effect(DatabaseMaintenance, make);
247
+
248
+/** Settings' Reclaim writes the request; the failure stays for Settings until the next request. */
249
+export const reclaimFiles = (path: Path.Path, databasePath: string) => ({
250
+ request: path.join(path.dirname(databasePath), "reclaim-requested"),
251
+ failure: path.join(path.dirname(databasePath), "reclaim-failed"),
252
+});
253
+
254
+/** Runs a repair that Settings requested. The server calls this on exit, once its database is closed. */
255
+export const runRequestedReclaim = Effect.fn("DatabaseMaintenance.runRequestedReclaim")(
256
+ function* (databasePath: string) {
257
+ const fs = yield* FileSystem.FileSystem;
258
+ const files = reclaimFiles(yield* Path.Path, databasePath);
259
+ if (!(yield* fs.exists(files.request))) return;
260
+ // One attempt per request, so a repair killed midway (it rolls back) cannot delay later exits.
261
+ yield* fs.remove(files.request, { force: true });
262
+ yield* Effect.logInfo("Reclaiming database space before the restart. This can take minutes.");
263
+ const maintenance = yield* DatabaseMaintenance;
264
+ yield* maintenance.compact(databasePath).pipe(
265
+ // Worker threads and agent processes can hold the file for a moment after the server stops.
266
+ Effect.retry({
267
+ times: 10,
268
+ while: (error) => error._tag === "DatabaseInUseError",
269
+ schedule: Schedule.spaced("1 second"),
270
+ }),
271
+ Effect.matchEffect({
272
+ onSuccess: (result) =>
273
+ fs
274
+ .remove(files.failure, { force: true })
275
+ .pipe(Effect.andThen(Effect.logInfo("Reclaimed database space", result))),
276
+ onFailure: (error) =>
277
+ fs
278
+ .writeFileString(
279
+ files.failure,
280
+ error._tag === "DatabaseInUseError"
281
+ ? "Another program kept the database open. Close other T3 Code apps and t3 commands on this machine, then try again."
282
+ : error.message,
283
+ )
284
+ .pipe(
285
+ Effect.andThen(Effect.logWarning("Database space reclamation failed", { error })),
286
+ ),
287
+ }),
288
+ );
289
+ },
290
+ Effect.catchCause((cause) => Effect.logWarning("Database space reclamation failed", { cause })),
291
+);
292
+
293
+// SQLite's search order for its temporary files (unixTempFileDir in os_unix.c).
294
+const sqliteTempDirectory = Effect.gen(function* () {
295
+ if ((yield* HostProcess.Platform) === "win32") return NodeOS.tmpdir();
296
+ const fs = yield* FileSystem.FileSystem;
297
+ const env = yield* HostProcess.Environment;
298
+ for (const directory of [env.SQLITE_TMPDIR, env.TMPDIR, "/var/tmp", "/usr/tmp", "/tmp"]) {
299
+ if (directory === undefined || directory === "") continue;
300
+ const info = yield* fs.stat(directory).pipe(Effect.option);
301
+ if (Option.isNone(info) || info.value.type !== "Directory") continue;
302
+ // SQLite skips directories it cannot write to and search: osAccess(zDir, 03).
303
+ const usable = yield* Effect.tryPromise({
304
+ try: () => NodeFSP.access(directory, NodeFSP.constants.W_OK | NodeFSP.constants.X_OK),
305
+ catch: (cause) => new DiskSpaceCheckError({ path: directory, cause }),
306
+ }).pipe(
307
+ Effect.as(true),
308
+ Effect.orElseSucceed(() => false),
309
+ );
310
+ if (usable) return directory;
311
+ }
312
+ return ".";
313
+});
314
+
315
+const freeBytes = (directory: string) =>
316
+ Effect.tryPromise({
317
+ try: () => NodeFSP.statfs(directory),
318
+ catch: (cause) => new DiskSpaceCheckError({ path: directory, cause }),
319
+ }).pipe(Effect.map((stats) => stats.bavail * stats.bsize));
320
+
321
+/**
322
+ * VACUUM copies the live pages to a temporary file, then writes them again to the WAL.
323
+ * Returns the free space the repair needs when either file system has less, else null.
324
+ */
325
+export const reclaimSpaceShortfall = Effect.fn("DatabaseMaintenance.reclaimSpaceShortfall")(
326
+ function* (databasePath: string, liveBytes: number) {
327
+ const fs = yield* FileSystem.FileSystem;
328
+ const path = yield* Path.Path;
329
+ const databaseDirectory = path.dirname(databasePath);
330
+ const tempDirectory = yield* sqliteTempDirectory;
331
+ const copyBytes = Math.ceil(liveBytes * 1.1);
332
+ const [databaseFree, tempFree, databaseDevice, tempDevice] = yield* Effect.all([
333
+ freeBytes(databaseDirectory),
334
+ freeBytes(tempDirectory),
335
+ fs.stat(databaseDirectory).pipe(Effect.map((info) => info.dev)),
336
+ fs.stat(tempDirectory).pipe(Effect.map((info) => info.dev)),
337
+ ]);
338
+ if (databaseDevice === tempDevice) {
339
+ return databaseFree < 2 * copyBytes
340
+ ? { neededBytes: 2 * copyBytes, freeBytes: databaseFree }
341
+ : null;
342
+ }
343
+ if (databaseFree < copyBytes) return { neededBytes: copyBytes, freeBytes: databaseFree };
344
+ return tempFree < copyBytes ? { neededBytes: copyBytes, freeBytes: tempFree } : null;
345
+ },
346
+);
apps/server/src/persistence/DatabaseStorage.test.ts
+72
@@ -5,11 +5,14 @@ import * as Effect from "effect/Effect";
5
import * as FileSystem from "effect/FileSystem";
6
import * as Layer from "effect/Layer";
7
import * as Path from "effect/Path";
8
+import * as Option from "effect/Option";
9
+import * as Stream from "effect/Stream";
10
import * as TestClock from "effect/testing/TestClock";
11
import * as SqlClient from "effect/sql/SqlClient";
12
13
import * as ServerConfig from "../config.ts";
14
import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
15
+import * as DatabaseMaintenance from "./DatabaseMaintenance.ts";
16
import * as DatabaseStorage from "./DatabaseStorage.ts";
17
import * as Sqlite from "./Sqlite.ts";
18
@@ -109,3 +112,72 @@ it.effect("remembers completion only after the paced pass finishes", () =>
112
);
113
}).pipe(Effect.provide(testConfig.pipe(Layer.provideMerge(NodeServices.layer)))),
114
);
115
+
116
+// NONE is a database from before automatic shrinking, which the repair converts.
117
+const reclaimLayer = (
118
+ restart: Effect.Effect<void> | null,
119
+ autoVacuum: "NONE" | "FULL" | "INCREMENTAL" = "NONE",
120
+) =>
121
+ DatabaseStorage.layer.pipe(
122
+ Layer.provide(ProjectionMaintenance.layer),
123
+ Layer.provide(Layer.succeed(DatabaseStorage.ServerRestart, restart)),
124
+ Layer.provide(
125
+ Layer.effectDiscard(
126
+ Effect.gen(function* () {
127
+ const sql = yield* SqlClient.SqlClient;
128
+ yield* sql.unsafe(`PRAGMA auto_vacuum = ${autoVacuum}`);
129
+ yield* sql`VACUUM`;
130
+ }),
131
+ ).pipe(Layer.provideMerge(Sqlite.layerMemory)),
132
+ ),
133
+ );
134
+
135
+it.effect(
136
+ "a reclaim from Settings saves its request, then restarts the server after replying",
137
+ () =>
138
+ Effect.gen(function* () {
139
+ const fs = yield* FileSystem.FileSystem;
140
+ const path = yield* Path.Path;
141
+ const config = yield* ServerConfig.ServerConfig;
142
+ const files = DatabaseMaintenance.reclaimFiles(path, config.dbPath);
143
+ const request = Effect.flatMap(
144
+ DatabaseStorage.DatabaseStorage,
145
+ (storage) => storage.requestReclaim,
146
+ );
147
+ const restarted = yield* Deferred.make<void>();
148
+ const restart = Deferred.succeed(restarted, undefined).pipe(Effect.asVoid);
149
+
150
+ // Nothing starts a server run by hand again, so it keeps pointing at the command.
151
+ const unsupervised = yield* request.pipe(Effect.flip, Effect.provide(reclaimLayer(null)));
152
+ assert.equal(unsupervised._tag, "DatabaseReclaimError");
153
+ // A database that already shrinks on its own (or a stale dialog after another client's
154
+ // repair) has nothing to reclaim, so it must not restart.
155
+ for (const autoVacuum of ["FULL", "INCREMENTAL"] as const) {
156
+ const refused = yield* request.pipe(
157
+ Effect.flip,
158
+ Effect.provide(reclaimLayer(restart, autoVacuum)),
159
+ );
160
+ assert.equal(refused._tag, "DatabaseReclaimError", autoVacuum);
161
+ }
162
+ assert.isFalse(yield* fs.exists(files.request));
163
+
164
+ yield* fs.writeFileString(files.failure, "an earlier failure");
165
+ yield* Effect.gen(function* () {
166
+ const storage = yield* DatabaseStorage.DatabaseStorage;
167
+ const shownFailure = storage.status.pipe(
168
+ Stream.filter((status) => status !== null),
169
+ Stream.runHead,
170
+ Effect.map((status) => Option.getOrThrow(status)?.reclaimFailure),
171
+ );
172
+ assert.equal(yield* shownFailure, "an earlier failure");
173
+ yield* storage.requestReclaim;
174
+ // The retry clears it at once, so Settings shows the restart, not the old failure.
175
+ assert.isUndefined(yield* shownFailure);
176
+ }).pipe(Effect.provide(reclaimLayer(restart)));
177
+ assert.isTrue(yield* fs.exists(files.request));
178
+ assert.isFalse(yield* fs.exists(files.failure));
179
+ assert.isFalse(yield* Deferred.isDone(restarted), "the reply must go out before the restart");
180
+ yield* TestClock.adjust(500);
181
+ yield* Deferred.await(restarted);
182
+ }).pipe(Effect.provide(testConfig.pipe(Layer.provideMerge(NodeServices.layer)))),
183
+);
apps/server/src/persistence/DatabaseStorage.ts
+92
-7
@@ -1,4 +1,4 @@
1
-import type { DatabaseStorageStatus } from "@t3tools/contracts";
1
+import { DatabaseReclaimError, type DatabaseStorageStatus } from "@t3tools/contracts";
2
import * as Clock from "effect/Clock";
3
import * as Context from "effect/Context";
4
import * as Duration from "effect/Duration";
@@ -6,6 +6,7 @@ import * as Effect from "effect/Effect";
6
import * as Equal from "effect/Equal";
7
import * as FileSystem from "effect/FileSystem";
8
import * as Layer from "effect/Layer";
9
+import * as Option from "effect/Option";
10
import * as Path from "effect/Path";
11
import * as Schedule from "effect/Schedule";
12
import * as Stream from "effect/Stream";
@@ -15,6 +16,7 @@ import * as SqlClient from "effect/sql/SqlClient";
16
import { resolveHostCliCommand } from "../cli/invocation.ts";
17
import * as ServerConfig from "../config.ts";
18
import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
19
+import * as DatabaseMaintenance from "./DatabaseMaintenance.ts";
20
import { forkParked } from "../serverActivation.ts";
21
22
// Bound each reclaim pass to one minute of churn.
@@ -28,9 +30,19 @@ export class DatabaseStorage extends Context.Service<
30
readonly reclaim: Effect.Effect<void>;
31
/** Current file accounting, re-published after each maintenance pass. Null until first read. */
32
readonly status: Stream.Stream<DatabaseStorageStatus | null>;
33
+ /** Checks free space, then stops the server; its shutdown runs the offline repair. */
34
+ readonly requestReclaim: Effect.Effect<void, DatabaseReclaimError>;
35
}
36
>()("t3/persistence/DatabaseStorage") {}
37
38
+/** Stops this server so its desktop app or background service starts it again; null when run by hand. */
39
+export const ServerRestart = Context.Reference<Effect.Effect<void> | null>(
40
+ "t3/persistence/DatabaseStorage/ServerRestart",
41
+ { defaultValue: () => null },
42
+);
43
+
44
+const formatGiB = (bytes: number) => `${(bytes / 1024 ** 3).toFixed(1)} GiB`;
45
+
46
const make = Effect.gen(function* () {
47
const sql = yield* SqlClient.SqlClient;
48
const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
@@ -38,6 +50,11 @@ const make = Effect.gen(function* () {
50
const fs = yield* FileSystem.FileSystem;
51
const path = yield* Path.Path;
52
const statusRef = yield* SubscriptionRef.make<DatabaseStorageStatus | null>(null);
53
+ const restart = yield* ServerRestart;
54
+ const reclaimFiles = DatabaseMaintenance.reclaimFiles(path, config.dbPath);
55
+ let reclaimFailure = Option.getOrUndefined(
56
+ yield* fs.readFileString(reclaimFiles.failure).pipe(Effect.option),
57
+ );
58
59
// The notice shows host-shell quoting verbatim; desktop needs its launcher because t3 is absent from PATH.
60
const { command: compactCommand } = yield* resolveHostCliCommand("doctor", [
@@ -49,30 +66,48 @@ const make = Effect.gen(function* () {
66
path.resolve(config.dbPath) ===
67
path.resolve(config.baseDir, "userdata", path.basename(config.dbPath));
68
// Only VACUUM changes these, and doctor refuses to VACUUM while a server has the database open.
52
- let layout: { readonly pageSize: number; readonly incrementalVacuum: boolean } | undefined;
69
+ let layout:
70
+ | {
71
+ readonly pageSize: number;
72
+ readonly autoVacuum: number;
73
+ readonly incrementalVacuum: boolean;
74
+ }
75
+ | undefined;
76
const readLayout = Effect.suspend(() =>
77
layout !== undefined
78
? Effect.succeed(layout)
79
: Effect.gen(function* () {
80
const size = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
81
const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;
82
+ const autoVacuum = mode[0]?.auto_vacuum ?? 0;
83
layout = {
84
pageSize: size[0]?.page_size ?? 0,
61
- incrementalVacuum: mode[0]?.auto_vacuum === 2,
85
+ autoVacuum,
86
+ incrementalVacuum: autoVacuum === 2,
87
};
88
return layout;
89
}),
90
);
66
- const publishStatus = Effect.gen(function* () {
67
- if (!doctorTargetsThisDatabase) return;
91
+ const readPages = Effect.gen(function* () {
92
const { pageSize, incrementalVacuum } = yield* readLayout;
93
const pages = yield* sql<{ readonly page_count: number }>`PRAGMA page_count`;
94
const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
71
- const next: DatabaseStorageStatus = {
95
+ return {
96
databaseBytes: (pages[0]?.page_count ?? 0) * pageSize,
97
reclaimableBytes: (free[0]?.freelist_count ?? 0) * pageSize,
98
+ incrementalVacuum,
99
+ };
100
+ });
101
+ const publishStatus = Effect.gen(function* () {
102
+ if (!doctorTargetsThisDatabase) return;
103
+ const { databaseBytes, reclaimableBytes, incrementalVacuum } = yield* readPages;
104
+ const next: DatabaseStorageStatus = {
105
+ databaseBytes,
106
+ reclaimableBytes,
107
incrementalVacuumEnabled: incrementalVacuum,
108
compactCommand,
109
+ canReclaim: restart !== null,
110
+ ...(reclaimFailure === undefined ? {} : { reclaimFailure }),
111
};
112
// Every set reaches each open Storage page; most passes change nothing.
113
if (!Equal.equals(yield* SubscriptionRef.get(statusRef), next)) {
@@ -149,7 +184,57 @@ const make = Effect.gen(function* () {
184
),
185
);
186
152
- return DatabaseStorage.of({ reclaim, status: SubscriptionRef.changes(statusRef) });
187
+ const requestReclaim = Effect.gen(function* () {
188
+ if (restart === null || !doctorTargetsThisDatabase) {
189
+ return yield* new DatabaseReclaimError({
190
+ reason: `Stop T3 Code on this machine, then run: ${compactCommand}`,
191
+ });
192
+ }
193
+ // Only databases without automatic shrinking need it; a stale dialog can ask after another client's repair.
194
+ if ((yield* readLayout).autoVacuum !== 0) {
195
+ return yield* new DatabaseReclaimError({
196
+ reason: "This database already shrinks on its own. Nothing to reclaim.",
197
+ });
198
+ }
199
+ const { databaseBytes, reclaimableBytes } = yield* readPages;
200
+ const shortfall = yield* DatabaseMaintenance.reclaimSpaceShortfall(
201
+ config.dbPath,
202
+ databaseBytes - reclaimableBytes,
203
+ ).pipe(
204
+ Effect.provideService(FileSystem.FileSystem, fs),
205
+ Effect.provideService(Path.Path, path),
206
+ );
207
+ if (shortfall !== null) {
208
+ return yield* new DatabaseReclaimError({
209
+ reason: `Reclaiming needs ${formatGiB(shortfall.neededBytes)} of free disk space on this machine. ${formatGiB(shortfall.freeBytes)} is free.`,
210
+ });
211
+ }
212
+ yield* fs.remove(reclaimFiles.failure, { force: true });
213
+ reclaimFailure = undefined;
214
+ yield* publishStatus;
215
+ const requestedAt = yield* Clock.currentTimeMillis;
216
+ // One step: a request interrupted between them would repair on some unrelated later exit.
217
+ yield* Effect.uninterruptible(
218
+ fs.writeFileString(reclaimFiles.request, String(requestedAt)).pipe(
219
+ // Reply before stopping: the restart closes this connection.
220
+ Effect.andThen(restart.pipe(Effect.delay("500 millis"), Effect.forkDetach)),
221
+ ),
222
+ );
223
+ yield* Effect.logInfo("Restarting to reclaim database space");
224
+ }).pipe(
225
+ Effect.mapError((cause) =>
226
+ cause._tag === "DatabaseReclaimError"
227
+ ? cause
228
+ : new DatabaseReclaimError({ reason: "Could not prepare the repair. Try again." }),
229
+ ),
230
+ Effect.withSpan("DatabaseStorage.requestReclaim"),
231
+ );
232
+
233
+ return DatabaseStorage.of({
234
+ reclaim,
235
+ status: SubscriptionRef.changes(statusRef),
236
+ requestReclaim,
237
+ });
238
});
239
240
export const layer = Layer.effect(DatabaseStorage, make);
apps/server/src/server.ts
+18
-1
@@ -627,13 +627,30 @@ const layerProviderInstallationRefresh = Layer.effectDiscard(
627
}),
628
);
629
630
+// The desktop app and the background service start the server again after it exits.
631
+const layerServerRestart = Layer.effect(
632
+ DatabaseStorage.ServerRestart,
633
+ Effect.gen(function* () {
634
+ const config = yield* ServerConfig.ServerConfig;
635
+ const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
636
+ // As in runServerCommand, only the desktop app passes a bootstrap token; `serve --mode desktop` by hand has no supervisor.
637
+ const desktopLaunched = config.mode === "desktop" && config.desktopBootstrapToken !== undefined;
638
+ if (!desktopLaunched && !launcher.managed) return null;
639
+ // Stop as a SIGTERM would: runMain's listener interrupts the server, so its shutdown path runs.
640
+ return Effect.sync(() => void process.emit("SIGTERM"));
641
+ }),
642
+);
643
+
644
const layerRuntimeCoreDependenciesBase = Layer.mergeAll(
645
AgentAwarenessRelay.layer,
646
HeldHooksWaker.layer,
647
layerThreadSettlementWorker,
648
layerIdleCompactionWorker,
649
StorageCleanup.layer.pipe(Layer.provide(ProjectionStoreV2.layer)),
636
- DatabaseStorage.layer.pipe(Layer.provide(ProjectionMaintenance.layer)),
650
+ DatabaseStorage.layer.pipe(
651
+ Layer.provide(ProjectionMaintenance.layer),
652
+ Layer.provide(layerServerRestart),
653
+ ),
654
layerThreadPullRequestWorker,
655
DelegatedTaskAnalytics.layer,
656
Layer.effectDiscard(
apps/server/src/ws.ts
+1
@@ -2692,6 +2692,7 @@ export const layerWsRpc = (
2692
[WS_METHODS.serverRunStorageCleanup]: () => storageCleanup.runNow,
2693
[WS_METHODS.serverGetStorageCleanupReport]: () => storageCleanup.reports,
2694
[WS_METHODS.serverGetDatabaseStorage]: () => databaseStorage.status,
2695
+ [WS_METHODS.serverReclaimDatabaseSpace]: () => databaseStorage.requestReclaim,
2696
[WS_METHODS.peerLinksList]: (_input) =>
2697
peerLinks.list.pipe(Effect.map((links) => ({ links }))),
2698
[WS_METHODS.peerLinksLink]: (input) => peerLinks.link(input),
apps/web/src/components/settings/DatabaseStorageNotice.tsx
+168
-37
@@ -1,70 +1,201 @@
1
import { useAtomValue } from "@effect/atom-react";
2
-import type { EnvironmentId } from "@t3tools/contracts";
2
+import {
3
+ isAtomCommandInterrupted,
4
+ squashAtomCommandFailure,
5
+} from "@t3tools/client-runtime/state/runtime";
6
+import {
7
+ databaseReclaimMinutes,
8
+ type DatabaseStorageStatus,
9
+ type EnvironmentId,
10
+} from "@t3tools/contracts";
11
import * as Schema from "effect/Schema";
12
+import { type ReactNode, useState } from "react";
13
14
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
15
import { useLocalStorage } from "../../hooks/useLocalStorage";
16
+import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
17
import { serverEnvironment } from "../../state/server";
18
+import { useAtomCommand } from "../../state/use-atom-command";
19
+import {
20
+ AlertDialog,
21
+ AlertDialogClose,
22
+ AlertDialogDescription,
23
+ AlertDialogFooter,
24
+ AlertDialogHeader,
25
+ AlertDialogPopup,
26
+ AlertDialogTitle,
27
+} from "../ui/alert-dialog";
28
import { Button } from "../ui/button";
29
+import { toastManager } from "../ui/toast";
30
import { SettingsRow, SettingsSection } from "./settingsLayout";
31
32
const DismissedEnvironmentIds = Schema.Array(Schema.String);
33
+const reclaimPermissionsAtom = environmentAtomList(
34
+ "web-database-reclaim-permissions",
35
+ serverEnvironment.reclaimDatabaseSpace.permissionAtom,
36
+);
37
13
-/** Suggests `t3 doctor` on every machine whose database still holds at least 1 GiB of freed pages. */
38
+const formatGiB = (bytes: number) => `${(bytes / 1024 ** 3).toFixed(1)} GiB`;
39
+
40
+/** Offers to reclaim the space on every machine whose database still holds at least 1 GiB of freed pages. */
41
export function DatabaseStorageNotice({
42
environments,
43
}: {
44
environments: ReadonlyArray<{ readonly environmentId: EnvironmentId; readonly label: string }>;
45
}) {
46
+ const environmentIds = environments.map((environment) => environment.environmentId);
47
const recommendations = useAtomValue(
20
- serverEnvironment.databaseCompactionRecommendations(
21
- JSON.stringify(environments.map((environment) => environment.environmentId)),
22
- ),
48
+ serverEnvironment.databaseCompactionRecommendations(JSON.stringify(environmentIds)),
49
);
50
+ const permissions = useAtomValue(reclaimPermissionsAtom(environmentIdsKey(environmentIds)));
51
const [dismissed, setDismissed] = useLocalStorage(
52
"database-storage-notice-dismissed",
53
[],
54
DismissedEnvironmentIds,
55
);
56
const { copyToClipboard } = useCopyToClipboard({ target: "command" });
30
- const visible = recommendations.filter(
31
- (recommendation) => !dismissed.includes(recommendation.environmentId),
32
- );
57
+ const visible = recommendations
58
+ .filter((recommendation) => !dismissed.includes(recommendation.environmentId))
59
+ .map((recommendation) => ({
60
+ ...recommendation,
61
+ label:
62
+ environments.find(
63
+ (environment) => environment.environmentId === recommendation.environmentId,
64
+ )?.label ?? recommendation.environmentId,
65
+ reclaimable:
66
+ recommendation.status.canReclaim === true &&
67
+ permissions[environmentIds.indexOf(recommendation.environmentId)] === true,
68
+ }));
69
if (visible.length === 0) return null;
70
return (
71
<SettingsSection id="storage-database" title="Database">
72
<SettingsRow
73
title="Reclaim freed database space"
38
- description="These databases still hold space freed by history cleanup. Run the command on each machine to reclaim it. It restarts the background service. Quit the desktop app first if it hosts the environment."
74
+ description={`These databases still hold space freed by history cleanup.${
75
+ visible.every((recommendation) => recommendation.reclaimable)
76
+ ? ""
77
+ : " Run the command on each machine to reclaim it. It restarts the background service. Quit the desktop app first if it hosts the environment."
78
+ }`}
79
/>
40
- {visible.map(({ environmentId, status }) => (
41
- <SettingsRow
42
- key={environmentId}
43
- title={`${(status.reclaimableBytes / 1024 ** 3).toFixed(1)} GiB on ${
44
- environments.find((environment) => environment.environmentId === environmentId)
45
- ?.label ?? environmentId
46
- }`}
47
- description={<code className="select-text break-all">{status.compactCommand}</code>}
48
- control={
49
- <div className="flex flex-wrap items-center gap-1.5">
50
- <Button
51
- variant="outline"
52
- size="xs"
53
- onClick={() => copyToClipboard(status.compactCommand, undefined)}
54
- >
55
- Copy command
56
- </Button>
57
- <Button
58
- variant="ghost"
59
- size="xs"
60
- onClick={() => setDismissed((current) => [...current, environmentId])}
61
- >
62
- Dismiss
63
- </Button>
64
- </div>
65
- }
66
- />
67
- ))}
80
+ {visible.map(({ environmentId, status, label, reclaimable }) => {
81
+ const dismiss = (
82
+ <Button
83
+ variant="ghost"
84
+ size="xs"
85
+ onClick={() => setDismissed((current) => [...current, environmentId])}
86
+ >
87
+ Dismiss
88
+ </Button>
89
+ );
90
+ return reclaimable ? (
91
+ <ReclaimRow
92
+ key={environmentId}
93
+ environmentId={environmentId}
94
+ label={label}
95
+ status={status}
96
+ dismiss={dismiss}
97
+ />
98
+ ) : (
99
+ <SettingsRow
100
+ key={environmentId}
101
+ title={`${formatGiB(status.reclaimableBytes)} on ${label}`}
102
+ description={<code className="select-text break-all">{status.compactCommand}</code>}
103
+ control={
104
+ <div className="flex flex-wrap items-center gap-1.5">
105
+ <Button
106
+ variant="outline"
107
+ size="xs"
108
+ onClick={() => copyToClipboard(status.compactCommand, undefined)}
109
+ >
110
+ Copy command
111
+ </Button>
112
+ {dismiss}
113
+ </div>
114
+ }
115
+ />
116
+ );
117
+ })}
118
</SettingsSection>
119
);
120
}
121
+
122
+function ReclaimRow({
123
+ environmentId,
124
+ label,
125
+ status,
126
+ dismiss,
127
+}: {
128
+ readonly environmentId: EnvironmentId;
129
+ readonly label: string;
130
+ readonly status: DatabaseStorageStatus;
131
+ readonly dismiss: ReactNode;
132
+}) {
133
+ const reclaim = useAtomCommand(serverEnvironment.reclaimDatabaseSpace);
134
+ const [confirming, setConfirming] = useState(false);
135
+ const [requested, setRequested] = useState(false);
136
+ // A failed repair reports back after the restart, which ends the wait.
137
+ const restarting = requested && status.reclaimFailure === undefined;
138
+ const minutes = databaseReclaimMinutes(status);
139
+ const amount = formatGiB(status.reclaimableBytes);
140
+ const start = async () => {
141
+ setConfirming(false);
142
+ setRequested(true);
143
+ const result = await reclaim({ environmentId, input: {} });
144
+ if (result._tag === "Success") {
145
+ toastManager.add({
146
+ type: "success",
147
+ title: `Reclaiming ${amount} on ${label}`,
148
+ description: `T3 Code there restarts and is back in about ${minutes} min.`,
149
+ });
150
+ return;
151
+ }
152
+ setRequested(false);
153
+ if (isAtomCommandInterrupted(result)) return;
154
+ const error = squashAtomCommandFailure(result);
155
+ toastManager.add({
156
+ type: "error",
157
+ title: `Could not reclaim space on ${label}`,
158
+ description: error instanceof Error ? error.message : "An error occurred.",
159
+ });
160
+ };
161
+ return (
162
+ <SettingsRow
163
+ title={`${amount} on ${label}`}
164
+ description={
165
+ status.reclaimFailure === undefined
166
+ ? `Restarts T3 Code there. It is offline for about ${minutes} min.`
167
+ : `The last attempt failed: ${status.reclaimFailure}`
168
+ }
169
+ control={
170
+ <div className="flex flex-wrap items-center gap-1.5">
171
+ <Button
172
+ variant="outline"
173
+ size="xs"
174
+ disabled={restarting}
175
+ onClick={() => setConfirming(true)}
176
+ >
177
+ {restarting ? "Restarting…" : "Reclaim"}
178
+ </Button>
179
+ {dismiss}
180
+ <AlertDialog open={confirming} onOpenChange={setConfirming}>
181
+ <AlertDialogPopup>
182
+ <AlertDialogHeader>
183
+ <AlertDialogTitle>
184
+ Reclaim {amount} on {label}?
185
+ </AlertDialogTitle>
186
+ <AlertDialogDescription>
187
+ T3 Code on {label} stops, rebuilds its database, and starts again. It is offline
188
+ for about {minutes} min. Running agents stop when it restarts.
189
+ </AlertDialogDescription>
190
+ </AlertDialogHeader>
191
+ <AlertDialogFooter>
192
+ <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
193
+ <Button onClick={() => void start()}>Restart and reclaim</Button>
194
+ </AlertDialogFooter>
195
+ </AlertDialogPopup>
196
+ </AlertDialog>
197
+ </div>
198
+ }
199
+ />
200
+ );
201
+}
docs/user/background-service.md
+13
-6
@@ -168,8 +168,15 @@ and turns on automatic shrinking. Settings > Maintenance (web and desktop) or
168
Settings > Maintenance (mobile) suggests the repair when at least 1 GiB can be
169
reclaimed.
170
171
-Run `t3 doctor` on the machine that hosts the environment. It reports the
172
-database size and the space it can reclaim, then asks which repairs to run;
171
+When the desktop app or the background service runs T3 Code on that machine,
172
+select **Reclaim** in Settings on web or desktop. T3 Code checks for free disk
173
+space, then stops, repairs the database, and starts again. It is offline while
174
+the repair runs, and running agents stop. If the repair fails, Settings shows
175
+why.
176
+
177
+In other cases, such as a server you started by hand, run `t3 doctor` on the
178
+machine that hosts the environment. It reports the database size and the
179
+space it can reclaim, then asks which repairs to run;
180
pass `--fix` to run the recommended ones without a prompt (for scripts), or
181
`--dry-run` to only report. An installed background service for the same data
182
directory is stopped for the repair and started again afterwards, also when
@@ -178,10 +185,10 @@ the repair refuses to touch a database that is in use. Use `--base-dir` for a
185
different data directory.
186
187
The repair can take several minutes on a large database. It rebuilds the
181
-database through a temporary copy, so it needs free space of about the
182
-database's size twice over: once in the system temporary directory (`TMPDIR`
183
-or `/tmp` on Linux and macOS) and once next to the database for its
184
-write-ahead log.
188
+database through a temporary copy, so it needs free space of about twice the
189
+data still in use (the database size minus the reclaimable space): once in the
190
+system temporary directory (on Linux and macOS, `TMPDIR`, or `/var/tmp` when it
191
+is not set) and once next to the database for its write-ahead log.
192
193
If you upgraded from a version before 0.1.0, its database (`state.sqlite`) is
194
still kept next to the current one so you can roll back. `t3 doctor` offers to
packages/client-runtime/src/state/commandPermissions.test.ts
+12
-12
@@ -9,6 +9,7 @@ import { vi } from "vite-plus/test";
9
import {
10
AuthAccessReadScope,
11
AuthAccessWriteScope,
12
+ AuthEnvironmentMaintainScope,
13
AuthOrchestrationOperateScope,
14
AuthOrchestrationReadScope,
15
AuthPreviewOperateScope,
@@ -157,28 +158,27 @@ describe("command permissions", () => {
158
),
159
);
160
160
- it.effect("requires the destination settings grant to run storage cleanup", () =>
161
+ it.effect.each([
162
+ { method: WS_METHODS.serverRunStorageCleanup, scope: AuthSettingsWriteScope },
163
+ { method: WS_METHODS.serverReclaimDatabaseSpace, scope: AuthEnvironmentMaintainScope },
164
+ ])("requires the destination $scope grant for $method", ({ method, scope }) =>
165
Effect.scoped(
166
Effect.gen(function* () {
167
const registry = yield* setup;
164
- const cleanup = createCommandPermissions(runtime, WS_METHODS.serverRunStorageCleanup);
168
+ const command = createCommandPermissions(runtime, method);
169
registry.set(sessions(env), AsyncResult.success(grant(true)));
166
- expect(registry.get(cleanup.permissionAtom(env))).toBe(false);
167
- expect((yield* cleanup.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
170
+ expect(registry.get(command.permissionAtom(env))).toBe(false);
171
+ expect((yield* command.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
172
"EnvironmentAuthorizationError",
173
);
174
registry.set(
175
sessions(env),
172
- AsyncResult.success({
173
- ...grant(true),
174
- scopes: [AuthSettingsWriteScope],
175
- permissions: [AuthSettingsWriteScope],
176
- }),
176
+ AsyncResult.success({ ...grant(true), scopes: [scope], permissions: [scope] }),
177
);
178
- expect(registry.get(cleanup.permissionAtom(env))).toBe(true);
179
- yield* cleanup.authorize(registry, env);
178
+ expect(registry.get(command.permissionAtom(env))).toBe(true);
179
+ yield* command.authorize(registry, env);
180
registry.set(sessions(other), AsyncResult.success(grant(false)));
181
- expect(registry.get(cleanup.permissionAtom(other))).toBe(false);
181
+ expect(registry.get(command.permissionAtom(other))).toBe(false);
182
}),
183
),
184
);
packages/client-runtime/src/state/server.ts
+5
@@ -1217,6 +1217,11 @@ export function createServerEnvironmentAtoms<R, E>(
1217
}),
1218
databaseStorage,
1219
databaseCompactionRecommendations,
1220
+ reclaimDatabaseSpace: createEnvironmentRpcCommand(runtime, {
1221
+ label: "environment-data:server:reclaim-database-space",
1222
+ tag: WS_METHODS.serverReclaimDatabaseSpace,
1223
+ concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId },
1224
+ }),
1225
storageCleanupReport: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1226
label: "environment-data:server:storage-cleanup-report",
1227
tag: WS_METHODS.serverGetStorageCleanupReport,
packages/contracts/src/clientRpcPermissions.ts
+3
@@ -2,6 +2,7 @@ import * as Schema from "effect/Schema";
2
import { GitPreparePullRequestThreadInput, GitRunStackedActionInput } from "./git.ts";
3
import {
4
AuthAccessWriteScope,
5
+ AuthEnvironmentMaintainScope,
6
AuthOrchestrationOperateScope,
7
AuthOrchestrationReadScope,
8
AuthPreviewOperateScope,
@@ -21,6 +22,8 @@ export const CLIENT_GUARDED_RPC_SCOPES = {
22
// Stopping a server signals its processes, as closing a terminal does.
23
[WS_METHODS.previewStopLocalServer]: AuthTerminalOperateScope,
24
[WS_METHODS.serverRunStorageCleanup]: AuthSettingsWriteScope,
25
+ // Restarts the server, as an update does.
26
+ [WS_METHODS.serverReclaimDatabaseSpace]: AuthEnvironmentMaintainScope,
27
[WS_METHODS.serverCheckOtlpEndpoint]: AuthSettingsWriteScope,
28
[WS_METHODS.serverRefreshProviders]: AuthOrchestrationReadScope,
29
[WS_METHODS.pullRequestsRunAction]: AuthSourceControlWriteScope,
packages/contracts/src/rpc.ts
+8
@@ -357,6 +357,7 @@ import {
357
import { UsagePricing, UsageReadError, UsageSummary, UsageSummaryInput } from "./usage.ts";
358
import {
359
StorageCleanupReport,
360
+ DatabaseReclaimError,
361
DatabaseStorageStatus,
362
ServerSettings,
363
ServerSettingsError,
@@ -512,6 +513,7 @@ export const WS_METHODS = {
513
serverRunStorageCleanup: "server.runStorageCleanup",
514
serverGetStorageCleanupReport: "server.getStorageCleanupReport",
515
serverGetDatabaseStorage: "server.getDatabaseStorage",
516
+ serverReclaimDatabaseSpace: "server.reclaimDatabaseSpace",
517
peerLinksList: "peerLinks.list",
518
peerLinksLink: "peerLinks.link",
519
peerLinksUnlink: "peerLinks.unlink",
@@ -811,6 +813,11 @@ const WsServerGetDatabaseStorageRpc = Rpc.make(WS_METHODS.serverGetDatabaseStora
813
error: EnvironmentAuthorizationError,
814
});
815
816
+const WsServerReclaimDatabaseSpaceRpc = Rpc.make(WS_METHODS.serverReclaimDatabaseSpace, {
817
+ payload: Schema.Struct({}),
818
+ error: Schema.Union([DatabaseReclaimError, EnvironmentAuthorizationError]),
819
+});
820
+
821
const WsPeerLinksListRpc = Rpc.make(WS_METHODS.peerLinksList, {
822
payload: Schema.Struct({}),
823
success: Schema.Struct({ links: Schema.Array(PeerLinkSummary) }),
@@ -2062,6 +2069,7 @@ export const WsRpcGroup = RpcGroup.make(
2069
WsServerRunStorageCleanupRpc,
2070
WsServerGetStorageCleanupReportRpc,
2071
WsServerGetDatabaseStorageRpc,
2072
+ WsServerReclaimDatabaseSpaceRpc,
2073
WsServerUpdateSettingsRpc,
2074
WsPeerLinksListRpc,
2075
WsPeerLinksLinkRpc,
packages/contracts/src/settings.ts
+19
@@ -1187,9 +1187,22 @@ export const DatabaseStorageStatus = Schema.Struct({
1187
incrementalVacuumEnabled: Schema.Boolean,
1188
/** Run on the host while offline. */
1189
compactCommand: Schema.String,
1190
+ /** The server can run the repair itself: the desktop app or background service restarts it. */
1191
+ canReclaim: Schema.optionalKey(Schema.Boolean),
1192
+ /** Why the last repair started from Settings failed. */
1193
+ reclaimFailure: Schema.optionalKey(Schema.String),
1194
});
1195
export type DatabaseStorageStatus = typeof DatabaseStorageStatus.Type;
1196
1197
+export class DatabaseReclaimError extends Schema.TaggedError<DatabaseReclaimError>()(
1198
+ "DatabaseReclaimError",
1199
+ { reason: Schema.String },
1200
+) {
1201
+ override get message() {
1202
+ return this.reason;
1203
+ }
1204
+}
1205
+
1206
export function shouldRecommendDatabaseCompaction(status: DatabaseStorageStatus): boolean {
1207
return (
1208
!status.incrementalVacuumEnabled &&
@@ -1197,6 +1210,12 @@ export function shouldRecommendDatabaseCompaction(status: DatabaseStorageStatus)
1210
);
1211
}
1212
1213
+/** Offline minutes the repair takes, at 30 s per GiB of live data (a BB-1 NVMe disk took 21 s). */
1214
+export function databaseReclaimMinutes(status: DatabaseStorageStatus): number {
1215
+ const liveGiB = (status.databaseBytes - status.reclaimableBytes) / 1024 ** 3;
1216
+ return Math.max(1, Math.ceil(liveGiB / 2));
1217
+}
1218
+
1219
export const StorageCleanupReportEntry = Schema.Struct({
1220
kind: Schema.Literals(["worktree", "browser-artifacts", "logs"]),
1221
outcome: Schema.Literals(["removed", "kept", "failed"]),