A local-first multi-agent app development platform, built on PenguinHarness
feat(cli): penguin storage scan, plan, apply, trash and mode
lmliheng6f40f901c159
diff --git a/packages/cli/src/commands/storage.ts b/packages/cli/src/commands/storage.tsindex 8fbad207..530d5e0c 100644--- a/packages/cli/src/commands/storage.ts+++ b/packages/cli/src/commands/storage.ts@@ -1,32 +1,51 @@/**- * `penguin storage` — the data root's storage ledger.+ * `penguin storage` — the data root's storage ledger, and the reviewed cleanup that reads it.** penguin storage [--top <n>] [--json] [--server <url>]+ * penguin storage report [--top <n>] [--json] [--server <url>]+ * penguin storage scan [--json] [--server <url>]+ * penguin storage plan [<planId>] [--json] [--server <url>]+ * penguin storage apply <planId> (--path <path> … | --all) [--json] [--server <url>]+ * penguin storage trash [list] [--json] [--server <url>]+ * penguin storage trash restore <id> [--json] [--server <url>]+ * penguin storage trash purge [<id>] [--json] [--server <url>]+ * penguin storage mode [on|off] [--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.+ * The bare command (an alias of `report`) reports what occupies `ADELIE_HOME`: one row per class (user data, temporary+ * Workspaces, Session drafts, Traces, tool environments, trash, the database, everything else),+ * the entries a person could clean up, the environments that look like the same toolchain+ * installed twice, and 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.+ * Everything else is the design's second step, and every one of those commands is a deliberate+ * act: `scan` writes a bill and moves nothing; `plan` reads one back (or lists the recent ones);+ * `apply` needs a plan id **and** the paths to move, which is why there is no `--yes` anywhere+ * in this file; `trash` is where a move lands, and `purge` — the only deletion — is spelled out+ * separately. The cleanup mode (`mode`) is off until somebody turns it on, and with it off the+ * server refuses every write, so the bare report is all this command can do.** 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.+ * Workspace as unreferenced, which is exactly the mistake the whole design is built to avoid;+ * and by the same rule the CLI never moves a file, it submits an approval (the server is the+ * single writer).** Docs: /docs/cli § "penguin storage".*/import type { Command } from "commander";import type {+ StorageApplyResponse,StorageCandidate,+ StoragePlanResponse,+ StoragePlanView,+ StoragePlansResponse,+ StoragePurgeResponse,StorageReport,StorageReportResponse,+ StorageRestoreResponse,+ StorageSettingsResponse,+ StorageTrashResponse,} from "@lmliheng/penguin-server/api";import { humanizeBytes } from "../render.js";import { resolveConnection, ServerClient } from "../client.js";@@ -57,9 +76,82 @@ function candidateRows(report: StorageReport, top: number, t: Messages): string[]);}+/** A plan's entries as a table: what it is, how big, when it last changed, and why it is on it. */+function billRows(plan: StoragePlanView, t: Messages): string[][] {+ return plan.entries.map((entry) => [+ t.storage.className(entry.class),+ humanizeBytes(entry.bytes),+ String(entry.files),+ lastModified(entry.lastModifiedAt, t),+ entry.rules.map((rule) => t.storage.ruleLabel(rule)).join(", "),+ entry.executable ? t.storage.moveMark() : t.storage.reportOnlyMark(),+ entry.path,+ ]);+}++/** The plan state a listing shows: open, applied, or past its day. */+function planState(plan: StoragePlanView, t: Messages): string {+ if (plan.appliedAt !== null) return t.storage.planStateApplied(lastModified(plan.appliedAt, t));+ if (plan.expired) return t.storage.planStateExpired(lastModified(plan.expiresAt, t));+ return t.storage.planStateOpen();+}++/** One bill, rendered the same way whether it was just written or read back. */+function renderPlan(plan: StoragePlanView, t: Messages): string {+ const out: string[] = [];+ out.push(+ t.storage.billHeading(+ plan.id,+ plan.entries.length,+ humanizeBytes(plan.totalBytes),+ lastModified(plan.expiresAt, t),+ ),+ );+ if (plan.entries.length === 0) {+ out.push(t.storage.billEmpty());+ } else {+ out.push(+ renderTable(+ [+ t.storage.colClass(),+ t.storage.colBytes(),+ t.storage.colFiles(),+ t.storage.colModified(),+ t.storage.colRules(),+ t.storage.colExecutable(),+ t.storage.colPath(),+ ],+ billRows(plan, t),+ ),+ );+ }+ if (plan.excluded.length > 0) out.push(t.storage.billExcluded(plan.excluded.length));+ out.push(t.storage.billReportOnly(plan.executableClasses.map((c) => t.storage.className(c))));+ out.push(plan.usable ? t.storage.billNotice(plan.id) : t.storage.billSpent(plan.id));+ return `${out.join("\n")}\n`;+}++/** Commander collector for a repeatable option; one value may also list several, comma-separated. */+function collect(value: string, previous: string[]): string[] {+ return [+ ...previous,+ ...value+ .split(",")+ .map((part) => part.trim())+ .filter((p) => p !== ""),+ ];+}+export function registerStorageCommand(program: Command, t: Messages): void {- program- .command("storage")+ const storage = program.command("storage").description(t.storage.desc);++ // The bare command is the report, and it is a subcommand rather than the parent's own action+ // for a reason that is easy to get wrong: a parent that declares `--json` AND a subcommand+ // that declares it too makes commander hand the flag to the parent, so `storage scan --json`+ // would silently print the human table. With nothing on the parent, every command's options+ // are its own — `storage --json` and `storage scan --json` both mean what they say.+ storage+ .command("report", { isDefault: true }).description(t.storage.desc).option("--top <n>", t.storage.top).option("--json", t.common.json)@@ -78,6 +170,13 @@ export function registerStorageCommand(program: Command, t: Messages): void {const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);const response = await client.request<StorageReportResponse>("GET", "/api/admin/storage");+ // The mode decides which sentence closes the report — "there is nothing else this command+ // does" or "here is the next step" — and an older server without the route simply keeps+ // the report-only wording.+ const mode = await client+ .request<StorageSettingsResponse>("GET", "/api/admin/storage/settings")+ .then((res) => res.settings.enabled)+ .catch(() => false);if (opts.json === true) {process.stdout.write(`${JSON.stringify(response)}\n`);@@ -173,6 +272,267 @@ export function registerStorageCommand(program: Command, t: Messages): void {for (const path of report.unreadable) out.write(` ${path}\n`);}- out.write(`\n${t.storage.readOnlyNotice()}\n`);+ out.write(`\n${mode ? t.storage.modeOnNotice() : t.storage.modeOffNotice()}\n`);+ });++ storage+ .command("scan")+ .description(t.storage.scanDesc)+ .option("--json", t.common.json)+ .option("--server <url>", t.common.server)+ .action(async (opts) => {+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);+ const response = await client.request<StoragePlanResponse>(+ "POST",+ "/api/admin/storage/plans",+ );+ if (opts.json === true) {+ process.stdout.write(`${JSON.stringify(response)}\n`);+ return;+ }+ process.stdout.write(renderPlan(response.plan, t));+ });++ storage+ .command("plan [planId]")+ .description(t.storage.planDesc)+ .option("--json", t.common.json)+ .option("--server <url>", t.common.server)+ .action(async (planId: string | undefined, opts) => {+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);+ if (planId !== undefined) {+ const response = await client.request<StoragePlanResponse>(+ "GET",+ `/api/admin/storage/plans/${encodeURIComponent(planId)}`,+ );+ if (opts.json === true) {+ process.stdout.write(`${JSON.stringify(response)}\n`);+ return;+ }+ process.stdout.write(renderPlan(response.plan, t));+ return;+ }+ const response = await client.request<StoragePlansResponse>(+ "GET",+ "/api/admin/storage/plans",+ );+ if (opts.json === true) {+ process.stdout.write(`${JSON.stringify(response)}\n`);+ return;+ }+ if (response.plans.length === 0) {+ process.stdout.write(`${t.storage.plansEmpty()}\n`);+ return;+ }+ process.stdout.write(+ renderTable(+ [+ t.storage.colPlanId(),+ t.storage.colCreated(),+ t.storage.colEntries(),+ t.storage.colBytes(),+ t.storage.colState(),+ ],+ response.plans.map((plan) => [+ plan.id,+ lastModified(plan.createdAt, t),+ String(plan.entries.length),+ humanizeBytes(plan.totalBytes),+ planState(plan, t),+ ]),+ ),+ );+ });++ storage+ .command("apply <planId>")+ .description(t.storage.applyDesc)+ .option("--path <path>", t.storage.applyPath, collect, [])+ .option("--all", t.storage.applyAll)+ .option("--json", t.common.json)+ .option("--server <url>", t.common.server)+ .action(async (planId: string, opts) => {+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);+ // A run with nothing named never reaches the server: "clean whatever you find" is exactly+ // the instruction this command does not accept.+ if (opts.all !== true && opts.path.length === 0) {+ process.stderr.write(`${t.error(t.storage.applyNoSelection())}\n`);+ process.exitCode = 1;+ return;+ }+ // The bill is read here rather than taken from an earlier print: the fingerprint that+ // authorizes the run has to be the one the server is holding now.+ const plan = (+ await client.request<StoragePlanResponse>(+ "GET",+ `/api/admin/storage/plans/${encodeURIComponent(planId)}`,+ )+ ).plan;+ const paths: string[] =+ opts.all === true+ ? plan.entries.filter((entry) => entry.executable).map((entry) => entry.path)+ : opts.path;+ if (paths.length === 0) {+ process.stderr.write(`${t.error(t.storage.applyNoSelection())}\n`);+ process.exitCode = 1;+ return;+ }+ const result = await client.request<StorageApplyResponse>(+ "POST",+ "/api/admin/storage/apply",+ {+ planId,+ fingerprint: plan.fingerprint,+ paths,+ },+ );+ if (opts.json === true) {+ process.stdout.write(`${JSON.stringify(result)}\n`);+ return;+ }+ const out = process.stdout;+ if (result.moved.length === 0) {+ out.write(`${t.storage.applyNothing()}\n`);+ } else {+ out.write(+ `${t.storage.applyMoved(+ result.moved.length,+ humanizeBytes(result.freedBytes),+ result.trashId ?? "",+ )}\n`,+ );+ }+ for (const failure of result.failed) {+ out.write(`${t.storage.applyFailedLine(failure.path, failure.reason)}\n`);+ }+ });++ const trash = storage.command("trash").description(t.storage.trashDesc);++ trash+ .command("list", { isDefault: true })+ .description(t.storage.trashListDesc)+ .option("--json", t.common.json)+ .option("--server <url>", t.common.server)+ .action(async (opts) => {+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);+ const response = await client.request<StorageTrashResponse>(+ "GET",+ "/api/admin/storage/trash",+ );+ if (opts.json === true) {+ process.stdout.write(`${JSON.stringify(response)}\n`);+ return;+ }+ if (response.entries.length === 0) {+ process.stdout.write(`${t.storage.trashEmpty()}\n`);+ return;+ }+ process.stdout.write(+ renderTable(+ [+ t.storage.colTrashId(),+ t.storage.colCreated(),+ t.storage.colItems(),+ t.storage.colBytes(),+ t.storage.colExpired(),+ ],+ response.entries.map((entry) => [+ entry.id,+ lastModified(entry.createdAt, t),+ String(entry.items.length),+ humanizeBytes(entry.bytes),+ entry.expired ? t.storage.expired(t.storage.trashTtlDays(response.ttlDays)) : "",+ ]),+ ),+ );+ for (const entry of response.entries) {+ for (const item of entry.items) {+ process.stdout.write(` ${entry.id} ${t.storage.className(item.class)} ${item.path}\n`);+ }+ }+ });++ trash+ .command("restore <id>")+ .description(t.storage.trashRestoreDesc)+ .option("--json", t.common.json)+ .option("--server <url>", t.common.server)+ .action(async (id: string, opts) => {+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);+ const result = await client.request<StorageRestoreResponse>(+ "POST",+ "/api/admin/storage/trash/restore",+ { id },+ );+ if (opts.json === true) {+ process.stdout.write(`${JSON.stringify(result)}\n`);+ return;+ }+ process.stdout.write(+ `${t.storage.trashRestored(result.id, result.restored.length, result.remaining)}\n`,+ );+ for (const skip of result.skipped) {+ process.stdout.write(`${t.storage.trashSkippedLine(skip.path, skip.reason)}\n`);+ }+ });++ trash+ .command("purge [id]")+ .description(t.storage.trashPurgeDesc)+ .option("--json", t.common.json)+ .option("--server <url>", t.common.server)+ .action(async (id: string | undefined, opts) => {+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);+ const result = await client.request<StoragePurgeResponse>(+ "POST",+ "/api/admin/storage/trash/purge",+ id === undefined ? {} : { id },+ );+ if (opts.json === true) {+ process.stdout.write(`${JSON.stringify(result)}\n`);+ return;+ }+ if (result.purged.length === 0) {+ process.stdout.write(`${t.storage.trashPurgeNothing()}\n`);+ return;+ }+ for (const entry of result.purged) {+ process.stdout.write(+ `${t.storage.trashPurgedLine(entry.id, humanizeBytes(entry.bytes))}\n`,+ );+ }+ });++ storage+ .command("mode [state]")+ .description(t.storage.modeDesc)+ .option("--json", t.common.json)+ .option("--server <url>", t.common.server)+ .action(async (state: string | undefined, opts) => {+ if (state !== undefined && state !== "on" && state !== "off") {+ process.stderr.write(`${t.error(t.storage.modeUsage())}\n`);+ process.exitCode = 1;+ return;+ }+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);+ const response =+ state === undefined+ ? await client.request<StorageSettingsResponse>("GET", "/api/admin/storage/settings")+ : await client.request<StorageSettingsResponse>("PUT", "/api/admin/storage/settings", {+ enabled: state === "on",+ });+ if (opts.json === true) {+ process.stdout.write(`${JSON.stringify(response)}\n`);+ return;+ }+ const free = response.settings.trashTtlDays;+ process.stdout.write(+ `${+ state === undefined+ ? t.storage.modeIs(response.settings.enabled, free, response.settings.pins.length)+ : t.storage.modeSet(response.settings.enabled, free, response.settings.pins.length)+ }\n`,+ );});}diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.tsindex f8199471..3f2519ad 100644--- a/packages/cli/src/i18n.ts+++ b/packages/cli/src/i18n.ts@@ -243,9 +243,62 @@ export interface Messages {groupKind(kind: "name" | "structure"): string;groupLine(kind: string, key: string, members: number, bytes: string): string;unreadableHeading(): string;- readOnlyNotice(): string;+ /** Closing sentence of the bare report when the cleanup mode is off. */+ modeOffNotice(): string;+ /** Closing sentence of the bare report when the mode is on: what the next step is. */+ modeOnNotice(): string;className(key: StorageClass): string;ruleLabel(rule: StorageCandidateRule): string;+ // ── the reviewed cleanup: scan → plan → apply → trash, and the mode switch ──+ scanDesc: string;+ planDesc: string;+ applyDesc: string;+ applyPath: string;+ applyAll: string;+ applyNoSelection(): string;+ applyNothing(): string;+ applyMoved(moved: number, bytes: string, trashId: string): string;+ applyFailedLine(path: string, reason: string): string;+ /** The `trash` group itself: what a trash is for, in one line. */+ trashDesc: string;+ /** `trash list` (the group's default): the entries a person can restore or purge. */+ trashListDesc: string;+ trashRestoreDesc: string;+ trashPurgeDesc: string;+ trashEmpty(): string;+ trashRestored(id: string, restored: number, remaining: boolean): string;+ trashSkippedLine(path: string, reason: string): string;+ trashPurgeNothing(): string;+ trashPurgedLine(id: string, bytes: string): string;+ /** Days a trash entry is kept; the retention the server reports beside the list. */+ trashTtlDays(days: number): string;+ /** Cell of a trash row that is past the retention and may be purged. */+ expired(ttl: string): string;+ modeDesc: string;+ modeUsage(): string;+ modeIs(enabled: boolean, ttlDays: number, pins: number): string;+ modeSet(enabled: boolean, ttlDays: number, pins: number): string;+ billHeading(id: string, entries: number, bytes: string, expires: string): string;+ billEmpty(): string;+ billExcluded(n: number): string;+ billReportOnly(classes: string[]): string;+ billNotice(id: string): string;+ billSpent(id: string): string;+ /** Mark in the bill's table for an entry this version only reports. */+ reportOnlyMark(): string;+ /** Mark in the bill's table for an entry an apply would accept. */+ moveMark(): string;+ plansEmpty(): string;+ planStateOpen(): string;+ planStateApplied(at: string): string;+ planStateExpired(at: string): string;+ colExecutable(): string;+ colPlanId(): string;+ colCreated(): string;+ colState(): string;+ colTrashId(): string;+ colItems(): string;+ colExpired(): 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: {@@ -1247,8 +1300,10 @@ const en: Messages = {`- ${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.",+ modeOffNotice: () =>+ "Read-only report: cleanup mode is off, so nothing here can move a file. Reviewing a candidate list is the next step — `penguin storage scan`. And nothing runs on a timer.",+ modeOnNotice: () =>+ "Cleanup mode is on. `penguin storage scan` writes a bill; `penguin storage apply <planId> --path <path>` moves the entries you select into the trash. Nothing here removes data, and nothing runs on a timer.",className: (key) =>key === "protected"? "user data"@@ -1275,7 +1330,67 @@ const en: Messages = {: rule === "idle"? "idle": "over budget",+ scanDesc:+ "Scan the data root and write a plan you can review (read-only; needs cleanup mode on)",+ planDesc: "Read a plan back, or list the recent ones when no id is given",+ applyDesc:+ "Move the entries you name into the trash: needs the plan's paths (there is no --yes, and no way to clean everything at once)",+ applyPath: "A path the plan lists (repeatable, or comma-separated)",+ applyAll:+ "Move every entry of this plan that this version may move (the plan marks which those are)",+ applyNoSelection: () =>+ "Nothing selected: give --path <path> for each entry you reviewed, or --all for every entry the plan marks cleanable.",+ applyNothing: () => "Nothing was moved (see the failures above).",+ applyMoved: (moved, bytes, trashId) =>+ `Moved ${moved} entr${moved === 1 ? "y" : "ies"} (${bytes}) into the trash as ${trashId}.`,+ applyFailedLine: (path, reason) => ` not moved: ${path} — ${reason}`,+ trashDesc:+ "Where a cleanup moves things instead of deleting them: list what is there, put it back, or purge it",+ trashListDesc: "List what previous cleanups moved (listing removes nothing)",+ trashRestoreDesc: "Put a trash entry's contents back where they came from",+ trashPurgeDesc:+ "Delete a trash entry for good — the named one, or everything past the retention",+ trashEmpty: () => "The trash is empty.",+ trashRestored: (id, restored, remaining) =>+ `Restored ${restored} entr${restored === 1 ? "y" : "ies"} from ${id}.` ++ (remaining ? " The entry still holds what could not be put back." : ""),+ trashSkippedLine: (path, reason) => ` not restored: ${path} — ${reason}`,+ trashPurgeNothing: () => "Nothing to purge (nothing is past the retention).",+ trashPurgedLine: (id, bytes) => `Purged ${id} (${bytes}).`,+ trashTtlDays: (days) => `${days}d`,+ expired: (ttl) => `past the retention (${ttl})`,+ modeDesc:+ "Show the cleanup mode, or turn it on/off (off — the default — refuses every cleanup write)",+ modeUsage: () => "usage: penguin storage mode [on|off]",+ modeIs: (enabled, ttlDays, pins) =>+ `Cleanup mode is ${enabled ? "on" : "off"}. Trash retention ${ttlDays} days, ${pins} pinned path(s).`,+ modeSet: (enabled, ttlDays, pins) =>+ `Cleanup mode is now ${enabled ? "on" : "off"}. Trash retention ${ttlDays} days, ${pins} pinned path(s).`,+ billHeading: (id, entries, bytes, expires) =>+ `Plan ${id} · ${entries} entr${entries === 1 ? "y" : "ies"} · ${bytes} · review it and approve with \`penguin storage apply\` · valid until ${expires}`,+ billEmpty: () => "No entry is a candidate under the current thresholds.",+ billExcluded: (n) => `${n} pinned path(s) left out of this plan.`,+ billReportOnly: (classes) =>+ `This version only moves ${classes.join(", ")}; every other entry is on the bill to be read, not selected.`,+ billNotice: (id) =>+ `Nothing has moved. Approve the entries you select: penguin storage apply ${id} --path <path> (or --all).`,+ billSpent: (id) =>+ `This plan cannot be applied (already used, or older than its day). Scan again for a new bill: penguin storage scan.`,+ reportOnlyMark: () => "—",+ moveMark: () => "✓",+ plansEmpty: () => "No plan has been written yet (`penguin storage scan`).",+ planStateOpen: () => "open",+ planStateApplied: (at) => `applied ${at}`,+ planStateExpired: (at) => `expired ${at}`,+ colExecutable: () => "MOVE",+ colPlanId: () => "PLAN",+ colCreated: () => "CREATED",+ colState: () => "STATE",+ colTrashId: () => "TRASH",+ colItems: () => "ITEMS",+ colExpired: () => "RETENTION",},+schedule: {desc: "Manage scheduled tasks",lsDesc: "List the project's scheduled tasks (all agents unless --agent-id is given)",@@ -2248,8 +2363,10 @@ const zh: Messages = {groupLine: (kind, key, members, bytes) =>`- ${kind}(${key}):${members} 个环境,合计 ${bytes}`,unreadableHeading: () => "读不到的部分(所以上面的合计是下限,不是精确值):",- readOnlyNotice: () =>- "只读报告。清理只会在你审核一份具体清单之后执行;这里不删数据,也没有任何定时任务在跑。",+ modeOffNotice: () =>+ "只读报告:清理模式未开启,这里没有任何操作会移动文件。下一步是审核一份清单 —— penguin storage scan。没有任何定时任务在跑。",+ modeOnNotice: () =>+ "清理模式已开启。用 penguin storage scan 生成账单;用 penguin storage apply <账单 id> --path <路径> 把你选中的条目移入回收站。这里不删数据,也没有任何定时任务在跑。",className: (key) =>key === "protected"? "用户资产"@@ -2276,6 +2393,58 @@ const zh: Messages = {: rule === "idle"? "静默超期": "超出预算",+ scanDesc: "扫描数据根并写出一份可审核的账单(只读;需要先开启清理模式)",+ planDesc: "读回一份账单;不给 id 时列出最近的几份",+ applyDesc: "把你指定的条目移入回收站:必须给出账单里的路径(没有 --yes,也不能一次清空全部)",+ applyPath: "账单里的一条路径(可重复给出,或用逗号分隔)",+ applyAll: "移动这份账单里本版本可以移动的全部条目(账单会标出哪些是)",+ applyNoSelection: () =>+ "没有选中任何条目:用 --path <路径> 逐条给出你审核过的项,或用 --all 选中账单里全部可清理项。",+ applyNothing: () => "什么都没移动(原因见上面的失败项)。",+ applyMoved: (moved, bytes, trashId) =>+ `已把 ${moved} 个条目(${bytes})移入回收站 ${trashId}。`,+ applyFailedLine: (path, reason) => ` 未移动:${path} —— ${reason}`,+ trashDesc: "清理把东西搬去的去处:列出、还原、或彻底清除",+ trashListDesc: "列出此前清理搬走的东西(列出本身不会删除任何东西)",+ trashRestoreDesc: "把某个回收站条目的内容放回原处",+ trashPurgeDesc: "彻底删除一个回收站条目:给 id 删那一个,不给则删所有超过保留期的",+ trashEmpty: () => "回收站是空的。",+ trashRestored: (id, restored, remaining) =>+ `已从 ${id} 还原 ${restored} 个条目。${remaining ? "放不回去的部分仍留在该条目里。" : ""}`,+ trashSkippedLine: (path, reason) => ` 未还原:${path} —— ${reason}`,+ trashPurgeNothing: () => "没有可清除的条目(没有超过保留期的)。",+ trashPurgedLine: (id, bytes) => `已清除 ${id}(${bytes})。`,+ trashTtlDays: (days) => `${days} 天`,+ expired: (ttl) => `已过保留期(${ttl})`,+ modeDesc: "查看清理模式,或开启/关闭它(默认关闭;关闭时任何清理写操作都会被拒绝)",+ modeUsage: () => "用法:penguin storage mode [on|off]",+ modeIs: (enabled, ttlDays, pins) =>+ `清理模式当前为${enabled ? "开启" : "关闭"}。回收站保留 ${ttlDays} 天,已保留(pin)${pins} 条路径。`,+ modeSet: (enabled, ttlDays, pins) =>+ `清理模式已${enabled ? "开启" : "关闭"}。回收站保留 ${ttlDays} 天,已保留(pin)${pins} 条路径。`,+ billHeading: (id, entries, bytes, expires) =>+ `账单 ${id} · ${entries} 个条目 · ${bytes} · 审核后用 penguin storage apply 批准 · 有效期至 ${expires}`,+ billEmpty: () => "按当前阈值没有候选。",+ billExcluded: (n) => `有 ${n} 条路径已被 pin,未进入本账单。`,+ billReportOnly: (classes) =>+ `本版本只能移动${classes.join("、")};其余条目出现在账单里供阅读,不会被选中。`,+ billNotice: (id) =>+ `尚未移动任何东西。批准你选中的条目:penguin storage apply ${id} --path <路径>(或 --all)。`,+ billSpent: (id) =>+ `账单 ${id} 已不可执行(已用过,或超过有效期)。重新扫描即可得到新账单:penguin storage scan。`,+ reportOnlyMark: () => "—",+ moveMark: () => "✓",+ plansEmpty: () => "还没有生成过账单(penguin storage scan)。",+ planStateOpen: () => "待审核",+ planStateApplied: (at) => `已执行 ${at}`,+ planStateExpired: (at) => `已过期 ${at}`,+ colExecutable: () => "可移动",+ colPlanId: () => "账单",+ colCreated: () => "创建时间",+ colState: () => "状态",+ colTrashId: () => "回收站",+ colItems: () => "条目",+ colExpired: () => "保留期",},schedule: {desc: "管理定时任务",diff --git a/packages/cli/test/fake-server.ts b/packages/cli/test/fake-server.tsindex 567ff43b..ced038b9 100644--- a/packages/cli/test/fake-server.ts+++ b/packages/cli/test/fake-server.ts@@ -113,6 +113,16 @@ interface Subscriber {closed: boolean;}+/**+ * The storage cleanup's settings as the fake stores them — the API's own shape, spelled out here+ * because the fake answers a PUT by merging a partial of it.+ */+interface FakeStorageSettings {+ enabled: boolean;+ trashTtlDays: number;+ pins: string[];+}+const encoder = new TextEncoder();/** The fake's fixed clock for company mode (the day file, the period, minted ids). */@@ -221,6 +231,27 @@ export class FakeServer {* test can pin the failure path as well as the happy one.*/storage: StorageReport | null = null;+ /**+ * The cleanup mode's settings, as the fake stores and answers them. Off by default, like the+ * server's own default, and mutated by PUT /api/admin/storage/settings and the pin route so a+ * test can watch the CLI both read and flip it.+ */+ storageSettings: FakeStorageSettings = { enabled: false, trashTtlDays: 14, pins: [] };+ /**+ * The plans the fake holds, keyed by id. A scan answers with `storageScan` (404 when it is+ * null) and files it here, so `plan`, `plan <id>` and `apply` read the same document back.+ */+ readonly storagePlans = new Map<string, Json>();+ /** What POST /api/admin/storage/plans answers: a plan view, or null for a 404. */+ storageScan: Json | null = null;+ /** What POST /api/admin/storage/apply answers; the fake moves nothing, it reports. */+ storageApply: Json = { planId: "", trashId: null, moved: [], failed: [], freedBytes: 0 };+ /** What GET /api/admin/storage/trash answers. */+ storageTrash: Json = { entries: [], ttlDays: 14 };+ /** What POST /api/admin/storage/trash/restore answers. */+ storageRestore: Json = { id: "", restored: [], skipped: [], remaining: false };+ /** What POST /api/admin/storage/trash/purge answers. */+ storagePurge: Json = { purged: [] };usage: Json = {summary: {today: { total: 1000, requests: 2, cost: 0.5, hasUncosted: false },@@ -1648,6 +1679,60 @@ export class FakeServer {return this.json({ report: this.storage });}+ // The reviewed cleanup's own surface. It answers what a test told it to and mutates only+ // the settings it is asked to change — the CLI's job is to send the right shape, and a fake+ // that also emulated moving files would be testing itself.+ if (apiPath === "/api/admin/storage/settings") {+ if (method === "PUT") {+ // The update is a partial of the stored shape, exactly as the server treats it: a field+ // the request omits keeps the value the fake is holding.+ const update = (body ?? {}) as Partial<FakeStorageSettings>;+ this.storageSettings = { ...this.storageSettings, ...update };+ }+ return this.json({ settings: this.storageSettings });+ }+ if (apiPath === "/api/admin/storage/plans") {+ if (method === "POST") {+ if (this.storageScan === null) {+ return this.error(404, "not_found", "No fake plan to scan.");+ }+ if (typeof this.storageScan.id === "string")+ this.storagePlans.set(this.storageScan.id, this.storageScan);+ return this.json({ plan: this.storageScan }, 201);+ }+ return this.json({ plans: [...this.storagePlans.values()] });+ }+ if (apiPath === "/api/admin/storage/apply") {+ return this.json({ ...this.storageApply, planId: String(body?.planId ?? "") });+ }+ if (apiPath === "/api/admin/storage/trash") {+ return this.json(this.storageTrash);+ }+ if (apiPath === "/api/admin/storage/trash/restore") {+ return this.json({ ...this.storageRestore, id: String(body?.id ?? "") });+ }+ if (apiPath === "/api/admin/storage/trash/purge") {+ return this.json(this.storagePurge);+ }+ let storagePlan = /^\/api\/admin\/storage\/plans\/([^/]+)$/.exec(apiPath);+ if (storagePlan) {+ const id = decodeURIComponent(storagePlan[1]!);+ const plan =+ this.storagePlans.get(id) ?? (this.storageScan?.id === id ? this.storageScan : null);+ if (plan === null) return this.error(404, "plan_not_found", `No plan ${id}.`);+ return this.json({ plan });+ }+ storagePlan = /^\/api\/admin\/storage\/plans\/([^/]+)\/pin$/.exec(apiPath);+ if (storagePlan && method === "POST") {+ const pin = String(body?.path ?? "");+ const pinned = body?.pinned !== false;+ const pins = pinned+ ? [...new Set([...this.storageSettings.pins, pin])]+ : this.storageSettings.pins.filter((p) => p !== pin);+ this.storageSettings = { ...this.storageSettings, pins };+ return this.json({ settings: this.storageSettings });+ }+// 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.tsindex 45eeccc1..7512c2ca 100644--- a/packages/cli/test/storage-command.test.ts+++ b/packages/cli/test/storage-command.test.ts@@ -13,7 +13,7 @@ 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 type { StoragePlanView, StorageReport } from "@lmliheng/penguin-server/api";import { cli } from "../src/index.js";import { FakeServer } from "./fake-server.js";@@ -170,8 +170,8 @@ describe("penguin storage", () => {// 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.");+ // And the one sentence that keeps this a report while the mode is off.+ expect(text).toContain("Read-only report: cleanup mode is off");expect(text).toContain("nothing runs on a timer");});@@ -218,10 +218,24 @@ describe("penguin storage", () => {expect(out()).toContain("scratchpad/sealed");});- it("sends the read-only GET and nothing else", async () => {+ it("reads the report and the mode, and writes nothing", async () => {server.storage = report();expect(await cli(["storage"])).toBe(0);- expect(server.requests.map((r) => `${r.method} ${r.path}`)).toEqual(["GET /api/admin/storage"]);+ // Two GETs, no POST, no PUT: the bare command reports, and the only thing it learns beyond+ // the ledger is whether cleanup mode is on, which decides its closing sentence.+ expect(server.requests.map((r) => `${r.method} ${r.path}`)).toEqual([+ "GET /api/admin/storage",+ "GET /api/admin/storage/settings",+ ]);+ });++ it("closes the report with the next step once the cleanup mode is on", async () => {+ server.storage = report();+ server.storageSettings = { enabled: true, trashTtlDays: 14, pins: [] };+ expect(await cli(["storage"])).toBe(0);+ expect(out()).toContain("Cleanup mode is on.");+ expect(out()).toContain("penguin storage apply <planId> --path <path>");+ expect(out()).not.toContain("cleanup mode is off");});it("reports a server that has no report to give", async () => {@@ -230,3 +244,229 @@ describe("penguin storage", () => {expect(err()).toContain("No fake storage report.");});});++const TMP = "proj/agents/default_agent/workspaces/tmp-8e8a3ace";+const DRAFT = "proj/agents/default_agent/scratchpad/session-2026-09-01-00-00-00-aaaaaaaa";++/** A bill with one entry this version may move and one it only reports, like a real one. */+function planView(over: Partial<StoragePlanView> = {}): StoragePlanView {+ return {+ id: "2026-10-10-13-05-22-4f2a",+ root: "/home/user/.adelie/data",+ createdAt: "2026-10-10T13:05:22.000Z",+ expiresAt: "2026-10-11T13:05:22.000Z",+ fingerprint: "0123456789abcdef0123456789abcdef",+ totalBytes: 138 * 1024 * 1024,+ entries: [+ {+ path: TMP,+ class: "tmp_workspaces",+ bytes: 138 * 1024 * 1024,+ files: 120,+ lastModifiedAt: "2026-09-01T04:05:06.000Z",+ rules: ["unreferenced"],+ fingerprint: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ executable: true,+ },+ {+ path: DRAFT,+ class: "session_drafts",+ bytes: 3_300_000,+ files: 4,+ lastModifiedAt: null,+ rules: ["orphan"],+ fingerprint: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",+ executable: false,+ },+ ],+ excluded: [],+ executableClasses: ["tmp_workspaces"],+ appliedAt: null,+ appliedPaths: [],+ usable: true,+ expired: false,+ ...over,+ };+}++/**+ * The reviewed cleanup at the command line: scan, read a bill back, apply a selection, and+ * empty the trash. Every case here is about the instruction the CLI sends or refuses to send —+ * the fake server records the requests, and the assertions read them — because that is what a+ * CLI can get wrong about a destructive operation: naming the wrong paths, or sending none.+ */+describe("penguin storage — the reviewed cleanup", () => {+ it("scans a bill, marks what may be moved, and points at the approval command", async () => {+ server.storageScan = planView() as unknown as Record<string, unknown>;+ expect(await cli(["storage", "scan"])).toBe(0);++ const text = out();+ expect(text).toContain("Plan 2026-10-10-13-05-22-4f2a");+ expect(text).toContain("2 entries · 138MB");+ expect(text).toMatch(/temp workspaces\s+138MB\s+120\s+2026-09-01 04:05\s+unreferenced\s+✓/);+ expect(text).toMatch(/session drafts\s+3.1MB\s+4\s+unknown\s+session gone\s+—/);+ expect(text).toContain("only moves temp workspaces");+ expect(text).toContain("Nothing has moved. Approve the entries you select:");+ expect(server.requests.map((r) => `${r.method} ${r.path}`)).toEqual([+ "POST /api/admin/storage/plans",+ ]);+ });++ it("prints the bill verbatim under --json", async () => {+ server.storageScan = planView() as unknown as Record<string, unknown>;+ expect(await cli(["storage", "scan", "--json"])).toBe(0);+ expect(JSON.parse(out())).toEqual({ plan: planView() });+ });++ it("lists the plans and reads one back by id", async () => {+ server.storageScan = planView() as unknown as Record<string, unknown>;+ await cli(["storage", "scan"]);++ stdout = [];+ expect(await cli(["storage", "plan"])).toBe(0);+ expect(out()).toContain("2026-10-10-13-05-22-4f2a");+ expect(out()).toContain("open");++ stdout = [];+ expect(await cli(["storage", "plan", "2026-10-10-13-05-22-4f2a"])).toBe(0);+ expect(out()).toContain("Nothing has moved.");+ expect(out()).toContain("valid until 2026-10-11 13:05");+ });++ it("says so when no plan has ever been written, and when an id is not a plan", async () => {+ expect(await cli(["storage", "plan"])).toBe(0);+ expect(out()).toContain("No plan has been written yet");++ stdout = [];+ expect(await cli(["storage", "plan", "2026-01-01-00-00-00-ffffff"])).toBe(1);+ expect(err()).toContain("No plan 2026-01-01-00-00-00-ffffff.");+ });++ it("applies the entries it is given, quoting the plan's own fingerprint", async () => {+ server.storageScan = planView() as unknown as Record<string, unknown>;+ server.storageApply = {+ planId: "",+ trashId: "20261010-130522",+ moved: [{ path: TMP, bytes: 138 * 1024 * 1024, files: 120 }],+ failed: [],+ freedBytes: 138 * 1024 * 1024,+ };+ expect(await cli(["storage", "apply", "2026-10-10-13-05-22-4f2a", "--path", TMP])).toBe(0);++ expect(out()).toContain("Moved 1 entry (138MB) into the trash as 20261010-130522.");+ const apply = server.requests.find((r) => r.path === "/api/admin/storage/apply");+ expect(apply?.body).toEqual({+ planId: "2026-10-10-13-05-22-4f2a",+ fingerprint: "0123456789abcdef0123456789abcdef",+ paths: [TMP],+ });+ });++ it("sends only the moveable entries under --all, and reports what could not move", async () => {+ server.storageScan = planView() as unknown as Record<string, unknown>;+ server.storageApply = {+ planId: "",+ trashId: "20261010-130522",+ moved: [],+ failed: [{ path: TMP, reason: "changed since the scan" }],+ freedBytes: 0,+ };+ expect(await cli(["storage", "apply", "2026-10-10-13-05-22-4f2a", "--all"])).toBe(0);+ const apply = server.requests.find((r) => r.path === "/api/admin/storage/apply");+ // The draft directory is on the bill but not in the selection: report-only means the CLI+ // does not offer it to the server at all.+ expect((apply?.body as { paths?: string[] })?.paths).toEqual([TMP]);+ expect(out()).toContain("Nothing was moved (see the failures above).");+ expect(out()).toContain(`not moved: ${TMP} — changed since the scan`);+ });++ it("refuses to apply without naming an entry", async () => {+ server.storageScan = planView() as unknown as Record<string, unknown>;+ expect(await cli(["storage", "apply", "2026-10-10-13-05-22-4f2a"])).toBe(1);+ expect(err()).toContain("Nothing selected");+ // Nothing was asked of the server at all: no plan was read, no approval was sent.+ expect(server.requests).toEqual([]);+ });++ it("lists the trash with what each entry holds, and says when it is empty", async () => {+ server.storageTrash = {+ entries: [+ {+ id: "20261010-130522",+ createdAt: "2026-10-10T13:05:22.000Z",+ planId: "2026-10-10-13-05-22-4f2a",+ bytes: 138 * 1024 * 1024,+ files: 120,+ items: [{ path: TMP, class: "tmp_workspaces", bytes: 138 * 1024 * 1024, files: 120 }],+ expired: true,+ },+ ],+ ttlDays: 14,+ };+ expect(await cli(["storage", "trash"])).toBe(0);+ const text = out();+ expect(text).toContain("20261010-130522");+ expect(text).toContain("past the retention (14d)");+ expect(text).toContain(`20261010-130522 temp workspaces ${TMP}`);++ stdout = [];+ server.storageTrash = { entries: [], ttlDays: 14 };+ expect(await cli(["storage", "trash"])).toBe(0);+ expect(out()).toContain("The trash is empty.");+ });++ it("restores an entry, and names what it could not put back", async () => {+ server.storageRestore = {+ id: "",+ restored: [TMP],+ skipped: [{ path: DRAFT, reason: "target_exists" }],+ remaining: true,+ };+ expect(await cli(["storage", "trash", "restore", "20261010-130522"])).toBe(0);+ const text = out();+ expect(text).toContain("Restored 1 entry from 20261010-130522.");+ expect(text).toContain("The entry still holds what could not be put back.");+ expect(text).toContain(`not restored: ${DRAFT} — target_exists`);+ const request = server.requests.find((r) => r.path === "/api/admin/storage/trash/restore");+ expect(request?.body).toEqual({ id: "20261010-130522" });+ });++ it("purges the named entry, and says when the retention has nothing to give", async () => {+ server.storagePurge = {+ purged: [{ id: "20261010-130522", bytes: 138 * 1024 * 1024, files: 120 }],+ };+ expect(await cli(["storage", "trash", "purge", "20261010-130522"])).toBe(0);+ expect(out()).toContain("Purged 20261010-130522 (138MB).");+ expect(server.requests.find((r) => r.path === "/api/admin/storage/trash/purge")?.body).toEqual({+ id: "20261010-130522",+ });++ stdout = [];+ server.storagePurge = { purged: [] };+ expect(await cli(["storage", "trash", "purge"])).toBe(0);+ expect(out()).toContain("Nothing to purge");+ // Without an id the body is empty: the server then removes only what is past the retention.+ expect(server.requests.filter((r) => r.path.endsWith("/trash/purge")).at(-1)?.body).toEqual({});+ });++ it("shows the cleanup mode and turns it on and off", async () => {+ expect(await cli(["storage", "mode"])).toBe(0);+ expect(out()).toContain("Cleanup mode is off. Trash retention 14 days, 0 pinned path(s).");++ stdout = [];+ expect(await cli(["storage", "mode", "on"])).toBe(0);+ expect(out()).toContain("Cleanup mode is now on.");+ expect(server.requests.find((r) => r.method === "PUT")?.body).toEqual({ enabled: true });++ stdout = [];+ expect(await cli(["storage", "mode", "off"])).toBe(0);+ expect(out()).toContain("Cleanup mode is now off.");+ expect(server.storageSettings.enabled).toBe(false);+ });++ it("refuses a mode it does not know, without asking the server", async () => {+ expect(await cli(["storage", "mode", "maybe"])).toBe(1);+ expect(err()).toContain("usage: penguin storage mode [on|off]");+ expect(server.requests).toEqual([]);+ });+});