Disk Space Analysis and Automated Cleanup with LLMs: A Practical Guide
This article walks through building an LLM-assisted disk space analyzer and cleanup tool, from framing the problem to shipping it safely. It covers how to turn a one-line request into explicit engineering constraints, the four risk areas to review in generated code (path safety, deletion semantics, edge cases, and resource control), a layered safety design that keeps automation read-only by default, a three-step validation process, and common pitfalls such as ignoring mount points and hard links. The takeaway: put constraints in the prompt, guardrails in the code, and validation in the process.
1. Background: The Golden Ten Minutes After a Disk Fills Up
Running out of disk space on a dev machine, test machine, or edge node is both frequent and highly disruptive. Typical symptoms include build jobs failing because they cannot write temporary files, logging stopping mid-stream so troubleshooting data goes missing, and databases refusing writes because they cannot extend their data files. In severe cases, service processes crash outright.
The traditional response relies on manual, layer-by-layer investigation: check overall usage first, drill down directory by directory, then manually confirm large files and cache directories. This process is slow and easy to get wrong, with accidental deletion a real risk. Handing this kind of task to an intelligent coding tool with code-generation capability can produce a reusable analyzer in a very short time, but only if safety comes before speed.
One thing must be clear: disk cleanup is an irreversible operation. Any automated approach has to follow three ground rules: read-only by default, deletion requires explicit confirmation, and every change is auditable and reversible.
2. Breaking Down the Requirement: From One Sentence to Executable Constraints
A request as short as “write me a disk analysis and cleanup program” works because the model fills in a large number of implicit constraints. In practice, the safer approach is to make those dimensions explicit in the prompt:
- Runtime environment and language: the OS family, runtime version, and whether zero dependencies are required.
- Scan scope: the starting path, whether to cross file systems, and whether to follow symbolic links.
- Output format: terminal table, structured file, or both.
- Cleanup policy: sort by size, filter by modification time, aggregate by directory, exclude via allowlist.
- Safety mechanisms: dry-run mode, confirmation interaction, operation log.
- Performance requirements: traversal efficiency on large directories, concurrency, and a memory ceiling.
A reusable prompt skeleton:
Implement a disk space analysis tool in Python using only the standard library:1) Recursively aggregate from a specified root directory, with --depth to control the aggregation level;2) Output a directory ranking sorted by usage descending, plus the Top-N largest files;3) Support --min-size and --older-than filters;4) Default to dry-run; delete only when --apply is passed and a second confirmation is given;5) Write a manifest log before deletion, recording path, size, and timestamp;6) Explicitly handle and skip permission errors, symbolic links, and mount point boundaries.
3. Core Review Points for Generated Code
Code produced by the model should not go straight into production. Review should focus on four categories of risk.
The first is path safety. Verify that the target path falls within the allowed root directory to prevent relative-path traversal; decide whether to resolve symbolic links so you do not delete the link target by mistake.
def is_within(root: str, target: str) -> bool:root_real = os.path.realpath(root)target_real = os.path.realpath(target)return os.path.commonpath([root_real, target_real]) == root_real
The second is deletion semantics. Distinguish three meanings of “cleanup”: empty-directory cleanup, cache-directory cleanup, and time-based cleanup. Avoid implementing “cleanup” as indiscriminate deletion.
The third is edge-case handling. Insufficient permissions, files in use, and directories deleted during the scan all raise exceptions. A robust implementation catches them, logs them, and continues rather than aborting the whole run.
The fourth is resource control. Recursive traversal should avoid blowing the stack on deep trees; for large directories, prefer an explicit stack or queue. Concurrent scanning needs a thread limit so I/O is not saturated and online workloads are not affected.
4. Safety Guardrails: Stopping Automation in the Right Place
A layered protection structure is recommended:
- Read-only layer: statistics and display only by default, with no write operations.
- Plan layer: generate a deletion candidate list, annotating the reason for each entry (size, time, directory type).
- Confirmation layer: manual review of the list, with batch selection by mode.
- Execution layer: write the manifest log first, then delete, collecting failures separately.
- Review layer: output the total space reclaimed and a summary of failure reasons.
The manifest log is best kept in a structured format for later auditing and, where needed, recovery reference:
{"ts":"2026-01-01T10:00:00","path":"/var/cache/demo","size":1048576,"reason":"cache_dir"}
5. Validation: Three Checks Before Rollout
First, sample validation. Build a test directory tree containing large files, empty directories, symbolic links, and directories without permissions, then verify the numbers and the ranking order.
Second, dry-run validation. Run against a real directory in dry-run mode, manually spot-check whether the list is reasonable, and confirm in particular that the allowlist was not hit.
Third, canary execution. Run on non-critical nodes first, watch the reclaimed space and business metrics, then widen the scope step by step. Keep logs throughout so the whole process can be reviewed.
6. Engineering Trade-offs for Performance and Experience
Three experience dimensions that come up often in practice can be abstracted into general engineering metrics:
- Inference and response length: an overly long chain of thought stretches both time-to-first-token and total latency. For ops scripts like this one, where the structure is clear and the constraints are explicit, the prompt should ask for runnable code directly with less preamble.
- Throughput: when generating long files, output rate directly affects waiting time; connection stability also matters, since a dropped long-lived connection leaves half-finished code. The engineering answer is retry from a breakpoint and segmented generation.
- Deployment model: cloud calls remove environment maintenance, while local deployment keeps data in-domain and latency controllable, at the cost of supplying your own compute and ops effort. Whether to go local depends on data sensitivity, concurrency scale, and the team’s ops capability.
In related practice at Baidu AI Cloud, this kind of capability is typically assembled from general product categories such as model services, container platforms, log services, and monitoring and alerting: model services handle code generation, the container platform hosts the runtime, and logging plus monitoring provide observability, closing the loop.
7. Common Pitfalls
- Shipping with dry-run off by default, which sharply raises the risk of accidental deletion.
- Not handling mount points, so cross-file-system aggregation produces misleading numbers.
- Ignoring hard links and counting the same usage twice.
- Not calling fsync on the directory entry after deletion, so delayed space reclamation leads to wrong conclusions.
- Logging only successful items, leaving failures impossible to locate afterward.
- A prompt that is too open-ended, letting the model improvise and pull in unnecessary dependencies.
8. Summary
Generating a disk analysis and cleanup tool from a single sentence is valuable not because it is fast, but because it hands repetitive work to the model while keeping the critical decisions with people. Put the constraints in the prompt, the guardrails in the code, and the validation in the process, and this kind of automation will run reliably in real environments.
