Disk Space Analysis and Cleanup with LLMs: A Practical Guide
This article explains how to use LLM-driven coding tools to build a disk space analysis and cleanup CLI. It covers turning a vague request into clear specifications, structuring prompts, designing core modules, enforcing safety with dry-run mode and protected paths, handling I/O performance constraints, and validating results through testing and operations. The focus is on turning ad-hoc scripts into reliable engineering workflows while keeping deletion decisions under human control.
1. Background: The Real Engineering Pain Behind a Full Disk
Whether on a local development machine, a CI node, or a container host, a full disk is a frequent failure. Typical symptoms include build jobs failing abruptly, logs that cannot be written, database write errors, and containers restarting repeatedly. What makes it harder is that a full disk rarely has a single cause. It is usually a combination of large files piling up, logs that were never rotated, bloated cache directories, and temporary files that were never cleaned.
Traditional troubleshooting relies on manually entering directories one level at a time and running statistics commands. It is slow and easy to miss things. Handing this kind of task to an AI coding tool to generate automation scripts turns experience-based investigation into a repeatable process. It is worth emphasizing that the value of the tool is to accelerate coding and structured thinking. The final decisions about which directories matter and what to delete must still be confirmed by the developer.
2. Requirement Breakdown: Turning a One-Line Request into an Executable Spec
The prerequisite for high-quality code generation is breaking a vague request into explicit specifications. Take “the disk is full, help me analyze and clean it” as an example. At minimum, the following dimensions should be clarified:
- Analysis goal: only top-level directory usage, or recursion to a specified depth;
- Output format: a terminal table, a text report, or structured data for further processing;
- Cleanup strategy: only list candidates, or allow automatic deletion;
- Safety boundaries: whether to set protected directories, threshold confirmation, and a dry-run preview;
- Runtime environment: operating system differences and whether administrator privileges are required.
Writing these constraints clearly significantly improves the controllability of the generated result.
3. Prompt Design: Constraining Model Output with Structured Descriptions
In practice, a structured prompt usually contains four parts: role, task, constraints, and output. An example is shown below:
Role: Senior systems operations development engineerTask: Implement a command-line program for disk space analysis and cleanupConstraints:1. Support a specified scan root directory and recursion depth;2. Default to dry-run, outputting candidate cleanup items only;3. Set a protection list for critical system directories and forbid deletion;4. Output a Top N list sorted by usage in descending order;5. Include unit tests and usage instructions.Output: Complete runnable code + explanation of key logic
The core of this approach is making implicit assumptions explicit, reducing the deviation caused by the model improvising.
4. Key Modules of the Generated Code
A usable disk analysis and cleanup program can usually be abstracted into four modules:
- Scanning module: traverse directories and accumulate usage at each level, taking care to avoid double-counting hard links and symbolic links;
- Sorting and aggregation module: aggregate results by directory and output them in descending order;
- Policy module: generate a candidate cleanup list based on file size, modification time, and a suffix whitelist;
- Execution module: perform deletion after a second confirmation and output an operation audit log.
A sample structure is as follows:
def scan(root, max_depth):# Return {path: size in bytes}...def build_candidates(stats, min_size, older_than_days):# Generate cleanup candidates, excluding protected directories...def apply_cleanup(candidates, dry_run=True):if dry_run:return report(candidates)for item in candidates:safe_remove(item)return audit_log()
5. Safety Design: The First Principle for Cleanup Tools
Cleanup programs are inherently destructive, so safety must come first. The following measures are recommended:
- Default to dry-run; deletion requires an explicit switch;
- Establish a protection list covering system directories and business-critical paths;
- Validate path ownership before deletion to prevent symbolic links from escaping boundaries;
- Keep operation logs to support traceability;
- Set a count or capacity limit for batch deletion; exceeding the limit requires manual confirmation.
6. Performance and Resource Constraints
Scanning an entire disk is an I/O-intensive operation. Pay attention to the following: control the number of concurrent traversals to avoid saturating the disk queue; use incremental statistics for large directories; skip network mounts and virtual file systems when necessary; persist results to disk as a cache to avoid repeated scans. If running in a container environment, also account for differences between mount points and the writable layer.
7. Testing and Acceptance
At minimum, cover the following cases: empty directories, extremely large files, deeply nested structures, directories without permissions, symbolic links pointing outside, and protection list hits on deletion requests. Acceptance criteria should include result accuracy, dry-run consistency, no crashes on exceptional paths, and complete, queryable logs.
8. Deployment and Operations Recommendations
The program can be packaged as a scheduled task that periodically outputs reports and pushes them to a monitoring and alerting channel; set warnings for growth beyond thresholds; and incorporate cleanup actions into a change process to prevent scripts from being executed arbitrarily. If elastic compute or centralized storage is needed, general cloud capabilities can be used, such as object storage for archiving cold data, container platforms for hosting tasks, and logging and monitoring services for tracking runtime status.
9. A Rational View of Model Usage
AI coding tools can significantly compress the time from idea to runnable code, but the generated results still require human review. Models differ in response speed, context length, and verbosity of reasoning. Developers should choose based on the task type and keep critical logic under review. Local deployment can improve data controllability, but hardware and operations costs also need to be evaluated.
10. Summary
Disk cleanup may look simple, but it is a combined problem of safety, performance, and process design. Driving code generation with structured prompts, then layering on dry-run, a protection list, audit logs, and testing acceptance, is what turns a one-off script into stable and reliable engineering capability.
