Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(core): the data root's storage ledger

lmlihenga8d6f7a963de
diff --git a/packages/core/src/state/index.ts b/packages/core/src/state/index.ts
index 1ccacf9d..3a3be0b2 100644
--- a/packages/core/src/state/index.ts
+++ b/packages/core/src/state/index.ts
@@ -19,4 +19,5 @@ export * from "./plugin-store.js";
export * from "./agent-vault.js";
export * from "./user-vault.js";
export * from "./memory.js";
+export * from "./storage.js";
export * from "./example-benchmark.js";
diff --git a/packages/core/src/state/storage.ts b/packages/core/src/state/storage.ts
new file mode 100644
index 00000000..b2617e05
--- /dev/null
+++ b/packages/core/src/state/storage.ts
@@ -0,0 +1,642 @@
+/**
+ * The data root's storage ledger — what is on disk, what it is for, and what migh be
+ * removable.
+ *
+ * This module is the **single definition point of the cleanup vocabulary** and it is
+ * deliberately pure: it walks a data root and reports, and it never moves or deletes
+ * anything. Every destructive action lives in the server's storage service, so the
+ * ledger can be produced by the CLI on a machine whose server is not running, and both
+ * callers can never disagree about what a class means.
+ *
+ * Two ideas carry the whole design:
+ *
+ * - **A class is a rule about provenance, not a directory name.** `protected` is user
+ * data (Agent State, Project config, a Workspace the user chose, user vaults, plugins,
+ * benchmarks, snapshots); everything else is derived — a temporary Workspace, a
+ * Session's drafts, a Trace shard, an environment the model built for itself. Nothing
+ * in the first group is ever reported as a candidate.
+ * - **A candidate is a claim, never an action.** An entry carries the rules it matched
+ * (`empty`, `unreferenced`, `orphan`, `idle`, `budget`) and whether it is still
+ * referenced; the caller reviews that list and decides. `referenced` is recomputed
+ * from live state by the caller at execution time, so a stale ledger can never be
+ * used to delete something that came alive in between.
+ *
+ * Liveness is an **input**, not something this module can discover: which Sessions still
+ * exist is a database question, and the database is the server's. `StorageLiveSet` is
+ * what the caller must supply, and an empty one means "nothing is referenced", which is
+ * why `emptyLiveSet()` is separate and named rather than a default argument.
+ *
+ * Cost: one walk of the root, `lstat` per file, no file contents read — except the
+ * `agent_state` text scan that the shared-environment text guard needs, which runs only
+ * when a policy enables the idle rule for that class and only for the one Agent whose
+ * environment is being judged.
+ *
+ * The numbers are **apparent sizes** (`st_size`), not allocated blocks, so a tree of many
+ * small files weighs less here than `du` reports for it — on the install this was written
+ * against, 5.4G of apparent size against `du`'s 6.0G, the difference being filesystem
+ * block rounding across ~100k files. A report is a map of what is there and what it is
+ * for; it is not a substitute for `df`, which is why the volume's own numbers ride along.
+ */
+import fs from "node:fs/promises";
+import type { Dirent } from "node:fs";
+import path from "node:path";
+
+/** The classes the ledger accounts for. Every byte under the root lands in exactly one. */
+export const STORAGE_CLASSES = [
+ "protected",
+ "tmp_workspaces",
+ "session_drafts",
+ "traces",
+ "shared_env",
+ "trash",
+ "database",
+ "other",
+] as const;
+
+export type StorageClass = (typeof STORAGE_CLASSES)[number];
+
+/**
+ * What a candidate matched. `empty` and `unreferenced` belong to temporary Workspaces,
+ * `orphan` to a Session's drafts, `idle` to anything judged by silence, and `budget` to
+ * anything evicted by a size cap (oldest first).
+ */
+export type CandidateRule = "empty" | "unreferenced" | "orphan" | "idle" | "budget";
+
+/**
+ * Thresholds. **Every one of them defaults to off** (`null`) except the temporary
+ * Workspace idle rule, whose candidate list is the least ambiguous thing the ledger can
+ * produce — and even that only lists.
+ *
+ * The defaults are off on purpose and for a measured reason: on the install this was
+ * designed against, the data root was ten days old, so an age-based rule reported zero
+ * bytes of anything older than thirty days while the root had grown to 6.0G. Age is a
+ * slow lever; the ledger's value is that it names the fast ones (references, budgets,
+ * duplicate environments) instead of pretending timestamps will save the disk.
+ */
+export interface StoragePolicy {
+ /** A temporary Workspace no Session references and untouched for this long. */
+ tmpIdleDays: number | null;
+ /** A draft directory whose Session has been silent for this long. */
+ draftIdleDays: number | null;
+ /** Per-Agent draft budget; exceeding it evicts the oldest drafts down to 70%. */
+ draftBudgetBytes: number | null;
+ /** A Trace date directory older than this. */
+ traceIdleDays: number | null;
+ /** Per-Agent Trace budget; exceeding it evicts the oldest date directories down to 70%. */
+ traceBudgetBytes: number | null;
+ /** A shared environment untouched for this long **and** unmentioned in Agent State. */
+ sharedEnvIdleDays: number | null;
+ /** Candidates kept per class in the returned list (the per-class totals stay exact). */
+ maxCandidatesPerClass: number;
+}
+
+export const DEFAULT_STORAGE_POLICY: StoragePolicy = {
+ tmpIdleDays: 30,
+ draftIdleDays: null,
+ draftBudgetBytes: null,
+ traceIdleDays: null,
+ traceBudgetBytes: null,
+ sharedEnvIdleDays: null,
+ maxCandidatesPerClass: 200,
+};
+
+/** Bytes a budget rule evicts down to, so a single run does not empty the class. */
+const BUDGET_EVICTION_TARGET = 0.7;
+
+/** What the caller must know about live state for the ledger to be meaningful. */
+export interface StorageLiveSet {
+ /** Session ids that still exist (the draft-directory test). */
+ sessionIds: ReadonlySet<string>;
+ /** Real paths of the Workspaces live Sessions still point at (the temporary-Workspace test). */
+ workspacePaths: ReadonlySet<string>;
+ /** Session id -> last activity, epoch ms (the draft idle test). */
+ sessionLastActiveMs: ReadonlyMap<string, number>;
+}
+
+/** A live set that claims nothing is referenced — named, so passing it is always a decision. */
+export function emptyLiveSet(): StorageLiveSet {
+ return { sessionIds: new Set(), workspacePaths: new Set(), sessionLastActiveMs: new Map() };
+}
+
+/** One accounted thing: a temporary Workspace, a Session's drafts, a Trace day, an environment. */
+export interface StorageEntry {
+ /** Path relative to the data root, `/`-separated (what a plan and a pin record). */
+ path: string;
+ class: StorageClass;
+ bytes: number;
+ files: number;
+ /** Newest modification inside the entry, epoch ms; 0 when nothing could be stat'd. */
+ newestMtimeMs: number;
+ /** Whether live state still points at this entry (a Workspace a Session uses, a Session's drafts). */
+ referenced: boolean;
+ /** Rules this entry matched; empty means it is not a candidate. */
+ rules: CandidateRule[];
+ /** For `shared_env`: the environment's own marker was found (see `.adelie-env.json`). */
+ marked?: boolean;
+ /** Subdirectories unreadable while measuring; the entry is still reported with what was read. */
+ unreadable: number;
+}
+
+export interface StorageClassReport {
+ class: StorageClass;
+ bytes: number;
+ files: number;
+ entries: number;
+ candidateEntries: number;
+ candidateBytes: number;
+}
+
+/**
+ * Environments that look like the same toolchain installed more than once. Report only:
+ * the remedy is a merge a person triggers, never a deletion, because two environments
+ * that look alike may be at different versions and only one of them may work.
+ */
+export interface SharedEnvGroup {
+ kind: "name" | "structure";
+ /** The normalized name or the structure signature the members share. */
+ key: string;
+ /** Relative paths, largest first. */
+ members: string[];
+ bytes: number;
+}
+
+export interface StorageLedger {
+ root: string;
+ scannedAtMs: number;
+ /** Sum of every entry, i.e. what the classification accounts for. */
+ totalBytes: number;
+ classes: StorageClassReport[];
+ /** Candidates, largest first, capped per class; the class totals above stay exact. */
+ candidates: StorageEntry[];
+ /** Duplicate-looking environments; never candidates. */
+ sharedEnvGroups: SharedEnvGroup[];
+ /** Disk facts beside the ledger, so a report can say how close the volume is. */
+ disk: { freeBytes: number; totalBytes: number } | null;
+ /** Paths that could not be read (capped); a report says so rather than guessing. */
+ unreadable: string[];
+}
+
+interface Measured {
+ bytes: number;
+ files: number;
+ newestMtimeMs: number;
+ /** Immediate subdirectory names (for the environment structure signature). */
+ topLevel: string[];
+ unreadable: number;
+}
+
+const UNREADABLE_REPORT_CAP = 20;
+const STATE_TEXT_READ_CAP_BYTES = 8 * 1024 * 1024;
+
+/** `realpath` with a fallback that still yields a stable absolute path for a vanished entry. */
+async function realPathOrResolve(p: string): Promise<string> {
+ try {
+ return await fs.realpath(p);
+ } catch {
+ return path.resolve(p);
+ }
+}
+
+/** Measures one file or directory tree. Symlinks are counted as entries and never followed. */
+async function measure(target: string, unreadable: string[]): Promise<Measured> {
+ let bytes = 0;
+ let files = 0;
+ let newest = 0;
+ let bad = 0;
+ const topLevel: string[] = [];
+
+ const note = (p: string): void => {
+ if (unreadable.length < UNREADABLE_REPORT_CAP) unreadable.push(p);
+ };
+
+ const visit = async (dir: string, depth: number): Promise<void> => {
+ let children;
+ try {
+ children = await fs.readdir(dir, { withFileTypes: true });
+ } catch {
+ bad += 1;
+ note(dir);
+ return;
+ }
+ if (depth === 0) for (const c of children) topLevel.push(c.name);
+ for (const child of children) {
+ const full = path.join(dir, child.name);
+ let st;
+ try {
+ st = await fs.lstat(full);
+ } catch {
+ bad += 1;
+ note(full);
+ continue;
+ }
+ if (st.mtimeMs > newest) newest = st.mtimeMs;
+ if (st.isSymbolicLink()) continue;
+ if (st.isDirectory()) await visit(full, depth + 1);
+ else if (st.isFile()) {
+ bytes += st.size;
+ files += 1;
+ }
+ }
+ };
+
+ let st;
+ try {
+ st = await fs.lstat(target);
+ } catch {
+ return { bytes: 0, files: 0, newestMtimeMs: 0, topLevel, unreadable: bad };
+ }
+ if (st.isDirectory()) {
+ const dirSt = st;
+ if (dirSt.mtimeMs > newest) newest = dirSt.mtimeMs;
+ await visit(target, 0);
+ } else if (st.isFile()) {
+ bytes = st.size;
+ files = 1;
+ if (st.mtimeMs > newest) newest = st.mtimeMs;
+ }
+ return { bytes, files, newestMtimeMs: newest, topLevel, unreadable: bad };
+}
+
+/** The relative, `/`-separated form of a path under the root — what a plan records. */
+function relativeTo(root: string, target: string): string {
+ return path.relative(root, target).split(path.sep).join("/");
+}
+
+function ageDays(newestMtimeMs: number, nowMs: number): number {
+ if (newestMtimeMs <= 0) return 0;
+ return (nowMs - newestMtimeMs) / 86_400_000;
+}
+
+/** A name with case, separators and punctuation removed: `csu-mail` and `csumail` collide. */
+function normalizedEnvName(name: string): string {
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "");
+}
+
+/** A structure signature: what the environment holds at its top level, and how many files. */
+function envStructureKey(measured: Measured): string {
+ const names = [...measured.topLevel].sort().join(",");
+ const bucket = measured.files < 100 ? "s" : measured.files < 10_000 ? "m" : "l";
+ return `${names}|${bucket}`;
+}
+
+/** Collector for one scan; holds the aggregates the report is built from and nothing else. */
+class Ledger {
+ readonly entries: StorageEntry[] = [];
+ readonly unreadable: string[] = [];
+
+ constructor(private readonly root: string) {}
+
+ entry(
+ target: string,
+ classKey: StorageClass,
+ measured: Measured,
+ options: { referenced?: boolean; rules?: CandidateRule[]; marked?: boolean } = {},
+ ): StorageEntry {
+ const entry: StorageEntry = {
+ path: relativeTo(this.root, target),
+ class: classKey,
+ bytes: measured.bytes,
+ files: measured.files,
+ newestMtimeMs: measured.newestMtimeMs,
+ referenced: options.referenced ?? false,
+ rules: options.rules ?? [],
+ unreadable: measured.unreadable,
+ ...(options.marked !== undefined ? { marked: options.marked } : {}),
+ };
+ this.entries.push(entry);
+ return entry;
+ }
+
+ async readdir(dir: string): Promise<Dirent[]> {
+ try {
+ return await fs.readdir(dir, { withFileTypes: true });
+ } catch {
+ if (this.unreadable.length < UNREADABLE_REPORT_CAP) this.unreadable.push(dir);
+ return [];
+ }
+ }
+
+ async fileExists(p: string): Promise<boolean> {
+ try {
+ await fs.access(p);
+ return true;
+ } catch {
+ return false;
+ }
+ }
+}
+
+/** All text under an Agent's `agent_state`, so the environment name guard is one pass per Agent. */
+async function readAgentStateText(agentState: string): Promise<string | null> {
+ const parts: string[] = [];
+ let budget = STATE_TEXT_READ_CAP_BYTES;
+ const visit = async (dir: string): Promise<void> => {
+ let children;
+ try {
+ children = await fs.readdir(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const child of children) {
+ if (budget <= 0) return;
+ const full = path.join(dir, child.name);
+ if (child.isDirectory()) {
+ await visit(full);
+ continue;
+ }
+ if (!child.isFile()) continue;
+ let st;
+ try {
+ st = await fs.lstat(full);
+ } catch {
+ continue;
+ }
+ if (st.size > budget) continue;
+ try {
+ parts.push(await fs.readFile(full, "utf8"));
+ budget -= st.size;
+ } catch {
+ // A file that vanished between readdir and read is simply not part of the text.
+ }
+ }
+ };
+ try {
+ await visit(agentState);
+ } catch {
+ return null;
+ }
+ return parts.join("\n");
+}
+
+/**
+ * Walks `root` and reports what it found. Pure with respect to the data root: reads only,
+ * and an entry that cannot be read is counted as unknown rather than assumed empty.
+ */
+export async function scanStorage(
+ root: string,
+ live: StorageLiveSet,
+ policy: StoragePolicy = DEFAULT_STORAGE_POLICY,
+ nowMs: number = Date.now(),
+): Promise<StorageLedger> {
+ const realRoot = await realPathOrResolve(root);
+ const ledger = new Ledger(realRoot);
+ const stateTextCache = new Map<string, string | null>();
+ const sharedEnvGroups: SharedEnvGroup[] = [];
+
+ const measured = (target: string): Promise<Measured> => measure(target, ledger.unreadable);
+
+ /** One Agent's shared environments: judged by silence only when the policy asks for it. */
+ const scanSharedEnv = async (envRoot: string, agentState: string): Promise<void> => {
+ const children = await ledger.readdir(envRoot);
+ const byName = new Map<string, StorageEntry[]>();
+ const byStructure = new Map<string, StorageEntry[]>();
+ for (const child of children) {
+ if (!child.isDirectory()) continue;
+ const full = path.join(envRoot, child.name);
+ const m = await measured(full);
+ const marked = await ledger.fileExists(path.join(full, ".adelie-env.json"));
+ const rules: CandidateRule[] = [];
+ if (
+ policy.sharedEnvIdleDays !== null &&
+ ageDays(m.newestMtimeMs, nowMs) > policy.sharedEnvIdleDays
+ ) {
+ if (!stateTextCache.has(agentState)) {
+ stateTextCache.set(agentState, await readAgentStateText(agentState));
+ }
+ const text = stateTextCache.get(agentState) ?? "";
+ const mentionedInState = text.includes(child.name);
+ const mentionedInWorkspaces = [...live.workspacePaths].some((w) => w.includes(child.name));
+ if (!mentionedInState && !mentionedInWorkspaces) rules.push("idle");
+ }
+ const entry = ledger.entry(full, "shared_env", m, { rules, marked });
+ const nameKey = normalizedEnvName(child.name);
+ const nameBucket = byName.get(nameKey);
+ if (nameBucket === undefined) byName.set(nameKey, [entry]);
+ else nameBucket.push(entry);
+ const structureKey = envStructureKey(m);
+ const structureBucket = byStructure.get(structureKey);
+ if (structureBucket === undefined) byStructure.set(structureKey, [entry]);
+ else structureBucket.push(entry);
+ }
+ for (const [key, members] of byName) {
+ if (members.length < 2) continue;
+ sharedEnvGroups.push({
+ kind: "name",
+ key,
+ members: members.map((m) => m.path).sort(),
+ bytes: members.reduce((sum, m) => sum + m.bytes, 0),
+ });
+ }
+ for (const [key, members] of byStructure) {
+ if (members.length < 2) continue;
+ sharedEnvGroups.push({
+ kind: "structure",
+ key,
+ members: members.map((m) => m.path).sort(),
+ bytes: members.reduce((sum, m) => sum + m.bytes, 0),
+ });
+ }
+ };
+
+ /** One Agent's drafts, with the orphan and idle rules and the optional budget eviction. */
+ const scanDrafts = async (draftRoot: string): Promise<StorageEntry[]> => {
+ const entries: StorageEntry[] = [];
+ for (const child of await ledger.readdir(draftRoot)) {
+ if (!child.isDirectory()) continue;
+ const full = path.join(draftRoot, child.name);
+ const m = await measured(full);
+ const referenced = live.sessionIds.has(child.name);
+ const rules: CandidateRule[] = [];
+ if (!referenced) rules.push("orphan");
+ else if (policy.draftIdleDays !== null) {
+ const last = live.sessionLastActiveMs.get(child.name);
+ if (last !== undefined && ageDays(last, nowMs) > policy.draftIdleDays) rules.push("idle");
+ }
+ entries.push(ledger.entry(full, "session_drafts", m, { referenced, rules }));
+ }
+ if (policy.draftBudgetBytes !== null) {
+ const total = entries.reduce((sum, e) => sum + e.bytes, 0);
+ if (total > policy.draftBudgetBytes) {
+ const target = policy.draftBudgetBytes * BUDGET_EVICTION_TARGET;
+ let running = total;
+ for (const entry of [...entries].sort((a, b) => a.newestMtimeMs - b.newestMtimeMs)) {
+ if (running <= target) break;
+ if (entry.rules.includes("orphan")) continue;
+ entry.rules.push("budget");
+ running -= entry.bytes;
+ }
+ }
+ }
+ return entries;
+ };
+
+ /** One Agent's Trace days, with the idle rule and the optional budget eviction. */
+ const scanTraces = async (traceRoot: string): Promise<StorageEntry[]> => {
+ const entries: StorageEntry[] = [];
+ for (const child of await ledger.readdir(traceRoot)) {
+ if (!child.isDirectory()) continue;
+ const full = path.join(traceRoot, child.name);
+ const m = await measured(full);
+ const rules: CandidateRule[] = [];
+ if (policy.traceIdleDays !== null && ageDays(m.newestMtimeMs, nowMs) > policy.traceIdleDays) {
+ rules.push("idle");
+ }
+ entries.push(ledger.entry(full, "traces", m, { rules }));
+ }
+ if (policy.traceBudgetBytes !== null) {
+ const total = entries.reduce((sum, e) => sum + e.bytes, 0);
+ if (total > policy.traceBudgetBytes) {
+ const target = policy.traceBudgetBytes * BUDGET_EVICTION_TARGET;
+ let running = total;
+ for (const entry of [...entries].sort((a, b) => a.newestMtimeMs - b.newestMtimeMs)) {
+ if (running <= target) break;
+ if (!entry.rules.includes("idle")) entry.rules.push("budget");
+ running -= entry.bytes;
+ }
+ }
+ }
+ return entries;
+ };
+
+ for (const top of await ledger.readdir(realRoot)) {
+ const full = path.join(realRoot, top.name);
+ if (!top.isDirectory()) {
+ // Root-level files: the database and its sidecars are accounted for as such, and
+ // anything else (the API token, the install id, the server lock) is `other` — small,
+ // but named, so the classification stays complete rather than nearly so.
+ const classKey: StorageClass =
+ top.name === "web.db" || top.name.startsWith("web.db-") ? "database" : "other";
+ ledger.entry(full, classKey, await measured(full));
+ continue;
+ }
+ if (top.name === ".trash") {
+ for (const child of await ledger.readdir(full)) {
+ ledger.entry(
+ path.join(full, child.name),
+ "trash",
+ await measured(path.join(full, child.name)),
+ );
+ }
+ continue;
+ }
+ if (top.name === "users" || top.name === "plugins") {
+ ledger.entry(full, "protected", await measured(full));
+ continue;
+ }
+ const agents = path.join(full, "agents");
+ if (!(await ledger.fileExists(agents))) {
+ ledger.entry(full, "other", await measured(full));
+ continue;
+ }
+ // A Project directory: `agents/` is walked Agent by Agent, and everything beside it
+ // (`benchmarks/`, the Project config) is user data.
+ for (const child of await ledger.readdir(full)) {
+ if (child.name === "agents") continue;
+ ledger.entry(
+ path.join(full, child.name),
+ "protected",
+ await measured(path.join(full, child.name)),
+ );
+ }
+ for (const agent of await ledger.readdir(agents)) {
+ if (!agent.isDirectory()) continue;
+ const agentRoot = path.join(agents, agent.name);
+ const agentState = path.join(agentRoot, "agent_state");
+ for (const child of await ledger.readdir(agentRoot)) {
+ const childPath = path.join(agentRoot, child.name);
+ if (!child.isDirectory()) {
+ ledger.entry(childPath, "other", await measured(childPath));
+ continue;
+ }
+ switch (child.name) {
+ case "agent_state":
+ case "snapshots":
+ ledger.entry(childPath, "protected", await measured(childPath));
+ break;
+ case "scratchpad":
+ await scanDrafts(childPath);
+ break;
+ case "traces":
+ await scanTraces(childPath);
+ break;
+ case "shared_env":
+ await scanSharedEnv(childPath, agentState);
+ break;
+ case "workspaces": {
+ for (const ws of await ledger.readdir(childPath)) {
+ const wsPath = path.join(childPath, ws.name);
+ const m = await measured(wsPath);
+ const isTemp = ws.name.startsWith("tmp-");
+ if (!isTemp) {
+ ledger.entry(wsPath, "protected", m, { referenced: true });
+ continue;
+ }
+ const referenced = live.workspacePaths.has(await realPathOrResolve(wsPath));
+ const rules: CandidateRule[] = [];
+ if (!referenced && m.files === 0) rules.push("empty");
+ if (!referenced) {
+ rules.push("unreferenced");
+ if (
+ policy.tmpIdleDays !== null &&
+ ageDays(m.newestMtimeMs, nowMs) > policy.tmpIdleDays
+ ) {
+ rules.push("idle");
+ }
+ }
+ ledger.entry(wsPath, "tmp_workspaces", m, { referenced, rules });
+ }
+ break;
+ }
+ default:
+ ledger.entry(childPath, "other", await measured(childPath));
+ }
+ }
+ }
+ }
+
+ // Aggregate. Every entry is in exactly one class, so the totals sum to the root's own size.
+ const classes: StorageClassReport[] = STORAGE_CLASSES.map((classKey) => {
+ const own = ledger.entries.filter((e) => e.class === classKey);
+ const candidates = own.filter((e) => e.rules.length > 0);
+ return {
+ class: classKey,
+ bytes: own.reduce((sum, e) => sum + e.bytes, 0),
+ files: own.reduce((sum, e) => sum + e.files, 0),
+ entries: own.length,
+ candidateEntries: candidates.length,
+ candidateBytes: candidates.reduce((sum, e) => sum + e.bytes, 0),
+ };
+ });
+
+ const candidates: StorageEntry[] = [];
+ for (const classKey of STORAGE_CLASSES) {
+ const own = ledger.entries
+ .filter((e) => e.class === classKey && e.rules.length > 0)
+ .sort((a, b) => b.bytes - a.bytes)
+ .slice(0, policy.maxCandidatesPerClass);
+ candidates.push(...own);
+ }
+
+ return {
+ root: realRoot,
+ scannedAtMs: nowMs,
+ totalBytes: ledger.entries.reduce((sum, e) => sum + e.bytes, 0),
+ classes,
+ candidates,
+ sharedEnvGroups: sharedEnvGroups.sort((a, b) => b.bytes - a.bytes),
+ disk: await diskFacts(realRoot),
+ unreadable: ledger.unreadable,
+ };
+}
+
+/** The volume's free/total bytes, or null where the platform cannot answer. */
+async function diskFacts(
+ target: string,
+): Promise<{ freeBytes: number; totalBytes: number } | null> {
+ try {
+ const st = await fs.statfs(target);
+ return { freeBytes: st.bavail * st.bsize, totalBytes: st.blocks * st.bsize };
+ } catch {
+ return null;
+ }
+}
diff --git a/packages/core/test/storage.test.ts b/packages/core/test/storage.test.ts
new file mode 100644
index 00000000..2e7f9f04
--- /dev/null
+++ b/packages/core/test/storage.test.ts
@@ -0,0 +1,374 @@
+/**
+ * The storage ledger (core/src/state/storage.ts).
+ *
+ * These tests pin the properties the design's promises rest on:
+ *
+ * - every byte under the root lands in exactly one class, and the classes sum to the root,
+ * so a report can never be "complete except for the part nobody looked at";
+ * - user data is never a candidate — `agent_state`, a Workspace the user chose, snapshots,
+ * Project config, plugins, vaults;
+ * - a candidate is a claim about provenance, not about age: a referenced temporary
+ * Workspace is not a candidate however old it is, and an unreferenced one is;
+ * - liveness is the caller's input: the same tree scanned with an empty live set and with a
+ * populated one yields different candidates, which is exactly why the ledger cannot be
+ * used to delete anything on its own;
+ * - thresholds default to off, so a scan of a frozen tree reports zero candidates unless a
+ * policy asks for some.
+ */
+import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import {
+ DEFAULT_STORAGE_POLICY,
+ emptyLiveSet,
+ scanStorage,
+ type StorageLiveSet,
+ type StoragePolicy,
+} from "../src/state/storage.js";
+
+const DAY_MS = 86_400_000;
+
+/** Roots created by a test, removed after it however it ended. */
+const roots: string[] = [];
+
+afterEach(async () => {
+ while (roots.length > 0) {
+ const root = roots.pop();
+ if (root !== undefined) await fs.rm(root, { recursive: true, force: true });
+ }
+});
+
+async function tempRoot(): Promise<string> {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "adelie-storage-"));
+ roots.push(root);
+ return root;
+}
+
+async function writeFile(file: string, content: string): Promise<void> {
+ await fs.mkdir(path.dirname(file), { recursive: true });
+ await fs.writeFile(file, content);
+}
+
+/** Backdates a whole tree, the parent directories included — the ledger's silent test. */
+async function backdate(target: string, days: number): Promise<void> {
+ const when = new Date(Date.now() - days * DAY_MS);
+ const visit = async (p: string): Promise<void> => {
+ const st = await fs.lstat(p);
+ if (st.isDirectory()) {
+ for (const name of await fs.readdir(p)) await visit(path.join(p, name));
+ }
+ await fs.utimes(p, when, when);
+ };
+ await visit(target);
+}
+
+/** A minimal install: one Project, one Agent, with the given extra directories. */
+async function scaffold(): Promise<string> {
+ const root = await tempRoot();
+ await writeFile(path.join(root, "web.db"), "database");
+ await writeFile(path.join(root, "web.db-wal"), "wal");
+ await writeFile(path.join(root, "api-token"), "token");
+ await writeFile(
+ path.join(root, "proj", "agents", "agent", "agent_state", "AGENTS.md"),
+ "you are an agent",
+ );
+ await writeFile(path.join(root, "proj", ".project_config.toml"), "name = 'p'");
+ return root;
+}
+
+function policy(overrides: Partial<StoragePolicy>): StoragePolicy {
+ return { ...DEFAULT_STORAGE_POLICY, ...overrides };
+}
+
+function live(overrides: Partial<StorageLiveSet>): StorageLiveSet {
+ return { ...emptyLiveSet(), ...overrides };
+}
+
+describe("scanStorage", () => {
+ it("accounts for every byte: classes sum to the root, and the database is its own class", async () => {
+ const root = await scaffold();
+ await writeFile(path.join(root, "proj", "agents", "agent", "scratchpad", "s1", "note.md"), "x");
+ await writeFile(path.join(root, "proj", "benchmarks", "bank.json"), "y");
+
+ const ledger = await scanStorage(root, emptyLiveSet());
+ const summed = ledger.classes.reduce((sum, c) => sum + c.bytes, 0);
+ expect(summed).toBe(ledger.totalBytes);
+ expect(ledger.totalBytes).toBeGreaterThan(0);
+
+ const byClass = (key: string) => ledger.classes.find((c) => c.class === key);
+ expect(byClass("database")?.bytes).toBe("database".length + "wal".length);
+ expect(byClass("session_drafts")?.entries).toBe(1);
+ expect(byClass("other")?.entries).toBe(1); // api-token
+ // The Project config and the benchmark bank are user data, whatever they weigh.
+ expect(byClass("protected")?.entries).toBeGreaterThanOrEqual(2);
+ });
+
+ it("reports the root's own file tools as `other` rather than leaving them out", async () => {
+ const root = await scaffold();
+ await writeFile(path.join(root, "install-id"), "id");
+ const ledger = await scanStorage(root, emptyLiveSet());
+ const other = ledger.candidates.filter((c) => c.class === "other");
+ expect(other).toEqual([]); // `other` is reported, never a candidate
+ expect(ledger.classes.find((c) => c.class === "other")?.entries).toBe(2);
+ });
+
+ it("never reports user data as a candidate, however old and unreferenced it is", async () => {
+ const root = await scaffold();
+ await writeFile(path.join(root, "proj", "agents", "agent", "agent_state", "vault.toml"), "s");
+ await writeFile(
+ path.join(root, "proj", "agents", "agent", "snapshots", "v1", "state.json"),
+ "s",
+ );
+ await writeFile(
+ path.join(root, "proj", "agents", "agent", "workspaces", "mine", "code.ts"),
+ "s",
+ );
+ await backdate(root, 400);
+
+ const ledger = await scanStorage(root, emptyLiveSet(), policy({ tmpIdleDays: 1 }));
+ expect(ledger.candidates).toEqual([]);
+ const protectedBytes = ledger.classes.find((c) => c.class === "protected")?.bytes ?? 0;
+ expect(protectedBytes).toBeGreaterThan(0);
+ });
+
+ it("judges a temporary Workspace by reference first: a referenced one is never a candidate", async () => {
+ const root = await scaffold();
+ const ws = path.join(root, "proj", "agents", "agent", "workspaces", "tmp-abcd1234");
+ await writeFile(path.join(ws, "deliverable.md"), "work");
+ await backdate(ws, 90);
+
+ // Referenced by a live Session: old, non-empty, still not a candidate.
+ const referenced = await scanStorage(
+ root,
+ live({ workspacePaths: new Set([await fs.realpath(ws)]) }),
+ policy({ tmpIdleDays: 1 }),
+ );
+ expect(referenced.candidates.filter((c) => c.class === "tmp_workspaces")).toEqual([]);
+ expect(referenced.classes.find((c) => c.class === "tmp_workspaces")?.entries).toBe(1);
+
+ // Nothing references it: unreferenced, and idle at a one-day threshold.
+ const orphan = await scanStorage(root, emptyLiveSet(), policy({ tmpIdleDays: 1 }));
+ const entry = orphan.candidates.find((c) => c.class === "tmp_workspaces");
+ expect(entry?.rules).toEqual(["unreferenced", "idle"]);
+ expect(entry?.referenced).toBe(false);
+ });
+
+ it("calls an unreferenced empty temporary Workspace `empty`, and still lists it as a candidate", async () => {
+ const root = await scaffold();
+ const ws = path.join(root, "proj", "agents", "agent", "workspaces", "tmp-empty");
+ await fs.mkdir(ws, { recursive: true });
+
+ const ledger = await scanStorage(root, emptyLiveSet(), policy({ tmpIdleDays: null }));
+ expect(ledger.candidates.find((c) => c.class === "tmp_workspaces")?.rules).toEqual([
+ "empty",
+ "unreferenced",
+ ]);
+ });
+
+ it("calls a draft directory whose Session is gone an orphan, and one whose Session is live not a candidate", async () => {
+ const root = await scaffold();
+ await writeFile(
+ path.join(root, "proj", "agents", "agent", "scratchpad", "gone", "tmp.txt"),
+ "x",
+ );
+ await writeFile(
+ path.join(root, "proj", "agents", "agent", "scratchpad", "here", "tmp.txt"),
+ "x",
+ );
+
+ const ledger = await scanStorage(root, live({ sessionIds: new Set(["here"]) }));
+ const candidates = ledger.candidates.filter((c) => c.class === "session_drafts");
+ expect(candidates.map((c) => c.path)).toEqual(["proj/agents/agent/scratchpad/gone"]);
+ expect(candidates[0]?.rules).toEqual(["orphan"]);
+ });
+
+ it("judges a live Session's drafts idle only against that Session's own last activity", async () => {
+ const root = await scaffold();
+ await writeFile(path.join(root, "proj", "agents", "agent", "scratchpad", "s1", "tmp.txt"), "x");
+ await backdate(path.join(root, "proj", "agents", "agent", "scratchpad", "s1"), 40);
+
+ const active = await scanStorage(
+ root,
+ live({ sessionIds: new Set(["s1"]), sessionLastActiveMs: new Map([["s1", Date.now()]]) }),
+ policy({ draftIdleDays: 30 }),
+ );
+ expect(active.candidates).toEqual([]);
+
+ const stale = await scanStorage(
+ root,
+ live({
+ sessionIds: new Set(["s1"]),
+ sessionLastActiveMs: new Map([["s1", Date.now() - 60 * DAY_MS]]),
+ }),
+ policy({ draftIdleDays: 30 }),
+ );
+ expect(stale.candidates[0]?.rules).toEqual(["idle"]);
+ });
+
+ it("evicts a draft budget oldest-first and stops at the target, leaving the newest alone", async () => {
+ const root = await scaffold();
+ const drafts = path.join(root, "proj", "agents", "agent", "scratchpad");
+ for (const [name, days] of [
+ ["old", 30],
+ ["middle", 20],
+ ["new", 1],
+ ] as const) {
+ await writeFile(path.join(drafts, name, "blob.bin"), "x".repeat(1000));
+ await backdate(path.join(drafts, name), days);
+ }
+
+ const ledger = await scanStorage(
+ root,
+ live({ sessionIds: new Set(["old", "middle", "new"]) }),
+ policy({ draftBudgetBytes: 2000 }),
+ );
+ const byPath = new Map(ledger.candidates.map((c) => [c.path, c]));
+ expect(byPath.get("proj/agents/agent/scratchpad/old")?.rules).toEqual(["budget"]);
+ expect(byPath.has("proj/agents/agent/scratchpad/new")).toBe(false);
+ });
+
+ it("judges Trace days by silence and by budget, and reports both as candidates", async () => {
+ const root = await scaffold();
+ const traces = path.join(root, "proj", "agents", "agent", "traces");
+ for (const [date, days] of [
+ ["2026-01-01", 60],
+ ["2026-02-01", 10],
+ ] as const) {
+ await writeFile(path.join(traces, date, "sess_000.jsonl"), "x".repeat(500));
+ await backdate(path.join(traces, date), days);
+ }
+
+ const byAge = await scanStorage(root, emptyLiveSet(), policy({ traceIdleDays: 30 }));
+ expect(byAge.candidates.map((c) => c.path)).toEqual(["proj/agents/agent/traces/2026-01-01"]);
+
+ const byBudget = await scanStorage(root, emptyLiveSet(), policy({ traceBudgetBytes: 900 }));
+ expect(byBudget.candidates.map((c) => c.path)).toEqual(["proj/agents/agent/traces/2026-01-01"]);
+ });
+
+ it("judges a shared environment idle only when Agent State does not mention its name", async () => {
+ const root = await scaffold();
+ const envs = path.join(root, "proj", "agents", "agent", "shared_env");
+ await writeFile(path.join(envs, "playwright", "lib", "node"), "x");
+ await writeFile(path.join(envs, "forgotten", "lib", "node"), "x");
+ await backdate(envs, 120);
+ await writeFile(
+ path.join(root, "proj", "agents", "agent", "agent_state", "AGENTS.md"),
+ "Always reuse shared_env/playwright for browsing.",
+ );
+ await backdate(path.join(root, "proj", "agents", "agent", "agent_state"), 120);
+
+ const ledger = await scanStorage(root, emptyLiveSet(), policy({ sharedEnvIdleDays: 90 }));
+ const candidates = ledger.candidates.filter((c) => c.class === "shared_env");
+ expect(candidates.map((c) => c.path)).toEqual(["proj/agents/agent/shared_env/forgotten"]);
+ // Both environments are still accounted for: judging one idle removes nothing from the ledger.
+ expect(ledger.classes.find((c) => c.class === "shared_env")?.entries).toBe(2);
+ });
+
+ it("reports environments that look duplicated without making them candidates", async () => {
+ const root = await scaffold();
+ const envs = path.join(root, "proj", "agents", "agent", "shared_env");
+ await writeFile(path.join(envs, "csu-mail", "lib", "a"), "xxxx");
+ await writeFile(path.join(envs, "csumail", "lib", "a"), "yyyy");
+ await writeFile(path.join(envs, "pw", "bin", "a"), "z");
+
+ const ledger = await scanStorage(root, emptyLiveSet());
+ expect(ledger.candidates.filter((c) => c.class === "shared_env")).toEqual([]);
+ const byName = ledger.sharedEnvGroups.find((g) => g.kind === "name");
+ expect(byName?.members).toEqual([
+ "proj/agents/agent/shared_env/csu-mail",
+ "proj/agents/agent/shared_env/csumail",
+ ]);
+ const byStructure = ledger.sharedEnvGroups.find((g) => g.kind === "structure");
+ expect(byStructure?.members).toEqual(byName?.members);
+ });
+
+ it("reports a shared environment's marker when it has one", async () => {
+ const root = await scaffold();
+ const env = path.join(root, "proj", "agents", "agent", "shared_env", "browser");
+ await writeFile(path.join(env, "lib", "a"), "x");
+ await writeFile(
+ path.join(env, ".adelie-env.json"),
+ JSON.stringify({ name: "browser", purpose: "headless checks" }),
+ );
+
+ const ledger = await scanStorage(root, emptyLiveSet());
+ expect(ledger.candidates).toEqual([]);
+ const envs = ledger.classes.find((c) => c.class === "shared_env");
+ expect(envs?.entries).toBe(1);
+ expect(envs?.bytes).toBeGreaterThan(1);
+ });
+
+ it("defaults every threshold to off except the temporary-Workspace idle rule", async () => {
+ const root = await scaffold();
+ await writeFile(
+ path.join(root, "proj", "agents", "agent", "workspaces", "tmp-old", "x.md"),
+ "x",
+ );
+ await writeFile(path.join(root, "proj", "agents", "agent", "shared_env", "old", "a"), "x");
+ await writeFile(path.join(root, "proj", "agents", "agent", "scratchpad", "s", "a"), "x");
+ await writeFile(
+ path.join(root, "proj", "agents", "agent", "traces", "2026-01-01", "s_0.jsonl"),
+ "x",
+ );
+ await backdate(root, 500);
+
+ // Age is the weakest rule the ledger has: what the defaults enable is exactly the two
+ // classes whose candidates need no judgement about a Session's history — a temporary
+ // Workspace nobody points at, and a draft directory whose Session is gone. Neither is a
+ // threshold an operator has to set, because both are statements about references. Drafts
+ // of *live* Sessions, Traces and environments stay out of the list until a policy names a
+ // threshold, and a policy is what an operator writes.
+ const ledger = await scanStorage(root, emptyLiveSet(), DEFAULT_STORAGE_POLICY);
+ expect(ledger.candidates.map((c) => `${c.class}:${c.path}`)).toEqual([
+ "tmp_workspaces:proj/agents/agent/workspaces/tmp-old",
+ "session_drafts:proj/agents/agent/scratchpad/s",
+ ]);
+ expect(DEFAULT_STORAGE_POLICY.tmpIdleDays).toBe(30);
+ expect(DEFAULT_STORAGE_POLICY.draftIdleDays).toBeNull();
+ expect(DEFAULT_STORAGE_POLICY.draftBudgetBytes).toBeNull();
+ expect(DEFAULT_STORAGE_POLICY.traceIdleDays).toBeNull();
+ expect(DEFAULT_STORAGE_POLICY.traceBudgetBytes).toBeNull();
+ expect(DEFAULT_STORAGE_POLICY.sharedEnvIdleDays).toBeNull();
+ });
+
+ it("caps the candidate list per class while the class totals stay exact", async () => {
+ const root = await scaffold();
+ const drafts = path.join(root, "proj", "agents", "agent", "scratchpad");
+ for (const name of ["a", "b", "c"]) await writeFile(path.join(drafts, name, "f"), "x");
+
+ const ledger = await scanStorage(root, emptyLiveSet(), policy({ maxCandidatesPerClass: 1 }));
+ expect(ledger.candidates.filter((c) => c.class === "session_drafts")).toHaveLength(1);
+ expect(ledger.classes.find((c) => c.class === "session_drafts")?.candidateEntries).toBe(3);
+ });
+
+ // A mode-000 directory is unreadable to the tests' own user but not to root, and CI runs as
+ // an ordinary user while a developer's container often does not. Skipping beats a test that
+ // passes for the wrong reason.
+ it.skipIf(process.getuid?.() === 0)(
+ "reports a directory it cannot read instead of throwing or guessing",
+ async () => {
+ const root = await scaffold();
+ const sealed = path.join(root, "proj", "agents", "agent", "scratchpad", "sealed");
+ await writeFile(path.join(sealed, "f"), "x");
+ await fs.chmod(sealed, 0o000);
+ try {
+ const ledger = await scanStorage(root, emptyLiveSet());
+ expect(ledger.unreadable).toContain(sealed);
+ expect(ledger.classes.find((c) => c.class === "session_drafts")?.entries).toBe(1);
+ } finally {
+ await fs.chmod(sealed, 0o755);
+ }
+ },
+ );
+
+ it("adds the volume's own numbers, so a report can say how close the disk is", async () => {
+ const root = await scaffold();
+ const ledger = await scanStorage(root, emptyLiveSet());
+ if (ledger.disk !== null) {
+ expect(ledger.disk.totalBytes).toBeGreaterThan(0);
+ expect(ledger.disk.freeBytes).toBeLessThanOrEqual(ledger.disk.totalBytes);
+ }
+ expect(ledger.root).toBe(await fs.realpath(root));
+ });
+});