A local-first multi-agent app development platform, built on PenguinHarness
feat(server): scan, review, approve — and only then move, into the trash
lmliheng5e47dc4c1820
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 090151f8..0fd1e8e3 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -370,6 +370,142 @@ export interface StorageReportResponse {report: StorageReport;}+/**+ * The cleanup mode's own settings, machine-wide like the data root they describe (one root,+ * one disk, one answer) rather than per Project. **`enabled` is off until a person turns it+ * on**, and everything that writes — scanning out a bill, pinning, moving, purging — is refused+ * while it is off. `pins` are paths, relative to the root, that a person decided to keep: they+ * are left out of every bill from then on.+ */+export interface StorageSettings {+ enabled: boolean;+ /** Days a trash entry is kept before `purge` without an id may remove it. */+ trashTtlDays: number;+ pins: string[];+}++export interface StorageSettingsResponse {+ settings: StorageSettings;+}++/** PUT body: every field optional, omitted fields keep their current value (mirrors prefs). */+export interface StorageSettingsUpdateRequest {+ enabled?: boolean;+ trashTtlDays?: number;+ pins?: string[];+}++/** One line of a bill, as the page and the CLI read it. */+export interface StoragePlanEntryView {+ /** Path relative to the root, `/`-separated — what was measured and what a move names. */+ path: string;+ class: StorageClass;+ bytes: number;+ files: number;+ /** Newest modification inside the entry at scan time; null when nothing could be stat'd. */+ lastModifiedAt: string | null;+ rules: StorageCandidateRule[];+ /** The entry as measured, as one short hash — what an apply re-checks before moving it. */+ fingerprint: string;+ /**+ * Whether this version may act on this class at all. False means report-only: the entry is+ * on the bill because a person should see it, and no selection of it can be executed.+ */+ executable: boolean;+}++/** A scan's output: the bill a person reviews before anything moves. */+export interface StoragePlanView {+ id: string;+ root: string;+ createdAt: string;+ expiresAt: string;+ /** Hash over the entries — quoted back by an approval, and what a stale plan is caught by. */+ fingerprint: string;+ /** Sum of the entries: what this bill accounts for, not the root's size. */+ totalBytes: number;+ entries: StoragePlanEntryView[];+ /** Paths a pin kept out of it. */+ excluded: string[];+ /** The classes `POST /apply` accepts; everything else on the bill is report-only. */+ executableClasses: StorageClass[];+ appliedAt: string | null;+ appliedPaths: string[];+ /** Whether it may still be applied: not used, and not past `expiresAt`. */+ usable: boolean;+ expired: boolean;+}++export interface StoragePlanResponse {+ plan: StoragePlanView;+}++export interface StoragePlansResponse {+ plans: StoragePlanView[];+}++export interface StorageApplyRequest {+ planId: string;+ /** The plan's own fingerprint, as read from the bill the person approved. */+ fingerprint: string;+ /** The entries to move, by their recorded path. Empty is refused rather than treated as all. */+ paths: string[];+}++export interface StorageApplyResponse {+ planId: string;+ /** The trash entry the moved trees went into; null when nothing moved. */+ trashId: string | null;+ moved: { path: string; bytes: number; files: number }[];+ /** Entries that were approved and validated but could not be moved; the run continued. */+ failed: { path: string; reason: string }[];+ freedBytes: number;+}++export interface StorageTrashItem {+ path: string;+ class: StorageClass;+ bytes: number;+ files: number;+}++/** One run's trash: what it holds, and what putting it back would restore. */+export interface StorageTrashEntry {+ id: string;+ createdAt: string;+ /** The plan that produced it, when the manifest still says. */+ planId: string | null;+ /** Measured now, not read from the manifest: a listing must not lie about what is on disk. */+ bytes: number;+ files: number;+ items: StorageTrashItem[];+ /** Older than the retention. Nothing removes it on its own; `purge` is a person's command. */+ expired: boolean;+}++export interface StorageTrashResponse {+ entries: StorageTrashEntry[];+ ttlDays: number;+}++export interface StorageRestoreResponse {+ id: string;+ restored: string[];+ skipped: { path: string; reason: string }[];+ /** Whether the trash entry still holds anything (it is removed once it holds nothing). */+ remaining: boolean;+}++export interface StoragePurgeResponse {+ purged: { id: string; bytes: number; files: number }[];+}++export interface StoragePinRequest {+ /** Path relative to the root, as the report and a bill record it. */+ path: string;+ pinned: boolean;+}+/** PUT body: every field optional, omitted fields keep their current value (mirrors prefs). */export interface ServerSettingsUpdateRequest {proxyForApp?: boolean;diff --git a/packages/server/src/http/routes/admin-storage.ts b/packages/server/src/http/routes/admin-storage.tsindex 44bb9fb2..0248ffb2 100644--- a/packages/server/src/http/routes/admin-storage.ts+++ b/packages/server/src/http/routes/admin-storage.ts@@ -1,23 +1,52 @@/**- * Admin storage ledger route (admin only, 403 `admin_required` for a non-admin), exactly like- * the server-settings route beside it:- * GET /api/admin/storage — the report on what the data root holds, class by class, with the- * entries a person could review.+ * Admin storage routes (admin only, 403 `admin_required` for a non-admin), exactly like the+ * server-settings route beside them:*- * One method and no request at all: there is no PUT and no DELETE here, and deliberately no- * query parameter either, because a parameter naming a class, a path or a policy would be the- * beginning of an instruction a caller could send — and a report's whole value is that reading- * it decides nothing. The work itself is services/storage-service.ts, which only reads.+ * - `GET /api/admin/storage` — the ledger: what the data root holds, class by class, with the+ * entries a person could review. Reads only, always available.+ * - `GET|PUT /api/admin/storage/settings` — the cleanup mode (off until somebody turns it on),+ * the trash retention, and the pins.+ * - `POST /api/admin/storage/plans` — scans and writes a bill; `GET .../plans` lists the recent+ * ones and `GET .../plans/:planId` reads one; `POST .../plans/:planId/pin` keeps an entry out+ * of every future bill.+ * - `POST /api/admin/storage/apply` — moves the approved entries into the trash. The only route+ * in this file that changes the data root, and it needs a plan id, that plan's fingerprint and+ * an explicit path list.+ * - `GET /api/admin/storage/trash`, `POST .../trash/restore`, `POST .../trash/purge` — what a+ * run moved, putting it back, and the one deletion there is.+ *+ * Nothing here runs on a timer, and no route accepts a policy: a caller cannot widen what a+ * scan considers, and cannot ask for "everything unreferenced" — the unit of approval is a+ * specific bill. The work itself is services/storage-service.ts.*/import { Hono } from "hono";-import type { StorageReportResponse } from "../../api/types.js";+import type {+ StorageApplyResponse,+ StorageApplyRequest,+ StoragePinRequest,+ StoragePlanResponse,+ StoragePlansResponse,+ StoragePurgeResponse,+ StorageReportResponse,+ StorageRestoreResponse,+ StorageSettingsResponse,+ StorageTrashResponse,+} from "../../api/types.js";import { HttpError } from "../errors.js";import type { AppEnv } from "../../auth/middleware.js";-import type { StorageLedgerReader } from "../../services/storage-service.js";+import {+ optionalBoolean,+ optionalNumber,+ optionalStringArray,+ pathParam,+ readJson,+ requireString,+} from "../validate.js";+import type { StorageAdmin } from "../../services/storage-service.js";/** What this route group reaches — bound by AdminRoutes, which builds it (src/http/routes/admin.ts). */export interface AdminStorageRouteDeps {- storage: StorageLedgerReader;+ storage: StorageAdmin;}export function adminStorageRoutes(deps: AdminStorageRouteDeps): Hono<AppEnv> {@@ -30,9 +59,94 @@ export function adminStorageRoutes(deps: AdminStorageRouteDeps): Hono<AppEnv> {await next();});+ const settings = (): StorageSettingsResponse => ({ settings: deps.storage.settings() });+app.get("/", async (c) =>c.json({ report: await deps.storage.report() } satisfies StorageReportResponse),);+ app.get("/settings", (c) => c.json(settings()));++ app.put("/settings", async (c) => {+ const body = await readJson(c);+ // Validated before anything is written, like the server-settings route: a PUT that names one+ // bad field leaves the mode, the retention and the pins exactly as they were.+ const enabled = optionalBoolean(body, "enabled");+ const trashTtlDays = optionalNumber(body, "trashTtlDays", {+ integer: true,+ nonNegative: true,+ label: "trashTtlDays",+ });+ const pins = optionalStringArray(body, "pins");+ return c.json({+ settings: deps.storage.updateSettings({+ ...(enabled !== undefined ? { enabled } : {}),+ ...(trashTtlDays !== undefined ? { trashTtlDays } : {}),+ ...(pins !== undefined ? { pins } : {}),+ }),+ } satisfies StorageSettingsResponse);+ });++ app.get("/plans", async (c) =>+ c.json({ plans: await deps.storage.plans() } satisfies StoragePlansResponse),+ );++ // A scan writes a bill and nothing else — it is a POST because it creates a file, not because+ // it changes anything a person would have to be warned about.+ app.post("/plans", async (c) =>+ c.json({ plan: await deps.storage.scan() } satisfies StoragePlanResponse, 201),+ );++ app.get("/plans/:planId", async (c) =>+ c.json({ plan: await deps.storage.plan(pathParam(c, "planId")) } satisfies StoragePlanResponse),+ );++ app.post("/plans/:planId/pin", async (c) => {+ const planId = pathParam(c, "planId");+ const body = await readJson(c);+ // The plan is read first so that pinning an entry of a plan that does not exist — a typo in+ // the id, a plan file deleted by hand — is told so rather than answered with a settings blob.+ await deps.storage.plan(planId);+ const request: StoragePinRequest = {+ path: requireString(body, "path", { label: "path" }),+ pinned: optionalBoolean(body, "pinned") ?? true,+ };+ return c.json({ settings: await deps.storage.pin(request) } satisfies StorageSettingsResponse);+ });++ app.post("/apply", async (c) => {+ const body = await readJson(c);+ // The selection is a list of paths and nothing else: there is no "all" and no class to name,+ // so what moves is exactly what somebody ticked on a bill they were reading.+ const request: StorageApplyRequest = {+ planId: requireString(body, "planId", { label: "planId" }),+ fingerprint: requireString(body, "fingerprint", { label: "fingerprint" }),+ paths: optionalStringArray(body, "paths") ?? [],+ };+ return c.json((await deps.storage.apply(request)) satisfies StorageApplyResponse);+ });++ app.get("/trash", async (c) =>+ c.json({+ entries: await deps.storage.trash(),+ ttlDays: deps.storage.settings().trashTtlDays,+ } satisfies StorageTrashResponse),+ );++ app.post("/trash/restore", async (c) => {+ const body = await readJson(c);+ const id = requireString(body, "id", { label: "id" });+ return c.json((await deps.storage.restore(id)) satisfies StorageRestoreResponse);+ });++ // Without an id this removes only what is past the retention, which is why the body may be+ // empty; with one it removes exactly that entry, which is how a person empties the trash of+ // one run they are done with.+ app.post("/trash/purge", async (c) => {+ const body = await readJson(c);+ const id = typeof body.id === "string" ? body.id : null;+ return c.json((await deps.storage.purge(id)) satisfies StoragePurgeResponse);+ });+return app;}diff --git a/packages/server/src/http/routes/admin.ts b/packages/server/src/http/routes/admin.tsindex 1a732508..8920fb56 100644--- a/packages/server/src/http/routes/admin.ts+++ b/packages/server/src/http/routes/admin.ts@@ -20,7 +20,7 @@ import { adminPluginConfigRoutes } from "./admin-plugin-config.js";import { PluginConfigAdmin } from "../../plugin/config-page.js";import type { Admin } from "../../mechanisms/identity.js";import type { Settings } from "../../mechanisms/settings.js";-import type { StorageLedgerReader } from "../../services/storage-service.js";+import type { StorageAdmin } from "../../services/storage-service.js";/** What this route group reaches — bound by its module (src/modules). */export interface AdminRouteDeps {@@ -102,7 +102,7 @@ export class AdminRoutes {@Use() private readonly proxy!: Proxy;@Use() private readonly settings!: Settings;@Use() private readonly pluginConfigAdmin!: PluginConfigAdmin;- @Use() private readonly storage!: StorageLedgerReader;+ @Use() private readonly storage!: StorageAdmin;@Bind("admin-api.users") usersRoutes!: Hono<AppEnv>;@Bind("admin-api.settings") settingsRoutes!: Hono<AppEnv>;@Bind("admin-api.plugin-config") pluginConfigRoutes!: Hono<AppEnv>;diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.tsindex 438548da..f9a06e4a 100644--- a/packages/server/src/platform.ts+++ b/packages/server/src/platform.ts@@ -87,7 +87,7 @@ import { SessionSources } from "./runtime/session-sources.js";import { ErrorRecorder } from "./runtime/error-recorder.js";import { UsageRecorder } from "./runtime/usage-recorder.js";import { UsageService } from "./services/usage-service.js";-import { StorageLedgerReader, StorageService } from "./services/storage-service.js";+import { StorageAdmin, StorageService } from "./services/storage-service.js";import { ProjectConfigService } from "./services/project-config-service.js";import { ModelOAuthService } from "./services/model-oauth-service.js";import { PlatformAuth, PlatformAuthProvider } from "./services/platform-auth-service.js";@@ -391,7 +391,7 @@ export class SandboxSettingsModule {}@Module({children: [ErrorsRepo, ErrorRecorder, UsageRepo, UsageRecorder, UsageService, StorageService],- exports: [ErrorLog, Errors, UsageStore, UsageRecording, UsageQueries, StorageLedgerReader],+ exports: [ErrorLog, Errors, UsageStore, UsageRecording, UsageQueries, StorageAdmin],})export class ObservabilityModule {}diff --git a/packages/server/src/services/storage-service.ts b/packages/server/src/services/storage-service.tsindex 75c5cc1b..8751f4e1 100644--- a/packages/server/src/services/storage-service.ts+++ b/packages/server/src/services/storage-service.ts@@ -1,55 +1,155 @@/**- * The data root's storage ledger, read-only — the numbers behind `GET /api/admin/storage`.+ * The data root's storage ledger, and the human-reviewed cleanup that reads it.*- * This node reports and nothing else: it walks the root, classifies what is there and answers- * with the ledger. It deletes nothing, moves nothing, creates nothing and writes no cache, so- * it is safe to call at any moment — and it is deliberately NOT reachable from a scheduler.- * A job that produced this report on a timer would be the first step back towards acting on- * it automatically, which is exactly what the design rules out: every removal is a person's- * decision, taken against a report they are looking at (see core's state/storage.ts, the- * single definition point of the vocabulary this service only maps).+ * Two halves, one vocabulary. `report()` walks the root and answers with what is there and+ * what could go — it deletes nothing, moves nothing and is safe to call at any moment (see+ * core's state/storage.ts, the single definition point of the classes it maps). Everything else+ * here is the design's second step: a **bill** written out of that ledger, reviewed by a person,+ * approved once, and only then moved — into the trash, never unlinked.*- * Liveness is what makes a ledger meaningful, and it is the server's own state, so this node- * assembles it here rather than in core's pure `scanStorage`, which cannot reach a database:- * `SessionIndex.listByProject` over `Projects.listAll` is every Session row that still exists- * — the index creation, Trace adoption and deletion all keep current — and each row carries- * both the Workspace that Session points at and its last activity.+ * The rules that shape the whole node, in one place:*- * A Session in the middle of being deleted (`SessionManager.beginSessionDeletion` /- * `assertSessionNotDeleting`) is NOT excluded here, because that window is not reachable from- * a node: `SessionManager` keeps its `deletingSessions` set private, and the `Sessions`- * mechanism exposes only the begin/end pair with no way to ask about one id. Counting such a- * Session as live is the safe direction for a read-only report — it can only make an entry- * look referenced, never claim that something a deletion is about to remove is free — whereas- * a query added to the session runtime for this one caller would be a change to the deletion- * window itself, which this slice does not need.+ * - **Nothing runs by itself.** There is no timer and no threshold that acts; a scan happens+ * because somebody asked for one, and a move because somebody selected entries and pressed+ * the button. What may happen automatically is a report.+ * - **The cleanup mode gates every write.** `enabled` is off until a person turns it on;+ * scanning, pinning, moving and purging are all refused while it is off, so an untouched+ * install has exactly the read-only behaviour the previous version had.+ * - **A plan is used once, and only if the disk still matches it.** An approval quotes the+ * bill's fingerprint; the entries are re-measured and re-checked against live state before+ * anything moves, so a tree that grew, was touched or came alive in the meantime stops the+ * run instead of being cleaned up half-reviewed.+ * - **A move is a rename into `<root>/.trash/<stamp>/items/<original path>`** plus a manifest,+ * which makes the whole thing reversible with the same call. The one deletion in the file is+ * `purge`, which removes a trash entry a person named (or one past the retention) — and it+ * never touches anything that is not already in the trash.+ *+ * Liveness is the server's own state, so it is assembled here rather than in core's pure+ * `scanStorage`: `SessionIndex.listByProject` over `Projects.listAll` is every Session row that+ * still exists — the index creation, Trace adoption and deletion all keep current — and each+ * row carries both the Workspace it points at and its last activity. At apply time it is read+ * again, so a Workspace that a Session started using after the scan is refused rather than+ * moved.+ *+ * A Session in the middle of being deleted (`SessionManager.beginSessionDeletion`) is NOT+ * excluded, because that window is not reachable from a node: `SessionManager` keeps its+ * `deletingSessions` set private, and the `Sessions` mechanism exposes only the begin/end pair+ * with no way to ask about one id. Counting such a Session as live is the safe direction — it+ * can only make an entry look referenced, never claim that something a deletion is about to+ * remove is free — and for apply it means the entry is refused, which is the answer a person+ * can act on (scan again once the deletion is done).*/import fs from "node:fs/promises";import path from "node:path";-import { scanStorage } from "@lmliheng/penguin-core";-import type { StorageLiveSet, StorageEntry as LedgerEntry } from "@lmliheng/penguin-core";+import { randomBytes } from "node:crypto";+import {+ buildStoragePlan,+ EXECUTABLE_STORAGE_CLASSES,+ isExecutableStorageClass,+ isPlannablePath,+ isInsideRoot,+ measureStorageEntry,+ planEntryFingerprint,+ resolveStorageEntry,+ scanStorage,+ storageLogFile,+ storagePlanId,+ storagePlansDir,+ storageTrashDir,+ storageTrashId,+} from "@lmliheng/penguin-core";+import type {+ StorageClass,+ StorageEntry as LedgerEntry,+ StorageLiveSet,+ StoragePlan,+ StoragePlanEntry,+} from "@lmliheng/penguin-core";import { Component, Interface, Use } from "@lmliheng/penguin-core/kernel";-import type { StorageCandidate, StorageReport } from "../api/types.js";+import { HttpError } from "../http/errors.js";+import type {+ StorageApplyResponse,+ StorageCandidate,+ StoragePlanView,+ StoragePurgeResponse,+ StorageReport,+ StorageRestoreResponse,+ StorageSettings,+ StorageSettingsUpdateRequest,+ StorageTrashEntry,+} from "../api/types.js";import type { Paths } from "../hmr/capabilities.js";import type { Projects } from "../mechanisms/projects.js";import type { SessionIndex } from "../mechanisms/sessions.js";+import type { Settings } from "../mechanisms/settings.js";/**- * What a node may require to read the storage ledger: the report, and nothing else. The DTO- * is the whole contract, so nothing on a route can reach a scan policy or a removal through- * it — a caller cannot ask for a wider candidate list than the design's defaults, because- * there is no argument to ask with.+ * What a node may require to work with the data root's storage: the report, and the reviewed+ * cleanup that reads it. There is no "clean this class" or "run a policy" method — the design's+ * guarantee is that a removal needs a specific bill a person looked at, and a surface narrower+ * than that could not express one.*/@Interface()-export abstract class StorageLedgerReader {+export abstract class StorageAdmin {abstract report(): Promise<StorageReport>;+ abstract settings(): StorageSettings;+ abstract updateSettings(update: StorageSettingsUpdateRequest): StorageSettings;+ /** Scans and writes a bill; refuses while the cleanup mode is off. */+ abstract scan(): Promise<StoragePlanView>;+ abstract plans(): Promise<StoragePlanView[]>;+ abstract plan(planId: string): Promise<StoragePlanView>;+ abstract pin(input: { path: string; pinned: boolean }): Promise<StorageSettings>;+ abstract apply(input: {+ planId: string;+ fingerprint: string;+ paths: string[];+ }): Promise<StorageApplyResponse>;+ abstract trash(): Promise<StorageTrashEntry[]>;+ abstract restore(trashId: string): Promise<StorageRestoreResponse>;+ abstract purge(trashId: string | null): Promise<StoragePurgeResponse>;+}++/** `server_settings` key holding the cleanup mode's settings, one JSON object. */+const STORAGE_SETTINGS_KEY = "storage";++/** Trash entries live this long before a purge without an id may remove them. */+const DEFAULT_TRASH_TTL_DAYS = 14;+const MIN_TRASH_TTL_DAYS = 1;+const MAX_TRASH_TTL_DAYS = 365;++/** Plans a listing returns, newest first — enough to review, not a second storage table. */+const PLAN_LIST_LIMIT = 20;++/** Ids are used as file and directory names, so they are checked before they are joined. */+const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/;++const TRASH_MANIFEST = "manifest.json";+const TRASH_ITEMS_DIR = "items";++/** The defaults of a machine that has never turned the cleanup mode on. */+const DEFAULT_STORAGE_SETTINGS: StorageSettings = {+ enabled: false,+ trashTtlDays: DEFAULT_TRASH_TTL_DAYS,+ pins: [],+};++/** What a trash entry's manifest records: enough to put every tree back where it came from. */+interface TrashManifest {+ id: string;+ createdAtMs: number;+ planId: string;+ items: { path: string; class: StorageClass; bytes: number; files: number }[];}@Component()-export class StorageService implements StorageLedgerReader {+export class StorageService implements StorageAdmin {@Use() private readonly paths!: Paths;@Use() private readonly projects!: Projects;@Use() private readonly sessions!: SessionIndex;+ @Use() private readonly settingsRepo!: Settings;++ /** The write in flight, by name — the single-writer rule, made visible rather than queued. */+ private running: string | null = null;async report(): Promise<StorageReport> {// The design's default policy, with no way to pass another one (see the interface above):@@ -73,6 +173,713 @@ export class StorageService implements StorageLedgerReader {};}+ settings(): StorageSettings {+ return this.readSettings();+ }++ updateSettings(update: StorageSettingsUpdateRequest): StorageSettings {+ const current = this.readSettings();+ const next: StorageSettings = {+ enabled: update.enabled ?? current.enabled,+ trashTtlDays: update.trashTtlDays ?? current.trashTtlDays,+ pins: update.pins ?? current.pins,+ };+ if (+ !Number.isInteger(next.trashTtlDays) ||+ next.trashTtlDays < MIN_TRASH_TTL_DAYS ||+ next.trashTtlDays > MAX_TRASH_TTL_DAYS+ ) {+ throw new HttpError(+ 400,+ "invalid_trash_ttl",+ `trashTtlDays must be a whole number of days between ${MIN_TRASH_TTL_DAYS} and ${MAX_TRASH_TTL_DAYS}.`,+ );+ }+ for (const pin of next.pins) this.assertPinnablePath(pin);+ if (next.enabled !== current.enabled) {+ this.audit({ action: next.enabled ? "mode_on" : "mode_off" });+ }+ // A changed pin list is a decision about data, so it is recorded like one: the audit file+ // is what answers "why is this entry not on the bill any more" months later.+ for (const pin of next.pins)+ if (!current.pins.includes(pin)) this.audit({ action: "pin", path: pin });+ for (const pin of current.pins)+ if (!next.pins.includes(pin)) this.audit({ action: "unpin", path: pin });+ this.settingsRepo.set(STORAGE_SETTINGS_KEY, JSON.stringify(next));+ return next;+ }++ async pin(input: { path: string; pinned: boolean }): Promise<StorageSettings> {+ this.assertModeOn("pinning");+ this.assertPinnablePath(input.path);+ const current = this.readSettings();+ const pins = input.pinned+ ? [...new Set([...current.pins, input.path])].sort()+ : current.pins.filter((pin) => pin !== input.path);+ return this.updateSettings({ pins });+ }++ async scan(): Promise<StoragePlanView> {+ this.assertModeOn("scanning");+ this.assertIdle("scan");+ this.running = "scan";+ try {+ const nowMs = Date.now();+ const pins = new Set(this.readSettings().pins);+ const ledger = await scanStorage(this.paths.root, await this.liveSet());+ const plan = buildStoragePlan(ledger, {+ id: storagePlanId(nowMs, randomBytes(3).toString("hex")),+ nowMs,+ pins,+ });+ await this.writePlan(plan);+ this.audit({+ action: "scan",+ planId: plan.id,+ entries: plan.entries.length,+ bytes: plan.totalBytes,+ excluded: plan.excluded.length,+ });+ return toPlanView(plan, nowMs);+ } finally {+ this.running = null;+ }+ }++ async plans(): Promise<StoragePlanView[]> {+ const dir = storagePlansDir(this.paths.root);+ let names: string[];+ try {+ names = await fs.readdir(dir);+ } catch {+ return [];+ }+ const nowMs = Date.now();+ const views: StoragePlanView[] = [];+ // The id starts with its local timestamp, so a reverse string sort is newest first.+ for (const name of names+ .filter((n) => n.endsWith(".json"))+ .sort()+ .reverse()) {+ if (views.length >= PLAN_LIST_LIMIT) break;+ const plan = await this.readPlanFile(name.slice(0, -".json".length));+ if (plan !== null) views.push(toPlanView(plan, nowMs));+ }+ return views;+ }++ async plan(planId: string): Promise<StoragePlanView> {+ const plan = await this.readPlanFile(planId);+ if (plan === null) {+ throw new HttpError(+ 404,+ "plan_not_found",+ "No plan with that id. Scan again for a new bill.",+ );+ }+ return toPlanView(plan, Date.now());+ }++ /**+ * The one destructive path: validate the whole batch against the bill and the disk, and only+ * then move each entry. Validation is all-or-nothing — a single stale, pinned, referenced or+ * disallowed entry refuses the run and names why, because a person approved a list and not a+ * subset of it — while the moves themselves are per entry, so one failure does not strand the+ * rest half-done (each move is logged before it happens, and a rerun converges).+ */+ async apply(input: {+ planId: string;+ fingerprint: string;+ paths: string[];+ }): Promise<StorageApplyResponse> {+ this.assertModeOn("applying");+ this.assertIdle("apply");+ this.running = "apply";+ try {+ const nowMs = Date.now();+ const plan = await this.readPlanFile(input.planId);+ if (plan === null) {+ throw new HttpError(+ 404,+ "plan_not_found",+ "No plan with that id. Scan again for a new bill.",+ );+ }+ if (plan.appliedAtMs !== undefined) {+ throw new HttpError(+ 409,+ "plan_used",+ "This plan has already been applied. A plan is valid for one run: scan again for a new bill.",+ );+ }+ if (nowMs > plan.expiresAtMs) {+ throw new HttpError(+ 409,+ "plan_expired",+ "This plan is older than 24 hours. Scan again so the bill describes the disk as it is now.",+ );+ }+ if (input.fingerprint !== plan.fingerprint) {+ throw new HttpError(+ 409,+ "plan_stale",+ "The fingerprint does not match this plan. Read the bill again before approving it.",+ );+ }+ if (input.paths.length === 0) {+ throw new HttpError(+ 400,+ "nothing_selected",+ "Nothing was selected. Approve at least one entry, by its recorded path.",+ );+ }+ const entries = this.selectEntries(plan, input.paths);+ await this.assertBatchStillValid(entries);+ const result = await this.moveToTrash(plan, entries, nowMs);+ // The plan is spent even when every move failed: it was approved once, and nothing may be+ // replayed against a disk the next scan will describe differently.+ await this.writePlan({+ ...plan,+ appliedAtMs: nowMs,+ appliedPaths: result.moved.map((item) => item.path),+ });+ this.audit({+ action: "apply",+ planId: plan.id,+ trashId: result.trashId,+ moved: result.moved.length,+ failed: result.failed.length,+ bytes: result.freedBytes,+ });+ return result;+ } finally {+ this.running = null;+ }+ }++ async trash(): Promise<StorageTrashEntry[]> {+ const dir = storageTrashDir(this.paths.root);+ let names: string[];+ try {+ names = await fs.readdir(dir);+ } catch {+ return [];+ }+ const nowMs = Date.now();+ const ttlMs = this.readSettings().trashTtlDays * 86_400_000;+ const entries: StorageTrashEntry[] = [];+ for (const name of names.sort().reverse()) {+ const entry = await this.readTrashEntry(name);+ if (entry === null) continue;+ entries.push({ ...entry, expired: nowMs - Date.parse(entry.createdAt) > ttlMs });+ }+ return entries;+ }++ /** Puts every tree in one trash entry back where it came from, refusing what is in the way. */+ async restore(trashId: string): Promise<StorageRestoreResponse> {+ this.assertModeOn("restoring");+ this.assertIdle("restore");+ this.running = "restore";+ try {+ const manifest = await this.readTrashManifest(trashId);+ if (manifest === null) {+ throw new HttpError(404, "trash_not_found", "No trash entry with that id.");+ }+ const entryDir = path.join(storageTrashDir(this.paths.root), trashId);+ const restored: string[] = [];+ const skipped: { path: string; reason: string }[] = [];+ for (const item of manifest.items) {+ const source = path.join(entryDir, TRASH_ITEMS_DIR, ...item.path.split("/"));+ const target = path.join(this.paths.root, ...item.path.split("/"));+ if (!(await exists(source))) {+ skipped.push({ path: item.path, reason: "not_in_trash" });+ continue;+ }+ if (await exists(target)) {+ // Something else is there now — the path was reused by a new Session's Workspace, or+ // the tree was put back by other means. Neither is a reason to overwrite it.+ skipped.push({ path: item.path, reason: "target_exists" });+ continue;+ }+ try {+ await fs.mkdir(path.dirname(target), { recursive: true });+ await this.audit({ action: "restore", trashId, path: item.path });+ await fs.rename(source, target);+ restored.push(item.path);+ } catch (e) {+ skipped.push({ path: item.path, reason: reasonOf(e) });+ }+ }+ // An entry that holds nothing any more is removed with the empty directories it leaves:+ // nothing in it is data a person put there, and an empty trash reads as a broken one.+ // "Holds nothing" is asked of the whole tree, not of the top level: moving one tree out+ // leaves the directories it was nested in behind, empty.+ const remaining = await hasAnyContent(path.join(entryDir, TRASH_ITEMS_DIR));+ if (!remaining) await fs.rm(entryDir, { recursive: true, force: true });+ this.audit({+ action: "restore_done",+ trashId,+ restored: restored.length,+ skipped: skipped.length,+ });+ return { id: trashId, restored, skipped, remaining };+ } finally {+ this.running = null;+ }+ }++ /**+ * The one place that deletes. With an id it removes that trash entry; without one it removes+ * the entries past the retention. Both are a person's command — nothing calls this on a+ * timer — and neither can reach anything outside `<root>/.trash`.+ */+ async purge(trashId: string | null): Promise<StoragePurgeResponse> {+ this.assertModeOn("purging");+ this.assertIdle("purge");+ this.running = "purge";+ try {+ if (trashId !== null && !ID_PATTERN.test(trashId)) {+ throw new HttpError(400, "invalid_trash_id", "That is not a trash id.");+ }+ const ttlMs = this.readSettings().trashTtlDays * 86_400_000;+ const nowMs = Date.now();+ const purged: { id: string; bytes: number; files: number }[] = [];+ const trashRoot = storageTrashDir(this.paths.root);+ if (trashId !== null && !(await exists(path.join(trashRoot, trashId)))) {+ throw new HttpError(404, "trash_not_found", "No trash entry with that id.");+ }+ const candidates =+ trashId === null+ ? (await this.trash()).filter((entry) => entry.expired).map((entry) => entry.id)+ : [trashId];+ for (const id of candidates) {+ const dir = path.join(trashRoot, id);+ const measured = await measureStorageEntry(dir);+ if (measured === null) continue;+ await this.audit({+ action: "purge",+ trashId: id,+ bytes: measured.bytes,+ expiredOnly: trashId === null,+ ageMs: nowMs,+ });+ await fs.rm(dir, { recursive: true, force: true });+ purged.push({ id, bytes: measured.bytes, files: measured.files });+ }+ return { purged };+ } finally {+ this.running = null;+ }+ }++ /**+ * The selected paths, as plan entries: every one must be on the bill, of a class this version+ * may act on, allowed by the prefix whitelist, and not pinned. Checked before the disk is+ * touched at all, and the failure names the path so the person can fix the selection.+ */+ private selectEntries(plan: StoragePlan, paths: string[]): StoragePlanEntry[] {+ const byPath = new Map(plan.entries.map((entry) => [entry.path, entry]));+ const pins = new Set(this.readSettings().pins);+ const selected: StoragePlanEntry[] = [];+ const seen = new Set<string>();+ for (const requested of paths) {+ if (seen.has(requested)) continue;+ seen.add(requested);+ const entry = byPath.get(requested);+ if (entry === undefined) {+ throw new HttpError(+ 400,+ "unknown_path",+ `Not an entry of this plan: ${requested}. Read the bill again.`,+ );+ }+ if (!isExecutableStorageClass(entry.class)) {+ throw new HttpError(+ 409,+ "class_not_executable",+ `This version does not clean ${entry.class} entries; it only reports them: ${entry.path}.`,+ );+ }+ if (!isPlannablePath(entry.path, entry.class)) {+ throw new HttpError(+ 400,+ "path_not_allowed",+ `Outside what this class may touch: ${entry.path}.`,+ );+ }+ if (pins.has(entry.path)) {+ throw new HttpError(+ 409,+ "pinned_path",+ `Pinned — it will never be cleaned: ${entry.path}.`,+ );+ }+ selected.push(entry);+ }+ return selected;+ }++ /**+ * The disk check, run against the whole selection before a single move: every entry still+ * resolves inside the root as a real directory, still measures exactly as the bill recorded,+ * and is still unreferenced by live state. All-or-nothing on purpose — the answer to any+ * mismatch is a new scan, and a partial run would clean up a list nobody reviewed as a whole.+ */+ private async assertBatchStillValid(entries: StoragePlanEntry[]): Promise<void> {+ const root = this.paths.root;+ const live = await this.liveSet();+ const gone: string[] = [];+ const changed: string[] = [];+ const escaped: string[] = [];+ const revived: string[] = [];+ const targets: { entry: StoragePlanEntry; target: string }[] = [];+ for (const entry of entries) {+ const target = await resolveStorageEntry(root, entry.path);+ if (target === null) {+ // Either it vanished, or it is a symlink (or a file) where the bill recorded a+ // directory: both are drift, and neither may be moved.+ escaped.push(entry.path);+ continue;+ }+ const measured = await measureStorageEntry(target);+ if (measured === null) {+ gone.push(entry.path);+ continue;+ }+ const nowFingerprint = planEntryFingerprint({+ path: entry.path,+ bytes: measured.bytes,+ newestMtimeMs: measured.newestMtimeMs,+ });+ if (nowFingerprint !== entry.fingerprint) {+ changed.push(entry.path);+ continue;+ }+ if (live.workspacePaths.has(target)) {+ revived.push(entry.path);+ continue;+ }+ targets.push({ entry, target });+ }+ if (escaped.length > 0) {+ throw new HttpError(+ 409,+ "path_not_allowed",+ `No longer a directory inside the data root, or not one this version may move: ${nameList(escaped)}.`,+ );+ }+ if (gone.length > 0) {+ throw new HttpError(409, "plan_stale", `Gone since the scan: ${nameList(gone)}. Scan again.`);+ }+ if (changed.length > 0) {+ throw new HttpError(+ 409,+ "plan_stale",+ `Changed since the scan (size or modification time): ${nameList(changed)}. Scan again.`,+ );+ }+ if (revived.length > 0) {+ throw new HttpError(+ 409,+ "entry_still_live",+ `A Session started using this after the scan, so it is not a candidate any more: ${nameList(revived)}.`,+ );+ }+ }++ /**+ * Moves each approved entry into this run's trash directory. A rename within one filesystem,+ * so a move is atomic and a failure leaves the tree exactly where it was; the audit line is+ * written *before* the move, which is what makes a torn run explainable.+ */+ private async moveToTrash(+ plan: StoragePlan,+ entries: StoragePlanEntry[],+ nowMs: number,+ ): Promise<StorageApplyResponse> {+ const trashRoot = storageTrashDir(this.paths.root);+ const moved: { path: string; bytes: number; files: number }[] = [];+ const failed: { path: string; reason: string }[] = [];+ // Resolve the entries again here rather than trusting the check above: the two are one+ // breath apart, but the path is what gets joined, and it is cheap to be sure.+ const resolved: { entry: StoragePlanEntry; target: string }[] = [];+ for (const entry of entries) {+ const target = await resolveStorageEntry(this.paths.root, entry.path);+ if (target === null) {+ failed.push({ path: entry.path, reason: "path_not_allowed" });+ continue;+ }+ resolved.push({ entry, target });+ }+ if (resolved.length === 0) {+ return { planId: plan.id, trashId: null, moved, failed, freedBytes: 0 };+ }+ const trashId = await this.createTrashEntry(trashRoot, plan, nowMs);+ const entryDir = path.join(trashRoot, trashId);+ const manifest: TrashManifest = {+ id: trashId,+ createdAtMs: nowMs,+ planId: plan.id,+ items: resolved.map(({ entry }) => ({+ path: entry.path,+ class: entry.class,+ bytes: entry.bytes,+ files: entry.files,+ })),+ };+ await fs.writeFile(+ path.join(entryDir, TRASH_MANIFEST),+ `${JSON.stringify(manifest, null, 2)}\n`,+ "utf8",+ );+ for (const { entry, target } of resolved) {+ const destination = path.join(entryDir, TRASH_ITEMS_DIR, ...entry.path.split("/"));+ try {+ await fs.mkdir(path.dirname(destination), { recursive: true });+ await this.audit({+ action: "move",+ planId: plan.id,+ trashId,+ path: entry.path,+ class: entry.class,+ bytes: entry.bytes,+ files: entry.files,+ rules: entry.rules,+ });+ await fs.rename(target, destination);+ moved.push({ path: entry.path, bytes: entry.bytes, files: entry.files });+ } catch (e) {+ failed.push({ path: entry.path, reason: reasonOf(e) });+ await this.audit({+ action: "move_failed",+ planId: plan.id,+ path: entry.path,+ reason: reasonOf(e),+ });+ }+ }+ return {+ planId: plan.id,+ trashId,+ moved,+ failed,+ freedBytes: moved.reduce((sum, item) => sum + item.bytes, 0),+ };+ }++ /** This run's trash directory, with a counter when another run already used the stamp. */+ private async createTrashEntry(+ trashRoot: string,+ plan: StoragePlan,+ nowMs: number,+ ): Promise<string> {+ const stamp = storageTrashId(nowMs);+ for (let attempt = 0; ; attempt += 1) {+ const id = attempt === 0 ? stamp : `${stamp}-${attempt + 1}`;+ const dir = path.join(trashRoot, id);+ try {+ await fs.mkdir(dir, { recursive: false });+ return id;+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code === "ENOENT") {+ await fs.mkdir(trashRoot, { recursive: true });+ continue;+ }+ if ((e as NodeJS.ErrnoException).code === "EEXIST" && attempt < 50) continue;+ // Inside the trash but outside a run's directory, so the manifest is still the record+ // of what moved: a failure to name the run's own directory is worth stopping for.+ throw new HttpError(+ 500,+ "trash_unavailable",+ `Could not create a trash entry under ${trashRoot} for plan ${plan.id}.`,+ );+ }+ }+ }++ /** Reads one trash entry: the manifest for its items, the disk for its size. */+ private async readTrashEntry(id: string): Promise<StorageTrashEntry | null> {+ const dir = path.join(storageTrashDir(this.paths.root), id);+ const measured = await measureStorageEntry(dir);+ if (measured === null) return null;+ const manifest = await this.readTrashManifest(id);+ const createdAtMs = manifest?.createdAtMs ?? (await mtimeMs(dir));+ return {+ id,+ createdAt: new Date(createdAtMs).toISOString(),+ planId: manifest?.planId ?? null,+ bytes: measured.bytes,+ files: measured.files,+ items: manifest?.items ?? [],+ // Overwritten by the caller, which is where the retention setting is read.+ expired: false,+ };+ }++ /**+ * A trash entry's manifest, or null when it is missing or unreadable. A hand-edited or+ * truncated manifest still lets the entry be listed and purged — it just cannot be restored+ * entry by entry, which is a documentable state rather than a crash.+ */+ private async readTrashManifest(id: string): Promise<TrashManifest | null> {+ if (!ID_PATTERN.test(id)) return null;+ try {+ const raw = await fs.readFile(+ path.join(storageTrashDir(this.paths.root), id, TRASH_MANIFEST),+ "utf8",+ );+ const parsed: unknown = JSON.parse(raw);+ if (typeof parsed !== "object" || parsed === null) return null;+ const manifest = parsed as Partial<TrashManifest>;+ if (!Array.isArray(manifest.items)) return null;+ return {+ id,+ createdAtMs: typeof manifest.createdAtMs === "number" ? manifest.createdAtMs : 0,+ planId: typeof manifest.planId === "string" ? manifest.planId : "",+ items: manifest.items.filter(+ (item): item is TrashManifest["items"][number] =>+ typeof item === "object" &&+ item !== null &&+ typeof (item as { path?: unknown }).path === "string",+ ),+ };+ } catch {+ return null;+ }+ }++ private async writePlan(plan: StoragePlan): Promise<void> {+ const dir = storagePlansDir(this.paths.root);+ await fs.mkdir(dir, { recursive: true });+ await fs.writeFile(+ path.join(dir, `${plan.id}.json`),+ `${JSON.stringify(plan, null, 2)}\n`,+ "utf8",+ );+ }++ private async readPlanFile(id: string): Promise<StoragePlan | null> {+ if (!ID_PATTERN.test(id)) return null;+ try {+ const raw = await fs.readFile(+ path.join(storagePlansDir(this.paths.root), `${id}.json`),+ "utf8",+ );+ const parsed: unknown = JSON.parse(raw);+ if (typeof parsed !== "object" || parsed === null) return null;+ const plan = parsed as Partial<StoragePlan>;+ if (typeof plan.fingerprint !== "string" || !Array.isArray(plan.entries)) return null;+ return {+ id,+ root: typeof plan.root === "string" ? plan.root : this.paths.root,+ createdAtMs: typeof plan.createdAtMs === "number" ? plan.createdAtMs : 0,+ expiresAtMs: typeof plan.expiresAtMs === "number" ? plan.expiresAtMs : 0,+ fingerprint: plan.fingerprint,+ totalBytes: typeof plan.totalBytes === "number" ? plan.totalBytes : 0,+ entries: plan.entries.filter((entry): entry is StoragePlanEntry => isPlanEntry(entry)),+ excluded: Array.isArray(plan.excluded)+ ? plan.excluded.filter((p) => typeof p === "string")+ : [],+ ...(typeof plan.appliedAtMs === "number" ? { appliedAtMs: plan.appliedAtMs } : {}),+ ...(Array.isArray(plan.appliedPaths)+ ? { appliedPaths: plan.appliedPaths.filter((p) => typeof p === "string") }+ : {}),+ };+ } catch {+ return null;+ }+ }++ private readSettings(): StorageSettings {+ const raw = this.settingsRepo.get(STORAGE_SETTINGS_KEY);+ if (raw === null) return { ...DEFAULT_STORAGE_SETTINGS };+ try {+ const parsed: unknown = JSON.parse(raw);+ if (typeof parsed !== "object" || parsed === null) return { ...DEFAULT_STORAGE_SETTINGS };+ const value = parsed as Partial<StorageSettings>;+ const ttl = value.trashTtlDays;+ return {+ // Default off on anything unreadable: the mode is the switch a person turns on, and an+ // unparseable row means nobody has.+ enabled: value.enabled === true,+ trashTtlDays:+ typeof ttl === "number" &&+ Number.isInteger(ttl) &&+ ttl >= MIN_TRASH_TTL_DAYS &&+ ttl <= MAX_TRASH_TTL_DAYS+ ? ttl+ : DEFAULT_TRASH_TTL_DAYS,+ pins: Array.isArray(value.pins) ? value.pins.filter((p) => typeof p === "string") : [],+ };+ } catch {+ return { ...DEFAULT_STORAGE_SETTINGS };+ }+ }++ /** The mode is the whole gate: with it off, nothing here writes and nothing may be planned. */+ private assertModeOn(what: string): void {+ if (!this.readSettings().enabled) {+ throw new HttpError(+ 409,+ "storage_mode_off",+ `Cleanup mode is off, so ${what} is not available. The ledger stays readable; turn the mode on in Settings → Storage.`,+ );+ }+ }++ private assertIdle(what: string): void {+ if (this.running !== null) {+ throw new HttpError(+ 409,+ "storage_busy",+ `Another storage ${this.running} is running; try ${what} once it finishes.`,+ );+ }+ }++ /**+ * A pin must name something inside the root that exists now — the same containment rule a+ * move obeys. A pin for a path that is not there would silently do nothing, and a pin that+ * escaped the root would be a decision about something this machine does not own.+ */+ private assertPinnablePath(relativePath: string): void {+ if (relativePath === "" || relativePath.startsWith("/") || relativePath.includes("\\")) {+ throw new HttpError(+ 400,+ "invalid_pin",+ `A pin is a path relative to the data root: ${relativePath}.`,+ );+ }+ if (relativePath.split("/").some((segment) => segment === "" || segment === "..")) {+ throw new HttpError(+ 400,+ "invalid_pin",+ `A pin must not contain empty or parent segments: ${relativePath}.`,+ );+ }+ const target = path.resolve(this.paths.root, relativePath);+ if (!isInsideRoot(this.paths.root, target)) {+ throw new HttpError(400, "invalid_pin", `Outside the data root: ${relativePath}.`);+ }+ }++ /**+ * One JSON line per decision about data, appended to `<root>/logs/storage-gc.jsonl` and never+ * rewritten. Best effort: a log that cannot be written must not take a move down with it (the+ * move is the thing the person asked for, and the trash manifest records it too), but the+ * failure is not swallowed silently either — it is reported on stderr of the server process.+ */+ private async audit(record: Record<string, unknown> & { action: string }): Promise<void> {+ const line = `${JSON.stringify({ at: new Date().toISOString(), ...record })}\n`;+ try {+ await fs.mkdir(path.dirname(storageLogFile(this.paths.root)), { recursive: true });+ await fs.appendFile(storageLogFile(this.paths.root), line, "utf8");+ } catch (e) {+ process.stderr.write(`storage: could not write the audit log: ${reasonOf(e)}\n`);+ }+ }+/*** The server's live state, in the shape core's `StorageLiveSet` asks for: every Session id* that still exists, the REAL path of each Workspace those Sessions point at (core compares@@ -128,6 +935,106 @@ function toCandidate(entry: LedgerEntry): StorageCandidate {};}+/** A stored plan as the page and the CLI read it: the same bill, with ISO instants. */+function toPlanView(plan: StoragePlan, nowMs: number): StoragePlanView {+ const expired = nowMs > plan.expiresAtMs;+ return {+ id: plan.id,+ root: plan.root,+ createdAt: new Date(plan.createdAtMs).toISOString(),+ expiresAt: new Date(plan.expiresAtMs).toISOString(),+ fingerprint: plan.fingerprint,+ totalBytes: plan.totalBytes,+ entries: plan.entries.map((entry) => ({+ path: entry.path,+ class: entry.class,+ bytes: entry.bytes,+ files: entry.files,+ lastModifiedAt:+ entry.newestMtimeMs === 0 ? null : new Date(entry.newestMtimeMs).toISOString(),+ rules: entry.rules,+ fingerprint: entry.fingerprint,+ executable: isExecutableStorageClass(entry.class),+ })),+ excluded: plan.excluded,+ executableClasses: [...EXECUTABLE_STORAGE_CLASSES],+ appliedAt: plan.appliedAtMs === undefined ? null : new Date(plan.appliedAtMs).toISOString(),+ appliedPaths: plan.appliedPaths ?? [],+ usable: plan.appliedAtMs === undefined && !expired,+ expired,+ };+}++/** Whether a parsed JSON value is one plan entry, field for field, before it is trusted. */+function isPlanEntry(value: unknown): value is StoragePlanEntry {+ if (typeof value !== "object" || value === null) return false;+ const entry = value as Partial<StoragePlanEntry>;+ return (+ typeof entry.path === "string" &&+ typeof entry.class === "string" &&+ typeof entry.bytes === "number" &&+ typeof entry.files === "number" &&+ typeof entry.newestMtimeMs === "number" &&+ typeof entry.fingerprint === "string" &&+ Array.isArray(entry.rules)+ );+}++/** A path list for a refusal message, capped so a wild selection cannot flood the response. */+function nameList(paths: string[]): string {+ const shown = paths.slice(0, 10).join(", ");+ return paths.length > 10 ? `${shown} … (${paths.length} in all)` : shown;+}++/** `fs.access` as a boolean, for the "is something already there" questions. */+async function exists(target: string): Promise<boolean> {+ try {+ await fs.access(target);+ return true;+ } catch {+ return false;+ }+}++/** Names in a directory, or none when it is not there. */+async function readdirNames(dir: string): Promise<string[]> {+ try {+ return await fs.readdir(dir);+ } catch {+ return [];+ }+}++/**+ * Whether anything under `dir` is not a directory: a file, a link, anything that would be lost+ * by removing the tree. Empty directories are what a restore leaves behind, and a trash entry+ * holding only those holds nothing.+ */+async function hasAnyContent(dir: string): Promise<boolean> {+ for (const name of await readdirNames(dir)) {+ const full = path.join(dir, name);+ const st = await fs.lstat(full).catch(() => null);+ if (st === null) continue;+ if (!st.isDirectory()) return true;+ if (await hasAnyContent(full)) return true;+ }+ return false;+}++/** A directory's own modification time, which is the fallback stamp of a manifest-less entry. */+async function mtimeMs(target: string): Promise<number> {+ try {+ return (await fs.stat(target)).mtimeMs;+ } catch {+ return 0;+ }+}++/** A failure's own words, for a report a person reads (`no such file or directory`). */+function reasonOf(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}+/*** The realpaths of a set of Workspace paths. A path that is gone still needs a stable form to* compare against, so it falls back to its resolved self — core's own rule for the directorydiff --git a/packages/server/test/storage-cleanup.test.ts b/packages/server/test/storage-cleanup.test.tsnew file mode 100644index 00000000..3c08b4ce--- /dev/null+++ b/packages/server/test/storage-cleanup.test.ts@@ -0,0 +1,634 @@+/**+ * The reviewed cleanup: scan a bill, approve some of it, move it to the trash, put it back.+ *+ * The route group's promises are what these tests pin, and every one of them is a refusal+ * except the happy path:+ *+ * - with the cleanup mode off nothing writes at all — the ledger stays readable and every+ * other route in the group is refused;+ * - a scan produces a file and nothing else: the data root is byte-for-byte as it was;+ * - an approval is bound to the bill it read (fingerprint), usable once, and good for 24+ * hours; an entry that changed, vanished, or came alive since the scan stops the run;+ * - only a temporary Workspace may be applied; every other class is on the bill and refused;+ * - a pin keeps an entry out of every later bill, and out of a run that still names it;+ * - a move lands in `<root>/.trash/<stamp>/items/<original path>` with a manifest, and a+ * restore puts the tree back exactly as it was;+ * - `purge` is the only deletion, and it only ever removes from the trash.+ */+import fs from "node:fs/promises";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { DEFAULT_PROJECT_ID, planEntryFingerprint } from "@lmliheng/penguin-core";+import type {+ StorageApplyResponse,+ StoragePlanView,+ StoragePlansResponse,+ StoragePlanResponse,+ StoragePurgeResponse,+ StorageReportResponse,+ StorageRestoreResponse,+ StorageSettingsResponse,+ StorageTrashResponse,+} from "../src/api/types.js";+import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";+import type { TestApp } from "./helpers.js";++describe("storage cleanup", () => {+ let t: TestApp;+ let admin: ReturnType<typeof apiClient>;++ beforeAll(async () => {+ t = await createTestApp();+ admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });++ const settings = async (): Promise<StorageSettingsResponse["settings"]> => {+ const res = await admin.get("/api/admin/storage/settings");+ expect(res.status).toBe(200);+ return ((await res.json()) as StorageSettingsResponse).settings;+ };++ const setSettings = async (body: unknown): Promise<StorageSettingsResponse["settings"]> => {+ const res = await admin.put("/api/admin/storage/settings", body);+ expect(res.status).toBe(200);+ return ((await res.json()) as StorageSettingsResponse).settings;+ };++ const enable = async (): Promise<void> => {+ if (!(await settings()).enabled) await setSettings({ enabled: true });+ };++ /** A temporary Workspace nothing points at — the one class this version may move. */+ const tempWorkspace = async (name: string, content = "left behind\n"): Promise<string> => {+ const dir = path.join(+ t.root,+ DEFAULT_PROJECT_ID,+ "agents",+ "default_agent",+ "workspaces",+ name,+ );+ await fs.mkdir(path.join(dir, "sub"), { recursive: true });+ await fs.writeFile(path.join(dir, "sub", "scratch.txt"), content);+ return relative(dir);+ };++ /** Writes a file, creating the directories above it — a draft directory may not exist yet. */+ const write = async (file: string, content: string): Promise<void> => {+ await fs.mkdir(path.dirname(file), { recursive: true });+ await fs.writeFile(file, content);+ };++ /** A draft directory of a Session the index does not know: a candidate, and report-only. */+ const orphanDraft = async (sessionId: string): Promise<string> => {+ const file = path.join(+ t.root,+ DEFAULT_PROJECT_ID,+ "agents",+ "default_agent",+ "scratchpad",+ sessionId,+ "note.md",+ );+ await write(file, "draft\n");+ return relative(path.dirname(file));+ };++ /** The recorded, `/`-separated path the report and a bill use. */+ const relative = (absolute: string): string =>+ path.relative(t.root, absolute).split(path.sep).join("/");++ const absolute = (recorded: string): string => path.join(t.root, ...recorded.split("/"));++ const scan = async (): Promise<StoragePlanView> => {+ await enable();+ const res = await admin.post("/api/admin/storage/plans");+ expect(res.status).toBe(201);+ return ((await res.json()) as StoragePlanResponse).plan;+ };++ const planFile = (id: string): string => path.join(t.root, "storage", "plans", `${id}.json`);++ /** Rewrites the stored bill, for the cases only the disk can set up (expiry, a hand-made entry). */+ const tamper = async (id: string, patch: (plan: Record<string, unknown>) => void) => {+ const file = planFile(id);+ const plan = JSON.parse(await fs.readFile(file, "utf8")) as Record<string, unknown>;+ patch(plan);+ await fs.writeFile(file, JSON.stringify(plan, null, 2));+ };++ const apply = async (body: unknown): Promise<Response> =>+ admin.post("/api/admin/storage/apply", body);++ const applyOrThrow = async (body: unknown): Promise<StorageApplyResponse> => {+ const res = await apply(body);+ expect(res.status).toBe(200);+ return (await res.json()) as StorageApplyResponse;+ };++ /** The status, error code and message of a refused request (the body is read once, here). */+ const refusal = async (+ res: Response,+ ): Promise<{ status: number; code: string; text: string }> => {+ const text = await res.text();+ const body = JSON.parse(text) as { error?: { code?: string } };+ return { status: res.status, code: body.error?.code ?? "", text };+ };++ /**+ * Everything under `root`: relative path, size and content, sorted. The point of a cleanup+ * test is that nothing appears, disappears or changes outside the trash, so a comparison is+ * only as good as what it looks at — this one looks at the bytes.+ *+ * Three things are left out because they are the machinery's own mutable state rather than+ * the data a cleanup acts on: the SQLite database and its sidecars (every settings write+ * lands there, and a read may checkpoint the WAL), `<root>/storage/plans` (a scan is supposed+ * to write one file there) and `<root>/logs` (every decision appends a line, including the+ * scans and mode switches these tests make). What matters — that no tree of the data root is+ * touched outside the trash — is untouched by that, because `.trash` is in the listing.+ */+ const snapshot = async (root: string): Promise<string[]> => {+ const out: string[] = [];+ const visit = async (dir: string): Promise<void> => {+ for (const name of (await fs.readdir(dir)).sort()) {+ const rel = path.relative(root, path.join(dir, name));+ if (dir === root && (name === "web.db" || name.startsWith("web.db-"))) continue;+ if (rel === "storage" || rel === "logs") continue;+ const full = path.join(dir, name);+ const st = await fs.lstat(full);+ if (st.isDirectory()) {+ out.push(`dir ${rel}`);+ await visit(full);+ continue;+ }+ if (st.isSymbolicLink()) {+ out.push(`link ${rel} -> ${await fs.readlink(full)}`);+ continue;+ }+ out.push(`file ${rel} ${st.size} ${await fs.readFile(full, "utf8")}`);+ }+ };+ await visit(root);+ return out;+ };++ it("refuses every write while the cleanup mode is off, and keeps the ledger readable", async () => {+ const workspace = await tempWorkspace("tmp-mode-off");+ await setSettings({ enabled: false });++ // Reading is always allowed: the mode gates doing, not knowing.+ expect((await admin.get("/api/admin/storage")).status).toBe(200);+ expect((await admin.get("/api/admin/storage/plans")).status).toBe(200);+ expect((await admin.get("/api/admin/storage/trash")).status).toBe(200);+ expect((await settings()).enabled).toBe(false);++ const plan = await scan();+ // The scan above enabled the mode (it is the one write there is), so turn it off again and+ // take the baseline after that: what follows must change nothing bytes either.+ await setSettings({ enabled: false });+ const before = await snapshot(t.root);++ expect(await refusal(await admin.post("/api/admin/storage/plans"))).toMatchObject({+ status: 409,+ code: "storage_mode_off",+ });+ expect(+ await refusal(await apply({ planId: plan.id, fingerprint: plan.fingerprint, paths: [] })),+ ).toMatchObject({ status: 409, code: "storage_mode_off" });+ expect(await refusal(await admin.post("/api/admin/storage/trash/purge", {}))).toMatchObject({+ status: 409,+ code: "storage_mode_off",+ });+ expect(+ await refusal(await admin.post("/api/admin/storage/trash/restore", { id: "x" })),+ ).toMatchObject({ status: 409, code: "storage_mode_off" });+ expect(+ await refusal(+ await admin.post(`/api/admin/storage/plans/${plan.id}/pin`, { path: workspace }),+ ),+ ).toMatchObject({ status: 409, code: "storage_mode_off" });++ // The refused writes left nothing behind: no trash entry, and the workspace untouched.+ expect(await fs.readdir(absolute(workspace))).toEqual(["sub"]);+ expect(await snapshot(t.root)).toEqual(before);+ });++ it("answers 403 admin_required to a non-admin on every route in the group", async () => {+ const { cookie } = await provisionUser(t.app, "storagenorm");+ const api = apiClient(t.app, cookie);+ const plan = await scan();+ const refused = [+ await api.get("/api/admin/storage"),+ await api.get("/api/admin/storage/settings"),+ await api.put("/api/admin/storage/settings", { enabled: true }),+ await api.get("/api/admin/storage/plans"),+ await api.post("/api/admin/storage/plans"),+ await api.get(`/api/admin/storage/plans/${plan.id}`),+ await api.post(`/api/admin/storage/plans/${plan.id}/pin`, { path: "x" }),+ await api.post("/api/admin/storage/apply", { planId: "x", fingerprint: "x", paths: [] }),+ await api.get("/api/admin/storage/trash"),+ await api.post("/api/admin/storage/trash/restore", { id: "x" }),+ await api.post("/api/admin/storage/trash/purge", {}),+ ];+ for (const res of refused) {+ expect(await refusal(res)).toMatchObject({ status: 403, code: "admin_required" });+ }+ });++ it("scans a bill that names the candidates and their reasons, and touches nothing else", async () => {+ const workspace = await tempWorkspace("tmp-bill");+ await orphanDraft("s-orphan");+ const before = await snapshot(t.root);+ const plan = await scan();++ const entry = plan.entries.find((e) => e.path === workspace);+ expect(entry?.class).toBe("tmp_workspaces");+ expect(entry?.rules).toContain("unreferenced");+ expect(entry?.executable).toBe(true);+ expect(entry?.files).toBe(1);+ expect(entry?.bytes).toBeGreaterThan(0);+ expect(entry?.fingerprint).toMatch(/^[0-9a-f]{32}$/);++ // The draft directory is on the bill too — a person should see it — but it is not+ // executable, and the bill says which classes are.+ const draft = plan.entries.find((e) => e.class === "session_drafts");+ expect(draft?.executable).toBe(false);+ expect(plan.executableClasses).toEqual(["tmp_workspaces"]);+ expect(plan.usable).toBe(true);+ expect(plan.expired).toBe(false);+ expect(Date.parse(plan.expiresAt) - Date.parse(plan.createdAt)).toBe(24 * 60 * 60 * 1000);++ // A scan is a read of the data root plus one file of its own: the root itself is unchanged.+ expect(await snapshot(t.root)).toEqual(before);+ expect(await fs.readFile(planFile(plan.id), "utf8")).toContain(plan.fingerprint);+ expect((await admin.get(`/api/admin/storage/plans/${plan.id}`)).status).toBe(200);+ const list = (await (+ await admin.get("/api/admin/storage/plans")+ ).json()) as StoragePlansResponse;+ expect(list.plans.map((p) => p.id)).toContain(plan.id);+ });++ it("moves an approved temporary Workspace into the trash and puts it back unchanged", async () => {+ const workspace = await tempWorkspace("tmp-happy", "a deliverable\n");+ const tree = await snapshot(absolute(workspace));+ const plan = await scan();++ const result = await applyOrThrow({+ planId: plan.id,+ fingerprint: plan.fingerprint,+ paths: [workspace],+ });+ expect(result.moved.map((m) => m.path)).toEqual([workspace]);+ expect(result.failed).toEqual([]);+ expect(result.freedBytes).toBeGreaterThan(0);+ expect(result.trashId).not.toBeNull();++ // The workspace is gone from where it was, and the trash holds it under its original path.+ expect(await fs.stat(absolute(workspace)).catch(() => null)).toBeNull();+ const trashId = result.trashId ?? "";+ expect(+ await snapshot(path.join(t.root, ".trash", trashId, "items", ...workspace.split("/"))),+ ).toEqual(tree);+ const manifest = JSON.parse(+ await fs.readFile(path.join(t.root, ".trash", trashId, "manifest.json"), "utf8"),+ ) as { planId: string; items: { path: string; class: string }[] };+ expect(manifest.planId).toBe(plan.id);+ expect(manifest.items).toEqual([+ {+ path: workspace,+ class: "tmp_workspaces",+ bytes: result.moved[0]?.bytes,+ files: result.moved[0]?.files,+ },+ ]);++ // Applying again is refused: this plan is spent.+ expect(+ await refusal(+ await apply({ planId: plan.id, fingerprint: plan.fingerprint, paths: [workspace] }),+ ),+ ).toMatchObject({ status: 409, code: "plan_used" });++ // The ledger now counts the trash, and the trash list names what is in it.+ const trash = (await (+ await admin.get("/api/admin/storage/trash")+ ).json()) as StorageTrashResponse;+ const entry = trash.entries.find((e) => e.id === trashId);+ expect(entry?.items.map((i) => i.path)).toEqual([workspace]);+ expect(entry?.expired).toBe(false);+ // The ledger counts the trash like everything else, so a report says what the runs hold.+ const report = (await (await admin.get("/api/admin/storage")).json()) as StorageReportResponse;+ expect(report.report.classes.find((c) => c.class === "trash")?.bytes).toBeGreaterThan(0);++ // Restore puts the bytes back, and an entry that holds nothing is removed with them.+ const restored = (await (+ await admin.post("/api/admin/storage/trash/restore", { id: trashId })+ ).json()) as StorageRestoreResponse;+ expect(restored.restored).toEqual([workspace]);+ expect(restored.skipped).toEqual([]);+ expect(restored.remaining).toBe(false);+ expect(await snapshot(absolute(workspace))).toEqual(tree);+ expect(await fs.stat(path.join(t.root, ".trash", trashId)).catch(() => null)).toBeNull();+ });++ it("refuses a fingerprint that is not this plan's", async () => {+ const workspace = await tempWorkspace("tmp-fingerprint");+ const plan = await scan();+ expect(+ await refusal(await apply({ planId: plan.id, fingerprint: "nope", paths: [workspace] })),+ ).toMatchObject({ status: 409, code: "plan_stale" });+ expect(await fs.stat(absolute(workspace))).not.toBeNull();+ });++ it("refuses an expired plan, and says so before it is applied", async () => {+ const workspace = await tempWorkspace("tmp-expired");+ const plan = await scan();+ await tamper(plan.id, (raw) => {+ raw.expiresAtMs = Date.now() - 1000;+ });+ const view = (await (+ await admin.get(`/api/admin/storage/plans/${plan.id}`)+ ).json()) as StoragePlanResponse;+ expect(view.plan.expired).toBe(true);+ expect(view.plan.usable).toBe(false);+ expect(+ await refusal(+ await apply({ planId: plan.id, fingerprint: plan.fingerprint, paths: [workspace] }),+ ),+ ).toMatchObject({ status: 409, code: "plan_expired" });+ expect(await fs.stat(absolute(workspace))).not.toBeNull();+ });++ it("refuses a batch whose entry changed since the scan", async () => {+ const workspace = await tempWorkspace("tmp-drift");+ const plan = await scan();+ await fs.writeFile(+ path.join(absolute(workspace), "sub", "later.txt"),+ "written after the scan\n",+ );+ const res = await apply({ planId: plan.id, fingerprint: plan.fingerprint, paths: [workspace] });+ const refused = await refusal(res);+ expect(refused).toMatchObject({ status: 409, code: "plan_stale" });+ expect(refused.text).toContain(workspace);+ expect(await fs.stat(absolute(workspace))).not.toBeNull();+ });++ it("refuses an entry a Session started using after the scan", async () => {+ const workspace = await tempWorkspace("tmp-revived");+ const plan = await scan();+ const now = new Date().toISOString();+ t.deps.sessionsRepo.insert({+ sessionId: "session-2026-01-01-00-00-00-revived",+ projectId: DEFAULT_PROJECT_ID,+ agentId: "default_agent",+ provider: "probe",+ modelId: "probe-model",+ workspace: absolute(workspace),+ approvalMode: "allow-all",+ title: null,+ client: "web",+ lastActiveAt: now,+ createdAt: now,+ });+ expect(+ await refusal(+ await apply({ planId: plan.id, fingerprint: plan.fingerprint, paths: [workspace] }),+ ),+ ).toMatchObject({ status: 409, code: "entry_still_live" });+ expect(await fs.stat(absolute(workspace))).not.toBeNull();+ });++ it("reports the classes it will not clean, and refuses a selection of them", async () => {+ await orphanDraft("s-report-only");+ const plan = await scan();+ const draft = plan.entries.find((e) => e.class === "session_drafts");+ expect(draft).toBeDefined();+ if (draft === undefined) return;+ expect(+ await refusal(+ await apply({ planId: plan.id, fingerprint: plan.fingerprint, paths: [draft.path] }),+ ),+ ).toMatchObject({ status: 409, code: "class_not_executable" });+ expect(await fs.stat(absolute(draft.path))).not.toBeNull();+ });++ it("keeps a pinned path out of the next bill and refuses a plan that still names it", async () => {+ const workspace = await tempWorkspace("tmp-pinned");+ const before = await scan();+ const pinned = (await (+ await admin.post(`/api/admin/storage/plans/${before.id}/pin`, { path: workspace })+ ).json()) as StorageSettingsResponse;+ expect(pinned.settings.pins).toContain(workspace);++ // A bill written after the pin leaves the entry out, and says that it did.+ const after = await scan();+ expect(after.entries.map((e) => e.path)).not.toContain(workspace);+ expect(after.excluded).toContain(workspace);++ // The older bill still names it, and a run against that bill is refused rather than obeyed.+ expect(+ await refusal(+ await apply({ planId: before.id, fingerprint: before.fingerprint, paths: [workspace] }),+ ),+ ).toMatchObject({ status: 409, code: "pinned_path" });+ expect(await fs.stat(absolute(workspace))).not.toBeNull();++ // Unpinning brings it back, and the settings round-trip is what an admin reads.+ const unpinned = (await (+ await admin.post(`/api/admin/storage/plans/${before.id}/pin`, {+ path: workspace,+ pinned: false,+ })+ ).json()) as StorageSettingsResponse;+ expect(unpinned.settings.pins).not.toContain(workspace);+ expect((await scan()).entries.map((e) => e.path)).toContain(workspace);+ });++ it("refuses a selection that is empty, unknown, or not a temporary Workspace", async () => {+ const workspace = await tempWorkspace("tmp-selection");+ const plan = await scan();+ expect(+ await refusal(await apply({ planId: plan.id, fingerprint: plan.fingerprint, paths: [] })),+ ).toMatchObject({ status: 400, code: "nothing_selected" });+ expect(+ await refusal(+ await apply({+ planId: plan.id,+ fingerprint: plan.fingerprint,+ paths: ["proj/agents/agent/nope"],+ }),+ ),+ ).toMatchObject({ status: 400, code: "unknown_path" });++ // A hand-written bill may name anything; what may be moved is still only the whitelist.+ await tamper(plan.id, (raw) => {+ const entries = raw.entries as unknown[];+ entries.push({+ path: `${DEFAULT_PROJECT_ID}/agents/default_agent/agent_state`,+ class: "tmp_workspaces",+ bytes: 1,+ files: 1,+ newestMtimeMs: 1,+ rules: ["unreferenced"],+ fingerprint: `deadbeef${"0".repeat(24)}`,+ });+ });+ expect(+ await refusal(+ await apply({+ planId: plan.id,+ fingerprint: plan.fingerprint,+ paths: [`${DEFAULT_PROJECT_ID}/agents/default_agent/agent_state`],+ }),+ ),+ ).toMatchObject({ status: 400, code: "path_not_allowed" });+ expect(await fs.stat(absolute(workspace))).not.toBeNull();+ });++ it("refuses a planned path that is a link out of the root", async () => {+ const outside = await fs.mkdtemp(path.join(t.root, "..", "adelie-storage-outside-"));+ await fs.writeFile(path.join(outside, "f.txt"), "outside the root\n");+ const link = path.join(+ t.root,+ DEFAULT_PROJECT_ID,+ "agents",+ "default_agent",+ "workspaces",+ "tmp-linked",+ );+ await fs.mkdir(path.dirname(link), { recursive: true });+ await fs.symlink(outside, link);+ try {+ const recorded = relative(link);+ const plan = await scan();+ const stat = await fs.stat(outside);+ // The scan never follows a link, so the entry has to be put on the bill by hand: this is+ // the "a plan file was edited, or written by an older version" case.+ await tamper(plan.id, (raw) => {+ const entries = raw.entries as unknown[];+ entries.push({+ path: recorded,+ class: "tmp_workspaces",+ bytes: stat.size,+ files: 1,+ newestMtimeMs: stat.mtimeMs,+ rules: ["unreferenced"],+ fingerprint: planEntryFingerprint({+ path: recorded,+ bytes: stat.size,+ newestMtimeMs: stat.mtimeMs,+ }),+ });+ });+ expect(+ await refusal(+ await apply({ planId: plan.id, fingerprint: plan.fingerprint, paths: [recorded] }),+ ),+ ).toMatchObject({ status: 409, code: "path_not_allowed" });+ expect(await fs.readFile(path.join(outside, "f.txt"), "utf8")).toBe("outside the root\n");+ expect(await fs.readlink(link)).toBe(outside);+ } finally {+ await fs.rm(outside, { recursive: true, force: true });+ await fs.rm(link, { force: true });+ }+ });++ it("purges the entry it is given, and only what is past the retention when given none", async () => {+ const first = await tempWorkspace("tmp-purge-one");+ const plan = await scan();+ const applied = await applyOrThrow({+ planId: plan.id,+ fingerprint: plan.fingerprint,+ paths: [first],+ });+ const keep = applied.trashId ?? "";++ // A purge without an id only reaches entries older than the retention, so a fresh one stays.+ await setSettings({ trashTtlDays: 14 });+ const nothing = (await (+ await admin.post("/api/admin/storage/trash/purge", {})+ ).json()) as StoragePurgeResponse;+ expect(nothing.purged).toEqual([]);+ expect(await fs.stat(path.join(t.root, ".trash", keep))).not.toBeNull();++ // Backdate the manifest and the same call takes it — the retention is days, not a timer.+ const manifestPath = path.join(t.root, ".trash", keep, "manifest.json");+ const manifest = JSON.parse(await fs.readFile(manifestPath, "utf8")) as Record<string, unknown>;+ manifest.createdAtMs = Date.now() - 20 * 86_400_000;+ await fs.writeFile(manifestPath, JSON.stringify(manifest));+ const expired = (await (+ await admin.post("/api/admin/storage/trash/purge", {})+ ).json()) as StoragePurgeResponse;+ expect(expired.purged.map((p) => p.id)).toEqual([keep]);+ expect(expired.purged[0]?.bytes).toBeGreaterThan(0);+ expect(await fs.stat(path.join(t.root, ".trash", keep)).catch(() => null)).toBeNull();++ // Naming an entry removes exactly that one, whatever its age.+ const second = await tempWorkspace("tmp-purge-two");+ const plan2 = await scan();+ const applied2 = await applyOrThrow({+ planId: plan2.id,+ fingerprint: plan2.fingerprint,+ paths: [second],+ });+ const named = applied2.trashId ?? "";+ const purged = (await (+ await admin.post("/api/admin/storage/trash/purge", { id: named })+ ).json()) as StoragePurgeResponse;+ expect(purged.purged.map((p) => p.id)).toEqual([named]);+ expect(await fs.stat(path.join(t.root, ".trash", named)).catch(() => null)).toBeNull();+ expect(+ await refusal(await admin.post("/api/admin/storage/trash/purge", { id: named })),+ ).toMatchObject({ status: 404, code: "trash_not_found" });+ // A purge never reaches outside the trash, whatever it is asked for.+ expect(+ await refusal(await admin.post("/api/admin/storage/trash/purge", { id: ".." })),+ ).toMatchObject({ status: 400, code: "invalid_trash_id" });+ });++ it("records every decision in the audit log, and refuses an unknown plan", async () => {+ const workspace = await tempWorkspace("tmp-audit");+ await setSettings({ enabled: true });+ const plan = await scan();+ await applyOrThrow({ planId: plan.id, fingerprint: plan.fingerprint, paths: [workspace] });+ await setSettings({ enabled: false });++ const lines = (await fs.readFile(path.join(t.root, "logs", "storage-gc.jsonl"), "utf8"))+ .trim()+ .split("\n")+ .map((line) => JSON.parse(line) as { action: string; path?: string; planId?: string });+ const actions = lines.map((line) => line.action);+ expect(actions).toContain("mode_on");+ expect(actions).toContain("mode_off");+ expect(actions).toContain("scan");+ expect(actions).toContain("apply");+ // The log accumulates across the runs this file makes, so the line is looked up by path.+ const move = lines.find((line) => line.action === "move" && line.path === workspace);+ expect(move?.path).toBe(workspace);+ expect(move?.planId).toBe(plan.id);++ expect(+ await refusal(await admin.get("/api/admin/storage/plans/2026-01-01-00-00-00-ffffff")),+ ).toMatchObject({ status: 404, code: "plan_not_found" });+ // A plan id is a file name, so anything that is not one never reaches the filesystem.+ const traversal = await admin.get("/api/admin/storage/plans/..%2F..%2Fetc");+ expect([400, 404]).toContain(traversal.status);+ });++ it("refuses a scan and a move while another run holds the writer", async () => {+ // The single-writer rule is one flag, and what it has to do is refuse rather than queue:+ // a second run would otherwise clean against a directory the first one is already moving.+ await enable();+ const running = t.deps.tree.api<{ scan(): Promise<unknown> }>(+ "ObservabilityModule",+ "StorageAdmin",+ );+ const first = running.scan();+ const second = await refusal(await admin.post("/api/admin/storage/plans"));+ await first;+ expect(second).toMatchObject({ status: 409, code: "storage_busy" });+ });+});