A local-first multi-agent app development platform, built on PenguinHarness
feat(cli): penguin storage prints the ledger
lmliheng5b623c0cee8c
diff --git a/packages/cli/src/commands/storage.ts b/packages/cli/src/commands/storage.tsnew file mode 100644index 00000000..8fbad207--- /dev/null+++ b/packages/cli/src/commands/storage.ts@@ -0,0 +1,178 @@+/**+ * `penguin storage` — the data root's storage ledger.+ *+ * penguin storage [--top <n>] [--json] [--server <url>]+ *+ * Reports what occupies `ADELIE_HOME`: one row per class (user data, temporary Workspaces,+ * Session drafts, Traces, tool environments, trash, the database, everything else), then the+ * entries a person could clean up, then the environments that look like the same toolchain+ * installed twice, then anything the scan could not read.+ *+ * **This command deletes nothing and has no flag that would.** Producing the ledger only+ * reads, and the design's rule is that a destructive step needs a human review of a specific+ * candidate list — a later subcommand, never something a report can trigger. The header, the+ * candidate section and the trailing notice all say so, because a table of "candidates" with+ * no sentence about who acts on it would read as a to-do list the tool already did.+ *+ * The numbers come from the server (see routes/admin-storage.ts), not from walking the disk+ * here: which Sessions still exist — and therefore which temporary Workspaces and draft+ * directories are still referenced — is a database question, and only the server holds the+ * database. A report computed locally against a stale lock file could name a live Session's+ * Workspace as unreferenced, which is exactly the mistake the whole design is built to avoid.+ *+ * Docs: /docs/cli § "penguin storage".+ */+import type { Command } from "commander";+import type {+ StorageCandidate,+ StorageReport,+ StorageReportResponse,+} from "@lmliheng/penguin-server/api";+import { humanizeBytes } from "../render.js";+import { resolveConnection, ServerClient } from "../client.js";+import { renderTable } from "../table.js";+import type { Messages } from "../i18n.js";++/** Candidates printed before the list is folded; `--top 0` prints every one. */+const DEFAULT_TOP = 20;++/** Free-space share below which the header carries a warning. Report-only: nothing acts on it. */+const LOW_FREE_RATIO = 0.15;++function lastModified(iso: string | null, t: Messages): string {+ if (iso === null) return t.storage.unknownDate();+ return iso.slice(0, 16).replace("T", " ");+}++/** The candidate rows, largest first as the server already ordered them. */+function candidateRows(report: StorageReport, top: number, t: Messages): string[][] {+ const shown = top === 0 ? report.candidates : report.candidates.slice(0, top);+ return shown.map((candidate: StorageCandidate) => [+ t.storage.className(candidate.class),+ humanizeBytes(candidate.bytes),+ String(candidate.files),+ lastModified(candidate.lastModifiedAt, t),+ candidate.rules.map((rule) => t.storage.ruleLabel(rule)).join(", "),+ candidate.path,+ ]);+}++export function registerStorageCommand(program: Command, t: Messages): void {+ program+ .command("storage")+ .description(t.storage.desc)+ .option("--top <n>", t.storage.top)+ .option("--json", t.common.json)+ .option("--server <url>", t.common.server)+ .action(async (opts) => {+ let top = DEFAULT_TOP;+ if (opts.top !== undefined) {+ const n = Number(opts.top);+ if (!Number.isInteger(n) || n < 0) {+ process.stderr.write(`${t.error(t.storage.topInvalid(String(opts.top)))}\n`);+ process.exitCode = 1;+ return;+ }+ top = n;+ }++ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);+ const response = await client.request<StorageReportResponse>("GET", "/api/admin/storage");++ if (opts.json === true) {+ process.stdout.write(`${JSON.stringify(response)}\n`);+ return;+ }++ const { report } = response;+ const out = process.stdout;++ if (report.disk === null) {+ out.write(`${t.storage.heading(report.root, humanizeBytes(report.totalBytes), null)}\n`);+ } else {+ const used = report.disk.totalBytes - report.disk.freeBytes;+ const ratio =+ report.disk.totalBytes === 0 ? 0 : report.disk.freeBytes / report.disk.totalBytes;+ out.write(+ `${t.storage.heading(report.root, humanizeBytes(report.totalBytes), {+ free: humanizeBytes(report.disk.freeBytes),+ total: humanizeBytes(report.disk.totalBytes),+ usedPercent: String(+ report.disk.totalBytes === 0 ? 0 : Math.round((used / report.disk.totalBytes) * 100),+ ),+ })}\n`,+ );+ if (ratio < LOW_FREE_RATIO) {+ out.write(`${t.storage.lowFree(humanizeBytes(report.disk.freeBytes))}\n`);+ }+ }++ out.write(+ renderTable(+ [+ t.storage.colClass(),+ t.storage.colBytes(),+ t.storage.colFiles(),+ t.storage.colEntries(),+ t.storage.colCandidates(),+ ],+ report.classes+ .filter((c) => c.entries > 0 || c.class === "protected")+ .map((c) => [+ t.storage.className(c.class),+ humanizeBytes(c.bytes),+ String(c.files),+ String(c.entries),+ c.candidateEntries === 0+ ? "-"+ : t.storage.candidateCell(c.candidateEntries, humanizeBytes(c.candidateBytes)),+ ]),+ ),+ );++ out.write(`\n${t.storage.candidatesHeading()}\n`);+ if (report.candidates.length === 0) {+ out.write(`${t.storage.candidatesEmpty()}\n`);+ } else {+ out.write(+ renderTable(+ [+ t.storage.colClass(),+ t.storage.colBytes(),+ t.storage.colFiles(),+ t.storage.colModified(),+ t.storage.colRules(),+ t.storage.colPath(),+ ],+ candidateRows(report, top, t),+ ),+ );+ if (top !== 0 && report.candidates.length > top) {+ out.write(`${t.storage.moreCandidates(report.candidates.length - top)}\n`);+ }+ out.write(`${t.storage.candidateCosts()}\n`);+ }++ if (report.sharedEnvGroups.length > 0) {+ out.write(`\n${t.storage.groupsHeading()}\n`);+ for (const group of report.sharedEnvGroups) {+ out.write(+ `${t.storage.groupLine(+ t.storage.groupKind(group.kind),+ group.key,+ group.members.length,+ humanizeBytes(group.bytes),+ )}\n`,+ );+ out.write(` ${group.members.join("\n ")}\n`);+ }+ }++ if (report.unreadable.length > 0) {+ out.write(`\n${t.storage.unreadableHeading()}\n`);+ for (const path of report.unreadable) out.write(` ${path}\n`);+ }++ out.write(`\n${t.storage.readOnlyNotice()}\n`);+ });+}diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.tsindex 2e4d6498..397f0717 100644--- a/packages/cli/src/i18n.ts+++ b/packages/cli/src/i18n.ts@@ -1,4 +1,8 @@-import type { OrgChannelNoticeKind } from "@lmliheng/penguin-server/api";+import type {+ OrgChannelNoticeKind,+ StorageCandidateRule,+ StorageClass,+} from "@lmliheng/penguin-server/api";/*** CLI text internationalization (i18n).@@ -204,6 +208,45 @@ export interface Messages {colCost(): string;colGroup(dimension: string): string;};+ /**+ * `penguin storage`: the data root's storage ledger. Report-only text — there is no+ * message here for a deletion, because this command has no way to cause one.+ */+ storage: {+ desc: string;+ top: string;+ topInvalid(value: string): string;+ /** Header: the data root, what the ledger accounts for, and the volume when it is known. */+ heading(+ root: string,+ total: string,+ disk: { free: string; total: string; usedPercent: string } | null,+ ): string;+ /** Below the low-free threshold; says what to do (read the list) and what will not happen (nothing acts). */+ lowFree(free: string): string;+ colClass(): string;+ colBytes(): string;+ colFiles(): string;+ colEntries(): string;+ colCandidates(): string;+ candidateCell(entries: number, bytes: string): string;+ candidatesHeading(): string;+ candidatesEmpty(): string;+ colModified(): string;+ colRules(): string;+ colPath(): string;+ moreCandidates(n: number): string;+ /** One sentence per class about what clearing it would cost, before anyone picks. */+ candidateCosts(): string;+ unknownDate(): string;+ groupsHeading(): string;+ groupKind(kind: "name" | "structure"): string;+ groupLine(kind: string, key: string, members: number, bytes: string): string;+ unreadableHeading(): string;+ readOnlyNotice(): string;+ className(key: StorageClass): string;+ ruleLabel(rule: StorageCandidateRule): string;+ };/** `penguin schedule`: scheduled-task listing and management (a validated writer over the schedules API; the TOML file stays the single source of truth). */schedule: {desc: string;@@ -1171,6 +1214,68 @@ const en: Messages = {colCost: () => "COST",colGroup: (dimension) => dimension.toUpperCase(),},+ storage: {+ desc: "Show what occupies the data root (read-only: this command deletes nothing)",+ top: "How many candidates to print (0 prints every one)",+ topInvalid: (value) => `Invalid --top value "${value}": expected zero or a positive integer.`,+ heading: (root, total, disk) =>+ disk === null+ ? `Data root ${root} · ledger total ${total} · volume unknown`+ : `Data root ${root} · ledger total ${total} · ${disk.free} free of ${disk.total} (${disk.usedPercent}% used)`,+ lowFree: (free) =>+ `Low on space: ${free} free. Read the candidates below — none of them is removed until you approve a specific list.`,+ colClass: () => "CLASS",+ colBytes: () => "SIZE",+ colFiles: () => "FILES",+ colEntries: () => "ENTRIES",+ colCandidates: () => "CANDIDATES",+ candidateCell: (entries, bytes) => `${entries} (${bytes})`,+ candidatesHeading: () =>+ "Candidates — a report, not a to-do list: nothing is removed without your approval.",+ candidatesEmpty: () => "Nothing is a candidate under the current thresholds.",+ colModified: () => "MODIFIED",+ colRules: () => "WHY",+ colPath: () => "PATH",+ moreCandidates: (n) => `… and ${n} more (raise --top, or --top 0 for all).`,+ candidateCosts: () =>+ "What clearing each class costs: session drafts — attachments in older messages stop previewing; traces — history replay and the Costs page lose their rebuild source; tool environments — reinstalling the next time the tool is used; temporary workspaces — whatever is inside goes with them.",+ unknownDate: () => "unknown",+ groupsHeading: () =>+ "Environments that look like the same toolchain installed more than once (report only — merging is a change a person triggers):",+ groupKind: (kind) => (kind === "name" ? "same name" : "same contents"),+ groupLine: (kind, key, members, bytes) =>+ `- ${kind} (${key}): ${members} environments, ${bytes} together`,+ unreadableHeading: () =>+ "Could not be read (so the totals above are a floor, not a measurement):",+ readOnlyNotice: () =>+ "Read-only report. Cleanup happens only after you review a specific candidate list; nothing here removes data, and nothing runs on a timer.",+ className: (key) =>+ key === "protected"+ ? "user data"+ : key === "tmp_workspaces"+ ? "temp workspaces"+ : key === "session_drafts"+ ? "session drafts"+ : key === "traces"+ ? "traces"+ : key === "shared_env"+ ? "tool environments"+ : key === "trash"+ ? "trash"+ : key === "database"+ ? "database"+ : "other",+ ruleLabel: (rule) =>+ rule === "empty"+ ? "empty"+ : rule === "unreferenced"+ ? "unreferenced"+ : rule === "orphan"+ ? "session gone"+ : rule === "idle"+ ? "idle"+ : "over budget",+ },schedule: {desc: "Manage scheduled tasks",lsDesc: "List the project's scheduled tasks (all agents unless --agent-id is given)",@@ -2110,6 +2215,66 @@ const zh: Messages = {colCost: () => "成本",colGroup: (dimension) => dimension.toUpperCase(),},+ storage: {+ desc: "查看数据根被什么占满(只读:本命令不删除任何东西)",+ top: "打印多少条候选(0 表示全部)",+ topInvalid: (value) => `--top 只能是 0 或正整数,收到 "${value}"。`,+ heading: (root, total, disk) =>+ disk === null+ ? `数据根 ${root} · 账本合计 ${total} · 磁盘信息不可用`+ : `数据根 ${root} · 账本合计 ${total} · 磁盘剩余 ${disk.free} / ${disk.total}(已用 ${disk.usedPercent}%)`,+ lowFree: (free) =>+ `磁盘余量偏低(剩 ${free})。下面列出的是候选,需要你审核具体清单之后才会清理,本命令不会动手。`,+ colClass: () => "类别",+ colBytes: () => "占用",+ colFiles: () => "文件数",+ colEntries: () => "条目",+ colCandidates: () => "可清理",+ candidateCell: (entries, bytes) => `${entries} 条(${bytes})`,+ candidatesHeading: () =>+ "可清理候选 —— 这是一份清单,不是待办:没有你的批准,任何东西都不会被删除。",+ candidatesEmpty: () => "按当前阈值没有候选。",+ colModified: () => "最后改动",+ colRules: () => "命中规则",+ colPath: () => "路径",+ moreCandidates: (n) => `…另有 ${n} 条未打印(用 --top 提高上限,--top 0 打印全部)。`,+ candidateCosts: () =>+ "各代价先说清:会话草稿 —— 旧消息里的附件图片不再能预览;轨迹 —— 历史回放与成本页失去重建依据;工具环境 —— 下次用到要重新装;临时工作区 —— 里面的东西会随它一起走。",+ unknownDate: () => "未知",+ groupsHeading: () => "看起来是同一套工具链装了多份的环境(仅报告,合并需要你手动触发一次):",+ groupKind: (kind) => (kind === "name" ? "同名" : "同结构"),+ groupLine: (kind, key, members, bytes) =>+ `- ${kind}(${key}):${members} 个环境,合计 ${bytes}`,+ unreadableHeading: () => "读不到的部分(所以上面的合计是下限,不是精确值):",+ readOnlyNotice: () =>+ "只读报告。清理只会在你审核一份具体清单之后执行;这里不删数据,也没有任何定时任务在跑。",+ className: (key) =>+ key === "protected"+ ? "用户资产"+ : key === "tmp_workspaces"+ ? "临时工作区"+ : key === "session_drafts"+ ? "会话草稿"+ : key === "traces"+ ? "轨迹"+ : key === "shared_env"+ ? "工具环境"+ : key === "trash"+ ? "回收站"+ : key === "database"+ ? "数据库"+ : "其他",+ ruleLabel: (rule) =>+ rule === "empty"+ ? "空目录"+ : rule === "unreferenced"+ ? "无引用"+ : rule === "orphan"+ ? "会话已删除"+ : rule === "idle"+ ? "静默超期"+ : "超出预算",+ },schedule: {desc: "管理定时任务",lsDesc: "列出 Project 的定时任务(未指定 --agent-id 时覆盖全部 Agent)",diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex 3f6cc092..a47236f5 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -18,6 +18,7 @@ import { registerLogsCommand } from "./commands/logs.js";import { registerAgentCommand } from "./commands/agent.js";import { registerProjectCommand } from "./commands/project.js";import { registerCostCommand } from "./commands/cost.js";+import { registerStorageCommand } from "./commands/storage.js";import { registerScheduleCommand } from "./commands/schedule.js";import { registerOrgCommand } from "./commands/org.js";import { registerBrowserCommand } from "./commands/browser.js";@@ -59,6 +60,7 @@ export async function cli(argv: string[]): Promise<number> {registerAgentCommand(program, t);registerProjectCommand(program, t);registerCostCommand(program, t);+ registerStorageCommand(program, t);registerScheduleCommand(program, t);registerOrgCommand(program, t);registerBrowserCommand(program, t);diff --git a/packages/cli/src/render.ts b/packages/cli/src/render.tsindex f872203b..bb959ac7 100644--- a/packages/cli/src/render.ts+++ b/packages/cli/src/render.ts@@ -174,6 +174,25 @@ function trimZero(v: number): string {return s.endsWith(".0") ? s.slice(0, -2) : s;}+/**+ * Converts a byte count into the unit a person reads on a disk: `0B`, `912B`, `1.2KB`,+ * `6.0GB`, `1.1TB`. Binary units (1024), like every other size on the filesystem — and the+ * abbreviation alone (no `i`), because the ledger's numbers come from `stat` and a reader+ * comparing them against `df` should not have to translate.+ */+export function humanizeBytes(n: number): string {+ const abs = Math.abs(n);+ if (abs < 1024) return `${n}B`;+ const units = ["KB", "MB", "GB", "TB", "PB"] as const;+ let v = n / 1024;+ let unit = 0;+ while (Math.abs(v) >= 1024 && unit < units.length - 1) {+ v /= 1024;+ unit += 1;+ }+ return `${trimZero(v)}${units[unit]}`;+}+/** Adds an explicit sign to a delta string: non-negative gets a `+` prefix, negative already has its own `-` (context can go negative after compaction shrinks it). */function signedDelta(formatted: string): string {return formatted.startsWith("-") ? formatted : `+${formatted}`;diff --git a/packages/cli/test/fake-server.ts b/packages/cli/test/fake-server.tsindex 4f073041..567ff43b 100644--- a/packages/cli/test/fake-server.ts+++ b/packages/cli/test/fake-server.ts@@ -2,7 +2,8 @@* In-process fake Adelie server for CLI tests: stubs `globalThis.fetch` with a* handler covering exactly the endpoints the server-backed commands touch (the current* user, session create/get/patch, tasks/steer/compact/switch-model/abort, SSE stream,- * messages, agents, projects, usage, schedules, organizations and their channels, and — through+ * messages, agents, projects, usage, schedules, organizations and their channels, the+ * admin storage report the `storage` field holds, and — through* the `builtinBrowser` handler a test sets — the built-in browser). Connection resolution is pinned via ADELIE_API_URL* (a loopback URL, so no token gate) and PENGUIN_HOME points at a scratch directory so* nothing of the developer's real data root is read.@@ -15,6 +16,7 @@import fs from "node:fs";import os from "node:os";import path from "node:path";+import type { StorageReport } from "@lmliheng/penguin-server/api";type Json = Record<string, unknown>;@@ -214,6 +216,11 @@ export class FakeServer {steerMode: "accept" | "reject" = "accept";/** When true, a task POST emits `running` + the script's messages but never `idle` — the turn hangs (soft-yield timeout tests). */hangTasks = false;+ /**+ * GET /api/admin/storage: the ledger `penguin storage` renders. `null` answers 404, so a+ * test can pin the failure path as well as the happy one.+ */+ storage: StorageReport | null = null;usage: Json = {summary: {today: { total: 1000, requests: 2, cost: 0.5, hasUncosted: false },@@ -1634,6 +1641,13 @@ export class FakeServer {return status === 204 ? new Response(null, { status }) : this.json(answer.body ?? {}, status);}+ if (apiPath === "/api/admin/storage") {+ if (this.storage === null) {+ return this.error(404, "not_found", "No fake storage report.");+ }+ return this.json({ report: this.storage });+ }+// Session createlet m = /^\/api\/projects\/([^/]+)\/agents\/([^/]+)\/sessions$/.exec(apiPath);if (m) {diff --git a/packages/cli/test/storage-command.test.ts b/packages/cli/test/storage-command.test.tsnew file mode 100644index 00000000..45eeccc1--- /dev/null+++ b/packages/cli/test/storage-command.test.ts@@ -0,0 +1,232 @@+/**+ * `penguin storage`, driven through `cli()` in-process against the fake server's storage+ * report.+ *+ * The command's contract is small and entirely about what it *shows*, because it can cause+ * nothing else: the class table accounts for the ledger, the candidate list spells out why+ * each row is there, `--top` folds the tail instead of hiding it, and the output says in so+ * many words that nothing is removed without an approval. The last case pins that: after a+ * run, the only request the fake saw was the read-only GET — a command that could clean+ * something up would have to send something else.+ */+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { StorageReport } from "@lmliheng/penguin-server/api";+import { cli } from "../src/index.js";+import { FakeServer } from "./fake-server.js";++const GB = 1024 * 1024 * 1024;++let server: FakeServer;+let uninstall: () => void;+let stdout: string[];+let stderr: string[];+let scratch: string;+let outSpy: { mockRestore(): void };+let errSpy: { mockRestore(): void };++beforeEach(() => {+ server = new FakeServer();+ uninstall = server.install();+ scratch = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-storage-cli-"));+ stdout = [];+ stderr = [];+ outSpy = vi.spyOn(process.stdout, "write").mockImplementation((chunk) => {+ stdout.push(String(chunk));+ return true;+ });+ errSpy = vi.spyOn(process.stderr, "write").mockImplementation((chunk) => {+ stderr.push(String(chunk));+ return true;+ });+});+afterEach(() => {+ outSpy.mockRestore();+ errSpy.mockRestore();+ uninstall();+ fs.rmSync(scratch, { recursive: true, force: true });+});++const out = () => stdout.join("");+const err = () => stderr.join("");++/** A ledger with one row of every kind the command has a branch for. */+function report(over: Partial<StorageReport> = {}): StorageReport {+ return {+ root: "/home/user/.adelie/data",+ scannedAt: "2026-10-10T12:00:00.000Z",+ totalBytes: 6 * GB,+ classes: [+ {+ class: "protected",+ bytes: 20 * 1024 * 1024,+ files: 1269,+ entries: 43,+ candidateEntries: 0,+ candidateBytes: 0,+ },+ {+ class: "shared_env",+ bytes: 3 * GB,+ files: 101755,+ entries: 28,+ candidateEntries: 0,+ candidateBytes: 0,+ },+ {+ class: "session_drafts",+ bytes: 1.4 * GB,+ files: 56181,+ entries: 282,+ candidateEntries: 1,+ candidateBytes: 3_300_000,+ },+ {+ class: "tmp_workspaces",+ bytes: 564 * 1024 * 1024,+ files: 23731,+ entries: 83,+ candidateEntries: 26,+ candidateBytes: 146 * 1024 * 1024,+ },+ {+ class: "database",+ bytes: 23 * 1024 * 1024,+ files: 3,+ entries: 3,+ candidateEntries: 0,+ candidateBytes: 0,+ },+ ],+ candidates: [+ {+ path: "proj/agents/default_agent/workspaces/tmp-8e8a3ace",+ class: "tmp_workspaces",+ bytes: 138 * 1024 * 1024,+ files: 120,+ lastModifiedAt: "2026-09-01T04:05:06.000Z",+ referenced: false,+ rules: ["unreferenced"],+ },+ {+ path: "proj/agents/default_agent/scratchpad/session-2026-09-01-00-00-00-aaaaaaaa",+ class: "session_drafts",+ bytes: 3_300_000,+ files: 4,+ lastModifiedAt: null,+ referenced: false,+ rules: ["orphan"],+ },+ {+ path: "proj/agents/default_agent/workspaces/tmp-00000000",+ class: "tmp_workspaces",+ bytes: 0,+ files: 0,+ lastModifiedAt: "2026-10-09T00:00:00.000Z",+ referenced: false,+ rules: ["empty", "unreferenced"],+ },+ ],+ sharedEnvGroups: [+ {+ kind: "name",+ key: "csumail",+ members: [+ "proj/agents/default_agent/shared_env/csu-mail",+ "proj/agents/default_agent/shared_env/csumail",+ ],+ bytes: 88 * 1024 * 1024,+ },+ ],+ disk: { freeBytes: 8 * GB, totalBytes: 49 * GB },+ unreadable: [],+ ...over,+ };+}++describe("penguin storage", () => {+ it("prints the ledger: a header with the volume, one row per class, candidates with their rule", async () => {+ server.storage = report();+ expect(await cli(["storage"])).toBe(0);++ const text = out();+ expect(text).toContain("Data root /home/user/.adelie/data · ledger total 6GB");+ expect(text).toContain("8GB free of 49GB (84% used)");+ // Class rows, translated, with the candidate cell for the two classes that have one.+ expect(text).toMatch(/user data\s+20MB\s+1269\s+43\s+-/);+ expect(text).toMatch(/tool environments\s+3GB\s+101755\s+28\s+-/);+ expect(text).toMatch(/session drafts\s+1.4GB\s+56181\s+282\s+1 \(3.1MB\)/);+ expect(text).toMatch(/temp workspaces\s+564MB\s+23731\s+83\s+26 \(146MB\)/);+ // The candidate rows: path, size, why, and the cost sentence before anyone picks.+ expect(text).toContain("proj/agents/default_agent/workspaces/tmp-8e8a3ace");+ expect(text).toContain("2026-09-01 04:05");+ expect(text).toContain("unreferenced");+ expect(text).toContain("session gone");+ expect(text).toContain("empty, unreferenced");+ expect(text).toContain("unknown"); // a candidate with no readable mtime says so+ expect(text).toContain("What clearing each class costs");+ // Duplicated environments are reported, not proposed.+ expect(text).toContain("same name (csumail): 2 environments, 88MB together");+ expect(text).toContain("proj/agents/default_agent/shared_env/csu-mail");+ // And the one sentence that keeps this a report.+ expect(text).toContain("Read-only report.");+ expect(text).toContain("nothing runs on a timer");+ });++ it("warns about low free space without implying the command will act", async () => {+ server.storage = report({ disk: { freeBytes: 3 * GB, totalBytes: 49 * GB } });+ expect(await cli(["storage"])).toBe(0);+ expect(out()).toContain("Low on space: 3GB free.");+ expect(out()).toContain("none of them is removed until you approve a specific list");+ });++ it("folds the tail of the candidate list behind --top, and --top 0 prints every row", async () => {+ server.storage = report();+ expect(await cli(["storage", "--top", "2"])).toBe(0);+ expect(out()).toContain("… and 1 more (raise --top, or --top 0 for all).");+ expect(out()).not.toContain("tmp-00000000");++ stdout = [];+ expect(await cli(["storage", "--top", "0"])).toBe(0);+ expect(out()).toContain("tmp-00000000");+ expect(out()).not.toContain("raise --top");+ });++ it("refuses a bad --top before it reaches the server", async () => {+ server.storage = report();+ expect(await cli(["storage", "--top", "three"])).toBe(1);+ expect(err()).toContain('Invalid --top value "three"');+ expect(server.requests).toEqual([]);+ });++ it("prints the report verbatim under --json", async () => {+ server.storage = report();+ expect(await cli(["storage", "--json"])).toBe(0);+ expect(JSON.parse(out())).toEqual({ report: server.storage });+ });++ it("says nothing about which classes exist when the scan could not read part of the root", async () => {+ server.storage = report({+ unreadable: ["/home/user/.adelie/data/proj/agents/a/scratchpad/sealed"],+ });+ expect(await cli(["storage"])).toBe(0);+ expect(out()).toContain(+ "Could not be read (so the totals above are a floor, not a measurement):",+ );+ expect(out()).toContain("scratchpad/sealed");+ });++ it("sends the read-only GET and nothing else", async () => {+ server.storage = report();+ expect(await cli(["storage"])).toBe(0);+ expect(server.requests.map((r) => `${r.method} ${r.path}`)).toEqual(["GET /api/admin/storage"]);+ });++ it("reports a server that has no report to give", async () => {+ server.storage = null;+ expect(await cli(["storage"])).toBe(1);+ expect(err()).toContain("No fake storage report.");+ });+});