diff --git a/.github/workflows/threatcrush.yml b/.github/workflows/threatcrush.yml index bd85eea..875d0b9 100644 --- a/.github/workflows/threatcrush.yml +++ b/.github/workflows/threatcrush.yml @@ -30,6 +30,10 @@ jobs: - name: Scan the dbbackup plugin run: threatcrush scan packages/plugin-dbbackup --deps --fail-on critical,high,medium + # The cleaner deletes files and runs shell on servers: the same bar. + - name: Scan the cleaner plugin + run: threatcrush scan packages/plugin-cleaner --deps --fail-on critical,high,medium + # The S3 engine signs requests and holds credentials: the same bar. - name: Scan the S3 engine run: threatcrush scan packages/s3-core --deps --fail-on critical,high,medium diff --git a/README.md b/README.md index 2ed147a..d3bb9f1 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,10 @@ diskpush dbbackup discover --save # every database on every server yo diskpush dbbackup add shop --kind postgres --push backup@nas:/srv/db diskpush dbbackup run --tags nightly diskpush dbbackup restore shop --to-env STAGING_DATABASE_URL + +# Disk full? See what fills and grows it, then free space safely (dry run unless --apply) +diskpush clean report web-1 # biggest dirs, live writers, growth, ranked plan with reasons +diskpush clean web-1 --apply # caches, docker build cache, idle build output, stale partials ``` ## Safety @@ -155,6 +159,7 @@ to make that flag hard to trigger by accident. | [docs/file-browser.md](docs/file-browser.md) | Why browsing is SFTP and transfers are rsync | | [docs/profiles.md](docs/profiles.md) | Saved, repeatable directory pairs | | [docs/fleet.md](docs/fleet.md) | Running one command, or an upgrade, across many servers | +| [docs/cleaner.md](docs/cleaner.md) | Free disk space safely: the analysis, the three classes, the guards, MCP | | [docs/s3.md](docs/s3.md) | S3-compatible buckets: saving, credentials, how transfers behave | | [docs/plugins.md](docs/plugins.md) | Plugins, MediaAnalyzer, database backups, writing one, and the security model | | [docs/threatcrush-scan.md](docs/threatcrush-scan.md) | What the ThreatCrush badge enforces, and every finding below it | @@ -178,6 +183,7 @@ packages/database the local store shared by desktop and CLI packages/plugin-api the plugin contract, registry and external loader packages/plugin-mediaanalyzer the built-in MediaAnalyzer plugin packages/plugin-dbbackup the built-in database backup plugin (Postgres, Supabase, MySQL, SQLite) +packages/plugin-cleaner the built-in Cleaner plugin (free disk space safely, local or over ssh) ``` `rsync-core` deliberately has no dependency on Electron or on the CLI, so the diff --git a/apps/cli/package.json b/apps/cli/package.json index 8de0e52..b5df260 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -19,6 +19,7 @@ "@diskpush/database": "workspace:*", "@diskpush/fleet-core": "workspace:*", "@diskpush/plugin-api": "workspace:*", + "@diskpush/plugin-cleaner": "workspace:*", "@diskpush/plugin-dbbackup": "workspace:*", "@diskpush/plugin-mediaanalyzer": "workspace:*", "@diskpush/rsync-core": "workspace:*", diff --git a/apps/cli/src/bin.ts b/apps/cli/src/bin.ts index 8bfd576..77d12f6 100644 --- a/apps/cli/src/bin.ts +++ b/apps/cli/src/bin.ts @@ -41,7 +41,7 @@ async function runPlugin(argv: readonly string[]): Promise { }) for (const { name, error } of failures) output.warn(`plugin ${name} did not load: ${error}`) if (await autoUpdate(call.pluginId, output) === 'updated') reexec() - return await runPluginCommand(registry, call.pluginId, call.args, output, serverDirectory(store)) + return await runPluginCommand(registry, call.pluginId, call.args, output, serverDirectory(store), call.defaultCommand) } catch (error) { if (error instanceof PluginError) { process.stderr.write(`${error.message}\n`) diff --git a/apps/cli/src/commands/plugins.test.ts b/apps/cli/src/commands/plugins.test.ts index 1688c62..7bf3801 100644 --- a/apps/cli/src/commands/plugins.test.ts +++ b/apps/cli/src/commands/plugins.test.ts @@ -76,6 +76,28 @@ describe('dispatch to a plugin', () => { expect(stripGlobalFlags(['--json', 'say', '-q', 'x'])).toEqual(['say', 'x']) }) + it('`diskpush clean` is the cleaner, and a missing command means run', async () => { + const { registry: r } = await loadPlugins(memoryBackend(), { external: false }) + expect(await r.isEnabled('cleaner')).toBe(true) + expect(findPluginCall(['clean', 'web-1', '--apply'], r)).toEqual({ pluginId: 'cleaner', args: ['web-1', '--apply'], defaultCommand: 'run' }) + expect(findPluginCall(['cleaner', 'report'], r)).toEqual({ pluginId: 'cleaner', args: ['report'] }) + const said: string[][] = [] + const fake = new PluginRegistry(memoryBackend()) + fake.register( + definePlugin({ + id: 'cleaner', + name: 'Cleaner', + version: '1', + description: 'x', + commands: ['run', 'report'].map((name) => ({ name, summary: name, usage: name, async run(args: string[]) { said.push([name, ...args]); return 0 } })), + }), + ) + await runPluginCommand(fake, 'cleaner', ['web-1', '--apply'], output(), undefined, 'run') + await runPluginCommand(fake, 'cleaner', ['report', 'web-1'], output(), undefined, 'run') + await runPluginCommand(fake, 'cleaner', [], output(), undefined, 'run') + expect(said).toEqual([['run', 'web-1', '--apply'], ['report', 'web-1'], ['run']]) + }) + it('runs the command with its own arguments and a context bound to the plugin', async () => { const r = registry() const code = await runPluginCommand(r, 'echo', ['say', 'hello', 'world', '--loud'], output()) diff --git a/apps/cli/src/commands/plugins.ts b/apps/cli/src/commands/plugins.ts index a0afb47..c2c7d2d 100644 --- a/apps/cli/src/commands/plugins.ts +++ b/apps/cli/src/commands/plugins.ts @@ -149,12 +149,27 @@ async function ask(question: string): Promise { export function findPluginCall( argv: readonly string[], registry: Pick, -): { pluginId: string; args: string[] } | null { +): { pluginId: string; args: string[]; defaultCommand?: string } | null { const at = argv.findIndex((token) => !token.startsWith('-')) if (at === -1) return null - const head = argv[at]! + const word = argv[at]! + const alias = PLUGIN_ALIASES[word] + const head = alias?.pluginId ?? word if (!registry.has(head)) return null - return { pluginId: head, args: [...argv.slice(0, at), ...argv.slice(at + 1)] } + return { + pluginId: head, + args: [...argv.slice(0, at), ...argv.slice(at + 1)], + ...(alias?.defaultCommand ? { defaultCommand: alias.defaultCommand } : {}), + } +} + +/** + * Short names for built-in plugins. `diskpush clean` is the cleaner, and + * `diskpush clean [TARGET] [--apply]` with no command means `run`. The alias + * words are reserved plugin ids, so an external plugin cannot take them. + */ +export const PLUGIN_ALIASES: Record = { + clean: { pluginId: 'cleaner', defaultCommand: 'run' }, } /** Global flags the CLI owns; everything else belongs to the plugin. */ @@ -176,9 +191,16 @@ export async function runPluginCommand( argv: readonly string[], output: Output, servers?: ServerDirectory, + defaultCommand?: string, ): Promise { const plugin = await registry.require(pluginId) - const args = stripGlobalFlags(argv) + let args = stripGlobalFlags(argv) + // An alias with a default command: `diskpush clean web-1 --apply` is `diskpush cleaner run web-1 --apply`. + if (defaultCommand) { + const first = args[0] + const isHelp = first === 'help' || first === '--help' || first === '-h' + if (!isHelp && (first === undefined || !(plugin.commands ?? []).some((command) => command.name === first))) args = [defaultCommand, ...args] + } const [name, ...rest] = args if (!name || name === 'help' || name === '--help' || name === '-h') { process.stdout.write(pluginUsage(plugin)) diff --git a/apps/cli/src/plugins.ts b/apps/cli/src/plugins.ts index 266a440..2b960bb 100644 --- a/apps/cli/src/plugins.ts +++ b/apps/cli/src/plugins.ts @@ -24,12 +24,13 @@ import { type SettingsBackend, } from '@diskpush/plugin-api' import { toServerRef } from '@diskpush/ssh-core' +import { cleanerPlugin } from '@diskpush/plugin-cleaner' import { dbBackupPlugin } from '@diskpush/plugin-dbbackup' import { mediaAnalyzerPlugin } from '@diskpush/plugin-mediaanalyzer' import { sshConfigHosts } from './resolve.js' /** Plugins that ship with DiskPush. */ -export const BUILTIN_PLUGINS = [mediaAnalyzerPlugin, dbBackupPlugin] +export const BUILTIN_PLUGINS = [mediaAnalyzerPlugin, dbBackupPlugin, cleanerPlugin] export type LoadedRegistry = { registry: PluginRegistry; failures: LoadFailure[] } diff --git a/apps/desktop/electron/main/ipc.ts b/apps/desktop/electron/main/ipc.ts index df9b523..a102154 100644 --- a/apps/desktop/electron/main/ipc.ts +++ b/apps/desktop/electron/main/ipc.ts @@ -12,6 +12,8 @@ import { ExternalUrlSchema, FleetCheckRequestSchema, FleetSyncRequestSchema, + CleanerScanRequestSchema, + CleanerApplyRequestSchema, FleetSyncIdSchema, FleetCommandSaveSchema, FleetListRenameSchema, @@ -53,6 +55,7 @@ import { startFleet, } from './services/fleet.js' import { startFleetSync, cancelFleetSync } from './services/fleet-sync.js' +import { cleanerApply, cleanerCancel, cleanerScan, cleanerTargets } from './services/cleaner.js' import { browserFor, dropSession, sessionFor, type RemoteBrowser } from './services/sessions.js' import { store } from './services/store.js' import { advanceSeries, handlersFor, openSeries, openWith, stopSeries } from './services/open-with.js' @@ -472,6 +475,18 @@ export function registerIpc(): void { setPluginEnabled(pluginId, enabled), ) + // --- cleaner ------------------------------------------------------------- + // The renderer names a target and, to apply, a report id plus item ids from + // that report. Paths only ever come from the main process's own scan. + + handle(IPC.cleanerTargets, z.undefined(), async () => cleanerTargets()) + + handle(IPC.cleanerScan, CleanerScanRequestSchema, async (request, event) => cleanerScan(request, event.sender)) + + handle(IPC.cleanerApply, CleanerApplyRequestSchema, async (request, event) => cleanerApply(request, event.sender)) + + handle(IPC.cleanerCancel, z.object({ jobId: JobIdSchema }), async ({ jobId }) => cleanerCancel(jobId)) + // --- shell --------------------------------------------------------------- handle(IPC.shellOpenExternal, z.object({ url: ExternalUrlSchema }), async ({ url }) => { diff --git a/apps/desktop/electron/main/services/cleaner.ts b/apps/desktop/electron/main/services/cleaner.ts new file mode 100644 index 0000000..9e6b550 --- /dev/null +++ b/apps/desktop/electron/main/services/cleaner.ts @@ -0,0 +1,81 @@ +/** + * The Cleaner tab, in the main process. + * + * Scans and applies run here through the cleaner plugin's own core (the same + * code the CLI and MCP use), with the plugin's settings and the Fleet tab's + * servers. A scan's report is kept here under an id; an apply names that id + * and item ids from it, so the renderer can choose among findings but can + * never name a path of its own. Progress goes out on `plugins:progress`. + */ +import { randomUUID } from 'node:crypto' +import type { WebContents } from 'electron' +import { PluginError } from '@diskpush/plugin-api' +import { applyClean, listTargets, scanTarget, CLEANER_ID, type ApplyResult, type Report, type Target } from '@diskpush/plugin-cleaner' +import { IPC, type CleanerApplyRequest, type CleanerScanRequest } from '../../shared/contract.js' +import { pluginHostContext, pluginRegistry } from './plugins.js' + +const reports = new Map() +const running = new Map() + +async function requireEnabled(): Promise { + const { registry } = await pluginRegistry() + if (!registry.has(CLEANER_ID)) throw new PluginError('The Cleaner plugin is not installed.') + if (!(await registry.isEnabled(CLEANER_ID))) throw new PluginError('The Cleaner plugin is disabled. Turn it on under Plugins….') +} + +export async function cleanerTargets(): Promise { + await requireEnabled() + return listTargets(await pluginHostContext(CLEANER_ID, 'cleaner-targets', null, new AbortController().signal)) +} + +async function track(jobId: string, work: (signal: AbortSignal) => Promise): Promise { + if (running.has(jobId)) throw new PluginError('That job id is already running.') + const controller = new AbortController() + running.set(jobId, controller) + try { + return await work(controller.signal) + } finally { + running.delete(jobId) + } +} + +export type CleanerScanResult = { reportId: string; report: Report } + +export async function cleanerScan(request: CleanerScanRequest, sender: WebContents): Promise { + await requireEnabled() + return track(request.jobId, async (signal) => { + const ctx = await pluginHostContext(CLEANER_ID, request.jobId, sender, signal) + const report = await scanTarget(ctx, request.target, { + ...(request.only.length ? { only: request.only } : {}), + ...(request.idleDays ? { idleDays: request.idleDays } : {}), + }) + const reportId = randomUUID() + // One report per target is enough to apply from; older ones go. + for (const [id, old] of reports) if (old.target === report.target) reports.delete(id) + reports.set(reportId, report) + return { reportId, report } + }) +} + +export async function cleanerApply(request: CleanerApplyRequest, sender: WebContents): Promise { + await requireEnabled() + const report = reports.get(request.reportId) + if (!report) throw new PluginError('That report is gone; scan again first.') + return track(request.jobId, async (signal) => { + const ctx = await pluginHostContext(CLEANER_ID, request.jobId, sender, signal) + const result = await applyClean(ctx, report, { apply: true, ids: request.ids }) + // What was removed is no longer in the report; a re-scan shows the new state. + reports.delete(request.reportId) + if (!sender.isDestroyed()) { + sender.send(IPC.eventPlugin, { jobId: request.jobId, event: { type: 'exit', ok: true, message: 'done', changed: true, cancelled: signal.aborted } }) + } + return result + }) +} + +export function cleanerCancel(jobId: string): boolean { + const controller = running.get(jobId) + if (!controller) return false + controller.abort() + return true +} diff --git a/apps/desktop/electron/main/services/plugins.ts b/apps/desktop/electron/main/services/plugins.ts index 4432aa1..316bb81 100644 --- a/apps/desktop/electron/main/services/plugins.ts +++ b/apps/desktop/electron/main/services/plugins.ts @@ -20,6 +20,7 @@ import { runAction, runTask, type ActionResult, + type BaseContext, type HostContext, type LoadFailure, type LogLevel, @@ -28,6 +29,7 @@ import { type SettingDef, } from '@diskpush/plugin-api' import { toServerRef } from '@diskpush/ssh-core' +import { cleanerPlugin } from '@diskpush/plugin-cleaner' import { dbBackupPlugin } from '@diskpush/plugin-dbbackup' import { mediaAnalyzerPlugin } from '@diskpush/plugin-mediaanalyzer' import { ExternalUrlSchema, IPC, type PluginActionRequest } from '../../shared/contract.js' @@ -36,7 +38,7 @@ import { isLocalConnectionId } from './local-session.js' import { store } from './store.js' /** The same built-in list as the CLI's (apps/cli/src/plugins.ts). */ -const BUILTIN_PLUGINS = [mediaAnalyzerPlugin, dbBackupPlugin] +const BUILTIN_PLUGINS = [mediaAnalyzerPlugin, dbBackupPlugin, cleanerPlugin] let loaded: Promise<{ registry: PluginRegistry; failures: LoadFailure[] }> | null = null @@ -138,6 +140,25 @@ const servers: ServerDirectory = { sshConfigFile: process.env.DISKPUSH_SSH_CONFIG ?? null, } +/** + * A plugin's full context for host-owned screens (the Cleaner tab) that call + * a built-in plugin's core directly instead of through an action. Progress + * goes out on `plugins:progress` under `jobId` when there is a window to send it to. + */ +export async function pluginHostContext(pluginId: string, jobId: string, sender: WebContents | null, signal: AbortSignal): Promise { + const { registry } = await pluginRegistry() + return { + settings: registry.settingsFor(pluginId), + secrets: registry.secretsFor(pluginId), + progress: sender ? sink(jobId, sender) : { start() {}, update() {}, log() {} }, + openUrl, + signal, + surface: 'desktop', + env: process.env, + servers, + } +} + /** Starts `work` under a fresh AbortController, reports its outcome, and returns at once. */ function launch(jobId: string, sender: WebContents, work: (host: HostContext) => Promise): { jobId: string } { if (running.has(jobId)) throw new PluginError('That job id is already running.') diff --git a/apps/desktop/electron/preload/index.ts b/apps/desktop/electron/preload/index.ts index 316efd9..0ecafc8 100644 --- a/apps/desktop/electron/preload/index.ts +++ b/apps/desktop/electron/preload/index.ts @@ -94,6 +94,14 @@ const api = { call(IPC.pluginsSetSettings, { pluginId, values }), setEnabled: (pluginId: string, enabled: boolean) => call(IPC.pluginsSetEnabled, { pluginId, enabled }), }, + // The Cleaner tab: targets by name, applies by report id + item ids. Never a path. + cleaner: { + targets: () => call(IPC.cleanerTargets), + scan: (jobId: string, target: string, only: string[] = [], idleDays?: number) => + call(IPC.cleanerScan, { jobId, target, only, ...(idleDays ? { idleDays } : {}) }), + apply: (jobId: string, reportId: string, ids: string[]) => call(IPC.cleanerApply, { jobId, reportId, ids }), + cancel: (jobId: string) => call(IPC.cleanerCancel, { jobId }), + }, events: { /** * Returns an unsubscribe function. The listener is wrapped so the diff --git a/apps/desktop/electron/shared/contract.ts b/apps/desktop/electron/shared/contract.ts index 1d32494..c7fc2a9 100644 --- a/apps/desktop/electron/shared/contract.ts +++ b/apps/desktop/electron/shared/contract.ts @@ -74,6 +74,12 @@ export const IPC = { pluginsSetSettings: 'plugins:set-settings', pluginsSetEnabled: 'plugins:set-enabled', + /** The Cleaner tab: free disk space on this machine or a server (plugin `cleaner`). */ + cleanerTargets: 'cleaner:targets', + cleanerScan: 'cleaner:scan', + cleanerApply: 'cleaner:apply', + cleanerCancel: 'cleaner:cancel', + /** Main -> renderer, progress and the outcome of a plugin action or task. */ eventPlugin: 'plugins:progress', @@ -529,6 +535,30 @@ export const PluginSettingsSetSchema = z.object({ .refine((values) => Object.keys(values).length <= 64, { message: 'Too many settings at once.' }), }) +/** + * The Cleaner tab. The renderer names a target (`local` or a server name the + * main process looks up) and, to apply, the id of a report the main process + * produced plus item ids from it. It never sends a path: what is removed is + * whatever the main process's own scan found, re-checked on the target. + */ +export const CleanerTargetSchema = z.string().regex(/^[A-Za-z0-9_.@:-]{1,128}$/, 'That is not a target name.') +export const CleanerCategorySchema = z.enum(['caches', 'docker', 'logs', 'build', 'partials']) + +export const CleanerScanRequestSchema = z.object({ + jobId: JobIdSchema, + target: CleanerTargetSchema, + only: z.array(CleanerCategorySchema).max(5).default([]), + idleDays: z.number().int().min(1).max(3650).optional(), +}) +export type CleanerScanRequest = z.infer + +export const CleanerApplyRequestSchema = z.object({ + jobId: JobIdSchema, + reportId: z.string().regex(/^[a-z0-9-]{1,64}$/), + ids: z.array(z.string().min(1).max(8192)).min(1).max(50000), +}) +export type CleanerApplyRequest = z.infer + /** Only http(s) may be handed to the system browser. */ export const ExternalUrlSchema = z.string().url().refine((value) => /^https?:\/\//i.test(value), { message: 'Only http and https URLs can be opened externally.', diff --git a/apps/desktop/electron/shared/plugin-contract.test.ts b/apps/desktop/electron/shared/plugin-contract.test.ts index f6035de..138c599 100644 --- a/apps/desktop/electron/shared/plugin-contract.test.ts +++ b/apps/desktop/electron/shared/plugin-contract.test.ts @@ -1,5 +1,7 @@ import { describe, expect, it } from 'vitest' import { + CleanerApplyRequestSchema, + CleanerScanRequestSchema, IPC, LocalDirectorySchema, PluginActionRequestSchema, @@ -77,3 +79,22 @@ describe('channels', () => { expect(IPC.eventPlugin).toBe('plugins:progress') }) }) + +describe('cleaner requests', () => { + const jobId = '6f9619ff-8b86-4011-b42d-00c04fc964ff' + it('name a target and categories, never a path', () => { + expect(CleanerScanRequestSchema.safeParse({ jobId, target: 'local' }).success).toBe(true) + expect(CleanerScanRequestSchema.safeParse({ jobId, target: 'dev-box.example', only: ['build', 'docker'] }).success).toBe(true) + expect(CleanerScanRequestSchema.safeParse({ jobId, target: '../../etc' }).success).toBe(false) + expect(CleanerScanRequestSchema.safeParse({ jobId, target: 'local', only: ['volumes'] }).success).toBe(false) + }) + it('apply names a report id and item ids', () => { + expect(CleanerApplyRequestSchema.safeParse({ jobId, reportId: '6f9619ff-8b86-4011-b42d-00c04fc964ff', ids: ['cache:npm'] }).success).toBe(true) + expect(CleanerApplyRequestSchema.safeParse({ jobId, reportId: 'x/../y', ids: ['cache:npm'] }).success).toBe(false) + expect(CleanerApplyRequestSchema.safeParse({ jobId, reportId: 'abc', ids: [] }).success).toBe(false) + }) + it('use the cleaner: channels', () => { + expect(IPC.cleanerScan).toBe('cleaner:scan') + expect(IPC.cleanerApply).toBe('cleaner:apply') + }) +}) diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 49f459e..8760591 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -18,6 +18,7 @@ "@diskpush/database": "workspace:*", "@diskpush/fleet-core": "workspace:*", "@diskpush/plugin-api": "workspace:*", + "@diskpush/plugin-cleaner": "workspace:*", "@diskpush/plugin-dbbackup": "workspace:*", "@diskpush/plugin-mediaanalyzer": "workspace:*", "@diskpush/rsync-core": "workspace:*", diff --git a/apps/desktop/src/app/page.tsx b/apps/desktop/src/app/page.tsx index 2927af6..03f17be 100644 --- a/apps/desktop/src/app/page.tsx +++ b/apps/desktop/src/app/page.tsx @@ -16,10 +16,12 @@ import { Settings, Users, X, + Brush, } from 'lucide-react' import { ConnectionDialog } from '@/components/connection-dialog' import { FleetView } from '@/components/fleet-view' import { FleetSyncPanel } from '@/components/fleet-sync-panel' +import { CleanerPanel } from '@/components/cleaner-panel' import { PluginsDialog } from '@/components/plugins-dialog' import { ProfileBar } from '@/components/profile-bar' import { ServerManager } from '@/components/server-manager' @@ -129,7 +131,7 @@ export default function Workspace() { const [showPlugins, setShowPlugins] = useState(false) /** Which pane a plugin job is working in, so the pane is re-read when it changes files. */ const pluginSideRef = useRef<{ jobId: string; side: 'left' | 'right' } | null>(null) - const [tab, setTab] = useState<'transfer' | 'fleet' | 'sync'>('transfer') + const [tab, setTab] = useState<'transfer' | 'fleet' | 'sync' | 'cleaner'>('transfer') const [profiles, setProfiles] = useState([]) const [outsideShell, setOutsideShell] = useState(false) @@ -604,6 +606,10 @@ export default function Workspace() { Fleet Sync + setTab('cleaner')}> + + Cleaner +
@@ -789,6 +795,10 @@ export default function Workspace() {
+
+ +
+ setShowServers(false)} diff --git a/apps/desktop/src/components/cleaner-panel.tsx b/apps/desktop/src/components/cleaner-panel.tsx new file mode 100644 index 0000000..ee24c1b --- /dev/null +++ b/apps/desktop/src/components/cleaner-panel.tsx @@ -0,0 +1,444 @@ +'use client' + +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { Brush, CircleAlert, Copy, Loader2, Search, ShieldAlert, ShieldCheck, Square, Trash2 } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Checkbox } from '@/components/ui/checkbox' +import { Dialog, DialogContent } from '@/components/ui/dialog' +import { ScrollArea } from '@/components/ui/scroll-area' +import { formatBytes } from '@/lib/format' +import { api, unwrap, type CleanerApplyResult, type CleanerItem, type CleanerReport, type CleanerTarget } from '@/lib/api' +import { CLEANER_CATEGORIES, categoryLabel, plannedItems, selectedBytes, sizeLabel } from '@/lib/cleaner' + +/** + * Cleaner — free disk space intelligently, on this machine or any server. + * + * Analyze first: filesystems, who is writing right now, the biggest + * directories, growth since the last analysis, and every finding classified + * (safe / safe-if-idle / needs a human) with the reason. Then tick what to + * remove and confirm. Only safe-class items can be ticked; needs-a-human items + * show a command to look closer and are never removed from here. + */ + +const SAFETY_BADGE: Record = { + safe: 'bg-ok/15 text-ok', + 'safe-if-idle': 'bg-primary/15 text-primary', + human: 'bg-destructive/10 text-destructive', +} + +export function CleanerPanel() { + const [targets, setTargets] = useState([]) + const [target, setTarget] = useState('local') + const [only, setOnly] = useState>(new Set(CLEANER_CATEGORIES)) + const [report, setReport] = useState(null) + const [reportId, setReportId] = useState(null) + const [chosen, setChosen] = useState>(new Set()) + const [jobId, setJobId] = useState(null) + const [busy, setBusy] = useState<'scan' | 'apply' | null>(null) + const [status, setStatus] = useState('') + const [error, setError] = useState(null) + const [confirming, setConfirming] = useState(false) + const [result, setResult] = useState(null) + const jobRef = useRef(null) + + useEffect(() => { + void unwrap(api()?.cleaner.targets()) + .then(setTargets) + .catch((caught) => setError(caught instanceof Error ? caught.message : String(caught))) + }, []) + + useEffect(() => { + const off = api()?.events.onPluginProgress(({ jobId: id, event }) => { + if (id !== jobRef.current) return + if (event.type === 'update' && event.message) setStatus(event.message) + if (event.type === 'log') setStatus(event.message) + }) + return off + }, []) + + const analyze = useCallback(async () => { + const id = crypto.randomUUID() + jobRef.current = id + setJobId(id) + setBusy('scan') + setError(null) + setResult(null) + setStatus(`Scanning ${target}…`) + try { + const out = await unwrap(api()?.cleaner.scan(id, target, only.size === CLEANER_CATEGORIES.length ? [] : [...only])) + setReport(out.report) + setReportId(out.reportId) + setChosen(new Set(plannedItems(out.report).map((i) => i.id))) + setStatus('') + } catch (caught) { + setError(caught instanceof Error ? caught.message : String(caught)) + } finally { + setBusy(null) + } + }, [target, only]) + + const apply = useCallback(async () => { + if (!reportId || !chosen.size) return + setConfirming(false) + const id = crypto.randomUUID() + jobRef.current = id + setJobId(id) + setBusy('apply') + setError(null) + setStatus('Removing…') + try { + const out = await unwrap(api()?.cleaner.apply(id, reportId, [...chosen])) + setResult(out) + setReportId(null) + setStatus('') + } catch (caught) { + setError(caught instanceof Error ? caught.message : String(caught)) + } finally { + setBusy(null) + } + }, [reportId, chosen]) + + const cancel = useCallback(async () => { + if (jobId) await api()?.cleaner.cancel(jobId) + }, [jobId]) + + const items = report?.items ?? [] + const eligible = useMemo(() => items.filter((i) => i.eligible && i.safety !== 'human'), [items]) + const kept = useMemo(() => items.filter((i) => !i.eligible && i.safety !== 'human'), [items]) + const human = useMemo(() => items.filter((i) => i.safety === 'human'), [items]) + const total = useMemo(() => selectedBytes(items, chosen), [items, chosen]) + + const toggle = (id: string) => + setChosen((current) => { + const next = new Set(current) + if (next.has(id)) next.delete(id) + else next.add(id) + return next + }) + + return ( +
+
+ + Free disk space + · analysis first; only safe items can be removed, and only after you confirm +
+ +
+ + + {CLEANER_CATEGORIES.map((c) => ( + + ))} + + {busy ? ( + + ) : null} + {status ? {status} : null} +
+ + {error ? ( +
+ + {error} +
+ ) : null} + + {result ? : null} + + + {!report ? ( +
+ Pick a target and Analyze. Nothing is deleted until you tick items and confirm. +
+ ) : ( +
+ + +
+
+ + Can be freed safely · {eligible.length} item{eligible.length === 1 ? '' : 's'} + ranked by bytes freed per unit of risk + + + + +
+ {eligible.length === 0 ?

Nothing can be freed safely right now.

: null} +
    + {eligible.map((i) => ( +
  • + toggle(i.id)} aria-label={`Remove ${i.title}`} /> + +
  • + ))} +
+
+ + {!reportId && result ? Analyze again to see the new state. : null} +
+
+ + {kept.length || report.kept.length ? ( +
+
Kept, and why
+
    + {kept.map((i) => ( +
  • + {sizeLabel(i)} {i.title}: {i.why.replace(/^Kept: /, '')} +
  • + ))} + {report.kept.slice(0, 50).map((k) => ( +
  • + {k.root}: {k.reason} + {k.dirs > 1 ? ` (${k.dirs} build dirs)` : ''} +
  • + ))} +
+
+ ) : null} + + {human.length ? ( +
+
+ + Needs a human · reported, never removed from here +
+
    + {human.map((i) => ( +
  • + + {i.suggested ? : null} +
  • + ))} +
+
+ ) : null} + + {report.warnings.map((w) => ( +

+ {w} +

+ ))} +
+ )} +
+ + !next && setConfirming(false)}> + +
+ +
+

+ Remove {chosen.size} item{chosen.size === 1 ? '' : 's'} on {report?.target === 'local' ? 'this machine' : report?.target}? +

+

+ About {formatBytes(total)}. Each item is checked again on the target as it goes: anything that became busy since the analysis is skipped. +

+
+
+
    + {items + .filter((i) => chosen.has(i.id)) + .map((i) => ( +
  • + {sizeLabel(i)} + + {i.title} + +
  • + ))} +
+
+ + +
+
+
+
+ ) +} + +function ItemRow({ item }: { item: CleanerItem }) { + return ( +
+
+ {sizeLabel(item)} + {item.safety === 'human' ? 'needs a human' : item.safety} + + {item.title} + +
+

{item.why}

+
+ ) +} + +function CommandLine({ command }: { command: string }) { + const [copied, setCopied] = useState(false) + return ( +
+ {command} + +
+ ) +} + +function Overview({ report }: { report: CleanerReport }) { + return ( +
+
+
Filesystems
+
    + {report.filesystems.slice(0, 6).map((f) => { + const grow = report.growth?.fs.find((g) => g.mount === f.mount) + return ( +
  • +
    + + {f.mount} + +
    +
    = 90 ? 'bg-destructive' : 'bg-primary'}`} style={{ width: `${f.usedPercent}%` }} /> +
    + {formatBytes(f.availBytes)} free +
    + {grow && grow.deltaBytes !== 0 ? ( +
    + {grow.deltaBytes > 0 ? '+' : '−'} + {formatBytes(Math.abs(grow.deltaBytes))} since the last analysis ({grow.bytesPerHour >= 0 ? '+' : '−'} + {formatBytes(Math.abs(grow.bytesPerHour))}/h) +
    + ) : null} +
  • + ) + })} +
+ {report.writers.length ? ( + <> +
Writing to disk right now
+
    + {report.writers.slice(0, 6).map((w) => ( +
  • + {formatBytes(w.bytesPerSecond)}/s + + {w.command} + {w.container ? · container {w.container} : null} + · pid {w.pid} + +
  • + ))} +
+ + ) : null} +
+
+
Biggest directories
+
    + {report.topDirs.slice(0, 12).map((d) => ( +
  • + {d.bytes < 0 ? '?' : `${d.timedOut ? '≥ ' : ''}${formatBytes(d.bytes)}`} + + {d.path} + + {d.kind ? [{d.kind}] : null} +
  • + ))} +
+
+
+ ) +} + +function ApplySummary({ result, items }: { result: CleanerApplyResult; items: CleanerItem[] }) { + const titles = new Map(items.map((i) => [i.id, i.title])) + const problems = result.results.filter((r) => r.status === 'failed' || r.status === 'skipped') + return ( +
+ {result.locked ? ( +

Another clean is already running on this target; nothing was done.

+ ) : ( +

+ Freed about {formatBytes(result.freedBytes)} · {result.results.filter((r) => r.status === 'ok').length} removed + {problems.length ? ` · ${problems.length} skipped` : ''} + {result.stopped ? ' · stopped once enough space was free' : ''} +

+ )} + {problems.length ? ( +
    + {problems.map((r) => ( +
  • + {titles.get(r.id) ?? r.id}: {r.message} +
  • + ))} +
+ ) : null} +
+ ) +} diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts index e5ca8ce..4506fcd 100644 --- a/apps/desktop/src/lib/api.ts +++ b/apps/desktop/src/lib/api.ts @@ -1,5 +1,9 @@ 'use client' +import type { ApplyResult as CleanerApplyResult, Item as CleanerItem, Report as CleanerReport, Target as CleanerTarget } from '@diskpush/plugin-cleaner' + +export type { CleanerApplyResult, CleanerItem, CleanerReport, CleanerTarget } + /** * The typed view of what `preload` exposed. * @@ -422,6 +426,12 @@ type Api = { setSettings(pluginId: string, values: Record): Promise> setEnabled(pluginId: string, enabled: boolean): Promise> } + cleaner: { + targets(): Promise> + scan(jobId: string, target: string, only?: string[], idleDays?: number): Promise> + apply(jobId: string, reportId: string, ids: string[]): Promise> + cancel(jobId: string): Promise> + } events: { onTransfer(listener: (payload: { jobId: string; event: TransferEvent }) => void): () => void onFleet(listener: (payload: { runId: string; event: FleetEvent }) => void): () => void diff --git a/apps/desktop/src/lib/cleaner.test.ts b/apps/desktop/src/lib/cleaner.test.ts new file mode 100644 index 0000000..8de8ec7 --- /dev/null +++ b/apps/desktop/src/lib/cleaner.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest' +import type { CleanerItem, CleanerReport } from './api' +import { plannedItems, selectedBytes, sizeLabel } from './cleaner' + +const item = (id: string, over: Partial = {}): CleanerItem => ({ + id, + category: 'build', + safety: 'safe-if-idle', + title: id, + path: `/x/${id}`, + bytes: 1000, + upTo: false, + eligible: true, + why: '', + suggested: null, + risk: 2, + score: 500, + step: null, + ...over, +}) + +describe('cleaner tab helpers', () => { + it('ticks only planned, eligible, safe-class items', () => { + const items = [item('a'), item('b', { eligible: false }), item('c', { safety: 'human', eligible: false }), item('d')] + const report = { items, plan: { ids: ['a', 'b', 'c'], bytes: 0 } } as unknown as CleanerReport + expect(plannedItems(report).map((i) => i.id)).toEqual(['a']) + }) + + it('never counts a needs-a-human item toward what will be freed', () => { + const items = [item('a'), item('c', { safety: 'human', eligible: false, bytes: 1e12 })] + expect(selectedBytes(items, new Set(['a', 'c']))).toBe(1000) + }) + + it('labels unknown and upper-bound sizes', () => { + expect(sizeLabel(item('a', { bytes: -1 }))).toBe('?') + expect(sizeLabel(item('a', { upTo: true }))).toMatch(/^≤ /) + }) +}) diff --git a/apps/desktop/src/lib/cleaner.ts b/apps/desktop/src/lib/cleaner.ts new file mode 100644 index 0000000..1e54c6e --- /dev/null +++ b/apps/desktop/src/lib/cleaner.ts @@ -0,0 +1,33 @@ +/** Pure helpers for the Cleaner tab, kept out of the component so they are tested on their own. */ +import type { CleanerItem, CleanerReport } from './api' +import { formatBytes } from './format' + +export const CLEANER_CATEGORIES = ['caches', 'docker', 'logs', 'build', 'partials'] as const + +const LABELS: Record = { + caches: 'Caches', + docker: 'Docker', + logs: 'Logs', + build: 'Build output', + partials: 'Partial files', +} + +export function categoryLabel(category: string): string { + return LABELS[category] ?? category +} + +/** The report's plan: what is ticked when a report arrives. Never a needs-a-human item. */ +export function plannedItems(report: CleanerReport): CleanerItem[] { + const planned = new Set(report.plan.ids) + return report.items.filter((i) => planned.has(i.id) && i.eligible && i.safety !== 'human') +} + +/** Bytes of the ticked items that can actually be removed. */ +export function selectedBytes(items: readonly CleanerItem[], chosen: ReadonlySet): number { + return items.filter((i) => chosen.has(i.id) && i.eligible && i.safety !== 'human').reduce((sum, i) => sum + Math.max(0, i.bytes), 0) +} + +export function sizeLabel(item: CleanerItem): string { + if (item.bytes < 0) return '?' + return `${item.upTo && item.bytes > 0 ? '≤ ' : ''}${formatBytes(item.bytes)}` +} diff --git a/apps/web/app/page.tsx b/apps/web/app/page.tsx index 7686ed0..d1c3a41 100644 --- a/apps/web/app/page.tsx +++ b/apps/web/app/page.tsx @@ -111,6 +111,7 @@ export default function HomePage() { + @@ -233,6 +234,40 @@ function Features() { ) } +function Cleaner() { + return ( +
+
+
+
+

Disk full? Cleaner finds out why.

+

+ The built-in Cleaner shows what is filling and growing a disk, on this machine or any + server: the biggest directories, which processes are writing right now, and growth since + the last look. Every finding is classified as safe, safe-if-idle or needs-a-human, ranked + by space freed per unit of risk, and explained. +

+

+ Analysis is always a dry run. Apply removes only regenerable caches, docker build cache, + old unused images, rotated logs, build output in idle projects and abandoned partial + files, re-checking every guard as it goes. Databases, backups and volumes are only ever + reported. CLI, TUI, the desktop Cleaner tab and MCP. +

+ + How the Cleaner decides what is safe → + +
+
+ {`diskpush clean report web-1`} + {`diskpush clean web-1 --apply`} + {`diskpush clean --min-free-gb 20 --apply`} +
+
+
+
+ ) +} + function Desktop() { return (
diff --git a/apps/web/lib/docs.ts b/apps/web/lib/docs.ts index cf47e76..b4ee4c0 100644 --- a/apps/web/lib/docs.ts +++ b/apps/web/lib/docs.ts @@ -24,6 +24,7 @@ const ORDER = [ 'rsync-options', 'profiles', 'fleet', + 'cleaner', 's3', 'direct-server-to-server', 'security', @@ -41,6 +42,7 @@ const DESCRIPTIONS: Record = { 'rsync-options': 'Every option, the flag it maps to, and its caveats.', profiles: 'Saved, repeatable directory pairs.', fleet: 'Run one command, or a whole upgrade, across many servers at once.', + cleaner: 'Free disk space safely: what fills and grows a disk, classified and ranked, removed only on apply.', s3: 'S3-compatible buckets (AWS, R2, B2, MinIO) saved, browsed and synced like a server.', 'direct-server-to-server': 'How the no-relay guarantee is implemented.', security: 'The threat model and the decisions that follow from it.', diff --git a/docs/architecture.md b/docs/architecture.md index 98b16ce..61d8203 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -12,6 +12,7 @@ packages/s3-core S3-compatible storage: a dependency-free SigV4 client, the packages/plugin-api The plugin contract, registry and external-plugin loader. packages/plugin-mediaanalyzer The built-in MediaAnalyzer plugin. packages/plugin-dbbackup The built-in database backup plugin. +packages/plugin-cleaner The built-in Cleaner plugin: disk analysis and safe cleanup, CLI/TUI/desktop/MCP. apps/cli The `diskpush` command. apps/desktop Electron main, preload, and the renderer. apps/web diskpush.com. diff --git a/docs/cleaner.md b/docs/cleaner.md new file mode 100644 index 0000000..ef03e57 --- /dev/null +++ b/docs/cleaner.md @@ -0,0 +1,160 @@ +# Cleaner + +The Cleaner frees disk space intelligently, on this machine or on any server +DiskPush can reach over ssh. It is a built-in plugin, on by default; turn it +off with `diskpush plugins disable cleaner` or under Plugins… in the desktop +app. + +It works in two steps, and the first one is the point: + +1. **Analysis (always a dry run).** What is using the disk and what is + growing it: every filesystem's free space, the biggest directories, which + processes are writing to disk right now, and how much each filesystem and + directory grew since the last analysis. Every finding is classified and + explained, then ranked by bytes freed per unit of risk into a plan. +2. **Apply (only when you say so).** Removes the items you chose, but only + items in the safe classes, and only after checking every guard again on + the target at the moment of deleting. + +```bash +diskpush clean report # this machine: analysis only +diskpush clean report web-1 # a server from `diskpush fleet servers` +diskpush clean # dry run: exactly what would be removed +diskpush clean --apply # remove it +diskpush clean web-1 --only docker,caches --apply +diskpush clean --min-free-gb 20 --apply # do nothing while 20 GB are free; stop once they are +diskpush clean cron --min-free-gb 20 # a crontab line for that, every 15 minutes +diskpush clean report --json # the whole report, for scripts +``` + +`clean` is short for `cleaner`; `diskpush clean [TARGET]` with no command is +`diskpush clean run [TARGET]`. + +## The three classes + +| Class | What | Removed? | +| --- | --- | --- | +| **safe** | Regenerable: package-manager caches, docker build cache, unused docker images older than 72 h, the systemd journal above a size cap, rotated logs (compressed, not deleted). The only cost is time: the next install or build fetches or rebuilds it. | On apply | +| **safe-if-idle** | Build output in projects nobody is using, and partial downloads whatever was writing them has abandoned. Removable only because the guards prove it. | On apply | +| **needs a human** | Database data, backups, docker volumes, stopped containers, media and downloads. | **Never.** Reported with a command to look closer. | + +Each item in a report carries its class, its estimated size, the reason it is +or is not safe, and a suggested command. + +## Categories + +Choose with `--only` (CLI), `only` (MCP) or the checkboxes (desktop). + +- **caches**: npm (`npm cache clean --force`), pnpm (`pnpm store prune`, + which only removes packages no project references), yarn, bun, uv, pip, + the cargo registry's downloads and unpacked sources, and the go build + cache. A cache is skipped while its tool is running. +- **docker**: `docker builder prune -f` (build cache no build is using) and + `docker image prune -a -f --filter until=72h` (images no container uses, + older than the age, so a recent deploy can still roll back; change it with + `--image-age`). Docker volumes and containers are never touched. +- **logs**: `journalctl --vacuum-size=1G` (`--journal-cap`) and gzip of + rotated, uncompressed logs over 1 MB in `/var/log` that no process has open. + Both usually need root: run as root, or pass `--sudo` to let these steps + use passwordless `sudo -n` where it works. Without either they are listed + with the command to run by hand. +- **build**: `node_modules`, `.next`, `.nuxt`, `.turbo`, `.svelte-kit`, + `.parcel-cache`, `.output`, `target`, `dist`, `build`, under the project + folders (default `~/src`, `~/code`, `~/projects`, `~/dev`, `~/work`, + `~/repos`, `~/git`, `~/worktrees`, `~/scratch`, `~/Developer`; set + `--roots` or the *Project folders* setting). +- **partials**: `*.partial`, `*.part` and `*.crdownload` files under your home + folder (or the *Partial-file folders* setting). + +## The guards + +Build output is removed only when **all** of these hold, at scan time and +again at delete time: + +- it is really build output: `node_modules` and friends sit next to a + `package.json`; `target` next to a `Cargo.toml` or holds a `CACHEDIR.TAG`; + it is not a symlink; +- git ignores it. `dist`, `build` and `.output` outside a git repository are + kept, because nothing proves they are generated; +- nothing in the whole project (the git repository) changed for N days + (default 3, `--idle-days`), build output and `.git` aside; +- no running process has its working directory or executable inside the + project; +- nothing wires the project to the running system: no command linked into a + bin directory (`~/.local/bin`, `/usr/local/bin`, npm/pnpm/bun globals), no + crontab or `/etc/cron.d` line, no systemd unit, no directory bind-mounted + into a running container names it. + +A `node_modules` in a folder that is not a project is not even listed. + +A partial file goes only when nothing has written to it for 24 hours and no +process has it open. A cache goes only while its tool is not running. A +rotated log is compressed only when no process has it open. + +Apply also never runs twice at once: a lock (in `$XDG_RUNTIME_DIR`, a tmpfs, +so it can be taken on a full disk) makes a second run on the same machine +exit with code 75 and touch nothing. That is what makes `--min-free-gb` safe +in cron. + +## Finding the culprit + +`report` answers "what is filling the disk right now" fast: + +- **Writing to disk right now**: per-process `write_bytes` from `/proc//io` + sampled twice a few seconds apart (`--sample`), mapped to a docker + container's name when the process runs in one. Without root only your own + processes can be read. +- **Biggest directories**: the children of `~`, `/var/lib`, `/var/log`, + `/opt`, `/srv`, `/tmp` and the like, sized several at a time, each `du` + bounded (`--du-timeout`, default 20 s). One that runs out of time shows as + `?`: it is the one to look inside first. Directories that look like + databases, backups or media are called out for a human. +- **Growth**: each full report keeps a snapshot (in the plugin's settings), and + the next one shows how much each filesystem and directory grew and the rate + per hour. + +The analysis writes no scratch files, so it works on a disk that is 100% full. + +## Servers + +A target is `local` or any name from `diskpush fleet servers` (saved +connections and `~/.ssh/config` hosts). The same programs run there over the +system `ssh` in BatchMode, so nothing ever waits on a password prompt; a +server that signs in with a password is listed but not usable. Nothing is +installed on the server; it needs a POSIX shell, `find`, `du` and `df`. + +## Desktop + +The **Cleaner** tab: pick a target and the categories, **Analyze**, read the +report (filesystems, writers, biggest directories, then every item with its +class and reason), tick what to remove (the plan is ticked for you; needs-a- +human items cannot be ticked), and confirm. The main process keeps the report +and the renderer only ever sends item ids from it, never a path. In the file +panes, right-click a folder for **Disk report: what can be freed here**. + +## TUI + +`a` on a directory: **Disk report: what can be freed here** sizes what is +inside, finds idle build output and stale partial files under it, and prints +the command that removes them. + +## MCP + +`diskpush clean mcp` serves the cleaner over MCP on stdio: + +```json +{ "mcpServers": { "diskpush-cleaner": { "command": "diskpush", "args": ["clean", "mcp"] } } } +``` + +| Tool | Does | +| --- | --- | +| `clean_targets` | This machine and every server DiskPush knows | +| `clean_report` | The full analysis (read-only); the report is in `structuredContent` | +| `clean_apply` | A dry run unless `apply: true`; then only eligible, safe-class items; `only`, `ids` and `minFreeGb` narrow it | + +## API + +The core is the `@diskpush/plugin-cleaner` package: `scanTarget(ctx, target, +options)` returns the report, `applyClean(ctx, report, { apply, only, ids, +minFreeGb })` removes, `listTargets(ctx)` lists. The CLI's `--json` prints the +same objects. diff --git a/docs/plugins.md b/docs/plugins.md index d1b447d..7fa09e6 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -226,6 +226,17 @@ database now* is under Plugins… in the desktop. command for pushes), `sqliteRoots` (where discovery looks for SQLite files), and `pg_dumpPath` / `mysqldumpPath` / `psqlPath` / `mysqlPath` / `sqlite3Path` to pin a tool. +## Cleaner + +`cleaner` (`diskpush clean`) finds what is filling and growing a disk and +frees space safely: caches, docker build cache, old unused images, rotated +logs, build output in idle projects, stale partial files. Analysis is always +a dry run; apply removes only safe-class items and re-checks every guard as +it deletes; databases, backups, volumes and media are only ever reported. +It runs locally or on any server over ssh, from the CLI, the TUI, the desktop +Cleaner tab and MCP (`diskpush clean mcp`). Everything else is in +[cleaner.md](cleaner.md). + ## Writing a plugin A plugin is an object. `definePlugin` checks its shape when it is defined, so diff --git a/packages/plugin-api/src/registry.ts b/packages/plugin-api/src/registry.ts index 0c18a39..0ef2b81 100644 --- a/packages/plugin-api/src/registry.ts +++ b/packages/plugin-api/src/registry.ts @@ -22,7 +22,7 @@ const SETTING_KEY = /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/ export const RESERVED_IDS = new Set([ 'sync', 'push', 'pull', 'publish', 'deploy', 'backup', 'mirror', 'rsync', 'ls', 'connections', 'profiles', 'profile', 'jobs', 'job', 'retry', 'update', 'upgrade', 'uninstall', 'remove', 'doctor', 'desktop', 'tui', - 'fleet', 'help', 'version', 'plugins', 'plugin', + 'fleet', 'help', 'version', 'plugins', 'plugin', 'clean', ]) export class PluginError extends Error { diff --git a/packages/plugin-cleaner/package.json b/packages/plugin-cleaner/package.json new file mode 100644 index 0000000..41eeaef --- /dev/null +++ b/packages/plugin-cleaner/package.json @@ -0,0 +1,28 @@ +{ + "name": "@diskpush/plugin-cleaner", + "version": "0.16.6", + "description": "DiskPush plugin: find what is filling a disk (biggest directories, current writers, growth), classify every finding by risk, and free space safely: regenerable caches, build output in idle projects, stale partial downloads, docker build cache, old logs. Dry run by default.", + "license": "MIT", + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "files": [ + "dist" + ], + "diskpush": { + "plugin": "cleaner" + }, + "scripts": { + "build": "tsc -p tsconfig.json", + "typecheck": "tsc -p tsconfig.json --noEmit" + }, + "dependencies": { + "@diskpush/plugin-api": "workspace:*" + } +} diff --git a/packages/plugin-cleaner/src/api.ts b/packages/plugin-cleaner/src/api.ts new file mode 100644 index 0000000..5bde2ce --- /dev/null +++ b/packages/plugin-cleaner/src/api.ts @@ -0,0 +1,353 @@ +/** + * The one core every surface calls: CLI, TUI, desktop and MCP. + * + * listTargets(ctx) this machine plus every server DiskPush knows + * scanTarget(ctx, target, opts) read-only: a Report (always a dry run) + * applyClean(ctx, report, opts) deletes the chosen eligible items, re-checking each on the target + * + * A target is `local` (run in a local shell) or a server name from the host's + * server directory (run over the system ssh, BatchMode, so nothing ever waits + * on a password prompt). The programs themselves are in script.ts. + */ +import { spawn } from 'node:child_process' +import type { BaseContext, ServerRef } from '@diskpush/plugin-api' +import { + buildReport, + parseCategories, + parseRecords, + selectSteps, + type CleanCategory, + type Report, + type Snapshot, +} from './model.js' +import { ALL_PHASES, DEFAULT_SCRIPT_OPTIONS, applyScript, scanScript, type ApplyStep, type Phase, type ScriptOptions } from './script.js' + +export const LOCAL_TARGET = 'local' + +export type Target = { name: string; local: boolean; host: string | null; usable: boolean; reason: string | null } + +export async function listTargets(ctx: Pick): Promise { + const targets: Target[] = [{ name: LOCAL_TARGET, local: true, host: null, usable: true, reason: null }] + for (const server of (await ctx.servers?.list()) ?? []) { + targets.push({ + name: server.name, + local: false, + host: server.host, + usable: !server.passwordAuth, + reason: server.passwordAuth ? 'signs in with a password; the cleaner needs a key or an agent' : null, + }) + } + return targets +} + +async function resolveTarget(ctx: Pick, name: string): Promise { + if (name === LOCAL_TARGET || name === 'localhost') return null + if (!ctx.servers) throw new Error(`This DiskPush cannot reach servers from here, so "${name}" is out of reach.`) + const server = (await ctx.servers.list()).find((candidate) => candidate.name === name) + if (!server) throw new Error(`No server called "${name}". See: diskpush fleet servers`) + if (server.passwordAuth) throw new Error(`${name} signs in with a password; the cleaner needs a key or an agent.`) + return server +} + +export type SshOptions = { knownHostsFiles?: readonly string[]; sshConfigFile?: string | null; connectTimeoutSeconds?: number } + +/** `ssh` argv that runs `sh -s` on the server, never prompting for anything. */ +export function sshArgs(server: ServerRef, options: SshOptions = {}): string[] { + const args = ['-T', '-o', 'BatchMode=yes', '-o', `ConnectTimeout=${options.connectTimeoutSeconds ?? 20}`, '-o', 'ServerAliveInterval=30', '-o', 'ServerAliveCountMax=6'] + if (options.knownHostsFiles?.length) args.push('-o', `UserKnownHostsFile=${options.knownHostsFiles.map((file) => `"${file}"`).join(' ')}`) + if (options.sshConfigFile) args.push('-F', options.sshConfigFile) + if (server.sshConfigAlias) { + args.push(server.sshConfigAlias) + } else { + args.push('-p', String(server.port)) + if (server.keyPath) args.push('-i', server.keyPath, '-o', 'IdentitiesOnly=yes') + if (server.jumpHost) args.push('-J', server.jumpHost) + args.push(server.username ? `${server.username}@${server.host}` : server.host) + } + args.push('--', 'sh -s') + return args +} + +export type RunResult = { code: number; stdout: string; stderr: string } + +/** How a program is run; replaced in tests. */ +export type Runner = ( + server: ServerRef | null, + script: string, + options: { signal: AbortSignal; env: Readonly>; ssh: SshOptions; onLine?: (line: string) => void }, +) => Promise + +/** Local process groups still running, stopped if this process exits first (a second Ctrl+C). */ +const liveGroups = new Set() +let exitHook = false +function trackGroup(pid: number | undefined): void { + if (!pid) return + liveGroups.add(pid) + if (exitHook) return + exitHook = true + process.once('exit', () => { + for (const group of liveGroups) { + try { + process.kill(-group, 'SIGTERM') + } catch { + // gone + } + } + }) +} + +export const defaultRunner: Runner = (server, script, options) => + new Promise((resolve, reject) => { + const program = server ? (options.env.DISKPUSH_SSH ?? 'ssh') : '/bin/sh' + const args = server ? sshArgs(server, options.ssh) : ['-s'] + // Its own process group, so a cancel stops the du and find it started too, not just the shell. + const child = spawn(program, args, { cwd: '/', env: options.env as NodeJS.ProcessEnv, stdio: ['pipe', 'pipe', 'pipe'], detached: !server }) + const stop = () => { + try { + if (!server && child.pid) process.kill(-child.pid, 'SIGTERM') + else child.kill('SIGTERM') + } catch { + // already gone + } + } + if (!server) trackGroup(child.pid) + if (options.signal.aborted) stop() + options.signal.addEventListener('abort', stop, { once: true }) + let stdout = '' + let stderr = '' + let pending = '' + child.stdout.setEncoding('utf8') + child.stderr.setEncoding('utf8') + child.stdout.on('data', (chunk: string) => { + stdout += chunk + if (!options.onLine) return + pending += chunk + const lines = pending.split('\n') + pending = lines.pop() ?? '' + for (const line of lines) options.onLine(line) + }) + child.stderr.on('data', (chunk: string) => { + if (stderr.length < 64 * 1024) stderr += chunk + }) + child.on('error', (error) => { + options.signal.removeEventListener('abort', stop) + reject(error) + }) + child.on('close', (code) => { + if (child.pid) liveGroups.delete(child.pid) + options.signal.removeEventListener('abort', stop) + resolve({ code: options.signal.aborted ? 130 : (code ?? 1), stdout, stderr }) + }) + child.stdin.on('error', () => {}) + child.stdin.end(script) + }) + +export type CleanOptions = { + idleDays?: number + partialHours?: number + sampleSeconds?: number + duTimeoutSeconds?: number + buildRoots?: string[] + partialRoots?: string[] + topRoots?: string[] + logDir?: string + journalCap?: string + imageAge?: string + useSudo?: boolean + /** Only scan for these categories (plus the disk report, unless `phases` says otherwise). */ + only?: CleanCategory[] + phases?: Phase[] + minFreeGb?: number + /** Persist and compare a snapshot for growth (default true for a full scan). */ + snapshot?: boolean + runner?: Runner +} + +const CATEGORY_PHASE: Record = { caches: 'caches', docker: 'docker', logs: 'logs', build: 'build', partials: 'partials' } + +function list(value: unknown): string[] { + if (Array.isArray(value)) return value.filter((v): v is string => typeof v === 'string' && v.trim() !== '').map((v) => v.trim()) + if (typeof value === 'string') return value.split(',').map((v) => v.trim()).filter(Boolean) + return [] +} + +/** Saved settings under the options given now. */ +export async function resolveOptions(ctx: Pick, options: CleanOptions): Promise { + const s = ctx.settings + const number = async (key: string, given: number | undefined, fallback: number) => { + if (given !== undefined) return given + const saved = Number(await s.get(key, String(fallback))) + return Number.isFinite(saved) && saved >= 0 ? Math.floor(saved) : fallback + } + const phases = options.phases ?? (options.only?.length ? ['fs', 'top', 'writers', ...options.only.map((c) => CATEGORY_PHASE[c])] : [...ALL_PHASES]) + return { + ...DEFAULT_SCRIPT_OPTIONS, + idleDays: await number('idleDays', options.idleDays, DEFAULT_SCRIPT_OPTIONS.idleDays), + partialHours: await number('partialHours', options.partialHours, DEFAULT_SCRIPT_OPTIONS.partialHours), + sampleSeconds: options.sampleSeconds ?? DEFAULT_SCRIPT_OPTIONS.sampleSeconds, + duTimeoutSeconds: options.duTimeoutSeconds ?? DEFAULT_SCRIPT_OPTIONS.duTimeoutSeconds, + buildRoots: options.buildRoots ?? list(await s.get('buildRoots', '')), + partialRoots: options.partialRoots ?? list(await s.get('partialRoots', '')), + topRoots: options.topRoots ?? [], + logDir: options.logDir ?? DEFAULT_SCRIPT_OPTIONS.logDir, + journalCap: options.journalCap ?? (await s.get('journalCap', DEFAULT_SCRIPT_OPTIONS.journalCap)), + imageAge: options.imageAge ?? (await s.get('imageAge', DEFAULT_SCRIPT_OPTIONS.imageAge)), + useSudo: options.useSudo ?? (await s.get('useSudo', false)), + phases: [...new Set(phases)], + minFreeBytes: Math.max(0, (options.minFreeGb ?? 0) * 1024 ** 3), + } +} + +function snapshotKey(target: string): string { + return `snapshot.${target.replace(/[^A-Za-z0-9_.-]/g, '_')}` +} + +function sshOptions(ctx: Pick): SshOptions { + return { knownHostsFiles: ctx.servers?.knownHostsFiles ?? [], sshConfigFile: ctx.servers?.sshConfigFile ?? null } +} + +/** Read-only. Scans the target and returns the report; deletes nothing. */ +export async function scanTarget(ctx: BaseContext, target: string, options: CleanOptions = {}): Promise { + const server = await resolveTarget(ctx, target) + const resolved = await resolveOptions(ctx, options) + const runner = options.runner ?? defaultRunner + ctx.progress.update({ message: `Scanning ${target}…` }) + const result = await runner(server, scanScript(resolved), { + signal: ctx.signal, + env: ctx.env, + ssh: sshOptions(ctx), + onLine: (line) => { + if (line.startsWith('STEP\t')) ctx.progress.update({ message: `${target}: ${line.slice(5)}` }) + }, + }) + if (ctx.signal.aborted) throw new Error('Cancelled.') + if (server && result.code === 255 && !result.stdout) { + throw new Error(`Could not reach ${target} over ssh: ${result.stderr.trim().split('\n').pop() ?? 'connection failed'}`) + } + const raw = parseRecords(result.stdout, { imageAge: resolved.imageAge }) + if (!raw.meta.uid && result.code !== 0) throw new Error(`The scan on ${target} failed: ${result.stderr.trim().slice(0, 500) || `exit ${result.code}`}`) + const fullScan = resolved.phases.includes('fs') && resolved.phases.includes('top') + const remember = options.snapshot ?? fullScan + const previous = remember ? await ctx.settings.get(snapshotKey(target), null) : null + const report = buildReport(raw, { + target, + idleDays: resolved.idleDays, + partialHours: resolved.partialHours, + journalCap: resolved.journalCap, + imageAge: resolved.imageAge, + useSudo: resolved.useSudo, + logDir: resolved.logDir, + minFreeBytes: resolved.minFreeBytes, + previous, + }) + if (remember && raw.complete) await ctx.settings.set(snapshotKey(target), report.snapshot) + return report +} + +export type ItemResult = { + id: string + status: 'ok' | 'skipped' | 'failed' | 'not-needed' + freedBytes: number + /** False: free space did not visibly change, so freedBytes is the scan's estimate. */ + measured: boolean + message: string +} + +export type ApplyResult = { + target: string + dryRun: boolean + locked: boolean + /** The free-space goal was reached and the rest was left alone. */ + stopped: boolean + results: ItemResult[] + freedBytes: number + /** In a dry run: what would be removed. */ + wouldRemove: { id: string; title: string; bytes: number }[] +} + +export type ApplyChoice = { + /** False: list what would be removed and delete nothing. */ + apply: boolean + only?: CleanCategory[] | string + ids?: string[] + minFreeGb?: number + useSudo?: boolean + runner?: Runner + /** Tests only. */ + lockDir?: string +} + +/** + * Removes the chosen eligible items of `report`. Never a `human` item, never + * anything outside the categories, and every item is re-checked on the target + * as it is removed. With `apply: false` it only says what would go. + */ +export async function applyClean(ctx: BaseContext, report: Report, choice: ApplyChoice): Promise { + const only = typeof choice.only === 'string' ? parseCategories(choice.only) : (choice.only ?? []) + const chosen = selectSteps(report, { only, ids: choice.ids ?? [] }) + const wouldRemove = chosen.map((i) => ({ id: i.id, title: i.title, bytes: i.bytes })) + const base: ApplyResult = { target: report.target, dryRun: !choice.apply, locked: false, stopped: false, results: [], freedBytes: 0, wouldRemove } + if (choice.minFreeGb && choice.minFreeGb > 0) { + const fs = report.filesystems.find((f) => f.mount === report.homeMount) ?? report.filesystems.find((f) => f.mount === '/') + if (fs && fs.availBytes >= choice.minFreeGb * 1024 ** 3) return { ...base, stopped: true, wouldRemove: [] } + } + if (!choice.apply || chosen.length === 0) return base + + const server = await resolveTarget(ctx, report.target) + const resolved = await resolveOptions(ctx, { + idleDays: report.idleDays, + logDir: report.scan.logDir, + imageAge: report.scan.imageAge, + journalCap: report.scan.journalCap, + partialHours: report.scan.partialHours, + ...(choice.useSudo !== undefined ? { useSudo: choice.useSudo } : {}), + }) + const minFreeKb = Math.max(0, Math.round((choice.minFreeGb ?? 0) * 1024 * 1024)) + const steps = chosen.map((i) => i.step!) as ApplyStep[] + const script = applyScript( + { ...resolved, stopAtKb: minFreeKb, stopPath: report.homeMount ?? report.home ?? '/', ...(choice.lockDir ? { lockDir: choice.lockDir } : {}) }, + steps, + ) + ctx.progress.start(steps.length) + let done = 0 + const runner = choice.runner ?? defaultRunner + const result = await runner(server, script, { + signal: ctx.signal, + env: ctx.env, + ssh: sshOptions(ctx), + onLine: (line) => { + if (line.startsWith('STEP\t')) ctx.progress.update({ message: line.slice(5) }) + if (line.startsWith('RESULT\t')) ctx.progress.update({ done: ++done, total: steps.length }) + }, + }) + const results: ItemResult[] = [] + const estimates = new Map(chosen.map((i) => [i.id, i.bytes])) + let locked = false + let stopped = false + for (const line of result.stdout.split('\n')) { + const f = line.split('\t') + if (f[0] === 'LOCKED') locked = true + if (f[0] === 'STOPPED') stopped = true + if (f[0] === 'RESULT' && f[1]) { + const before = Number(f[3]) || 0 + const after = Number(f[4]) || 0 + const status = f[2] === 'ok' || f[2] === 'failed' ? f[2] : 'skipped' + // Free space before and after, on the item's filesystem. When that shows nothing (an item smaller + // than the noise, or other writers at the same time), the scan's estimate stands in. + const measured = Math.max(0, after - before) * 1024 + const estimate = Math.max(0, estimates.get(f[1]) ?? 0) + results.push({ id: f[1], status, freedBytes: status === 'ok' ? measured || estimate : measured, measured: measured > 0 || status !== 'ok', message: f.slice(5).join('\t') }) + } + } + const reported = new Set(results.map((r) => r.id)) + for (const step of steps) { + if (!reported.has(step.id)) { + results.push({ id: step.id, status: stopped ? 'not-needed' : 'skipped', freedBytes: 0, measured: true, message: stopped ? 'enough space was free already' : locked ? 'another clean is running' : 'did not run' }) + } + } + if (!locked && result.code !== 0 && results.every((r) => r.status !== 'ok')) { + const why = result.stderr.trim().slice(0, 500) + if (why && !results.length) throw new Error(`The clean on ${report.target} failed: ${why}`) + } + return { ...base, locked, stopped, results, freedBytes: results.reduce((sum, r) => sum + r.freedBytes, 0) } +} diff --git a/packages/plugin-cleaner/src/cleaner.test.ts b/packages/plugin-cleaner/src/cleaner.test.ts new file mode 100644 index 0000000..79c72fb --- /dev/null +++ b/packages/plugin-cleaner/src/cleaner.test.ts @@ -0,0 +1,366 @@ +/** + * The cleaner end to end: the real scan and apply programs run in a real + * shell against a fixture home, with docker, npm, journalctl, crontab and + * pgrep replaced by shims on PATH so nothing on the machine running the + * tests is looked at or touched. + */ +import { spawn, execFileSync, type ChildProcess } from 'node:child_process' +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync, readdirSync, statSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { PassThrough } from 'node:stream' +import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' + +// Every test runs the real programs in a real shell: seconds, not milliseconds. +vi.setConfig({ testTimeout: 120_000, hookTimeout: 60_000 }) +import type { BaseContext } from '@diskpush/plugin-api' +import { applyClean, scanTarget, sshArgs, type CleanOptions } from './api.js' +import { serveMcp } from './mcp.js' +import { buildReport, classifyDir, dockerTime, parseDockerSize, growthSince, parseCategories, parseRecords } from './model.js' +import { applyScript, scanScript, DEFAULT_SCRIPT_OPTIONS } from './script.js' + +const base = mkdtempSync(join(tmpdir(), 'diskpush-cleaner-test-')) +afterAll(() => rmSync(base, { recursive: true, force: true })) + +const OLD = (Date.now() - 10 * 86400_000) / 1000 + +function write(path: string, content: string | Buffer = 'x'): void { + mkdirSync(join(path, '..'), { recursive: true }) + writeFileSync(path, content) +} + +/** Every file and directory under `dir` gets an mtime 10 days ago. */ +function age(dir: string): void { + for (const name of readdirSync(dir)) { + const path = join(dir, name) + if (statSync(path).isDirectory()) age(path) + utimesSync(path, OLD, OLD) + } + utimesSync(dir, OLD, OLD) +} + +function git(cwd: string, ...args: string[]): void { + execFileSync('git', ['-c', 'user.email=t@example.com', '-c', 'user.name=t', '-C', cwd, ...args], { stdio: 'ignore' }) +} + +function project(dir: string, options: { builds: string[]; ignore?: string[]; cargo?: boolean }): void { + write(join(dir, options.cargo ? 'Cargo.toml' : 'package.json'), options.cargo ? '[package]\nname="x"\n' : '{}') + write(join(dir, 'src', 'index.js'), 'console.log(1)') + write(join(dir, '.gitignore'), `${(options.ignore ?? options.builds).join('\n')}\n`) + for (const build of options.builds) write(join(dir, build, 'blob.bin'), Buffer.alloc(64 * 1024, 1)) + mkdirSync(dir, { recursive: true }) + git(dir, 'init', '-q') + git(dir, 'add', '.gitignore', 'src') +} + +let n = 0 +type Fixture = { home: string; shims: string; calls: string; log: string; lock: string; ctx: BaseContext; options: CleanOptions } + +function shim(dir: string, name: string, body: string): void { + writeFileSync(join(dir, name), `#!/bin/sh\n${body}\n`) + chmodSync(join(dir, name), 0o755) +} + +/** A fresh home with every case the guards must tell apart. */ +function fixture(): Fixture { + const root = join(base, `f${++n}`) + const home = join(root, 'home') + const shims = join(root, 'bin') + const calls = join(root, 'calls.txt') + const log = join(root, 'log') + mkdirSync(shims, { recursive: true }) + writeFileSync(calls, '') + + const src = join(home, 'src') + project(join(src, 'idle'), { builds: ['node_modules', '.next', 'dist'] }) + project(join(src, 'rusty'), { builds: ['target'], cargo: true }) + project(join(src, 'committed-dist'), { builds: ['node_modules', 'dist'], ignore: ['node_modules'] }) + project(join(src, 'active'), { builds: ['node_modules'] }) + project(join(src, 'busy'), { builds: ['node_modules'] }) + project(join(src, 'wired'), { builds: ['node_modules'] }) + write(join(src, 'not-a-project', 'node_modules', 'blob.bin'), Buffer.alloc(4096, 1)) + write(join(home, 'Downloads', 'dead.iso.partial'), Buffer.alloc(8192, 1)) + write(join(home, 'Downloads', 'fresh.iso.partial'), Buffer.alloc(8192, 1)) + write(join(home, '.npm', '_cacache', 'content', 'blob'), Buffer.alloc(16384, 1)) + write(join(log, 'app.log.1'), Buffer.alloc(1100 * 1024, 65)) + write(join(log, 'app.log'), Buffer.alloc(1100 * 1024, 65)) + for (const dir of ['idle', 'rusty', 'committed-dist', 'busy', 'wired', 'not-a-project']) age(join(src, dir)) + age(join(home, 'Downloads')) + utimesSync(join(home, 'Downloads', 'fresh.iso.partial'), new Date(), new Date()) + age(log) + utimesSync(join(log, 'app.log'), new Date(), new Date()) + + shim(shims, 'docker', `echo "docker $*" >> '${calls}' +case "$1" in + info) [ "$2" = --format ] && echo '${root}/docker'; exit 0 ;; + system) echo '{"Images":[{"Containers":"0","CreatedAt":"2020-01-01 00:00:00 +0000 UTC","Size":"3GB","UniqueSize":"2GB"},{"Containers":"0","CreatedAt":"2999-01-01 00:00:00 +0000 UTC","Size":"1GB","UniqueSize":"1GB"},{"Containers":"1","CreatedAt":"2020-01-01 00:00:00 +0000 UTC","Size":"9GB"}],"Containers":[{"State":"exited","Size":"500MB"}],"Volumes":[{"Name":"app_pgdata","Links":"0","Size":"40GB"},{"Name":"used","Links":"1","Size":"1GB"}],"BuildCache":[{"InUse":"false","Size":"5GB"},{"InUse":"true","Size":"1GB"}]}' ;; + ps) exit 0 ;; + *) exit 0 ;; +esac`) + shim(shims, 'npm', `echo "npm $*" >> '${calls}' +[ "$1 $2" = "cache clean" ] && rm -rf "$HOME/.npm/_cacache" +exit 0`) + shim(shims, 'journalctl', `echo "journalctl $*" >> '${calls}' +[ "$1" = --disk-usage ] && echo "Archived and active journals take up 3.0G in the file system." +exit 0`) + shim(shims, 'crontab', `[ "$1" = -l ] && echo "0 * * * * cd '${join(src, 'wired')}' && npm start"; exit 0`) + shim(shims, 'pgrep', 'exit 1') + shim(shims, 'sudo', 'exit 1') + + const settings = new Map() + const ctx: BaseContext = { + settings: { get: async (key, fallback) => (settings.has(key) ? (settings.get(key) as never) : fallback), set: async (key, value) => void settings.set(key, value) }, + secrets: { get: async () => null, set: async () => {} }, + progress: { start() {}, update() {}, log() {} }, + openUrl: async () => {}, + signal: new AbortController().signal, + surface: 'cli', + env: { ...process.env, HOME: home, PATH: `${shims}:/usr/bin:/bin`, XDG_RUNTIME_DIR: root, npm_config_cache: '' }, + } + const options: CleanOptions = { + sampleSeconds: 0, + buildRoots: [src], + partialRoots: [home], + topRoots: [home], + logDir: log, + } + return { home, shims, calls, log, lock: join(root, 'lock'), ctx, options } +} + +let f: Fixture +let busy: ChildProcess | null = null + +beforeEach(() => { + busy?.kill() + f = fixture() + // A process working inside "busy": its build output must stay. + busy = spawn('sleep', ['60'], { cwd: join(f.home, 'src', 'busy'), stdio: 'ignore' }) + // "active" has a file changed just now. + write(join(f.home, 'src', 'active', 'src', 'new.js'), 'x') +}) +afterAll(() => busy?.kill()) + +const src = (...parts: string[]) => join(f.home, 'src', ...parts) + +describe('scan', () => { + it('finds exactly the eligible build output, partials, caches, docker and logs, and explains the rest', async () => { + const report = await scanTarget(f.ctx, 'local', f.options) + const eligible = report.items.filter((i) => i.eligible).map((i) => i.id).sort() + expect(eligible).toEqual( + [ + `build:${src('idle', '.next')}`, + `build:${src('idle', 'dist')}`, + `build:${src('idle', 'node_modules')}`, + `build:${src('rusty', 'target')}`, + `build:${src('committed-dist', 'node_modules')}`, + 'cache:npm', + 'docker:buildcache', + 'docker:images', + `log:${join(f.log, 'app.log.1')}`, + `partial:${join(f.home, 'Downloads', 'dead.iso.partial')}`, + ].sort(), + ) + const why = (path: string) => report.kept.find((k) => k.root === path || k.root === src(path))?.reason + expect(why(src('active'))).toMatch(/changed in the last 3 days/) + expect(why(src('busy'))).toMatch(/running process/) + expect(why(src('wired'))).toMatch(/cron job/) + expect(why(src('committed-dist', 'dist'))).toMatch(/not git-ignored/) + // A node_modules outside any project is not even listed. + expect(JSON.stringify(report)).not.toContain('not-a-project') + const fresh = report.items.find((i) => i.id.endsWith('fresh.iso.partial'))! + expect(fresh.eligible).toBe(false) + expect(fresh.why).toMatch(/may still be in progress/) + + // Docker numbers: unused cache only, images older than 72h and unused only. + expect(report.items.find((i) => i.id === 'docker:buildcache')!.bytes).toBe(5e9) + expect(report.items.find((i) => i.id === 'docker:images')!.bytes).toBe(2e9) + // Volumes, stopped containers and a journal that needs root are never eligible. + const volume = report.items.find((i) => i.id === 'volume:app_pgdata')! + expect(volume.safety).toBe('human') + expect(volume.eligible).toBe(false) + expect(volume.suggested).toContain('docker volume rm app_pgdata') + expect(report.items.find((i) => i.id === 'volume:used')).toBeUndefined() + expect(report.items.find((i) => i.id === 'docker:containers')!.eligible).toBe(false) + expect(report.items.find((i) => i.id === 'journal')!.eligible).toBe(false) + + // Ranked: bytes per unit of risk, safe classes before humans. + const scores = report.items.filter((i) => i.safety !== 'human').map((i) => i.score) + expect([...scores].sort((a, b) => b - a)).toEqual(scores) + expect(report.plan.ids[0]).toBe('docker:buildcache') + expect(report.topDirs.map((d) => d.path)).toContain(join(f.home, 'src')) + }) + + it('remembers a snapshot and reports growth on the next full scan', async () => { + const options = { ...f.options, phases: ['fs', 'top'] as const } + const first = await scanTarget(f.ctx, 'local', { ...options, phases: [...options.phases] }) + expect(first.growth).toBeNull() + write(join(f.home, 'src', 'grow.bin'), Buffer.alloc(512 * 1024, 1)) + await new Promise((r) => setTimeout(r, 1100)) + const second = await scanTarget(f.ctx, 'local', { ...options, phases: [...options.phases] }) + expect(second.growth).not.toBeNull() + expect(second.growth!.dirs.find((d) => d.path === join(f.home, 'src'))!.deltaBytes).toBeGreaterThan(400 * 1024) + }) +}) + +describe('apply', () => { + const survivors = () => [ + src('active', 'node_modules'), + src('busy', 'node_modules'), + src('wired', 'node_modules'), + src('committed-dist', 'dist'), + src('not-a-project', 'node_modules'), + src('idle', 'src', 'index.js'), + src('idle', 'package.json'), + join(f.home, 'Downloads', 'fresh.iso.partial'), + join(f.log, 'app.log'), + ] + + it('a dry run deletes nothing and lists exactly the eligible set', async () => { + const report = await scanTarget(f.ctx, 'local', f.options) + const result = await applyClean(f.ctx, report, { apply: false, lockDir: f.lock }) + expect(result.dryRun).toBe(true) + expect(result.results).toEqual([]) + expect(result.wouldRemove.map((i) => i.id).sort()).toEqual(report.items.filter((i) => i.eligible).map((i) => i.id).sort()) + for (const item of report.items) if (item.path && item.category !== 'docker') expect(existsSync(item.path), item.path).toBe(true) + expect(readFileSync(f.calls, 'utf8')).not.toMatch(/prune|cache clean|vacuum/) + }) + + it('apply removes exactly the eligible set and nothing else', async () => { + const report = await scanTarget(f.ctx, 'local', f.options) + const result = await applyClean(f.ctx, report, { apply: true, lockDir: f.lock }) + expect(result.results.filter((r) => r.status !== 'ok')).toEqual([]) + for (const id of report.items.filter((i) => i.eligible && (i.category === 'build' || i.category === 'partials')).map((i) => i.path!)) { + expect(existsSync(id), id).toBe(false) + } + for (const path of survivors()) expect(existsSync(path), path).toBe(true) + expect(existsSync(join(f.log, 'app.log.1'))).toBe(false) + expect(existsSync(join(f.log, 'app.log.1.gz'))).toBe(true) + expect(existsSync(join(f.home, '.npm', '_cacache'))).toBe(false) + const calls = readFileSync(f.calls, 'utf8') + expect(calls).toContain('docker builder prune -f') + expect(calls).toContain('docker image prune -a -f --filter until=72h') + expect(calls).not.toMatch(/volume|docker rm|journalctl --vacuum/) + expect(existsSync(f.lock)).toBe(false) + }) + + it('only touches the chosen categories', async () => { + const report = await scanTarget(f.ctx, 'local', f.options) + await applyClean(f.ctx, report, { apply: true, only: 'partials', lockDir: f.lock }) + expect(existsSync(join(f.home, 'Downloads', 'dead.iso.partial'))).toBe(false) + expect(existsSync(src('idle', 'node_modules'))).toBe(true) + expect(readFileSync(f.calls, 'utf8')).not.toContain('prune') + }) + + it('re-checks every guard at deletion time: a project that became active is skipped', async () => { + const report = await scanTarget(f.ctx, 'local', { ...f.options, only: ['build'] }) + write(src('idle', 'src', 'touched.js'), 'now') + const result = await applyClean(f.ctx, report, { apply: true, only: ['build'], lockDir: f.lock }) + const idle = result.results.filter((r) => r.id.includes('/idle/')) + expect(idle.length).toBe(3) + for (const r of idle) { + expect(r.status).toBe('skipped') + expect(r.message).toMatch(/changed in the last 3 days/) + } + expect(existsSync(src('idle', 'node_modules'))).toBe(true) + expect(existsSync(src('rusty', 'target'))).toBe(false) + }) + + it('never runs two cleans at once', async () => { + const report = await scanTarget(f.ctx, 'local', { ...f.options, only: ['partials'] }) + mkdirSync(f.lock) + writeFileSync(join(f.lock, 'pid'), String(process.pid)) + const result = await applyClean(f.ctx, report, { apply: true, lockDir: f.lock }) + expect(result.locked).toBe(true) + expect(existsSync(join(f.home, 'Downloads', 'dead.iso.partial'))).toBe(true) + }) + + it('threshold mode does nothing while enough space is free', async () => { + const report = await scanTarget(f.ctx, 'local', { ...f.options, only: ['partials'] }) + const result = await applyClean(f.ctx, report, { apply: true, minFreeGb: 0.0001, lockDir: f.lock }) + expect(result.stopped).toBe(true) + expect(result.results).toEqual([]) + expect(existsSync(join(f.home, 'Downloads', 'dead.iso.partial'))).toBe(true) + }) +}) + +describe('mcp', () => { + it('lists the tools and treats clean_apply without apply: true as a dry run', async () => { + const input = new PassThrough() + const output = new PassThrough() + let text = '' + output.on('data', (chunk) => (text += chunk)) + const ctx = { ...f.ctx, settings: f.ctx.settings } + // Route the MCP scans through the fixture's roots. + const served = serveMcp(ctx, input, output, { version: 'test' }, async (server, script, opts) => { + const { defaultRunner } = await import('./api.js') + return defaultRunner(server, script.replace(/^build_roots\(\).*$/m, `build_roots() { printf '%s\\n' '${src()}'; }`).replace(/^partial_roots\(\).*$/m, `partial_roots() { printf '%s\\n' '${f.home}'; }`).replace(/^top_roots\(\).*$/m, `top_roots() { printf '%s\\n' '${f.home}'; }`).replace(/^LOG_DIR=.*$/m, `LOG_DIR='${f.log}'`), opts) + }) + const send = (message: object) => input.write(`${JSON.stringify({ jsonrpc: '2.0', ...message })}\n`) + send({ id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 't', version: '1' } } }) + send({ method: 'notifications/initialized' }) + send({ id: 2, method: 'tools/list' }) + send({ id: 3, method: 'tools/call', params: { name: 'clean_apply', arguments: { only: ['build', 'partials'], sampleSeconds: 0 } } }) + input.end() + await served + const replies = text.trim().split('\n').map((line) => JSON.parse(line)) + expect(replies.find((r) => r.id === 1).result.serverInfo.name).toBe('diskpush-cleaner') + expect(replies.find((r) => r.id === 2).result.tools.map((t: { name: string }) => t.name)).toEqual(['clean_targets', 'clean_report', 'clean_apply']) + const call = replies.find((r) => r.id === 3).result + expect(call.isError).toBeUndefined() + expect(call.structuredContent.dryRun).toBe(true) + expect(call.structuredContent.wouldRemove.length).toBeGreaterThan(0) + expect(call.content[0].text).toContain('apply: true') + expect(existsSync(src('idle', 'node_modules'))).toBe(true) + }) +}) + +describe('pieces', () => { + it('parses docker sizes and times', () => { + expect(parseDockerSize('1.5GB (40%)')).toBe(1.5e9) + expect(parseDockerSize('225kB')).toBe(225e3) + expect(parseDockerSize('0B')).toBe(0) + expect(dockerTime('2026-11-11 09:56:23 +0000 UTC')).toBe(Date.parse('2026-11-11T09:56:23Z') / 1000) + expect(dockerTime('2026-11-11 09:49:27.393197051 +0100 CET')).toBe(Date.parse('2026-11-11T08:49:27Z') / 1000) + }) + + it('keeps what a timed-out du had counted as a lower bound, and ranks unknown sizes first', () => { + const raw = parseRecords(['META\t1000\tLinux\t1700000000\t0\t/h', 'TOP\t/h/a', 'SIZE\t/h/a\t100\t0', 'TOP\t/h/big', 'SIZE\t/h/big\t5000\t1', 'TOP\t/h/huge', 'SIZE\t/h/huge\t0\t1', 'END'].join('\n')) + const report = buildReport(raw, { target: 'local', idleDays: 3, partialHours: 24, journalCap: '1G', imageAge: '72h', useSudo: false }) + expect(report.topDirs.map((d) => [d.path, d.bytes, d.timedOut])).toEqual([ + ['/h/huge', -1, true], + ['/h/big', 5000 * 1024, true], + ['/h/a', 100 * 1024, false], + ]) + }) + + it('classifies big directories for a human', () => { + expect(classifyDir('/srv/app/pgdata', null)).toBe('database') + expect(classifyDir('/home/u/Backups', null)).toBe('backups') + expect(classifyDir('/home/u/Videos', null)).toBe('media') + expect(classifyDir('/var/lib/docker', null)).toBe('docker') + expect(classifyDir('/home/u/src', null)).toBeNull() + }) + + it('computes growth between snapshots', () => { + const growth = growthSince({ at: '2026-01-01T00:00:00Z', fs: { '/': 100 }, dirs: { '/a': 10 } }, { at: '2026-01-01T01:00:00Z', fs: { '/': 3700 }, dirs: { '/a': 30 } }) + expect(growth!.fs[0]).toEqual({ mount: '/', deltaBytes: 3600, bytesPerHour: 3600 }) + expect(growth!.dirs[0]).toEqual({ path: '/a', deltaBytes: 20 }) + }) + + it('rejects unknown categories and bad option values', () => { + expect(parseCategories('cache,build')).toEqual(['caches', 'build']) + expect(() => parseCategories('volumes')).toThrow(/not a category/) + expect(() => scanScript({ ...DEFAULT_SCRIPT_OPTIONS, imageAge: '1; rm -rf /' })).toThrow(/not valid/) + }) + + it('quotes every path it is handed', () => { + const script = applyScript({ ...DEFAULT_SCRIPT_OPTIONS, stopAtKb: 0, stopPath: '/' }, [{ kind: 'build', id: 'build:x', path: "/a/it's $(reboot)/node_modules" }]) + expect(script).toContain(`go && do_build build:x '/a/it'\\''s $(reboot)/node_modules'`) + }) + + it('builds a non-interactive ssh command', () => { + const args = sshArgs({ name: 'box', host: 'box.example', port: 2222, username: 'me', keyPath: null, jumpHost: null, sshConfigAlias: null, passwordAuth: false }) + expect(args).toContain('BatchMode=yes') + expect(args.slice(-4)).toEqual(['2222', 'me@box.example', '--', 'sh -s']) + }) +}) diff --git a/packages/plugin-cleaner/src/format.ts b/packages/plugin-cleaner/src/format.ts new file mode 100644 index 0000000..a4ff4bf --- /dev/null +++ b/packages/plugin-cleaner/src/format.ts @@ -0,0 +1,109 @@ +/** The report as text, for the CLI, the TUI's job log and MCP. */ +import type { ApplyResult } from './api.js' +import { formatBytes, type Item, type Report } from './model.js' + +const SAFETY_LABEL: Record = { safe: 'safe', 'safe-if-idle': 'safe-if-idle', human: 'needs-a-human' } + +function size(item: Item): string { + return `${item.upTo && item.bytes > 0 ? '≤' : ''}${formatBytes(item.bytes)}`.padStart(9) +} + +function ago(seconds: number): string { + if (seconds < 3600) return `${Math.round(seconds / 60)} min` + if (seconds < 86400 * 2) return `${(seconds / 3600).toFixed(1)} h` + return `${Math.round(seconds / 86400)} days` +} + +export function formatReport(report: Report, options: { limit?: number; why?: boolean } = {}): string[] { + const limit = options.limit ?? 25 + const why = options.why ?? true + const out: string[] = [`Disk report for ${report.target} (dry run: nothing was deleted)`, ''] + + if (report.filesystems.length) { + out.push('Filesystems') + for (const f of report.filesystems.slice(0, 8)) { + const grow = report.growth?.fs.find((g) => g.mount === f.mount) + const trend = grow && grow.deltaBytes !== 0 ? ` ${grow.deltaBytes > 0 ? '+' : '-'}${formatBytes(Math.abs(grow.deltaBytes))} in ${ago(report.growth!.seconds)} (${grow.bytesPerHour >= 0 ? '+' : '-'}${formatBytes(Math.abs(grow.bytesPerHour))}/h)` : '' + out.push(` ${f.mount.padEnd(24)} ${String(f.usedPercent).padStart(3)}% used ${formatBytes(f.availBytes).padStart(9)} free of ${formatBytes(f.sizeBytes)}${trend}`) + } + out.push('') + } + + if (report.writers.length) { + out.push('Writing to disk right now') + for (const w of report.writers.slice(0, 8)) { + out.push(` ${`${formatBytes(w.bytesPerSecond)}/s`.padStart(11)} ${w.command}${w.container ? ` (container ${w.container})` : ''} pid ${w.pid}`) + } + out.push('') + } + + if (report.topDirs.length) { + out.push('Biggest directories') + for (const d of report.topDirs.slice(0, 12)) { + const grown = report.growth?.dirs.find((g) => g.path === d.path) + out.push(` ${(d.bytes < 0 ? '?' : `${d.timedOut ? '≥' : ''}${formatBytes(d.bytes)}`).padStart(10)} ${d.path}${d.kind ? ` [${d.kind}]` : ''}${grown ? ` (${grown.deltaBytes > 0 ? '+' : '-'}${formatBytes(Math.abs(grown.deltaBytes))})` : ''}`) + } + out.push('') + } + + const planned = new Set(report.plan.ids) + const plan = report.items.filter((i) => planned.has(i.id)) + if (plan.length) { + out.push(`Plan: about ${formatBytes(report.plan.bytes)} can be freed safely, best value first (ranked by bytes per unit of risk)`) + plan.slice(0, limit).forEach((i, n) => { + out.push(` ${String(n + 1).padStart(3)}. ${size(i)} ${SAFETY_LABEL[i.safety].padEnd(12)} ${i.title}`) + if (why) out.push(` ${i.why}`) + }) + if (plan.length > limit) out.push(` … and ${plan.length - limit} more (--all lists them)`) + out.push('') + } else { + out.push('Nothing can be freed safely right now.', '') + } + + const notEligible = report.items.filter((i) => !i.eligible && i.safety !== 'human') + if (notEligible.length) { + out.push('Kept, and why') + for (const i of notEligible.slice(0, limit)) out.push(` ${size(i)} ${i.title}: ${i.why.replace(/^Kept: /, '')}${i.suggested && /needs root|Needs root/.test(i.why) ? ` [by hand: ${i.suggested}]` : ''}`) + out.push('') + } + if (report.kept.length) { + out.push('Build output kept because the project is in use') + for (const k of report.kept.slice(0, limit)) out.push(` ${k.root}: ${k.reason}${k.dirs > 1 ? ` (${k.dirs} dirs)` : ''}`) + if (report.kept.length > limit) out.push(` … and ${report.kept.length - limit} more`) + out.push('') + } + + const human = report.items.filter((i) => i.safety === 'human') + if (human.length) { + out.push('Needs a human (reported, never deleted)') + for (const i of human.slice(0, limit)) { + out.push(` ${size(i)} ${i.title}`) + if (why) out.push(` ${i.why}`) + if (i.suggested) out.push(` look: ${i.suggested}`) + } + out.push('') + } + + for (const w of report.warnings) out.push(`! ${w}`) + return out +} + +export function formatApply(result: ApplyResult, titles: Map): string[] { + if (result.dryRun) { + const total = result.wouldRemove.reduce((sum, i) => sum + Math.max(0, i.bytes), 0) + if (result.stopped) return ['Enough space is free already; nothing to do.'] + if (!result.wouldRemove.length) return ['Nothing to remove.'] + return [ + `Dry run: would remove ${result.wouldRemove.length} item${result.wouldRemove.length === 1 ? '' : 's'}, about ${formatBytes(total)}. Nothing was deleted.`, + ...result.wouldRemove.map((i) => ` ${formatBytes(i.bytes).padStart(9)} ${i.title}`), + 'Run again with --apply to remove them.', + ] + } + if (result.locked) return ['Another clean is already running on this target; nothing was done.'] + const lines = result.results.map((r) => ` ${r.status.padEnd(10)} ${`${r.measured ? '' : '*'}${formatBytes(r.freedBytes)}`.padStart(9)} ${titles.get(r.id) ?? r.id}${r.status === 'ok' ? '' : `: ${r.message}`}`) + return [ + `Freed about ${formatBytes(result.freedBytes)} on ${result.target}${result.results.some((r) => !r.measured) ? ' (measured as free space before and after each step; * = too small to measure, estimated)' : ' (measured as free space before and after each step)'}.`, + ...lines, + ...(result.stopped ? ['Stopped early: the free-space goal was reached.'] : []), + ] +} diff --git a/packages/plugin-cleaner/src/index.ts b/packages/plugin-cleaner/src/index.ts new file mode 100644 index 0000000..1c44839 --- /dev/null +++ b/packages/plugin-cleaner/src/index.ts @@ -0,0 +1,251 @@ +/** + * Cleaner: free disk space intelligently. + * + * First it finds what is actually using and growing the disk (filesystems, + * the biggest directories, which processes are writing right now, growth + * since the last report), then classifies every finding as safe + * (regenerable), safe-if-idle, or needs-a-human, ranks them by bytes freed per + * unit of risk, explains each one, and proposes a plan. Only the safe classes + * are ever removed, only on an explicit apply, and every guard is checked + * again at the moment of deleting. Works on this machine or any server + * DiskPush can ssh to. + * + * Surfaces: + * CLI diskpush clean report|run|targets|cron|mcp (`clean` is short for `cleaner`) + * MCP diskpush clean mcp: clean_targets, clean_report, clean_apply + * TUI `a` on a directory: "Disk report: what can be freed here" + * desktop the Cleaner tab (targets, report, select + apply with confirm); the same right-click action + */ +import { createRequire } from 'node:module' +import { resolve } from 'node:path' +import { definePlugin, type ActionResult, type CommandContext, type DiskpushPlugin } from '@diskpush/plugin-api' +import { applyClean, listTargets, scanTarget, LOCAL_TARGET, type CleanOptions } from './api.js' +import { formatApply, formatReport } from './format.js' +import { serveMcp } from './mcp.js' +import { CLEAN_CATEGORIES, formatBytes, parseCategories } from './model.js' +import type { Phase } from './script.js' + +export * from './api.js' +export * from './format.js' +export * from './mcp.js' +export * from './model.js' +export { ALL_PHASES, BUILD_NAMES, CACHE_IDS, DEFAULT_SCRIPT_OPTIONS, applyScript, scanScript, shq, type ApplyStep, type Phase, type ScriptOptions } from './script.js' + +const PACKAGE_VERSION: string = createRequire(import.meta.url)('../package.json').version + +export const CLEANER_ID = 'cleaner' + +class UsageError extends Error {} + +/** `--flag`, `--key value`, `--key=value`, positionals. Unknown flags are an error: a typo never deletes by default. */ +export function parseArgs(args: readonly string[], spec: { values?: string[]; flags?: string[] }) { + const values = new Map() + const flags = new Set() + const positional: string[] = [] + for (let i = 0; i < args.length; i++) { + const arg = args[i]! + if (arg === '--') { + positional.push(...args.slice(i + 1)) + break + } + if (!arg.startsWith('--')) { + positional.push(arg) + continue + } + const eq = arg.indexOf('=') + const key = eq === -1 ? arg.slice(2) : arg.slice(2, eq) + if (spec.flags?.includes(key) && eq === -1) flags.add(key) + else if (spec.values?.includes(key)) { + const value = eq === -1 ? args[++i] : arg.slice(eq + 1) + if (value === undefined) throw new UsageError(`--${key} needs a value.`) + values.set(key, value) + } else throw new UsageError(`Unknown option --${key}.`) + } + return { positional, flag: (key: string) => flags.has(key), value: (key: string) => values.get(key) } +} + +function wholeNumber(text: string | undefined, name: string, min = 0): number | undefined { + if (text === undefined) return undefined + const value = Number(text) + if (!Number.isFinite(value) || value < min) throw new UsageError(`--${name} takes a number of ${min} or more.`) + return value +} + +const SCAN_VALUES = ['only', 'idle-days', 'sample', 'roots', 'image-age', 'journal-cap', 'du-timeout', 'min-free-gb'] + +function scanOptions(a: ReturnType, cwd: string): CleanOptions { + const only = parseCategories(a.value('only')) + const roots = a.value('roots')?.split(',').map((r) => r.trim()).filter(Boolean).map((r) => (r.startsWith('~') ? r : resolve(cwd, r))) + const idleDays = wholeNumber(a.value('idle-days'), 'idle-days', 1) + const sample = wholeNumber(a.value('sample'), 'sample') + const duTimeout = wholeNumber(a.value('du-timeout'), 'du-timeout', 1) + const minFreeGb = wholeNumber(a.value('min-free-gb'), 'min-free-gb') + return { + ...(only.length ? { only } : {}), + ...(idleDays !== undefined ? { idleDays: Math.floor(idleDays) } : {}), + ...(sample !== undefined ? { sampleSeconds: Math.min(60, Math.floor(sample)) } : {}), + ...(duTimeout !== undefined ? { duTimeoutSeconds: Math.floor(duTimeout) } : {}), + ...(roots?.length ? { buildRoots: roots, partialRoots: roots } : {}), + ...(a.value('image-age') ? { imageAge: a.value('image-age')! } : {}), + ...(a.value('journal-cap') ? { journalCap: a.value('journal-cap')! } : {}), + ...(a.flag('sudo') ? { useSudo: true } : {}), + ...(minFreeGb ? { minFreeGb } : {}), + } +} + +function fail(ctx: CommandContext, error: unknown): number { + const message = error instanceof Error ? error.message : String(error) + if (ctx.json) ctx.printJson({ ok: false, error: message }) + else ctx.warn(message) + return error instanceof UsageError ? 2 : 1 +} + +export function createCleanerPlugin(): DiskpushPlugin { + return definePlugin({ + id: CLEANER_ID, + name: 'Cleaner', + version: PACKAGE_VERSION, + description: + 'Find what is filling a disk (biggest directories, live writers, growth) and free space safely: caches, docker build cache, old unused images, rotated logs, idle build output, stale partial files. Dry run by default; databases, backups and volumes are only ever reported.', + settings: [ + { key: 'idleDays', label: 'Idle days', description: 'Build output is removed only from projects with no changed file for this many days.', type: 'string', default: '3' }, + { key: 'buildRoots', label: 'Project folders', description: 'Comma-separated folders searched for projects. Empty: ~/src, ~/code, ~/projects, ~/dev, ~/work, ~/repos, ~/git, ~/worktrees, ~/scratch, ~/Developer.', type: 'string', default: '' }, + { key: 'partialRoots', label: 'Partial-file folders', description: 'Comma-separated folders searched for stale *.partial / *.part / *.crdownload files. Empty: your home folder.', type: 'string', default: '' }, + { key: 'imageAge', label: 'Docker image age', description: 'Unused docker images newer than this stay (so a deploy can roll back), e.g. 72h.', type: 'string', default: '72h' }, + { key: 'journalCap', label: 'Journal size cap', description: 'systemd journal vacuum target, e.g. 1G.', type: 'string', default: '1G' }, + { key: 'useSudo', label: 'Use passwordless sudo', description: 'Let docker, journald and system-log steps use `sudo -n` when it works.', type: 'boolean', default: false }, + ], + actions: [ + { + id: 'disk-report', + label: 'Disk report: what can be freed here', + description: 'Sizes this folder\'s contents and finds idle build output and stale partial files under it. Read-only.', + tuiKey: 'f', + appliesTo: (entries) => entries.length === 1 && entries[0]!.isDirectory, + async run(ctx): Promise { + const path = resolve(ctx.dir, ctx.names[0]!) + const report = await scanTarget(ctx, LOCAL_TARGET, { + phases: ['top', 'build', 'partials'], + topRoots: [path], + buildRoots: [path], + partialRoots: [path], + sampleSeconds: 0, + snapshot: false, + }) + for (const line of formatReport(report, { limit: 15 })) if (line) ctx.progress.log('info', line) + const n = report.plan.ids.length + return { + ok: true, + message: n + ? `${formatBytes(report.plan.bytes)} can be freed safely in ${n} item${n === 1 ? '' : 's'} under ${path}. To remove them: diskpush clean run --roots '${path}' --only build,partials --apply` + : `Nothing under ${path} can be freed safely right now.`, + } + }, + }, + ], + commands: [ + { + name: 'report', + summary: 'read-only: what fills the disk, what is growing, who is writing, and what can be freed safely (ranked, with reasons)', + usage: 'report [TARGET] [--only caches,docker,logs,build,partials] [--idle-days 3] [--sample 3] [--roots DIR,DIR] [--sudo] [--all]', + async run(args, ctx) { + try { + const a = parseArgs(args, { values: SCAN_VALUES, flags: ['sudo', 'all', 'brief'] }) + const target = a.positional[0] ?? LOCAL_TARGET + const report = await scanTarget(ctx, target, scanOptions(a, ctx.cwd)) + if (ctx.json) ctx.printJson(report) + else for (const line of formatReport(report, { limit: a.flag('all') ? Infinity : 25, why: !a.flag('brief') })) ctx.print(line) + return 0 + } catch (error) { + return fail(ctx, error) + } + }, + }, + { + name: 'run', + summary: 'free space: a dry run listing exactly what would go, unless --apply; only safe, eligible items', + usage: 'run [TARGET] [--apply] [--only caches,docker,logs,build,partials] [--ids ID,ID] [--idle-days 3] [--min-free-gb N] [--roots DIR,DIR] [--sudo]', + async run(args, ctx) { + try { + const a = parseArgs(args, { values: [...SCAN_VALUES, 'ids'], flags: ['apply', 'sudo', 'all', 'yes'] }) + const target = a.positional[0] ?? LOCAL_TARGET + const options = scanOptions(a, ctx.cwd) + // A run needs the findings, not the disk report: skip sizing the top directories and watching writers. + const phases = ['fs', ...(options.only?.length ? options.only : CLEAN_CATEGORIES)] as Phase[] + const report = await scanTarget(ctx, target, { ...options, phases, snapshot: false }) + const ids = a.value('ids')?.split(',').map((id) => id.trim()).filter(Boolean) + const result = await applyClean(ctx, report, { + apply: a.flag('apply'), + ...(options.only ? { only: options.only } : {}), + ...(ids?.length ? { ids } : {}), + ...(options.minFreeGb ? { minFreeGb: options.minFreeGb } : {}), + ...(options.useSudo ? { useSudo: true } : {}), + }) + const titles = new Map(report.items.map((i) => [i.id, i.title])) + if (ctx.json) ctx.printJson(result) + else for (const line of formatApply(result, titles)) ctx.print(line) + if (result.locked) return 75 + return result.results.some((r) => r.status === 'failed') ? 1 : 0 + } catch (error) { + return fail(ctx, error) + } + }, + }, + { + name: 'targets', + summary: 'the machines the cleaner can work on: local and every server DiskPush knows', + usage: 'targets', + async run(_args, ctx) { + const targets = await listTargets(ctx) + if (ctx.json) ctx.printJson(targets) + else for (const t of targets) ctx.print(` ${t.name.padEnd(24)} ${t.local ? 'this machine' : t.host ?? ''}${t.usable ? '' : ` (${t.reason})`}`) + return 0 + }, + }, + { + name: 'cron', + summary: 'print a crontab line that cleans when free space drops below a threshold (two runs never overlap)', + usage: 'cron [TARGET] [--min-free-gb 20] [--at "*/15 * * * *"] [--only caches,docker,logs,build,partials]', + async run(args, ctx) { + try { + const a = parseArgs(args, { values: ['min-free-gb', 'at', 'only', 'idle-days'] }) + const at = a.value('at') ?? '*/15 * * * *' + if (at.trim().split(/\s+/).length !== 5) throw new UsageError('--at takes a five-field cron schedule.') + const gb = wholeNumber(a.value('min-free-gb') ?? '20', 'min-free-gb', 1)! + const only = parseCategories(a.value('only')) + const target = a.positional[0] + if (target && !/^[A-Za-z0-9_.@-]+$/.test(target)) throw new UsageError('That target name cannot go in a crontab line.') + const command = ['diskpush', 'clean', 'run', ...(target ? [target] : []), '--apply', '--min-free-gb', String(gb), ...(only.length ? ['--only', only.join(',')] : []), ...(a.value('idle-days') ? ['--idle-days', String(wholeNumber(a.value('idle-days'), 'idle-days', 1))] : []), '--quiet'].join(' ') + const line = `${at} mkdir -p "$HOME/.local/state" && ${command} >> "$HOME/.local/state/diskpush-clean.log" 2>&1` + if (ctx.json) ctx.printJson({ line }) + else { + ctx.print('# Add with: crontab -e (it does nothing while enough space is free; a lock keeps runs from overlapping)') + ctx.print(`PATH=${ctx.env.PATH ?? '/usr/local/bin:/usr/bin:/bin'}`) + ctx.print(line) + } + return 0 + } catch (error) { + return fail(ctx, error) + } + }, + }, + { + name: 'mcp', + summary: 'serve the cleaner over MCP on stdio (tools: clean_targets, clean_report, clean_apply)', + usage: 'mcp', + async run(_args, ctx) { + // stdout belongs to the protocol from here on; progress would corrupt it. + const quiet = { ...ctx, progress: { start() {}, update() {}, log() {} } } + await serveMcp(quiet, process.stdin, process.stdout, { version: PACKAGE_VERSION }) + return 0 + }, + }, + ], + }) +} + +export const cleanerPlugin = createCleanerPlugin() +export default cleanerPlugin + +/** For hosts that want the categories without importing the model. */ +export const CATEGORIES = CLEAN_CATEGORIES diff --git a/packages/plugin-cleaner/src/mcp.ts b/packages/plugin-cleaner/src/mcp.ts new file mode 100644 index 0000000..db349b4 --- /dev/null +++ b/packages/plugin-cleaner/src/mcp.ts @@ -0,0 +1,165 @@ +/** + * The cleaner as an MCP server: `diskpush clean mcp` speaks MCP over stdio + * (newline-delimited JSON-RPC 2.0), so an agent can ask what is filling a + * disk and free space with the same guards as everyone else. + * + * Tools: + * clean_targets this machine and the servers DiskPush knows + * clean_report read-only analysis of one target + * clean_apply dry run unless `apply: true`; only eligible, safe-class items + * + * Written against the protocol directly (it is small) so the CLI gains no + * dependency. Nothing but protocol messages is written to stdout. + */ +import { createInterface } from 'node:readline' +import type { Readable, Writable } from 'node:stream' +import type { BaseContext } from '@diskpush/plugin-api' +import { applyClean, listTargets, scanTarget, LOCAL_TARGET, type CleanOptions, type Runner } from './api.js' +import { formatApply, formatReport } from './format.js' +import { CLEAN_CATEGORIES, parseCategories } from './model.js' + +export const MCP_PROTOCOL_VERSION = '2025-06-18' + +const categories = { type: 'array', items: { type: 'string', enum: [...CLEAN_CATEGORIES] }, description: 'Limit to these categories. Default: all of them.' } +const target = { type: 'string', description: `"${LOCAL_TARGET}" (this machine, the default) or a server name from clean_targets.` } + +export const MCP_TOOLS = [ + { + name: 'clean_targets', + description: 'List the machines the cleaner can work on: this machine ("local") and every server DiskPush knows (saved connections and ~/.ssh/config hosts).', + inputSchema: { type: 'object', properties: {}, additionalProperties: false }, + annotations: { readOnlyHint: true }, + }, + { + name: 'clean_report', + description: + 'Read-only disk analysis of a target: filesystems and free space, the biggest directories, which processes are writing to disk right now, growth since the last report, and every finding classified as safe (regenerable), safe-if-idle, or needs-a-human, ranked by bytes freed per unit of risk, each with the reason it is or is not safe and a suggested command. Deletes nothing.', + inputSchema: { + type: 'object', + properties: { + target, + only: categories, + idleDays: { type: 'integer', minimum: 1, description: 'A project counts as idle after this many days without a changed file. Default 3.' }, + sampleSeconds: { type: 'integer', minimum: 0, maximum: 30, description: 'How long to watch disk writers. Default 3.' }, + }, + additionalProperties: false, + }, + annotations: { readOnlyHint: true }, + }, + { + name: 'clean_apply', + description: + 'Free space on a target. Scans first, then removes ONLY eligible items in the safe classes (caches, docker build cache and old unused images, rotated logs, idle build output, stale partial files), re-checking every guard at the moment of deletion. Needs-a-human items (databases, backups, volumes, media, stopped containers) are never touched. Without apply: true it is a dry run that lists exactly what would be removed.', + inputSchema: { + type: 'object', + properties: { + target, + apply: { type: 'boolean', description: 'Must be true to delete anything. Anything else is a dry run.' }, + only: categories, + ids: { type: 'array', items: { type: 'string' }, description: 'Only these item ids from a clean_report.' }, + idleDays: { type: 'integer', minimum: 1 }, + minFreeGb: { type: 'number', minimum: 0, description: 'Do nothing when this much is free already, and stop once it is.' }, + }, + additionalProperties: false, + }, + annotations: { destructiveHint: true }, + }, +] as const + +type Json = Record + +function text(value: string, structured?: unknown, isError = false): Json { + return { content: [{ type: 'text', text: value }], ...(structured === undefined ? {} : { structuredContent: structured }), ...(isError ? { isError: true } : {}) } +} + +function str(value: unknown): string | undefined { + return typeof value === 'string' && value ? value : undefined +} + +function int(value: unknown): number | undefined { + return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.floor(value) : undefined +} + +function cats(value: unknown) { + return Array.isArray(value) ? parseCategories(value.filter((v) => typeof v === 'string').join(',')) : undefined +} + +export async function callTool(ctx: BaseContext, name: string, args: Json, runner?: Runner): Promise { + try { + if (name === 'clean_targets') { + const targets = await listTargets(ctx) + return text(targets.map((t) => `${t.name}${t.host ? ` (${t.host})` : ''}${t.usable ? '' : `: ${t.reason}`}`).join('\n'), { targets }) + } + const options: CleanOptions = { + ...(cats(args.only) ? { only: cats(args.only)! } : {}), + ...(int(args.idleDays) ? { idleDays: int(args.idleDays)! } : {}), + ...(int(args.sampleSeconds) !== undefined ? { sampleSeconds: Math.min(30, int(args.sampleSeconds)!) } : {}), + ...(typeof args.minFreeGb === 'number' && args.minFreeGb > 0 ? { minFreeGb: args.minFreeGb } : {}), + ...(runner ? { runner } : {}), + } + const report = await scanTarget(ctx, str(args.target) ?? LOCAL_TARGET, options) + if (name === 'clean_report') return text(formatReport(report, { limit: 40 }).join('\n'), report) + if (name === 'clean_apply') { + const result = await applyClean(ctx, report, { + apply: args.apply === true, + ...(options.only ? { only: options.only } : {}), + ...(Array.isArray(args.ids) ? { ids: args.ids.filter((v): v is string => typeof v === 'string') } : {}), + ...(options.minFreeGb ? { minFreeGb: options.minFreeGb } : {}), + ...(runner ? { runner } : {}), + }) + const titles = new Map(report.items.map((i) => [i.id, i.title])) + return text(formatApply(result, titles).join('\n').replace('Run again with --apply', 'Call again with apply: true'), result) + } + return text(`No tool called ${name}.`, undefined, true) + } catch (error) { + return text(error instanceof Error ? error.message : String(error), undefined, true) + } +} + +/** Serves MCP on `input`/`output` until input ends. */ +export async function serveMcp(ctx: BaseContext, input: Readable, output: Writable, info: { version: string }, runner?: Runner): Promise { + const send = (message: Json) => output.write(`${JSON.stringify({ jsonrpc: '2.0', ...message })}\n`) + const lines = createInterface({ input, crlfDelay: Infinity }) + const pending: Promise[] = [] + for await (const line of lines) { + if (!line.trim()) continue + let message: { id?: string | number | null; method?: string; params?: Json } + try { + message = JSON.parse(line) + } catch { + send({ id: null, error: { code: -32700, message: 'Parse error' } }) + continue + } + const { id, method, params = {} } = message + const isRequest = id !== undefined && id !== null + const reply = (result: Json) => isRequest && send({ id, result }) + const fail = (code: number, text: string) => isRequest && send({ id, error: { code, message: text } }) + switch (method) { + case 'initialize': + reply({ + protocolVersion: typeof params.protocolVersion === 'string' ? params.protocolVersion : MCP_PROTOCOL_VERSION, + capabilities: { tools: { listChanged: false } }, + serverInfo: { name: 'diskpush-cleaner', version: info.version }, + instructions: 'Call clean_report first and read each item\'s safety and reason. clean_apply deletes only with apply: true, and only safe-class items.', + }) + break + case 'ping': + reply({}) + break + case 'tools/list': + reply({ tools: MCP_TOOLS }) + break + case 'tools/call': + pending.push( + callTool(ctx, String(params.name ?? ''), (params.arguments as Json) ?? {}, runner).then((result) => { + reply(result) + }), + ) + break + default: + if (method?.startsWith('notifications/')) break + fail(-32601, `Method not found: ${method}`) + } + } + await Promise.all(pending) +} diff --git a/packages/plugin-cleaner/src/model.ts b/packages/plugin-cleaner/src/model.ts new file mode 100644 index 0000000..1dddfa2 --- /dev/null +++ b/packages/plugin-cleaner/src/model.ts @@ -0,0 +1,733 @@ +/** + * From scan records to a report a person can act on. + * + * Every finding becomes an item with a safety class and a reason: + * + * safe regenerable: a cache, docker build cache, an old log. The + * only cost of removing it is time the next install or build + * spends fetching or rebuilding it. + * safe-if-idle build output and partial downloads, removable only because + * the guards prove nobody is using them right now. + * human databases, backups, volumes, media, stopped containers: + * reported with a command to look closer, NEVER deleted. + * + * Items are ranked by bytes freed per unit of risk; the plan is the eligible + * items in that order. Pure: no I/O here, so it is tested on fixed text. + */ +import { CACHE_IDS, type ApplyStep, type CacheId } from './script.js' + +export type Safety = 'safe' | 'safe-if-idle' | 'human' +export const CLEAN_CATEGORIES = ['caches', 'docker', 'logs', 'build', 'partials'] as const +export type CleanCategory = (typeof CLEAN_CATEGORIES)[number] +export type Category = CleanCategory | 'review' + +export type Item = { + /** Stable for a target: `build:/path`, `cache:npm`, `docker:buildcache`. */ + id: string + category: Category + safety: Safety + title: string + path: string | null + /** Estimated bytes freed. -1: unknown (a du ran out of time). */ + bytes: number + /** The size is an upper bound (pnpm prunes only unreferenced packages; images are age-filtered). */ + upTo: boolean + /** Applied when its category is chosen. False for every `human` item and for anything a guard stopped. */ + eligible: boolean + /** Why it is (or is not) safe to remove. */ + why: string + /** A command a person can run to look closer or do it by hand. */ + suggested: string | null + /** 1 = regenerable at no cost but time; higher = more to lose if a guard is wrong. */ + risk: number + /** bytes / risk: the ranking. */ + score: number + step: ApplyStep | null +} + +export type Filesystem = { device: string; mount: string; sizeBytes: number; usedBytes: number; availBytes: number; usedPercent: number } +/** `timedOut`: du ran out of time; `bytes` is then a lower bound (what it had counted), or -1 when it had nothing. */ +export type DirSize = { path: string; bytes: number; timedOut: boolean; kind: string | null } +export type Writer = { pid: number; bytesPerSecond: number; command: string; container: string | null; cmdline: string } +export type Kept = { root: string; reason: string; dirs: number } +export type Snapshot = { at: string; fs: Record; dirs: Record } +export type Growth = { + since: string + seconds: number + fs: { mount: string; deltaBytes: number; bytesPerHour: number }[] + dirs: { path: string; deltaBytes: number }[] +} + +export type Report = { + target: string + at: string + dryRun: true + os: string + isRoot: boolean + sudo: boolean + home: string + homeMount: string | null + idleDays: number + /** The scan's settings; an apply of this report re-checks with the same ones. */ + scan: { logDir: string; imageAge: string; journalCap: string; partialHours: number } + filesystems: Filesystem[] + topDirs: DirSize[] + writers: Writer[] + items: Item[] + kept: Kept[] + plan: { ids: string[]; bytes: number } + totals: Record + growth: Growth | null + docker: 'ok' | 'denied' | 'absent' + warnings: string[] + snapshot: Snapshot +} + +const KIB = 1024 +const GIB = 1024 ** 3 + +/** `12.3GB`, `512MB (40%)`, `0B`: docker's decimal units. */ +export function parseDockerSize(text: string | undefined): number { + const match = /([0-9.]+)\s*([kKMGTP]?B)/.exec(text ?? '') + if (!match) return 0 + const scale: Record = { B: 1, kB: 1e3, KB: 1e3, MB: 1e6, GB: 1e9, TB: 1e12, PB: 1e15 } + return Math.round(Number(match[1]) * (scale[match[2]!] ?? 1)) +} + +/** journalctl's `3.9G`, `512.0M`: binary units. */ +export function parseBinarySize(text: string | undefined): number { + const match = /^([0-9.]+)([BKMGT])?$/.exec((text ?? '').trim()) + if (!match) return 0 + const power = { B: 0, K: 1, M: 2, G: 3, T: 4 }[(match[2] ?? 'B') as 'B'] ?? 0 + return Math.round(Number(match[1]) * 1024 ** power) +} + +export function formatBytes(bytes: number): string { + if (bytes < 0) return '?' + const units = ['B', 'KB', 'MB', 'GB', 'TB'] + let value = bytes + let unit = 0 + while (value >= 1024 && unit < units.length - 1) { + value /= 1024 + unit += 1 + } + return `${value >= 100 || unit === 0 ? Math.round(value) : value.toFixed(1)} ${units[unit]}` +} + +type DockerVerbose = { + Images?: { Containers?: string | number; CreatedAt?: string; Size?: string; UniqueSize?: string }[] + Containers?: { State?: string; Size?: string }[] + Volumes?: { Name?: string; Links?: number | string; Size?: string }[] + BuildCache?: { InUse?: string | boolean; Size?: string }[] +} + +/** `2026-11-11 09:56:23 +0000 UTC` -> epoch seconds; 0 when unreadable (so it counts as old). */ +export function dockerTime(text: string | undefined): number { + const match = /^(\d{4}-\d\d-\d\d) (\d\d:\d\d:\d\d)(?:\.\d+)? ([+-]\d{4})/.exec(text ?? '') + if (!match) return 0 + const zone = `${match[3]!.slice(0, 3)}:${match[3]!.slice(3)}` + const ms = Date.parse(`${match[1]}T${match[2]}${zone}`) + return Number.isNaN(ms) ? 0 : ms / 1000 +} + +/** `72h`, `30m`, `90s` -> seconds. */ +export function ageSeconds(text: string): number { + const match = /^(\d+)([smh])$/.exec(text) + if (!match) return 72 * 3600 + return Number(match[1]) * { s: 1, m: 60, h: 3600 }[match[2] as 's' | 'm' | 'h'] +} + +/** Pseudo and per-container filesystems that only repeat a real one. */ +function isNoiseFs(device: string, mount: string): boolean { + return ( + /^(tmpfs|devtmpfs|udev|none|overlay|shm|squashfs|efivarfs|proc|sysfs|cgroup2?)$/.test(device) || + device.startsWith('/dev/loop') || + /^\/(run|snap|sys|proc|dev)(\/|$)/.test(mount) || + mount.includes('/containerd-mount') || + /\/docker\/(overlay2|containers)\//.test(mount) + ) +} + +const REGEN: Record = { + node_modules: 'the package manager reinstalls it (npm/pnpm/yarn/bun install)', + '.next': 'the next `next build` or `next dev` recreates it', + '.nuxt': 'the next `nuxt build` or `nuxt dev` recreates it', + '.turbo': 'turbo rebuilds its cache on the next run', + '.svelte-kit': 'the next `vite build` or `vite dev` recreates it', + '.parcel-cache': 'parcel rebuilds it on the next run', + '.output': 'the next build recreates it', + target: 'the next `cargo build` recreates it', + dist: 'the project\'s build recreates it', + build: 'the project\'s build recreates it', +} + +const CACHE_INFO: Record = { + npm: { title: 'npm download cache', command: 'npm cache clean --force' }, + pnpm: { title: 'pnpm content store', command: 'pnpm store prune', note: 'prune removes only packages no project on this machine references, so it frees up to this much' }, + yarn: { title: 'yarn cache', command: 'yarn cache clean' }, + bun: { title: 'bun install cache', command: 'bun pm cache rm' }, + uv: { title: 'uv cache', command: 'uv cache clean' }, + pip: { title: 'pip wheel cache', command: 'pip cache purge' }, + cargo: { title: 'cargo registry downloads', command: 'rm -rf ~/.cargo/registry/cache' }, + 'cargo-src': { title: 'cargo registry sources (unpacked crates)', command: 'rm -rf ~/.cargo/registry/src' }, + go: { title: 'go build cache', command: 'go clean -cache' }, +} + +/** What a big directory probably is, judged by its name. Null: nothing to say. */ +export function classifyDir(path: string, dockerRoot: string | null): string | null { + const lower = path.toLowerCase() + const base = lower.split('/').pop() ?? '' + if (dockerRoot && (path === dockerRoot || path.startsWith(`${dockerRoot}/`))) return 'docker' + if (lower === '/var/lib/docker' || lower.startsWith('/var/lib/docker/') || lower === '/var/lib/containerd') return 'docker' + if (/(^|[-_.])(postgres(ql)?|pgdata|pg_?wal|mysql|mariadb|mongo(db)?|redis|clickhouse|elasticsearch|opensearch|influxdb|cassandra|etcd|supabase[-_]?db)([-_.]|$)|\.(sqlite3?|db)$/.test(base)) return 'database' + if (/(^|[-_.])(backups?|bak|dumps?|snapshots?|archives?)([-_.]|$)/.test(base)) return 'backups' + if (/^(videos?|movies|music|pictures|photos|media|recordings|downloads|torrents?|desktop)$/.test(base)) return 'media' + if (lower === '/var/log' || lower.startsWith('/var/log/')) return 'logs' + return null +} + +const REVIEW_WHY: Record = { + database: 'Looks like live database data. Deleting files under a running database corrupts it; free space from inside the database (drop or archive data, lower WAL or binlog retention) or move it to a bigger disk.', + backups: 'Looks like backups. Only you know which copies you still need; prune them with their own retention (for DiskPush dumps: diskpush dbbackup prune), never in a sweep.', + media: 'Looks like media or downloads: personal files, not regenerable. Move them to another disk (diskpush push) or delete what you no longer want, by hand.', +} + +type Raw = { + meta: { uid: string; os: string; epoch: number; sudo: boolean; home: string } + homeMount: string | null + fs: Filesystem[] + sizes: Map + /** Paths whose size is only a lower bound. */ + partial: Set + top: string[] + writers: Writer[] + caches: { id: CacheId; path: string; tool: boolean; busy: boolean }[] + dockerState: 'ok' | 'denied' | 'absent' + /** Reclaimable bytes per docker category; null when docker did not say. */ + docker: { buildCache: number | null; images: number | null; containers: number | null } + dockerVolumes: { name: string; links: number; bytes: number }[] + dockerRoot: string | null + journal: { bytes: number; root: boolean } | null + logs: { path: string; writable: number; open: boolean }[] + builds: { path: string; root: string }[] + kept: { path: string; root: string; reason: string }[] + partials: { path: string; state: 'stale' | 'open' | 'recent' }[] + warnings: string[] + complete: boolean +} + +/** Scan output, line by line, into raw records. Unknown lines are ignored. */ +export function parseRecords(output: string, options: { imageAge?: string } = {}): Raw { + const imageAgeSeconds = ageSeconds(options.imageAge ?? '72h') + const raw: Raw = { + meta: { uid: '', os: '', epoch: Date.now() / 1000, sudo: false, home: '' }, + homeMount: null, + fs: [], + sizes: new Map(), + partial: new Set(), + top: [], + writers: [], + caches: [], + dockerState: 'absent', + docker: { buildCache: null, images: null, containers: null }, + dockerVolumes: [], + dockerRoot: null, + journal: null, + logs: [], + builds: [], + kept: [], + partials: [], + warnings: [], + complete: false, + } + const seenFs = new Set() + for (const line of output.split('\n')) { + const f = line.split('\t') + switch (f[0]) { + case 'META': + raw.meta = { uid: f[1] ?? '', os: f[2] ?? '', epoch: Number(f[3]) || Date.now() / 1000, sudo: f[4] === '1', home: f[5] ?? '' } + break + case 'HOMEFS': + raw.homeMount = f[1] || null + break + case 'FS': { + const [device = '', size, used, avail, mount = ''] = f.slice(1) + if (isNoiseFs(device, mount) || seenFs.has(device)) break + seenFs.add(device) + const sizeBytes = Number(size) * KIB + const usedBytes = Number(used) * KIB + const availBytes = Number(avail) * KIB + if (!sizeBytes) break + raw.fs.push({ device, mount, sizeBytes, usedBytes, availBytes, usedPercent: Math.round(((usedBytes) / (usedBytes + availBytes || 1)) * 100) }) + break + } + case 'SIZE': { + if (!f[1]) break + const kb = Number(f[2]) + const partial = f[3] === '1' + raw.sizes.set(f[1], Number.isFinite(kb) && kb >= 0 && !(partial && kb === 0) ? kb * KIB : -1) + if (partial) raw.partial.add(f[1]) + break + } + case 'TOP': + if (f[1]) raw.top.push(f[1]) + break + case 'WRITER': + raw.writers.push({ + pid: Number(f[1]), + bytesPerSecond: Number(f[2]) || 0, + command: (f[3] ?? '').trim(), + container: (f[4] ?? '').trim() || null, + cmdline: (f[5] ?? '').trim(), + }) + break + case 'CACHE': + if ((CACHE_IDS as readonly string[]).includes(f[1] ?? '') && f[2]) { + raw.caches.push({ id: f[1] as CacheId, path: f[2], tool: f[3] === '1', busy: f[4] === '1' }) + } + break + case 'DOCKERSTATE': + raw.dockerState = f[1] === 'ok' ? 'ok' : 'denied' + break + case 'DOCKERDF': + try { + const row = JSON.parse(f.slice(1).join('\t')) as { Type?: string; Reclaimable?: string } + const bytes = parseDockerSize(row.Reclaimable) + if (row.Type === 'Build Cache') raw.docker.buildCache = bytes + else if (row.Type === 'Images') raw.docker.images = bytes + else if (row.Type === 'Containers') raw.docker.containers = bytes + } catch { + // a docker that prints something else: no docker numbers + } + break + case 'DOCKERV': + try { + const parsed = JSON.parse(f.slice(1).join('\t')) as DockerVerbose + const now = raw.meta.epoch + raw.docker.buildCache = (parsed.BuildCache ?? []).filter((b) => String(b.InUse) !== 'true').reduce((sum, b) => sum + parseDockerSize(b.Size), 0) + raw.docker.images = (parsed.Images ?? []) + .filter((i) => String(i.Containers) === '0' && now - dockerTime(i.CreatedAt) > imageAgeSeconds) + .reduce((sum, i) => sum + parseDockerSize(i.UniqueSize ?? i.Size), 0) + raw.docker.containers = (parsed.Containers ?? []).filter((c) => c.State === 'exited' || c.State === 'created').reduce((sum, c) => sum + parseDockerSize(c.Size), 0) + for (const v of parsed.Volumes ?? []) { + if (v.Name) raw.dockerVolumes.push({ name: v.Name, links: Number(v.Links) || 0, bytes: parseDockerSize(v.Size) }) + } + } catch { + // no docker numbers + } + break + case 'DOCKERROOT': + raw.dockerRoot = f[1] || null + break + case 'JOURNAL': + raw.journal = { bytes: parseBinarySize(f[1]), root: f[2] === '1' } + break + case 'ROTLOG': + if (f[1]) raw.logs.push({ path: f[1], writable: Number(f[2]) || 0, open: f[3] === '1' }) + break + case 'BUILD': + if (f[1] && f[2]) raw.builds.push({ path: f[1], root: f[2] }) + break + case 'KEPT': + if (f[1]) raw.kept.push({ path: f[1], root: f[2] || f[1], reason: f[3] ?? 'kept' }) + break + case 'PARTIAL': + if (f[1] && (f[2] === 'stale' || f[2] === 'open' || f[2] === 'recent')) raw.partials.push({ path: f[1], state: f[2] }) + break + case 'WARN': + if (f[1]) raw.warnings.push(f[1]) + break + case 'END': + raw.complete = true + break + } + } + return raw +} + +function item(partial: Omit & Partial>): Item { + const bytes = partial.bytes + return { + upTo: false, + suggested: null, + step: null, + ...partial, + score: partial.safety === 'human' || bytes <= 0 ? 0 : bytes / partial.risk, + } +} + +export type BuildOptions = { + target: string + idleDays: number + partialHours: number + journalCap: string + imageAge: string + useSudo: boolean + logDir?: string + /** Don't plan beyond this much free space (bytes) on the home filesystem. 0: plan everything. */ + minFreeBytes?: number + previous?: Snapshot | null + now?: Date +} + +/** Turns raw records into the report. */ +export function buildReport(raw: Raw, options: BuildOptions): Report { + const items: Item[] = [] + const size = (path: string) => raw.sizes.get(path) ?? -1 + const sudoHint = raw.meta.uid === '0' ? '' : 'sudo ' + + for (const c of raw.caches) { + const info = CACHE_INFO[c.id] + const bytes = size(c.path) + const runnable = c.id === 'pnpm' ? c.tool : true + const reasons = [c.busy ? `${c.id === 'cargo-src' ? 'cargo' : c.id} is running right now` : '', runnable ? '' : 'pnpm is not installed, and only pnpm can prune its store safely'] + .filter(Boolean) + .join('; ') + items.push( + item({ + id: `cache:${c.id}`, + category: 'caches', + safety: 'safe', + title: info.title, + path: c.path, + bytes, + upTo: c.id === 'pnpm', + eligible: !reasons && bytes !== 0, + why: reasons + ? `Kept: ${reasons}.` + : `A download cache: everything in it is fetched again the next time it is needed, so the only cost is a slower next install or build${info.note ? `; ${info.note}` : ''}.`, + suggested: info.command, + risk: 1, + step: { kind: 'cache', id: `cache:${c.id}`, cache: c.id }, + }), + ) + } + + if (raw.dockerState === 'denied') { + items.push( + item({ + id: 'docker:denied', + category: 'review', + safety: 'human', + title: 'Docker is here but this user cannot reach it', + path: null, + bytes: -1, + eligible: false, + why: 'Docker build cache and images are often the biggest regenerable use of a disk, but this user is not in the docker group. Run the report as a user who is, or allow sudo (--sudo) when passwordless sudo is set up.', + suggested: 'sudo docker system df', + risk: 3, + }), + ) + } + if (raw.docker.buildCache !== null) { + const reclaim = raw.docker.buildCache + items.push( + item({ + id: 'docker:buildcache', + category: 'docker', + safety: 'safe', + title: 'Docker build cache', + path: raw.dockerRoot, + bytes: reclaim, + eligible: reclaim > 0, + why: 'Layers cached by past `docker build`s that no build is using now. The next build of each image is slower once; nothing else depends on them.', + suggested: 'docker builder prune -f', + risk: 1, + step: { kind: 'docker', id: 'docker:buildcache', what: 'buildcache' }, + }), + ) + } + if (raw.docker.images !== null) { + const reclaim = raw.docker.images + items.push( + item({ + id: 'docker:images', + category: 'docker', + safety: 'safe', + title: `Unused docker images older than ${options.imageAge}`, + path: raw.dockerRoot, + bytes: reclaim, + upTo: true, + eligible: reclaim > 0, + why: `Images no container (running or stopped) uses, created more than ${options.imageAge} ago. Newer ones stay so a recent deploy can still roll back; anything removed is pulled or rebuilt when it is needed again.`, + suggested: `docker image prune -a -f --filter until=${options.imageAge}`, + risk: 1.5, + step: { kind: 'docker', id: 'docker:images', what: 'images' }, + }), + ) + } + if (raw.docker.containers) { + items.push( + item({ + id: 'docker:containers', + category: 'review', + safety: 'human', + title: 'Stopped docker containers', + path: null, + bytes: raw.docker.containers, + eligible: false, + why: 'Stopped containers are often stopped on purpose and can be started again; removing one loses its writable layer. Review them one by one, never in bulk.', + suggested: 'docker ps -a --filter status=exited --format "table {{.Names}}\\t{{.Status}}\\t{{.Size}}"', + risk: 3, + }), + ) + } + const unusedVolumes = raw.dockerVolumes.filter((v) => v.links === 0 && v.bytes > 0).sort((a, b) => b.bytes - a.bytes) + for (const v of unusedVolumes.slice(0, 15)) { + items.push( + item({ + id: `volume:${v.name}`, + category: 'review', + safety: 'human', + title: `Docker volume ${v.name} (no container uses it)`, + path: null, + bytes: v.bytes, + eligible: false, + why: 'Volumes hold data, often a database\'s. "Unused" only means no container is attached right now; a stopped stack\'s data looks exactly the same. Look inside before removing it.', + suggested: `docker run --rm -v ${v.name}:/v:ro alpine du -sh /v/* # then, only if it is junk: docker volume rm ${v.name}`, + risk: 3, + }), + ) + } + + if (raw.journal) { + const cap = parseBinarySize(options.journalCap) + const over = raw.journal.bytes - cap + if (over > 0) { + items.push( + item({ + id: 'journal', + category: 'logs', + safety: 'safe', + title: `systemd journal (${formatBytes(raw.journal.bytes)}) down to ${options.journalCap}`, + path: '/var/log/journal', + bytes: over, + eligible: raw.journal.root, + why: raw.journal.root + ? `Removes the oldest archived journal files until the journal fits in ${options.journalCap}; recent logs stay.` + : `Removes the oldest archived journal files until the journal fits in ${options.journalCap}. Needs root: run as root, or with --sudo when passwordless sudo works.`, + suggested: `${sudoHint}journalctl --vacuum-size=${options.journalCap}`, + risk: 1, + step: { kind: 'journal', id: 'journal' }, + }), + ) + } + } + for (const log of raw.logs) { + const bytes = size(log.path) + const eligible = !log.open && log.writable > 0 + items.push( + item({ + id: `log:${log.path}`, + category: 'logs', + safety: 'safe', + title: `Rotated log ${log.path}`, + path: log.path, + bytes: bytes > 0 ? Math.round(bytes * 0.85) : bytes, + upTo: true, + eligible, + why: log.open + ? 'Kept: a process still has it open.' + : log.writable > 0 + ? 'An old, already-rotated log left uncompressed. It is compressed with gzip (about 85% smaller), not deleted.' + : 'An old, already-rotated log left uncompressed; compressing it needs root.', + suggested: `${log.writable === 1 ? '' : sudoHint}gzip -9 '${log.path}'`, + risk: 1, + step: { kind: 'log', id: `log:${log.path}`, path: log.path }, + }), + ) + } + + for (const build of raw.builds) { + const name = build.path.split('/').pop() ?? '' + const marker = name === 'target' ? 'Cargo.toml or CACHEDIR.TAG' : 'package.json' + items.push( + item({ + id: `build:${build.path}`, + category: 'build', + safety: 'safe-if-idle', + title: `${name} in ${build.root}`, + path: build.path, + bytes: size(build.path), + eligible: true, + why: `Build output of a project nobody is working on: ${marker} beside it, ignored by git, nothing in the project changed for ${options.idleDays}+ days, no running process inside it, and no service, cron job, container mount or linked command uses it. If it is needed again, ${REGEN[name] ?? 'the project\'s build recreates it'}.`, + suggested: `rm -rf '${build.path}'`, + risk: 2, + step: { kind: 'build', id: `build:${build.path}`, path: build.path }, + }), + ) + } + + for (const partial of raw.partials) { + const eligible = partial.state === 'stale' + items.push( + item({ + id: `partial:${partial.path}`, + category: 'partials', + safety: 'safe-if-idle', + title: `Partial file ${partial.path}`, + path: partial.path, + bytes: size(partial.path), + eligible, + why: + partial.state === 'stale' + ? `An unfinished download or copy: nothing has written to it for ${options.partialHours}+ hours and no process has it open, so whatever was writing it died. A retry starts over.` + : partial.state === 'open' + ? 'Kept: a process has it open, so the download or copy may still be running.' + : `Kept: written to in the last ${options.partialHours} hours, so it may still be in progress.`, + suggested: `rm -f '${partial.path}'`, + risk: 1.5, + step: { kind: 'partial', id: `partial:${partial.path}`, path: partial.path }, + }), + ) + } + + const topDirs: DirSize[] = raw.top + .map((path) => { + const bytes = size(path) + return { path, bytes, timedOut: bytes < 0 || raw.partial.has(path), kind: classifyDir(path, raw.dockerRoot) } + }) + // Unknown first (it ran out of time with nothing counted, so it may be the biggest), then by size; a lower bound counts as its size. + .sort((a, b) => (b.bytes < 0 ? Infinity : b.bytes) - (a.bytes < 0 ? Infinity : a.bytes)) + + for (const dir of topDirs) { + if (!dir.kind || !REVIEW_WHY[dir.kind]) continue + if (!dir.timedOut && dir.bytes < GIB) continue + items.push( + item({ + id: `review:${dir.path}`, + category: 'review', + safety: 'human', + title: `${dir.kind === 'database' ? 'Database data' : dir.kind === 'backups' ? 'Backups' : 'Media and downloads'}: ${dir.path}`, + path: dir.path, + bytes: dir.bytes, + eligible: false, + why: REVIEW_WHY[dir.kind]!, + suggested: `du -xh -d 1 '${dir.path}' 2>/dev/null | sort -h | tail -20`, + risk: 3, + }), + ) + } + + // Kept build dirs, one line per project and reason. + const keptMap = new Map() + for (const k of raw.kept) { + const key = `${k.root}\t${k.reason}` + const entry = keptMap.get(key) ?? { root: k.root, reason: k.reason, dirs: 0 } + entry.dirs += 1 + keptMap.set(key, entry) + } + + const order = (a: Item, b: Item) => b.score - a.score || b.bytes - a.bytes + items.sort((a, b) => (a.safety === 'human' ? 1 : 0) - (b.safety === 'human' ? 1 : 0) || order(a, b)) + + const plan = planFor(items, raw, options) + const totals = Object.fromEntries( + [...CLEAN_CATEGORIES, 'review'].map((category) => { + const inCategory = items.filter((i) => i.category === category) + return [ + category, + { + bytes: inCategory.filter((i) => i.eligible || category === 'review').reduce((sum, i) => sum + Math.max(0, i.bytes), 0), + count: inCategory.length, + eligible: inCategory.filter((i) => i.eligible).length, + }, + ] + }), + ) as Report['totals'] + + const now = options.now ?? new Date(raw.meta.epoch * 1000) + const snapshot: Snapshot = { + at: now.toISOString(), + fs: Object.fromEntries(raw.fs.map((f) => [f.mount, f.usedBytes])), + dirs: Object.fromEntries(topDirs.filter((d) => d.bytes >= 0).map((d) => [d.path, d.bytes])), + } + + const warnings = [...raw.warnings] + if (!raw.complete) warnings.push('The scan did not finish; the report is partial.') + const timedOut = topDirs.filter((d) => d.timedOut).length + if (timedOut) warnings.push(`${timedOut} director${timedOut === 1 ? 'y was' : 'ies were'} too big to size in time (shown as ≥ what was counted, or ?): look inside them first.`) + + return { + target: options.target, + at: now.toISOString(), + dryRun: true, + os: raw.meta.os, + isRoot: raw.meta.uid === '0', + sudo: raw.meta.sudo, + home: raw.meta.home, + homeMount: raw.homeMount, + idleDays: options.idleDays, + scan: { logDir: options.logDir ?? '/var/log', imageAge: options.imageAge, journalCap: options.journalCap, partialHours: options.partialHours }, + filesystems: raw.fs.sort((a, b) => b.usedPercent - a.usedPercent), + topDirs: topDirs.slice(0, 25), + writers: raw.writers, + items, + kept: [...keptMap.values()].sort((a, b) => b.dirs - a.dirs), + plan, + totals, + growth: growthSince(options.previous ?? null, snapshot), + docker: raw.dockerState, + warnings, + snapshot, + } +} + +/** The eligible items, best first, stopping once a free-space goal is met. */ +function planFor(items: readonly Item[], raw: Raw, options: BuildOptions): Report['plan'] { + const eligible = items.filter((i) => i.eligible && i.safety !== 'human') + let need = Infinity + if (options.minFreeBytes && options.minFreeBytes > 0) { + const fs = raw.fs.find((f) => f.mount === raw.homeMount) ?? raw.fs.find((f) => f.mount === '/') + need = fs ? options.minFreeBytes - fs.availBytes : Infinity + if (need <= 0) return { ids: [], bytes: 0 } + } + const ids: string[] = [] + let bytes = 0 + for (const i of eligible) { + if (bytes >= need) break + ids.push(i.id) + bytes += Math.max(0, i.bytes) + } + return { ids, bytes } +} + +export function growthSince(previous: Snapshot | null, now: Snapshot): Growth | null { + if (!previous) return null + const seconds = (Date.parse(now.at) - Date.parse(previous.at)) / 1000 + if (!(seconds > 0)) return null + const fs = Object.entries(now.fs) + .filter(([mount]) => previous.fs[mount] !== undefined) + .map(([mount, used]) => { + const deltaBytes = used - previous.fs[mount]! + return { mount, deltaBytes, bytesPerHour: Math.round((deltaBytes / seconds) * 3600) } + }) + .sort((a, b) => b.deltaBytes - a.deltaBytes) + const dirs = Object.entries(now.dirs) + .filter(([path]) => previous.dirs[path] !== undefined) + .map(([path, bytes]) => ({ path, deltaBytes: bytes - previous.dirs[path]! })) + .filter((d) => d.deltaBytes !== 0) + .sort((a, b) => b.deltaBytes - a.deltaBytes) + .slice(0, 10) + return { since: previous.at, seconds, fs, dirs } +} + +/** The items an apply would run: eligible, in a chosen category, optionally only the given ids. */ +export function selectSteps(report: Report, choice: { only?: readonly CleanCategory[]; ids?: readonly string[] } = {}): Item[] { + const only = new Set(choice.only?.length ? choice.only : CLEAN_CATEGORIES) + const ids = choice.ids?.length ? new Set(choice.ids) : null + return report.items.filter((i) => i.eligible && i.safety !== 'human' && i.step && only.has(i.category as CleanCategory) && (!ids || ids.has(i.id))) +} + +export function parseCategories(text: string | undefined): CleanCategory[] { + if (!text) return [] + const out: CleanCategory[] = [] + for (const word of text.split(',').map((w) => w.trim()).filter(Boolean)) { + const normal = word === 'partial' ? 'partials' : word === 'cache' ? 'caches' : word === 'log' ? 'logs' : word + if (!(CLEAN_CATEGORIES as readonly string[]).includes(normal)) { + throw new Error(`"${word}" is not a category. Choose from: ${CLEAN_CATEGORIES.join(', ')}.`) + } + if (!out.includes(normal as CleanCategory)) out.push(normal as CleanCategory) + } + return out +} diff --git a/packages/plugin-cleaner/src/script.ts b/packages/plugin-cleaner/src/script.ts new file mode 100644 index 0000000..57b668a --- /dev/null +++ b/packages/plugin-cleaner/src/script.ts @@ -0,0 +1,586 @@ +/** + * The two shell programs the cleaner runs ON the target: a read-only scan and + * an apply that deletes only what it is handed AND still passes every guard. + * + * Both are plain POSIX sh, fed to `sh -s` on stdin, so the same text runs on + * this machine and on any server over ssh, with nothing installed there. + * Neither writes a scratch file: a scan has to work on a disk that is 100% + * full, which is exactly when it is needed. State lives in shell variables; + * the one thing written is the apply lock, under $XDG_RUNTIME_DIR (a tmpfs) + * when there is one. + * + * Output is one record per line, fields separated by tabs. Paths holding a + * tab or a newline are skipped outright rather than escaped. + */ + +/** Shell `${...}` has to be written `\${...}` inside a JS template; this undoes the backslash. */ +function unescape(text: string): string { + return text.replaceAll('\\${', '${') +} + +/** Directory names that can be build output, and what makes each one provably so. */ +export const BUILD_NAMES = ['node_modules', '.next', '.nuxt', '.turbo', '.svelte-kit', '.parcel-cache', '.output', 'target', 'dist', 'build'] as const + +/** Partial-download suffixes. */ +export const PARTIAL_PATTERNS = ['*.partial', '*.part', '*.crdownload'] as const + +export const CACHE_IDS = ['npm', 'pnpm', 'yarn', 'bun', 'uv', 'pip', 'cargo', 'cargo-src', 'go'] as const +export type CacheId = (typeof CACHE_IDS)[number] + +export type ScriptOptions = { + idleDays: number + partialHours: number + /** Seconds between the two /proc io samples. 0 skips writers. */ + sampleSeconds: number + duTimeoutSeconds: number + findTimeoutSeconds: number + parallel: number + /** Directories searched for projects. Empty: the usual ones under $HOME. */ + buildRoots: readonly string[] + /** Directories searched for stale partial files. Empty: $HOME. */ + partialRoots: readonly string[] + /** Directories whose children are sized for the report. Empty: the usual system ones. */ + topRoots: readonly string[] + /** Where rotated logs are looked for. */ + logDir: string + /** `journalctl --vacuum-size` cap, e.g. 1G. */ + journalCap: string + /** `docker image prune --filter until=` age, e.g. 72h. */ + imageAge: string + /** Allow `sudo -n` for the root-only categories (docker without the group, journald, system logs). */ + useSudo: boolean + /** Which phases to run. */ + phases: readonly Phase[] + /** Apply only: the lock directory. Default: $XDG_RUNTIME_DIR or /tmp. */ + lockDir?: string +} + +export type Phase = 'fs' | 'top' | 'writers' | 'caches' | 'docker' | 'logs' | 'build' | 'partials' +export const ALL_PHASES: readonly Phase[] = ['fs', 'top', 'writers', 'caches', 'docker', 'logs', 'build', 'partials'] + +export const DEFAULT_SCRIPT_OPTIONS: ScriptOptions = { + idleDays: 3, + partialHours: 24, + sampleSeconds: 3, + duTimeoutSeconds: 20, + findTimeoutSeconds: 180, + parallel: 6, + buildRoots: [], + partialRoots: [], + topRoots: [], + logDir: '/var/log', + journalCap: '1G', + imageAge: '72h', + useSudo: false, + phases: ALL_PHASES, +} + +/** Single-quotes a word for sh. */ +export function shq(word: string): string { + return /^[A-Za-z0-9_./:=@%+,-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'` +} + +/** `name() { printf '%s\n' a b; }`: a list, with `$HOME` left for the target's shell to expand. */ +function listFunction(name: string, items: readonly string[], fallback: string): string { + const words = items.map((item) => (item === '~' ? '"$HOME"' : item.startsWith('~/') ? `"$HOME"/${shq(item.slice(2))}` : shq(item))) + return `${name}() { ${items.length ? `printf '%s\\n' ${words.join(' ')}` : fallback}; }` +} + +function positiveInt(value: number, name: string): number { + if (!Number.isInteger(value) || value < 0) throw new Error(`${name} must be a whole number of 0 or more.`) + return value +} + +function sizeWord(value: string, name: string, pattern: RegExp): string { + if (!pattern.test(value)) throw new Error(`${name} "${value}" is not valid.`) + return value +} + +/** Variables and helpers both programs share. */ +export function prelude(options: ScriptOptions): string { + const o = options + return [ + 'LC_ALL=C; export LC_ALL', + `IDLE_DAYS=${positiveInt(o.idleDays, 'idleDays')}`, + `PARTIAL_MIN=${positiveInt(o.partialHours, 'partialHours') * 60}`, + `SAMPLE=${positiveInt(o.sampleSeconds, 'sampleSeconds')}`, + `DU_TIMEOUT=${Math.max(1, positiveInt(o.duTimeoutSeconds, 'duTimeoutSeconds'))}; export DU_TIMEOUT`, + `FIND_TIMEOUT=${Math.max(1, positiveInt(o.findTimeoutSeconds, 'findTimeoutSeconds'))}`, + `PAR=${Math.max(1, Math.min(32, positiveInt(o.parallel, 'parallel')))}`, + `LOG_DIR=${shq(o.logDir)}`, + `JOURNAL_CAP=${sizeWord(o.journalCap, 'journalCap', /^[0-9]+[KMGT]?$/)}`, + `IMAGE_AGE=${sizeWord(o.imageAge, 'imageAge', /^[0-9]+[smh]$/)}`, + `USE_SUDO=${o.useSudo ? 1 : 0}`, + listFunction( + 'build_roots', + o.buildRoots, + `for d in src code projects dev work repos git worktrees scratch Developer; do printf '%s\\n' "$HOME/$d"; done`, + ), + listFunction('partial_roots', o.partialRoots, `printf '%s\\n' "$HOME"`), + listFunction( + 'top_roots', + o.topRoots, + `printf '%s\\n' "$HOME" /home /root /var/lib /var/log /var/cache /var/tmp /tmp /opt /srv /usr/local /var/www`, + ), + SHARED, + ].join('\n') +} + +/** + * Helpers. Kept as one raw block so the shell reads exactly what is here. + * + * BUILD_FIND is the find(1) predicate for every build-output name; ACTIVE_PRUNE + * is what an "is this project idle" search skips (build output and .git), + * so a fresh `npm install` does not count as someone working on it. + */ +const SHARED = unescape(String.raw` +have() { command -v "$1" >/dev/null 2>&1; } +tmo() { t=$1; shift; if have timeout; then timeout "$t" "$@"; else "$@"; fi; } +emit() { printf '%s' "$1"; shift; for f in "$@"; do printf '\t%s' "$f"; done; printf '\n'; } +step() { emit STEP "$*"; } +okpath() { case "$1" in *' '*|*' +'*|'') return 1 ;; esac; return 0; } +clean_text() { tr '\t\n\r' ' ' | cut -c1-160; } +avail_kb() { df -kP -- "$1" 2>/dev/null | awk 'NR==2{print $4}'; } +is_root() { [ "$(id -u)" = 0 ]; } +SUDO= +if ! is_root && [ "$USE_SUDO" = 1 ] && have sudo && sudo -n true 2>/dev/null; then SUDO='sudo -n'; fi +can_root() { is_root || [ -n "$SUDO" ]; } + +# Sizes, in KiB, of paths on stdin (one per line), several du at once, each +# bounded. A du that runs out of time still printed every subfolder it +# finished, so their sum is reported as a lower bound (last field 1) instead +# of nothing: "at least 120 GB, still counting" is what finds a culprit. +SIZE_ONE='p=$1; [ -n "$p" ] || exit 0 +if command -v timeout >/dev/null 2>&1; then o=$(timeout "$DU_TIMEOUT" du -xk -d 1 -- "$p" 2>/dev/null); rc=$?; else o=$(du -xk -d 1 -- "$p" 2>/dev/null); rc=$?; fi +if [ "$rc" = 124 ] || [ "$rc" = 137 ]; then + k=$(printf "%s\n" "$o" | awk -F "\t" -v p="$p" "\$2!=p && \$1 ~ /^[0-9]+\$/ {s+=\$1} END{print s+0}"); printf "SIZE\t%s\t%s\t1\n" "$p" "$k" +else + k=$(printf "%s\n" "$o" | awk -F "\t" -v p="$p" "\$2==p {k=\$1} END{print (k==\"\" ? -1 : k)}"); printf "SIZE\t%s\t%s\t0\n" "$p" "$k" +fi' +sizes() { tr '\n' '\0' | xargs -0 -P "$PAR" -n 1 sh -c "$SIZE_ONE" sh; } + +# Every path some process works in or runs from right now. +# One ls over /proc, not a readlink per process: on a box with thousands of +# processes the loop takes tens of seconds, the ls a fraction of one. +live_paths() { ls -l /proc/[0-9]*/cwd /proc/[0-9]*/exe 2>/dev/null | sed -n 's/^.* -> //p' | sed 's/ (deleted)$//' | sort -u; } +# stdin: paths. True when one is $1 itself or inside it. +any_under() { awk -v r="$1" '$0==r || index($0, r "/")==1 {f=1; exit} END{exit !f}'; } +# stdin: text. True when $1 appears as a whole path (not a prefix of a longer name). +mentions() { + awk -v r="$1" '{ s=$0; while ((i=index(s, r)) > 0) { c=substr(s, i+length(r), 1); if (c=="" || c !~ /[A-Za-z0-9._-]/) {f=1; exit}; s=substr(s, i+1) } } END{exit !f}' +} + +DOCKER= +docker_init() { + have docker || return 0 + if tmo 15 docker info >/dev/null 2>&1; then DOCKER=docker + elif [ "$USE_SUDO" = 1 ] && [ -n "$SUDO" ] && tmo 15 sudo -n docker info >/dev/null 2>&1; then DOCKER='sudo -n docker' + else DOCKER_DENIED=1; fi +} + +# What wires a project to the running system: commands linked into a bin +# directory, crontabs, systemd units, and directories bind-mounted into +# running containers. A project any of these names is never cleaned. +wired_text() { + for d in "$HOME/.local/bin" "$HOME/bin" "$HOME/.bun/bin" "$HOME/.bun/install/global/node_modules" "$HOME/.cargo/bin" "$HOME/go/bin" "$HOME/.npm-global/bin" "$HOME/.npm-global/lib/node_modules" "$HOME/.local/share/pnpm" /usr/local/bin /usr/local/lib/node_modules; do + [ -d "$d" ] || continue + for f in "$d"/* "$d"/@*/*; do [ -L "$f" ] && readlink -f -- "$f" 2>/dev/null; done + done + if have npm; then g=$(tmo 15 npm root -g 2>/dev/null); [ -d "$g" ] && for f in "$g"/* "$g"/@*/*; do [ -L "$f" ] && readlink -f -- "$f" 2>/dev/null; done; fi + if have pnpm; then g=$(tmo 15 pnpm root -g 2>/dev/null); [ -d "$g" ] && for f in "$g"/* "$g"/@*/*; do [ -L "$f" ] && readlink -f -- "$f" 2>/dev/null; done; fi + crontab -l 2>/dev/null + cat /etc/crontab /etc/cron.d/* 2>/dev/null + cat /etc/systemd/system/*.service /etc/systemd/system/*.d/*.conf "$HOME"/.config/systemd/user/*.service 2>/dev/null + if [ -n "$DOCKER" ]; then ids=$(tmo 15 $DOCKER ps -q 2>/dev/null); [ -n "$ids" ] && tmo 30 $DOCKER inspect --format '{{range .Mounts}}{{.Source}} +{{end}}' $ids 2>/dev/null; fi +} + +BUILD_FIND='( -name node_modules -o -name .next -o -name .nuxt -o -name .turbo -o -name .svelte-kit -o -name .parcel-cache -o -name .output -o -name target -o -name dist -o -name build )' +is_build_name() { case "$1" in node_modules|.next|.nuxt|.turbo|.svelte-kit|.parcel-cache|.output|target|dist|build) return 0 ;; esac; return 1; } + +# Why build dir $1 must stay, or nothing (and true) when it is provably build output. +build_shape() { + a=$1; d=\${a%/*}; n=\${a##*/} + [ -L "$a" ] && { echo "a symlink"; return 1; } + [ -d "$a" ] || { echo "gone"; return 1; } + is_build_name "$n" || { echo "not a build-output name"; return 1; } + case "$n" in + target) [ -f "$d/Cargo.toml" ] || [ -f "$a/CACHEDIR.TAG" ] || { echo "no Cargo.toml or CACHEDIR.TAG"; return 1; } ;; + *) [ -f "$d/package.json" ] || { echo "no package.json next to it"; return 1; } ;; + esac + if git -C "$d" rev-parse --git-dir >/dev/null 2>&1; then + git -C "$d" check-ignore -q -- "$a" 2>/dev/null || { echo "not git-ignored (it may be committed)"; return 1; } + else + case "$n" in dist|build|.output) echo "not in a git repository, so nothing proves $n is generated"; return 1 ;; esac + fi + return 0 +} + +project_root() { git -C "$1" rev-parse --show-toplevel 2>/dev/null || echo "$1"; } + +# Why project $1 is busy, or nothing (and true) when it is idle. +# Needs LIVE and WIRED set. +project_busy() { + r=$1 + printf '%s\n' "$LIVE" | any_under "$r" && { echo "a running process works in it"; return 1; } + printf '%s\n' "$WIRED" | mentions "$r" && { echo "a service, cron job, container mount or linked command uses it"; return 1; } + f=$(find "$r" -xdev \( -name .git -o $BUILD_FIND \) -prune -o -type f -mtime -"$IDLE_DAYS" -print 2>/dev/null | head -n 1) + [ -n "$f" ] && { echo "files changed in the last $IDLE_DAYS days"; return 1; } + return 0 +} + +# Is file $1 open by any process we can see? +is_open() { + if have fuser; then fuser -s -- "$1" 2>/dev/null && return 0; return 1; fi + ls -l /proc/[0-9]*/fd/ 2>/dev/null | sed -n 's/^.* -> //p' | grep -qxF -- "$1" +} +is_partial_name() { case "\${1##*/}" in *.partial|*.part|*.crdownload) return 0 ;; esac; return 1; } +is_rotated_log() { + case "$1" in "$LOG_DIR"/*) ;; *) return 1 ;; esac + case "$1" in *.gz|*.xz|*.zst|*.bz2|*.lz4) return 1 ;; esac + case "\${1##*/}" in *.[0-9]|*.[0-9][0-9]|*.log.[0-9]*|*-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]) return 0 ;; esac + return 1 +} + +# Where each cache lives on this machine. +cache_path() { + case "$1" in + npm) echo "\${npm_config_cache:-$HOME/.npm}/_cacache" ;; + pnpm) p=; have pnpm && p=$(tmo 15 pnpm store path 2>/dev/null); echo "\${p:-$HOME/.local/share/pnpm/store}" ;; + yarn) p=; have yarn && p=$(tmo 15 yarn cache dir 2>/dev/null); echo "\${p:-$HOME/.cache/yarn}" ;; + bun) echo "\${BUN_INSTALL_CACHE_DIR:-$HOME/.bun/install/cache}" ;; + uv) echo "\${UV_CACHE_DIR:-$HOME/.cache/uv}" ;; + pip) echo "\${PIP_CACHE_DIR:-$HOME/.cache/pip}" ;; + cargo) echo "\${CARGO_HOME:-$HOME/.cargo}/registry/cache" ;; + cargo-src) echo "\${CARGO_HOME:-$HOME/.cargo}/registry/src" ;; + go) p=; have go && p=$(tmo 15 go env GOCACHE 2>/dev/null); echo "\${p:-$HOME/.cache/go-build}" ;; + esac +} +# The program whose own command empties the cache (and that must not be running). +cache_tool() { case "$1" in cargo|cargo-src) echo cargo ;; *) echo "$1" ;; esac; } +cache_busy() { have pgrep && pgrep -x "$(cache_tool "$1")" >/dev/null 2>&1; } +`) + +/** The read-only scan. Prints records; deletes nothing, writes nothing. */ +export function scanScript(options: ScriptOptions): string { + const phases = new Set(options.phases) + const parts = [prelude(options), SCAN_HEAD] + if (phases.has('fs')) parts.push(SCAN_FS) + if (phases.has('docker') || phases.has('build')) parts.push('docker_init; [ -n "${DOCKER_DENIED:-}" ] && emit DOCKERSTATE denied; [ -n "$DOCKER" ] && emit DOCKERSTATE ok') + if (phases.has('writers')) parts.push(SCAN_WRITERS) + if (phases.has('top')) parts.push(SCAN_TOP) + if (phases.has('caches')) parts.push(SCAN_CACHES) + if (phases.has('docker')) parts.push(SCAN_DOCKER) + if (phases.has('logs')) parts.push(SCAN_LOGS) + if (phases.has('build')) parts.push(SCAN_BUILD) + if (phases.has('partials')) parts.push(SCAN_PARTIALS) + parts.push('emit END') + return parts.join('\n') +} + +const SCAN_HEAD = unescape(String.raw` +emit META "$(id -u)" "$(uname -s)" "$(date +%s)" "$([ -n "$SUDO" ] && echo 1 || echo 0)" "$HOME" +emit HOMEFS "$(df -kP -- "$HOME" 2>/dev/null | awk 'NR==2{print $6}')" +`) + +const SCAN_FS = unescape(String.raw` +step "filesystems" +df -kP 2>/dev/null | awk 'NR>1 && NF>=6 {m=$6; for (i=7;i<=NF;i++) m=m" "$i; printf "FS\t%s\t%s\t%s\t%s\t%s\n", $1, $2, $3, $4, m}' +`) + +const SCAN_WRITERS = unescape(String.raw` +if [ "$SAMPLE" -gt 0 ] && [ -r /proc/self/io ]; then + step "sampling disk writers for $SAMPLE s" + wa=$(grep -H '^write_bytes' /proc/[0-9]*/io 2>/dev/null) + sleep "$SAMPLE" + wb=$(grep -H '^write_bytes' /proc/[0-9]*/io 2>/dev/null) + NAMES= + [ -n "$DOCKER" ] && NAMES=$(tmo 15 $DOCKER ps --no-trunc --format '{{.ID}} {{.Names}}' 2>/dev/null) + { printf '%s\n' "$wa" | sed 's/^/A /'; printf '%s\n' "$wb" | sed 's/^/B /'; } \ + | awk -v s="$SAMPLE" '{ split($2, p, "/"); pid=p[3]; v=$3+0; if ($1=="A") a[pid]=v; else if (pid in a) { d=v-a[pid]; if (d>0) print pid, int(d/s) } }' \ + | sort -k2 -nr | head -n 12 | while read -r pid rate; do + comm=$(cat "/proc/$pid/comm" 2>/dev/null | clean_text) + cmd=$(tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null | clean_text) + cid=$(grep -oE '[0-9a-f]{64}' "/proc/$pid/cgroup" 2>/dev/null | head -n 1) + cname= + [ -n "$cid" ] && cname=$(printf '%s\n' "$NAMES" | awk -v c="$cid" '$1==c {print $2; exit}') + [ -n "$cid" ] && [ -z "$cname" ] && cname=$(printf '%.12s' "$cid") + emit WRITER "$pid" "$rate" "$comm" "$cname" "$cmd" + done +fi +`) + +const SCAN_TOP = unescape(String.raw` +step "sizing the biggest directories" +# One bounded du per root sizes all its children in a single pass. When it runs +# out of time, the children it finished keep their exact sizes and only the +# rest are sized one by one (several at a time, each bounded, a lower bound +# when even that runs out). A root that holds another root (/home holding +# $HOME) goes folder by folder from the start, skipping that root. +ROOTS=$(top_roots) +per_child() { + done_list=$2 + kids=$(for c in "$1"/* "$1"/.[!.]* "$1"/..?*; do + [ -d "$c" ] && [ ! -L "$c" ] && okpath "$c" || continue + printf '%s\n' "$ROOTS" | grep -qxF -- "$c" && continue + [ -n "$done_list" ] && printf '%s\n' "$done_list" | grep -qxF -- "$c" && continue + printf '%s\n' "$c" + done | head -n 400) + printf '%s\n' "$kids" | while IFS= read -r c; do [ -n "$c" ] && emit TOP "$c"; done + printf '%s\n' "$kids" | sizes +} +printf '%s\n' "$ROOTS" | while IFS= read -r r; do + [ -d "$r" ] && [ ! -L "$r" ] || continue + okpath "$r" || continue + case "$r" in /proc|/proc/*|/sys|/sys/*|/dev|/dev/*|/run|/run/*) continue ;; esac + step "sizing $r" + if printf '%s\n' "$ROOTS" | awk -v r="$r" 'index($0, r "/")==1 && substr($0, length(r)+2) !~ /\// {f=1} END{exit !f}'; then + per_child "$r" "" + continue + fi + out=$(tmo $((DU_TIMEOUT * 3)) du -xak -d 1 -- "$r" 2>/dev/null; echo "rc=$?") + rc=\${out##*rc=} + printf '%s\n' "$out" | awk -F '\t' -v r="$r" 'NF==2 && $2!=r && $1 ~ /^[0-9]+$/ { printf "TOP\t%s\nSIZE\t%s\t%s\t0\n", $2, $2, $1 }' + if [ "$rc" = 124 ] || [ "$rc" = 137 ]; then + emit WARN "$r is too big to size in one pass; sized the rest of its folders one by one" + per_child "$r" "$(printf '%s\n' "$out" | awk -F '\t' -v r="$r" 'NF==2 && $2!=r {print $2}')" + fi +done +`) + +const SCAN_CACHES = unescape(String.raw` +step "package-manager caches" +for id in npm pnpm yarn bun uv pip cargo cargo-src go; do + p=$(cache_path "$id") + [ -d "$p" ] && [ ! -L "$p" ] && okpath "$p" || continue + avail=0; have "$(cache_tool "$id")" && avail=1 + busy=0; cache_busy "$id" && busy=1 + emit CACHE "$id" "$p" "$avail" "$busy" + printf '%s\n' "$p" | sizes +done +`) + +const SCAN_DOCKER = unescape(String.raw` +if [ -n "$DOCKER" ]; then + # One verbose call carries images (with ages), containers, volumes and the + # build cache. It can take minutes on a busy host; the summary is the fallback. + step "docker disk usage (can take a few minutes on a busy host)" + v=$(tmo 240 $DOCKER system df -v --format '{{json .}}' 2>/dev/null | tr -d '\n\t') + if [ -n "$v" ]; then emit DOCKERV "$v" + else tmo 120 $DOCKER system df --format '{{json .}}' 2>/dev/null | while IFS= read -r l; do emit DOCKERDF "$l"; done; fi + root=$(tmo 15 $DOCKER info --format '{{.DockerRootDir}}' 2>/dev/null) + [ -n "$root" ] && emit DOCKERROOT "$root" +fi +`) + +const SCAN_LOGS = unescape(String.raw` +step "logs" +if have journalctl; then + u=$(journalctl --disk-usage 2>/dev/null | grep -oE '[0-9.]+[BKMGT]' | head -n 1) + [ -n "$u" ] && emit JOURNAL "$u" "$(can_root && echo 1 || echo 0)" +fi +if [ -d "$LOG_DIR" ]; then + OUT=$(tmo "$FIND_TIMEOUT" find "$LOG_DIR" -xdev -type f -size +1024k 2>/dev/null | while IFS= read -r f; do + okpath "$f" && is_rotated_log "$f" || continue + w=0; { [ -w "$f" ] && [ -w "\${f%/*}" ]; } && w=1; [ "$w" = 0 ] && can_root && w=2 + open=0; is_open "$f" && open=1 + emit ROTLOG "$f" "$w" "$open" + done) + printf '%s\n' "$OUT" + printf '%s\n' "$OUT" | awk -F '\t' '$1=="ROTLOG" {print $2}' | sizes +fi +`) + +const SCAN_BUILD = unescape(String.raw` +step "finding build output" +LIVE=$(live_paths) +WIRED=$(wired_text) +OUT=$(build_roots | while IFS= read -r r; do + [ -d "$r" ] || continue + tmo "$FIND_TIMEOUT" find "$r" -xdev -name .git -prune -o -type d $BUILD_FIND -prune -print 2>/dev/null + [ $? = 124 ] && emit WARN "the search of $r ran out of time; some build output may be missing" +done | { + VERDICTS= + while IFS= read -r a; do + case "$a" in WARN' '*) printf '%s\n' "$a"; continue ;; esac + okpath "$a" || continue + if ! why=$(build_shape "$a"); then + # Not a project at all (a node_modules in a random folder): not worth a line. + case "$why" in "no package.json next to it"|"no Cargo.toml or CACHEDIR.TAG") ;; *) emit KEPT "$a" "$a" "$why" ;; esac + continue + fi + root=$(project_root "\${a%/*}") + if ! v=$(printf '%s' "$VERDICTS" | awk -F '\t' -v r="$root" '$1==r {print $2; f=1; exit} END{exit !f}'); then + v=$(project_busy "$root") && v=idle + VERDICTS="$VERDICTS$root $v +" + fi + if [ "$v" = idle ]; then emit BUILD "$a" "$root"; else emit KEPT "$a" "$root" "$v"; fi + done +}) +printf '%s\n' "$OUT" +printf '%s\n' "$OUT" | awk -F '\t' '$1=="BUILD" {print $2}' | sizes +`) + +const SCAN_PARTIALS = unescape(String.raw` +step "stale partial files" +OUT=$(partial_roots | while IFS= read -r r; do + [ -d "$r" ] || continue + tmo "$FIND_TIMEOUT" find "$r" -xdev \( -name .git -o -name node_modules -o -name .cache -o -name .rustup -o -name .cargo \) -prune -o -type f \( -name '*.partial' -o -name '*.part' -o -name '*.crdownload' \) -print 2>/dev/null +done | while IFS= read -r f; do + okpath "$f" && [ ! -L "$f" ] || continue + if [ -z "$(find "$f" -mmin +"$PARTIAL_MIN" 2>/dev/null)" ]; then s=recent; elif is_open "$f"; then s=open; else s=stale; fi + emit PARTIAL "$f" "$s" +done) +printf '%s\n' "$OUT" +printf '%s\n' "$OUT" | awk -F '\t' '$1=="PARTIAL" {print $2}' | sizes +`) + +/** One thing to remove, as the apply program takes it. */ +export type ApplyStep = + | { kind: 'build'; id: string; path: string } + | { kind: 'partial'; id: string; path: string } + | { kind: 'log'; id: string; path: string } + | { kind: 'cache'; id: string; cache: CacheId } + | { kind: 'docker'; id: string; what: 'buildcache' | 'images' } + | { kind: 'journal'; id: string } + +export type ApplyOptions = ScriptOptions & { + /** Stop once this many KiB are free on `stopPath`. 0: do every step. */ + stopAtKb: number + stopPath: string +} + +/** + * The apply program. Every step is checked again here, on the target, at + * the moment of deleting: a project that became active since the scan, a + * partial file someone opened, a path that turned into a symlink, are all + * skipped. Commands come from a fixed table keyed by id, never from input. + */ +export function applyScript(options: ApplyOptions, steps: readonly ApplyStep[]): string { + const lines = [prelude(options), applyHead(options)] + for (const s of steps) { + const id = shq(s.id) + switch (s.kind) { + case 'build': + case 'partial': + case 'log': + lines.push(`go && do_${s.kind} ${id} ${shq(s.path)}`) + break + case 'cache': + if (!(CACHE_IDS as readonly string[]).includes(s.cache)) throw new Error(`Unknown cache ${s.cache}.`) + lines.push(`go && do_cache ${id} ${s.cache}`) + break + case 'docker': + if (s.what !== 'buildcache' && s.what !== 'images') throw new Error(`Unknown docker step ${s.what}.`) + lines.push(`go && do_docker ${id} ${s.what}`) + break + case 'journal': + lines.push(`go && do_journal ${id}`) + break + } + } + lines.push('emit END') + return lines.join('\n') +} + +function applyHead(options: ApplyOptions): string { + return [ + `STOP_AT_KB=${positiveInt(options.stopAtKb, 'stopAtKb')}`, + `STOP_PATH=${shq(options.stopPath || '/')}`, + `LOCKD=${options.lockDir ? shq(options.lockDir) : '"${XDG_RUNTIME_DIR:-/tmp}/diskpush-cleaner-$(id -u).lock"'}`, + APPLY_LIB, + ].join('\n') +} + +const APPLY_LIB = unescape(String.raw` +# One clean at a time per user per machine: a cron run and a click never overlap. +if ! mkdir "$LOCKD" 2>/dev/null; then + op=$(cat "$LOCKD/pid" 2>/dev/null) + if [ -n "$op" ] && kill -0 "$op" 2>/dev/null; then emit LOCKED "$op"; exit 75; fi + rm -rf "$LOCKD"; mkdir "$LOCKD" 2>/dev/null || { emit LOCKED unknown; exit 75; } +fi +echo $$ > "$LOCKD/pid" 2>/dev/null +trap 'rm -rf "$LOCKD"' EXIT +trap 'exit 130' INT TERM +docker_init +LIVE=$(live_paths) +WIRED=$(wired_text) +STOPPED=0 +go() { + [ "$STOPPED" = 1 ] && return 1 + if [ "$STOP_AT_KB" -gt 0 ]; then + av=$(avail_kb "$STOP_PATH") + if [ -n "$av" ] && [ "$av" -ge "$STOP_AT_KB" ]; then emit STOPPED "$av"; STOPPED=1; return 1; fi + fi + return 0 +} +# result ID ok|skipped|failed BEFORE_KB AFTER_KB MESSAGE (avail on the path's filesystem) +result() { emit RESULT "$@"; } +do_build() { + id=$1; a=$2 + okpath "$a" || { result "$id" skipped 0 0 "unusable path"; return 0; } + why=$(build_shape "$a") || { result "$id" skipped 0 0 "$why"; return 0; } + root=$(project_root "\${a%/*}") + why=$(project_busy "$root") || { result "$id" skipped 0 0 "$why"; return 0; } + b=$(avail_kb "\${a%/*}") + step "removing $a" + if rm -rf -- "$a" 2>/dev/null; then result "$id" ok "$b" "$(avail_kb "\${a%/*}")" "removed" + else result "$id" failed "$b" "$(avail_kb "\${a%/*}")" "partly removed: some files are not yours to delete"; fi +} +do_partial() { + id=$1; f=$2 + okpath "$f" && [ -f "$f" ] && [ ! -L "$f" ] && is_partial_name "$f" || { result "$id" skipped 0 0 "not a partial file any more"; return 0; } + [ -n "$(find "$f" -mmin +"$PARTIAL_MIN" 2>/dev/null)" ] || { result "$id" skipped 0 0 "written to recently"; return 0; } + is_open "$f" && { result "$id" skipped 0 0 "a process has it open"; return 0; } + b=$(avail_kb "\${f%/*}") + if rm -f -- "$f"; then result "$id" ok "$b" "$(avail_kb "\${f%/*}")" "removed"; else result "$id" failed "$b" "$b" "could not remove"; fi +} +do_log() { + id=$1; f=$2 + okpath "$f" && [ -f "$f" ] && [ ! -L "$f" ] && is_rotated_log "$f" || { result "$id" skipped 0 0 "not a rotated log"; return 0; } + is_open "$f" && { result "$id" skipped 0 0 "a process has it open"; return 0; } + have gzip || { result "$id" skipped 0 0 "no gzip"; return 0; } + run=; { [ -w "$f" ] && [ -w "\${f%/*}" ]; } || run=$SUDO + { [ -w "$f" ] && [ -w "\${f%/*}" ]; } || [ -n "$run" ] || is_root || { result "$id" skipped 0 0 "needs root"; return 0; } + b=$(avail_kb "\${f%/*}") + if $run gzip -9 -- "$f" 2>/dev/null; then result "$id" ok "$b" "$(avail_kb "\${f%/*}")" "compressed"; else result "$id" failed "$b" "$(avail_kb "\${f%/*}")" "gzip failed"; fi +} +do_cache() { + id=$1; c=$2; p=$(cache_path "$c"); t=$(cache_tool "$c") + [ -d "$p" ] && [ ! -L "$p" ] || { result "$id" skipped 0 0 "no cache at $p"; return 0; } + cache_busy "$c" && { result "$id" skipped 0 0 "$t is running"; return 0; } + b=$(avail_kb "$p") + step "emptying the $c cache" + case "$c" in + npm) if have npm; then npm cache clean --force >/dev/null 2>&1; else rm -rf -- "$p"; fi ;; + pnpm) if have pnpm; then pnpm store prune >/dev/null 2>&1; else result "$id" skipped 0 0 "pnpm is not installed, and its store is pruned only by pnpm"; return 0; fi ;; + yarn) if have yarn; then yarn cache clean >/dev/null 2>&1; else rm -rf -- "$p"; fi ;; + bun) if have bun; then bun pm cache rm >/dev/null 2>&1; else rm -rf -- "$p"; fi ;; + uv) if have uv; then uv cache clean >/dev/null 2>&1; else rm -rf -- "$p"; fi ;; + pip) if have pip; then pip cache purge >/dev/null 2>&1; elif have python3; then python3 -m pip cache purge >/dev/null 2>&1; else rm -rf -- "$p"; fi ;; + cargo|cargo-src) rm -rf -- "$p" ;; + go) if have go; then go clean -cache >/dev/null 2>&1; else rm -rf -- "$p"; fi ;; + esac + result "$id" ok "$b" "$(avail_kb "$p")" "emptied" +} +do_docker() { + id=$1; w=$2 + [ -n "$DOCKER" ] || { result "$id" skipped 0 0 "docker is not reachable$( [ -n "\${DOCKER_DENIED:-}" ] && echo ' (permission denied)')"; return 0; } + r=$(tmo 15 $DOCKER info --format '{{.DockerRootDir}}' 2>/dev/null); [ -d "$r" ] || r=/ + b=$(avail_kb "$r") + case "$w" in + buildcache) step "pruning the docker build cache"; tmo 1800 $DOCKER builder prune -f >/dev/null 2>&1 ;; + images) step "pruning unused docker images older than $IMAGE_AGE"; tmo 1800 $DOCKER image prune -a -f --filter "until=$IMAGE_AGE" >/dev/null 2>&1 ;; + esac + if [ $? = 0 ]; then result "$id" ok "$b" "$(avail_kb "$r")" "pruned"; else result "$id" failed "$b" "$(avail_kb "$r")" "docker prune failed"; fi +} +do_journal() { + id=$1 + have journalctl || { result "$id" skipped 0 0 "no journalctl"; return 0; } + can_root || { result "$id" skipped 0 0 "needs root"; return 0; } + b=$(avail_kb /var/log) + if $SUDO journalctl --vacuum-size="$JOURNAL_CAP" >/dev/null 2>&1; then result "$id" ok "$b" "$(avail_kb /var/log)" "vacuumed to $JOURNAL_CAP"; else result "$id" failed "$b" "$(avail_kb /var/log)" "journalctl failed"; fi +} +`) diff --git a/packages/plugin-cleaner/tsconfig.json b/packages/plugin-cleaner/tsconfig.json new file mode 100644 index 0000000..7940fdc --- /dev/null +++ b/packages/plugin-cleaner/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { "outDir": "dist", "rootDir": "src" }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.test.ts", "src/**/*.fixture.ts"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7b347c8..ac6709d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -42,6 +42,9 @@ importers: '@diskpush/plugin-api': specifier: workspace:* version: link:../../packages/plugin-api + '@diskpush/plugin-cleaner': + specifier: workspace:* + version: link:../../packages/plugin-cleaner '@diskpush/plugin-dbbackup': specifier: workspace:* version: link:../../packages/plugin-dbbackup @@ -87,6 +90,9 @@ importers: '@diskpush/plugin-api': specifier: workspace:* version: link:../../packages/plugin-api + '@diskpush/plugin-cleaner': + specifier: workspace:* + version: link:../../packages/plugin-cleaner '@diskpush/plugin-dbbackup': specifier: workspace:* version: link:../../packages/plugin-dbbackup @@ -168,7 +174,7 @@ importers: dependencies: '@profullstack/footer': specifier: latest - version: 0.2.6(react@19.3.1) + version: 0.6.19(react@19.3.1) '@profullstack/x402-gateway': specifier: ^0.13.1 version: 0.13.1 @@ -230,6 +236,12 @@ importers: packages/plugin-api: {} + packages/plugin-cleaner: + dependencies: + '@diskpush/plugin-api': + specifier: workspace:* + version: link:../plugin-api + packages/plugin-dbbackup: dependencies: '@diskpush/plugin-api': @@ -1062,8 +1074,8 @@ packages: resolution: {integrity: sha512-kX2mMvxsfsz89u3RIj2cGRIb89TUVUgwNO1rlTowPuHQrsStsOCNtz8KQ/VqPgJ2FjpfAj0CCQwCRgXaehPL5w==} engines: {node: '>=18'} - '@profullstack/footer@0.2.6': - resolution: {integrity: sha512-BKwbDszAc7e0mYIBiPjgr/5WS8WyDt8IW718s/zW/8pCWOIB1BGwSNs6fmImRSo5kqIjQKUVbXp22jZQ5GEipA==} + '@profullstack/footer@0.6.19': + resolution: {integrity: sha512-DAS2jHDJFnH1w6lDtYbEnvuV2n4NY2vrRwnUKeQPC+Nwfg1f2Me9ClZ6KlXs6Dv0pgJSg2ATLSX0hV+Mq7co3w==} engines: {node: '>=18'} hasBin: true peerDependencies: @@ -4717,7 +4729,7 @@ snapshots: '@profullstack/cli@0.1.0': {} - '@profullstack/footer@0.2.6(react@19.3.1)': + '@profullstack/footer@0.6.19(react@19.3.1)': optionalDependencies: react: 19.3.1 @@ -4730,7 +4742,7 @@ snapshots: '@modelcontextprotocol/sdk': 1.32.2(supports-color@7.2.0)(zod@4.6.7) '@profullstack/auth-system': 0.8.3 '@profullstack/cli': 0.1.0 - '@profullstack/footer': 0.2.6(react@19.3.1) + '@profullstack/footer': 0.6.19(react@19.3.1) '@profullstack/hqtui': 0.11.0 '@profullstack/synconfig': 0.1.3 '@profullstack/x402-gateway': 0.11.0 diff --git a/scripts/release.mjs b/scripts/release.mjs index d989bad..926fcb4 100755 --- a/scripts/release.mjs +++ b/scripts/release.mjs @@ -32,6 +32,7 @@ const MANIFESTS = [ 'packages/plugin-api/package.json', 'packages/plugin-mediaanalyzer/package.json', 'packages/plugin-dbbackup/package.json', + 'packages/plugin-cleaner/package.json', 'packages/s3-core/package.json', ] const TAG_SOURCE = 'apps/cli/package.json'