Skip to content

Write HTML. Render video. Built for agents.

fix(studio-server): remove the history of a project that no longer exists (#4634)

Miguel Ángelbee6a8e17d91
diff --git a/packages/cli/src/utils/historyOwner.ts b/packages/cli/src/utils/historyOwner.ts
index 74bfadad71..341b4d96b8 100644
--- a/packages/cli/src/utils/historyOwner.ts
+++ b/packages/cli/src/utils/historyOwner.ts
@@ -155,6 +155,7 @@ async function directOwner(projectDir: string, turn: Turn | null): Promise<Owner
const history = await openProjectHistory({
projectDir,
historyRoot: historyDeps.historyRoot,
+ pruneGoneProjectsBudgetMs: 1000,
// A turn begun through a preview that has since stopped is still the agent's, until its idle limit.
...(turn && {
closedWindow: {
diff --git a/packages/studio-server/src/history/historyId.ts b/packages/studio-server/src/history/historyId.ts
index e09a6ae41a..a00184ac8f 100644
--- a/packages/studio-server/src/history/historyId.ts
+++ b/packages/studio-server/src/history/historyId.ts
@@ -7,6 +7,8 @@ export const ID_PATH = join(".hyperframes", "history-id");
/** The only shape minted here; the id is project content and becomes a path, so nothing else is trusted. */
const ID_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+export const isHistoryId = (name: string) => ID_SHAPE.test(name);
+
export function readId(projectDir: string): string | null {
try {
const id = readFileSync(join(projectDir, ID_PATH), "utf-8").trim();
@@ -30,7 +32,9 @@ export function isRecordedFolder(historyDir: string, folder: FolderIdentity): bo
return !isCopyOf0878Folder(was!.dir as string, basename(historyDir), folder);
}
-function readRecord(historyDir: string): { dir?: unknown; ino?: unknown; born?: number } | null {
+export function readRecord(
+ historyDir: string,
+): { dir?: unknown; ino?: unknown; born?: number; dev?: unknown } | null {
try {
return JSON.parse(readFileSync(join(historyDir, "project.json"), "utf-8"));
} catch {
@@ -79,8 +83,12 @@ export class HistoryIdError extends Error {
}
}
-export function recordProject(historyDir: string, dir: string, folder: FolderIdentity): void {
- const record = { dir, ino: folder.ino, born: folder.birthtimeMs };
+export function recordProject(
+ historyDir: string,
+ dir: string,
+ folder: FolderIdentity & { dev: number },
+): void {
+ const record = { dir, ino: folder.ino, born: folder.birthtimeMs, dev: folder.dev };
mkdirSync(historyDir, { recursive: true });
replaceFileAtomically(join(historyDir, "project.json"), JSON.stringify(record), 0o644);
}
diff --git a/packages/studio-server/src/history/projectHistory.ts b/packages/studio-server/src/history/projectHistory.ts
index 75a957bbba..5882b69a69 100644
--- a/packages/studio-server/src/history/projectHistory.ts
+++ b/packages/studio-server/src/history/projectHistory.ts
@@ -26,6 +26,7 @@ import {
} from "../helpers/fileVersion.js";
import { affectsProjectSignature, listProjectFiles } from "../helpers/projectSignature.js";
import { openBlobStore, type BlobStore } from "./blobStore.js";
+import { pruneGoneProjectHistoriesDaily } from "./pruneHistories.js";
import {
ID_PATH,
isRecordedFolder,
@@ -77,6 +78,7 @@ export interface ProjectHistoryOptions {
/** A CLI turn's window from an earlier open: writes since, within its idle limit, become the entry with its id. */
closedWindow?: ClosedWindow;
undoScope?: "own" | "everyone";
+ pruneGoneProjectsBudgetMs?: number;
}
interface ClaimOptions {
@@ -1085,6 +1087,10 @@ export async function openProjectHistory(options: ProjectHistoryOptions): Promis
const blobs = await openBlobStore(join(options.historyRoot, projectId, "blobs"));
const engine = new Engine(options, projectId, blobs);
await engine.queue(() => engine.start());
+ pruneGoneProjectHistoriesDaily(options.historyRoot, engine.now(), {
+ onError: options.onError,
+ budgetMs: options.pruneGoneProjectsBudgetMs,
+ });
const api = engine.api();
return {
...api,
diff --git a/packages/studio-server/src/history/pruneHistories.test.ts b/packages/studio-server/src/history/pruneHistories.test.ts
new file mode 100644
index 0000000000..1e65e8f446
--- /dev/null
+++ b/packages/studio-server/src/history/pruneHistories.test.ts
@@ -0,0 +1,282 @@
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { describe, expect, it, onTestFinished, vi } from "vitest";
+import { ID_PATH, readId } from "./historyId.js";
+import { takeHistoryOwnership } from "./ownerLock.js";
+import { openProjectHistory } from "./projectHistory.js";
+import { KEEP_GONE_PROJECT_HISTORY_MS, pruneGoneProjectHistories } from "./pruneHistories.js";
+
+vi.mock("./ownerLock.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("./ownerLock.js")>();
+ return { ...actual, takeHistoryOwnership: vi.fn(actual.takeHistoryOwnership) };
+});
+
+function tempDir(prefix: string): string {
+ const dir = mkdtempSync(join(tmpdir(), prefix));
+ onTestFinished(() => rmSync(dir, { recursive: true, force: true }));
+ return dir;
+}
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+async function projectWithHistory(
+ historyRoot: string,
+ {
+ at = Date.now(),
+ projectDir = tempDir("hf-prune-project-"),
+ pruneGoneProjectsBudgetMs = undefined as number | undefined,
+ } = {},
+) {
+ mkdirSync(projectDir, { recursive: true });
+ writeFileSync(join(projectDir, "index.html"), "<h1>A</h1>");
+ const history = await openProjectHistory({
+ projectDir,
+ historyRoot,
+ now: () => at,
+ pruneGoneProjectsBudgetMs,
+ });
+ // Lets the open's own daily prune scan first, so it cannot race the test's.
+ await new Promise((settle) => setImmediate(settle));
+ return { projectDir, history, id: readId(projectDir)! };
+}
+
+function editRecord(
+ historyRoot: string,
+ id: string,
+ edit: (record: Record<string, unknown>) => Record<string, unknown>,
+) {
+ const file = join(historyRoot, id, "project.json");
+ writeFileSync(file, JSON.stringify(edit(JSON.parse(readFileSync(file, "utf-8")))));
+}
+
+const prunedIds = async (...args: Parameters<typeof pruneGoneProjectHistories>) =>
+ (await pruneGoneProjectHistories(...args)).map((pruned) => pruned.id);
+
+describe("pruneGoneProjectHistories", () => {
+ it("in a dry run reports what would go, with its folder and size, and removes nothing", async () => {
+ const historyRoot = tempDir("hf-prune-root-");
+ const gone = await projectWithHistory(historyRoot);
+ await gone.history.close();
+ rmSync(gone.projectDir, { recursive: true, force: true });
+
+ const [pruned, ...rest] = await pruneGoneProjectHistories(historyRoot, { dryRun: true });
+ expect(rest).toEqual([]);
+ expect(pruned).toMatchObject({ id: gone.id, projectDir: gone.projectDir });
+ expect(pruned!.bytes).toBeGreaterThan(0);
+ expect(existsSync(join(historyRoot, gone.id))).toBe(true);
+ });
+
+ it("removes a deleted project's history once no process holds it, and keeps a live project's", async () => {
+ const historyRoot = tempDir("hf-prune-root-");
+ const gone = await projectWithHistory(historyRoot);
+ const kept = await projectWithHistory(historyRoot);
+ rmSync(gone.projectDir, { recursive: true, force: true });
+
+ expect(await prunedIds(historyRoot)).toEqual([]);
+ await gone.history.close();
+ expect(await prunedIds(historyRoot)).toEqual([gone.id]);
+
+ expect(existsSync(join(historyRoot, gone.id))).toBe(false);
+ expect(existsSync(join(historyRoot, kept.id))).toBe(true);
+ await kept.history.close();
+ });
+
+ it("keeps a gone project's history outside the temp folder until it has gone unused for 14 days", async () => {
+ const historyRoot = tempDir("hf-prune-root-");
+ const gone = await projectWithHistory(historyRoot);
+ await gone.history.close();
+ rmSync(gone.projectDir, { recursive: true, force: true });
+ const elsewhere = { tempDir: historyRoot };
+
+ expect(await prunedIds(historyRoot, elsewhere)).toEqual([]);
+ expect(await prunedIds(historyRoot, { ...elsewhere, now: Date.now() + 13 * DAY_MS })).toEqual(
+ [],
+ );
+ expect(await prunedIds(historyRoot, { ...elsewhere, now: Date.now() + 14 * DAY_MS })).toEqual([
+ gone.id,
+ ]);
+ });
+
+ it("prunes when a history opens a day after the last full prune", async () => {
+ const historyRoot = tempDir("hf-prune-root-");
+ const start = Date.now();
+ const gone = await projectWithHistory(historyRoot, { at: start });
+ await gone.history.close();
+ rmSync(gone.projectDir, { recursive: true, force: true });
+
+ const cli = await projectWithHistory(historyRoot, {
+ at: start + DAY_MS,
+ pruneGoneProjectsBudgetMs: 0,
+ });
+ expect(existsSync(join(historyRoot, gone.id))).toBe(true);
+ await cli.history.close();
+ const next = await projectWithHistory(historyRoot, { at: start + DAY_MS });
+ await vi.waitFor(() => expect(existsSync(join(historyRoot, gone.id))).toBe(false));
+ await next.history.close();
+ });
+
+ it("finishes an interrupted removal and leaves folders that are not histories alone", async () => {
+ const historyRoot = tempDir("hf-prune-root-");
+ const leftover = join(historyRoot, ".pruned-leftover");
+ mkdirSync(join(leftover, "blobs"), { recursive: true });
+ writeFileSync(join(leftover, "blobs", "b"), "bytes");
+ const copy = join(historyRoot, "backup");
+ mkdirSync(copy);
+ writeFileSync(join(copy, "project.json"), JSON.stringify({ dir: join(historyRoot, "gone") }));
+
+ expect(await prunedIds(historyRoot)).toEqual([]);
+ expect(existsSync(leftover)).toBe(false);
+ expect(existsSync(copy)).toBe(true);
+ });
+
+ it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
+ "lets go of a history it could not move away",
+ async () => {
+ const historyRoot = tempDir("hf-prune-root-");
+ const gone = await projectWithHistory(historyRoot);
+ await gone.history.close();
+ rmSync(gone.projectDir, { recursive: true, force: true });
+ const errors: unknown[] = [];
+
+ chmodSync(historyRoot, 0o500);
+ try {
+ expect(await prunedIds(historyRoot, { onError: (error) => errors.push(error) })).toEqual(
+ [],
+ );
+ } finally {
+ chmodSync(historyRoot, 0o700);
+ }
+ expect(errors).toHaveLength(1);
+ expect(existsSync(join(historyRoot, gone.id, "owner.pid"))).toBe(false);
+ },
+ );
+
+ it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
+ "reports a history it cannot check and still prunes the rest",
+ async () => {
+ const historyRoot = tempDir("hf-prune-root-");
+ const locked = tempDir("hf-prune-locked-");
+ const hidden = await projectWithHistory(historyRoot, { projectDir: join(locked, "project") });
+ await hidden.history.close();
+ const gone = await projectWithHistory(historyRoot);
+ await gone.history.close();
+ rmSync(gone.projectDir, { recursive: true, force: true });
+ const errors: unknown[] = [];
+
+ chmodSync(locked, 0o000);
+ try {
+ const later = Date.now() + KEEP_GONE_PROJECT_HISTORY_MS;
+ const onError = (error: unknown) => errors.push(error);
+ expect(await prunedIds(historyRoot, { now: later, onError })).toEqual([gone.id]);
+ } finally {
+ chmodSync(locked, 0o700);
+ }
+ expect(errors).toHaveLength(1);
+ expect(existsSync(join(historyRoot, hidden.id))).toBe(true);
+ },
+ );
+
+ it("keeps a gone project's history while the disk that held it is not here", async () => {
+ const historyRoot = tempDir("hf-prune-root-");
+ const onDrive = await projectWithHistory(historyRoot, {
+ projectDir: join(tempDir("hf-prune-drive-"), "project"),
+ });
+ const deleted = await projectWithHistory(historyRoot, {
+ projectDir: join(tempDir("hf-prune-tree-"), "project"),
+ });
+ const mountPoint = await projectWithHistory(historyRoot);
+ await Promise.all([onDrive, deleted, mountPoint].map(({ history }) => history.close()));
+ for (const { id } of [onDrive, mountPoint])
+ editRecord(historyRoot, id, (record) => ({ ...record, dev: Number(record.dev) + 1 }));
+ rmSync(dirname(onDrive.projectDir), { recursive: true, force: true });
+ // What an unmounted drive leaves at its mount point: the folder, without the project in it.
+ rmSync(join(mountPoint.projectDir, ".hyperframes"), { recursive: true, force: true });
+ rmSync(dirname(deleted.projectDir), { recursive: true, force: true });
+
+ const later = Date.now() + KEEP_GONE_PROJECT_HISTORY_MS;
+ expect(await prunedIds(historyRoot, { tempDir: historyRoot, now: later })).toEqual([
+ deleted.id,
+ ]);
+ });
+
+ it("prunes a history recorded without its disk only when its folder is there without the project", async () => {
+ const historyRoot = tempDir("hf-prune-root-");
+ const emptied = await projectWithHistory(historyRoot);
+ const folderGone = await projectWithHistory(historyRoot);
+ const parentGone = await projectWithHistory(historyRoot, {
+ projectDir: join(tempDir("hf-prune-parent-"), "project"),
+ });
+ const all = [emptied, folderGone, parentGone];
+ await Promise.all(all.map(({ history }) => history.close()));
+ for (const { id } of all) editRecord(historyRoot, id, ({ dev: _dev, ...record }) => record);
+ rmSync(join(emptied.projectDir, ".hyperframes"), { recursive: true, force: true });
+ // An unmounted disk leaves its mount point, so a missing folder under it may just be unplugged.
+ rmSync(folderGone.projectDir, { recursive: true, force: true });
+ rmSync(dirname(parentGone.projectDir), { recursive: true, force: true });
+
+ const later = Date.now() + KEEP_GONE_PROJECT_HISTORY_MS;
+ expect(await prunedIds(historyRoot, { tempDir: historyRoot, now: later })).toEqual([
+ emptied.id,
+ ]);
+ });
+
+ it("prunes a history recorded without its disk under the temp folder once its project is gone", async () => {
+ const historyRoot = tempDir("hf-prune-root-");
+ const scratch = await projectWithHistory(historyRoot, {
+ projectDir: join(tempDir("hf-prune-scratch-"), "project"),
+ });
+ await scratch.history.close();
+ editRecord(historyRoot, scratch.id, ({ dev: _dev, ...record }) => record);
+ rmSync(dirname(scratch.projectDir), { recursive: true, force: true });
+
+ expect(await prunedIds(historyRoot)).toEqual([scratch.id]);
+ });
+
+ it("keeps a history whose project comes back while the prune takes its lock", async () => {
+ const historyRoot = tempDir("hf-prune-root-");
+ const back = await projectWithHistory(historyRoot);
+ await back.history.close();
+ const idFile = join(back.projectDir, ID_PATH);
+ const id = readFileSync(idFile, "utf-8");
+ rmSync(dirname(idFile), { recursive: true, force: true });
+ const real = await vi.importActual<typeof import("./ownerLock.js")>("./ownerLock.js");
+ vi.mocked(takeHistoryOwnership).mockImplementationOnce(async (home, waitMs) => {
+ mkdirSync(dirname(idFile), { recursive: true });
+ writeFileSync(idFile, id);
+ return real.takeHistoryOwnership(home, waitMs);
+ });
+
+ expect(await prunedIds(historyRoot)).toEqual([]);
+ expect(existsSync(idFile)).toBe(true);
+ expect(existsSync(join(historyRoot, back.id))).toBe(true);
+ });
+
+ it("removes the history of a folder that now holds another project", async () => {
+ const historyRoot = tempDir("hf-prune-root-");
+ const replaced = await projectWithHistory(historyRoot);
+ await replaced.history.close();
+ writeFileSync(join(replaced.projectDir, ID_PATH), "00000000-0000-4000-8000-000000000000\n");
+
+ expect(await prunedIds(historyRoot)).toEqual([replaced.id]);
+ });
+
+ it("keeps the history of a project whose id file cannot be read", async () => {
+ const historyRoot = tempDir("hf-prune-root-");
+ const unreadable = await projectWithHistory(historyRoot);
+ await unreadable.history.close();
+ mkdirSync(join(unreadable.projectDir, ".hyperframes"), { recursive: true });
+ writeFileSync(join(unreadable.projectDir, ID_PATH), "not an id\n");
+
+ expect(await prunedIds(historyRoot)).toEqual([]);
+ expect(existsSync(join(historyRoot, unreadable.id))).toBe(true);
+ });
+});
diff --git a/packages/studio-server/src/history/pruneHistories.ts b/packages/studio-server/src/history/pruneHistories.ts
new file mode 100644
index 0000000000..de2de44259
--- /dev/null
+++ b/packages/studio-server/src/history/pruneHistories.ts
@@ -0,0 +1,206 @@
+import { randomUUID } from "node:crypto";
+import { readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
+import { lstat, readdir, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { isSafePath } from "../helpers/safePath.js";
+import { ID_PATH, isHistoryId, readId, readRecord } from "./historyId.js";
+import { HistoryBusyError, takeHistoryOwnership } from "./ownerLock.js";
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+/** A gone project's history stays this long after its last use, so a moved project reopened in time keeps it. */
+export const KEEP_GONE_PROJECT_HISTORY_MS = 14 * DAY_MS;
+const PRUNED_PREFIX = ".pruned-";
+const LAST_PRUNE_FILE = ".last-prune";
+
+interface PruneOptions {
+ now?: number;
+ /** Reports what would go, with the same checks, and removes nothing. */
+ dryRun?: boolean;
+ /** Projects under this folder are scratch: their history goes as soon as they do. */
+ tempDir?: string;
+ /** One history that could not be checked or removed; the rest are still pruned. */
+ onError?: (error: unknown) => void;
+ /** Starts no further history after this long; the rest wait for the next run. */
+ budgetMs?: number;
+}
+
+export interface PrunedHistory {
+ id: string;
+ projectDir: string;
+ bytes: number;
+}
+
+/** Removes the histories whose project is gone and that no live process holds. */
+export async function pruneGoneProjectHistories(
+ historyRoot: string,
+ options: PruneOptions = {},
+): Promise<PrunedHistory[]> {
+ return (await pruneWithin(historyRoot, options)).pruned;
+}
+
+async function pruneWithin(
+ historyRoot: string,
+ {
+ now = Date.now(),
+ dryRun = false,
+ tempDir = tmpdir(),
+ onError = (error) => console.warn("[history] could not prune a history:", error),
+ budgetMs = Infinity,
+ measure = true,
+ }: PruneOptions & { measure?: boolean },
+): Promise<{ pruned: PrunedHistory[]; finished: boolean }> {
+ const started = performance.now();
+ let names: string[];
+ try {
+ names = readdirSync(historyRoot);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { pruned: [], finished: true };
+ throw error;
+ }
+ const pruned: PrunedHistory[] = [];
+ for (const name of names) {
+ if (performance.now() - started >= budgetMs) return { pruned, finished: false };
+ try {
+ const gone = await pruneEntry(historyRoot, name, { now, dryRun, tempDir, measure });
+ if (gone) pruned.push(gone);
+ } catch (error) {
+ onError(error);
+ }
+ }
+ return { pruned, finished: true };
+}
+
+async function pruneEntry(historyRoot: string, name: string, run: PruneRun) {
+ if (name.startsWith(PRUNED_PREFIX)) {
+ if (!run.dryRun) await rm(join(historyRoot, name), { recursive: true, force: true });
+ return null;
+ }
+ return isHistoryId(name) ? pruneOne(historyRoot, name, run) : null;
+}
+
+type PruneRun = { now: number; dryRun: boolean; tempDir: string; measure: boolean };
+
+async function pruneOne(
+ historyRoot: string,
+ id: string,
+ run: PruneRun,
+): Promise<PrunedHistory | null> {
+ const home = join(historyRoot, id);
+ if (abandonedProject(home, id, run.now, run.tempDir) === null) return null;
+ const release = await takeUnlessBusy(home);
+ if (!release) return null;
+ let taken: { projectDir: string; trash: string | null } | null;
+ try {
+ taken = recheckAndMoveAway(historyRoot, id, run);
+ } catch (error) {
+ release();
+ throw error;
+ }
+ if (!taken?.trash) release();
+ if (!taken) return null;
+ const bytes = await clearAway(taken.trash, home, run.measure);
+ return { id, projectDir: taken.projectDir, bytes };
+}
+
+/** Removes the moved-away history, if any; its size when asked, measured first. */
+async function clearAway(trash: string | null, home: string, measure: boolean): Promise<number> {
+ const bytes = measure ? await bytesIn(trash ?? home) : 0;
+ if (trash) await rm(trash, { recursive: true, force: true });
+ return bytes;
+}
+
+async function takeUnlessBusy(home: string): Promise<(() => void) | null> {
+ try {
+ return await takeHistoryOwnership(home, 0);
+ } catch (error) {
+ if (error instanceof HistoryBusyError) return null;
+ throw error;
+ }
+}
+
+function recheckAndMoveAway(historyRoot: string, id: string, { now, dryRun, tempDir }: PruneRun) {
+ const home = join(historyRoot, id);
+ // Re-read under the lock: an open that recorded this project again meanwhile keeps it.
+ const projectDir = abandonedProject(home, id, now, tempDir);
+ if (projectDir === null) return null;
+ if (dryRun) return { projectDir, trash: null };
+ // One rename takes the lock along, so an interrupted delete leaves a `.pruned-` folder the next run finishes.
+ const trash = join(historyRoot, `${PRUNED_PREFIX}${id}-${randomUUID()}`);
+ renameSync(home, trash);
+ return { projectDir, trash };
+}
+
+/** The folder a history was recorded for, when that project is gone; null while it may still need its history. */
+function abandonedProject(home: string, id: string, now: number, tempDir: string): string | null {
+ const record = readRecord(home);
+ const dir = record?.dir;
+ if (typeof dir !== "string") return null;
+ if (now - lastUsed(home) < KEEP_GONE_PROJECT_HISTORY_MS && !isSafePath(tempDir, dir)) return null;
+ return projectGone(dir, id, record?.dev, tempDir) ? dir : null;
+}
+
+function projectGone(dir: string, id: string, dev: unknown, tempDir: string): boolean {
+ if (!statSync(join(dir, ID_PATH), { throwIfNoEntry: false }))
+ return diskStillHere(dir, dev, tempDir);
+ // An id file this version cannot read is refused, never replaced, so its history is still the project's.
+ const there = readId(dir);
+ return there !== null && there !== id;
+}
+
+/** A project without its id is gone only if the disk that held it is here: an unmounted drive or share keeps it. */
+function diskStillHere(dir: string, dev: unknown, tempDir: string): boolean {
+ let at = dir;
+ let stat = statSync(at, { throwIfNoEntry: false });
+ while (!stat) {
+ if (dirname(at) === at) return false;
+ at = dirname(at);
+ stat = statSync(at, { throwIfNoEntry: false });
+ }
+ if (typeof dev === "number") return stat.dev === dev;
+ // Recorded before `dev`: a missing folder may sit on an unmounted disk, so only an emptied folder or temp counts.
+ return at === dir || isSafePath(tempDir, at);
+}
+
+function lastUsed(home: string): number {
+ const mtime = (file: string) =>
+ statSync(join(home, file), { throwIfNoEntry: false })?.mtimeMs ?? 0;
+ return Math.max(mtime("project.json"), mtime("log.jsonl"));
+}
+
+async function bytesIn(dir: string): Promise<number> {
+ let total = 0;
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
+ const path = join(dir, entry.name);
+ total += entry.isDirectory() ? await bytesIn(path) : (await lstat(path)).size;
+ }
+ return total;
+}
+
+function prunedWithinADay(stamp: string, now: number): boolean {
+ try {
+ const last = Number(readFileSync(stamp, "utf-8"));
+ return last <= now && now - last < DAY_MS;
+ } catch {
+ return false;
+ }
+}
+
+const pruning = new Set<string>();
+
+/** Prunes `historyRoot` in the background until one run finishes a day, whichever process opens a history first. */
+export function pruneGoneProjectHistoriesDaily(
+ historyRoot: string,
+ now: number,
+ { onError, budgetMs }: Pick<PruneOptions, "onError" | "budgetMs"> = {},
+): void {
+ const stamp = join(historyRoot, LAST_PRUNE_FILE);
+ if (pruning.has(historyRoot) || prunedWithinADay(stamp, now)) return;
+ pruning.add(historyRoot);
+ setImmediate(() => {
+ pruneWithin(historyRoot, { now, onError, budgetMs, measure: false })
+ .then(({ finished }) => finished && writeFileSync(stamp, String(now)))
+ .catch((error) => onError?.(error))
+ .finally(() => pruning.delete(historyRoot));
+ });
+}
diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.ts
index a6b9adb11e..931e341e56 100644
--- a/packages/studio-server/src/index.ts
+++ b/packages/studio-server/src/index.ts
@@ -19,6 +19,7 @@ export {
export { HistoryBusyError } from "./history/ownerLock.js";
export { HistoryIdError } from "./history/historyId.js";
export { historyCache } from "./history/historyCache.js";
+export { pruneGoneProjectHistories, type PrunedHistory } from "./history/pruneHistories.js";
export {
START as HISTORY_START,
type HistoryEntry,