A local-first multi-agent app development platform, built on PenguinHarness
feat(server): GET /api/admin/storage reports the storage ledger
lmliheng73f8b1b90844
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 8bff6f0a..712c38e7 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -281,6 +281,91 @@ export interface ServerSettingsResponse {settings: ServerSettings;}+/**+ * The data root's storage ledger (GET /api/admin/storage) — what is on disk under+ * `ADELIE_HOME`, what each thing is for, and what a person could clean up.+ *+ * **This is a report and nothing else.** Producing it moves no file and deletes none, and+ * nothing in the API can execute a cleanup on the strength of a stale report: the class,+ * rule and reference vocabulary is shared with `@lmliheng/penguin-core`'s storage ledger+ * (its `storage.ts` is where the rules are defined), and the DTO is spelled out here+ * rather than imported because this file is the Web contract and takes types from core's+ * pure subpaths only.+ */+export type StorageClass =+ | "protected"+ | "tmp_workspaces"+ | "session_drafts"+ | "traces"+ | "shared_env"+ | "trash"+ | "database"+ | "other";++/**+ * Why an entry is listed as a candidate: `empty` and `unreferenced` for a temporary+ * Workspace no Session points at, `orphan` for drafts of a Session that no longer exists+ * (or of one being deleted), `idle` for anything judged by silence, `budget` for anything+ * a size cap evicted (oldest first). A candidate is a claim about provenance, never an+ * action.+ */+export type StorageCandidateRule = "empty" | "unreferenced" | "orphan" | "idle" | "budget";++export interface StorageClassSummary {+ class: StorageClass;+ bytes: number;+ files: number;+ entries: number;+ candidateEntries: number;+ candidateBytes: number;+}++export interface StorageCandidate {+ /** Path relative to the data root, `/`-separated — what a future plan and a pin would record. */+ path: string;+ class: StorageClass;+ bytes: number;+ files: number;+ /** Newest modification inside the entry (ISO), or null when nothing could be stat'd. */+ lastModifiedAt: string | null;+ /** Whether live state still points at it. Recomputed at execution time, never trusted from a report. */+ referenced: boolean;+ rules: StorageCandidateRule[];+}++/**+ * Environments that look like the same toolchain installed more than once, by normalized+ * name (`csu-mail` vs `csumail`) or by what they hold. Report only: two look-alike+ * environments may be at different versions, so the remedy is a merge a person triggers,+ * never a deletion.+ */+export interface StorageEnvGroup {+ kind: "name" | "structure";+ key: string;+ members: string[];+ bytes: number;+}++export interface StorageReport {+ root: string;+ /** When this was measured (ISO) — the report describes that instant, not the present. */+ scannedAt: string;+ /** Sum of every class; the classification is complete, so this is the root's own size. */+ totalBytes: number;+ classes: StorageClassSummary[];+ /** Candidates, largest first, capped per class; the class totals above stay exact. */+ candidates: StorageCandidate[];+ sharedEnvGroups: StorageEnvGroup[];+ /** The volume's own numbers, so a report can say how close the disk is; null where unknown. */+ disk: { freeBytes: number; totalBytes: number } | null;+ /** Paths that could not be read (capped), so a report says so instead of guessing. */+ unreadable: string[];+}++export interface StorageReportResponse {+ report: StorageReport;+}+/** 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.tsnew file mode 100644index 00000000..44bb9fb2--- /dev/null+++ b/packages/server/src/http/routes/admin-storage.ts@@ -0,0 +1,38 @@+/**+ * 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.+ *+ * 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.+ */+import { Hono } from "hono";+import type { StorageReportResponse } from "../../api/types.js";+import { HttpError } from "../errors.js";+import type { AppEnv } from "../../auth/middleware.js";+import type { StorageLedgerReader } 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;+}++export function adminStorageRoutes(deps: AdminStorageRouteDeps): Hono<AppEnv> {+ const app = new Hono<AppEnv>();++ app.use("*", async (c, next) => {+ if (!c.var.user.isAdmin) {+ throw new HttpError(403, "admin_required", "Only an admin can perform this operation.");+ }+ await next();+ });++ app.get("/", async (c) =>+ c.json({ report: await deps.storage.report() } satisfies StorageReportResponse),+ );++ return app;+}diff --git a/packages/server/src/http/routes/admin.ts b/packages/server/src/http/routes/admin.tsindex e7736f30..1a732508 100644--- a/packages/server/src/http/routes/admin.ts+++ b/packages/server/src/http/routes/admin.ts@@ -2,6 +2,8 @@* Admin user-backend routes: only the built-in admin can use these (403 for non-admins),* and desktop mode rejects the whole surface (single-user; 403 `desktop_single_user`).* GET|POST /api/admin/users, POST /api/admin/users/:userId/password, DELETE /api/admin/users/:userId.+ * The other admin surfaces are their own route groups contributed from this component: the+ * server settings, the settings groups plugins declare, and the read-only storage ledger.*/import { Hono } from "hono";import type { AdminUserCreateResponse, AdminUsersResponse } from "../../api/types.js";@@ -13,10 +15,12 @@ import { pathParam, readJson, requireString } from "../validate.js";import { Bind, Component, Use } from "@lmliheng/penguin-core/kernel";import type { Desktop, Proxy } from "../../hmr/capabilities.js";import { adminSettingsRoutes } from "./admin-settings.js";+import { adminStorageRoutes } from "./admin-storage.js";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";/** What this route group reaches — bound by its module (src/modules). */export interface AdminRouteDeps {@@ -83,6 +87,12 @@ export function adminUsersRoutes(deps: AdminRouteDeps): Hono<AppEnv> {auth: "user",order: 45,},+ {+ id: "admin-api.storage",+ prefix: "/api/admin/storage",+ auth: "user",+ order: 50,+ },],},})@@ -92,9 +102,11 @@ export class AdminRoutes {@Use() private readonly proxy!: Proxy;@Use() private readonly settings!: Settings;@Use() private readonly pluginConfigAdmin!: PluginConfigAdmin;+ @Use() private readonly storage!: StorageLedgerReader;@Bind("admin-api.users") usersRoutes!: Hono<AppEnv>;@Bind("admin-api.settings") settingsRoutes!: Hono<AppEnv>;@Bind("admin-api.plugin-config") pluginConfigRoutes!: Hono<AppEnv>;+ @Bind("admin-api.storage") storageRoutes!: Hono<AppEnv>;setup() {this.pluginConfigRoutes = adminPluginConfigRoutes(this.pluginConfigAdmin);this.usersRoutes = adminUsersRoutes({@@ -105,5 +117,6 @@ export class AdminRoutes {proxyControl: (settings) => this.proxy.apply(settings),serverSettingsRepo: this.settings,});+ this.storageRoutes = adminStorageRoutes({ storage: this.storage });}}diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.tsindex 2caa5b9c..438548da 100644--- a/packages/server/src/platform.ts+++ b/packages/server/src/platform.ts@@ -87,6 +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 { ProjectConfigService } from "./services/project-config-service.js";import { ModelOAuthService } from "./services/model-oauth-service.js";import { PlatformAuth, PlatformAuthProvider } from "./services/platform-auth-service.js";@@ -389,8 +390,8 @@ export class PluginConfigModule {}export class SandboxSettingsModule {}@Module({- children: [ErrorsRepo, ErrorRecorder, UsageRepo, UsageRecorder, UsageService],- exports: [ErrorLog, Errors, UsageStore, UsageRecording, UsageQueries],+ children: [ErrorsRepo, ErrorRecorder, UsageRepo, UsageRecorder, UsageService, StorageService],+ exports: [ErrorLog, Errors, UsageStore, UsageRecording, UsageQueries, StorageLedgerReader],})export class ObservabilityModule {}diff --git a/packages/server/src/services/storage-service.ts b/packages/server/src/services/storage-service.tsnew file mode 100644index 00000000..75c5cc1b--- /dev/null+++ b/packages/server/src/services/storage-service.ts@@ -0,0 +1,148 @@+/**+ * The data root's storage ledger, read-only — the numbers behind `GET /api/admin/storage`.+ *+ * 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).+ *+ * 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.+ *+ * 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.+ */+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 { Component, Interface, Use } from "@lmliheng/penguin-core/kernel";+import type { StorageCandidate, StorageReport } 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";++/**+ * 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.+ */+@Interface()+export abstract class StorageLedgerReader {+ abstract report(): Promise<StorageReport>;+}++@Component()+export class StorageService implements StorageLedgerReader {+ @Use() private readonly paths!: Paths;+ @Use() private readonly projects!: Projects;+ @Use() private readonly sessions!: SessionIndex;++ async report(): Promise<StorageReport> {+ // The design's default policy, with no way to pass another one (see the interface above):+ // the report lists what is provably unreferenced or empty, and every age- or budget-based+ // rule stays off.+ const ledger = await scanStorage(this.paths.root, await this.liveSet());+ return {+ root: ledger.root,+ // The instant the walk observed, as ISO: the report describes that moment rather than+ // the moment it is read, which is why the stamp is not taken here.+ scannedAt: new Date(ledger.scannedAtMs).toISOString(),+ totalBytes: ledger.totalBytes,+ // Field-for-field the ledger's own: the DTO spells the shape out instead of importing+ // core's types (api/types.ts is the Web contract and takes core's pure subpaths only),+ // so the compiler is what keeps the two in step.+ classes: ledger.classes,+ candidates: ledger.candidates.map(toCandidate),+ sharedEnvGroups: ledger.sharedEnvGroups,+ disk: ledger.disk,+ unreadable: ledger.unreadable,+ };+ }++ /**+ * 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+ * realpaths, and a Workspace can sit under a symlinked parent — a user's home on macOS+ * reaches it through `/var` → `/private/var`), and each Session's last activity in epoch ms.+ *+ * One row per Session is enough for all three, so this is two indexed queries per Project+ * and no filesystem work beyond resolving the Workspace paths.+ *+ * Which Projects exist is the database's answer too (`Projects.listAll`), the same enumeration+ * the scheduler and the organization runtime make — so a Session whose Project the index does+ * not know (a root copied onto a machine whose index was never rebuilt for it) is not in the+ * set. That gap closes on its own: bringing such a root into the index is exactly what the+ * boot-time adoption sweep does.+ */+ private async liveSet(): Promise<StorageLiveSet> {+ const sessionIds = new Set<string>();+ const sessionLastActiveMs = new Map<string, number>();+ const workspaces = new Set<string>();+ for (const project of this.projects.listAll()) {+ for (const row of this.sessions.listByProject(project.projectId)) {+ sessionIds.add(row.sessionId);+ // A stamp that cannot be parsed is left out rather than replaced with "now": a Session+ // with no known activity is then never judged idle, which is the conservative way+ // round for a report a person may act on.+ const lastActiveMs = Date.parse(row.lastActiveAt);+ if (!Number.isNaN(lastActiveMs)) sessionLastActiveMs.set(row.sessionId, lastActiveMs);+ if (row.workspace !== "") workspaces.add(row.workspace);+ }+ }+ return {+ sessionIds,+ workspacePaths: await realPathsOf(workspaces),+ sessionLastActiveMs,+ };+ }+}++/**+ * A candidate as the Web contract spells it. Core reports the newest mtime as epoch ms and 0+ * for "nothing could be stat'd"; the DTO asks for ISO or null, because a 0 turned into a date+ * would read as a file from 1970 — an ancient entry — rather than one of unknown age.+ */+function toCandidate(entry: LedgerEntry): StorageCandidate {+ return {+ path: entry.path,+ class: entry.class,+ bytes: entry.bytes,+ files: entry.files,+ lastModifiedAt: entry.newestMtimeMs === 0 ? null : new Date(entry.newestMtimeMs).toISOString(),+ referenced: entry.referenced,+ rules: entry.rules,+ };+}++/**+ * 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 directory+ * it is walking — which keeps both sides of the temporary-Workspace comparison agreeing+ * whether or not that Workspace still exists.+ */+async function realPathsOf(workspaces: ReadonlySet<string>): Promise<Set<string>> {+ const resolved = await Promise.all(+ [...workspaces].map(async (workspace) => {+ try {+ return await fs.realpath(workspace);+ } catch {+ return path.resolve(workspace);+ }+ }),+ );+ return new Set(resolved);+}diff --git a/packages/server/test/admin-storage.test.ts b/packages/server/test/admin-storage.test.tsnew file mode 100644index 00000000..ce5af5ac--- /dev/null+++ b/packages/server/test/admin-storage.test.ts@@ -0,0 +1,161 @@+/**+ * The storage ledger, as an admin reads it through GET /api/admin/storage.+ *+ * - Given a non-admin, the route answers 403 `admin_required`, and the data root is untouched.+ * - Given an admin, the report answers 200 with the root it walked, a parseable instant, and+ * the class summaries adding up to `totalBytes` — the ledger's own completeness claim: every+ * byte on disk lands in exactly one class, so the root's size is what the report accounts for.+ * - The request is read-only: a recursive listing of the root — every path, its size and its+ * kind — is identical before and after the GET.+ * - The volume's own numbers are either absent or sane (`freeBytes <= totalBytes`).+ * - A temporary Workspace is a candidate while no Session points at it and stops being one the+ * moment one does: the naming rule reads live state, not a stamp on disk.+ *+ * One app serves the file; the only disk state it creates is the one that case needs (a+ * temporary Workspace and the Session row claiming it) — the report describes whatever the root+ * holds, and the claims above hold for any root.+ */+import fs from "node:fs/promises";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { DEFAULT_PROJECT_ID, STORAGE_CLASSES } from "@lmliheng/penguin-core";+import type { StorageReport, StorageReportResponse } from "../src/api/types.js";+import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";+import type { TestApp } from "./helpers.js";++describe("admin storage ledger", () => {+ 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 getReport = async (api = admin): Promise<StorageReport> => {+ const res = await api.get("/api/admin/storage");+ expect(res.status).toBe(200);+ return ((await res.json()) as StorageReportResponse).report;+ };++ it("a non-admin gets 403 admin_required, and the root is untouched", async () => {+ const { cookie } = await provisionUser(t.app, "norm");+ const api = apiClient(t.app, cookie);+ const before = await listing(t.root);+ const res = await api.get("/api/admin/storage");+ expect(res.status).toBe(403);+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe("admin_required");+ // Nothing about the refusal touches the disk either: a report is not produced and then+ // thrown away by the gate.+ expect(await listing(t.root)).toEqual(before);+ });++ it("an admin gets a report whose classes account for every byte of the root", async () => {+ const report = await getReport();+ // The root core walked is the real one: it resolves the path before classifying, so a+ // data root reached through a symlinked parent (/var → /private/var) still matches here.+ expect(report.root).toBe(await fs.realpath(t.root));+ expect(Number.isNaN(Date.parse(report.scannedAt))).toBe(false);++ // The app's own root holds an account and its Project, so there are bytes to account for.+ expect(report.totalBytes).toBeGreaterThan(0);+ expect(report.classes.reduce((sum, c) => sum + c.bytes, 0)).toBe(report.totalBytes);+ // Every class of the vocabulary is named, including the ones this root leaves empty: the+ // report is the whole classification, not only the parts that happen to be non-zero.+ expect(report.classes.map((c) => c.class)).toEqual([...STORAGE_CLASSES]);+ expect(report.candidates.every((c) => c.rules.length > 0)).toBe(true);+ });++ it("answers with the volume's own numbers, or with none", async () => {+ const { disk } = await getReport();+ if (disk !== null) expect(disk.freeBytes).toBeLessThanOrEqual(disk.totalBytes);+ });++ it("writes nothing: the root lists identically before and after the request", async () => {+ const before = await listing(t.root);+ // Twice, because a cache file written on the first read would show up on the second.+ await getReport();+ await getReport();+ expect(await listing(t.root)).toEqual(before);+ });++ it("stops calling a temporary Workspace unreferenced once a Session points at it", async () => {+ // The naming rule runs on live state, not on a stamp on disk: the same directory is a+ // candidate while nothing claims it and stops being one the moment a Session does.+ const workspace = path.join(+ t.root,+ DEFAULT_PROJECT_ID,+ "agents",+ "default_agent",+ "workspaces",+ "tmp-probe",+ );+ await fs.mkdir(workspace, { recursive: true });+ await fs.writeFile(path.join(workspace, "scratch.txt"), "left behind\n");+ const relative = path.relative(t.root, workspace);+ const candidate = (report: StorageReport) =>+ report.candidates.find((entry) => entry.path === relative);++ expect(candidate(await getReport())?.rules).toContain("unreferenced");++ const now = new Date().toISOString();+ t.deps.sessionsRepo.insert({+ sessionId: "session-2026-01-01-00-00-00-probe001",+ projectId: DEFAULT_PROJECT_ID,+ agentId: "default_agent",+ provider: "probe",+ modelId: "probe-model",+ workspace,+ approvalMode: "allow-all",+ title: null,+ client: "web",+ lastActiveAt: now,+ createdAt: now,+ });+ expect(candidate(await getReport())).toBeUndefined();+ });+});++/** One entry of a recursive listing: where it is, how big it is, and what it is. */+interface ListingEntry {+ path: string;+ size: number;+ kind: "dir" | "file" | "link" | "other";+}++/**+ * Everything under `root`, paths relative and sorted, with each entry's size and kind.+ * Directories are listed too, with their own sizes: a request that created or removed one+ * would change this list even if every file inside it stayed exactly where it was. Symlinks+ * are neither followed (a link out of the root would pull the whole filesystem in) nor+ * resolved, so the listing describes the root alone.+ */+async function listing(root: string): Promise<ListingEntry[]> {+ const out: ListingEntry[] = [];+ const visit = async (dir: string): Promise<void> => {+ const entries = (await fs.readdir(dir, { withFileTypes: true })).sort((a, b) =>+ a.name.localeCompare(b.name),+ );+ for (const entry of entries) {+ const full = path.join(dir, entry.name);+ const st = await fs.lstat(full);+ out.push({+ path: path.relative(root, full),+ size: st.size,+ kind: entry.isDirectory()+ ? "dir"+ : entry.isFile()+ ? "file"+ : entry.isSymbolicLink()+ ? "link"+ : "other",+ });+ if (entry.isDirectory()) await visit(full);+ }+ };+ await visit(root);+ return out;+}