Disk Space Analysis and Automated Cleanup with LLMs: A Practical Guide
This article explains how to use LLM-powered coding tools to build a disk space analysis and cleanup program when a 1TB drive fills up. It covers why generating an executable script is more useful than asking for advice, four constraints to include in the prompt, a three-layer architecture that separates analysis from execution, and five safety mechanisms such as dry-run defaults, path validation, retention periods, and audit logs. It also discusses response latency, cloud API bottlenecks, local deployment options, and how to evolve a one-off script into a recurring operational capability.
1. Background: When a 1TB Disk Fills Up
A developer’s local disk filling up is a frequent problem that is easy to underestimate. Model weights, container images, build caches, log files, VM images, and dataset snapshots are all large artifacts that can quietly consume 1TB-class storage within weeks. Once free space drops below a certain threshold, the first things to break are usually not the disk itself but the builds, database writes, and container runtimes that depend on temporary files.
The traditional approach is manual investigation: cd into directories one level at a time, run size commands, and rely on experience to decide what can be deleted. The problem is that this depends heavily on personal memory and judgment, and carries a risk of deleting the wrong files. A better approach is to hand the task to a programmatic workflow, and smart coding tools can compress the cost of “writing this program” into a single sentence.
2. Why Have the Model Write a Tool Instead of Give Advice
When disk space runs low, there are two typical ways to ask a smart coding tool: have it list investigation ideas, or have it produce an executable script directly. The former seems safer but pushes the work back onto the human. The value of the latter is that a script can be rerun, scheduled, and shared across a team once generated.
It is worth emphasizing that the model acts as a code generator here, not a decision executor. The authority to decide what gets deleted must stay with the human. This division of labor is the premise for all the safety design that follows.
3. Prompt Design: Four Constraints Behind One Sentence
A sentence like “write me a disk space analysis and cleanup program” produces usable results because mature smart coding tools automatically fill in implicit requirements. To keep the output controllable, it is worth explicitly stating four categories of constraints in the prompt:
- Scope: specify the starting directory and a maximum depth so the scan does not traverse the entire filesystem from the root.
- Output format: require a size-sorted listing first, then cleanup suggestions, rather than immediate deletion.
- Safety boundaries: explicitly exclude critical system directories, user document directories, and version control metadata directories.
- Run mode: default to dry-run, and perform deletion only when a confirmation flag is explicitly passed.
A sample prompt:
Write a cross-platform script that scans the top 30 largest subdirectories under aspecified directory, outputs them in descending order by size, and labels thecleanup type (cache/log/temp file).Analyze only by default; do not delete anything without a confirmation flag.
4. Program Structure: Keep the Analysis Layer and Execution Layer Separate
A reliable disk governance script is usually organized into three layers.
The first layer is traversal and statistics. It recursively scans directories, accumulates file sizes, and outputs structured results. For performance, traversal should skip symlink loops, skip directories without permission, and prune oversized directories.
The second layer is classification and decision. It groups candidate objects by path characteristics, such as build caches, package manager caches, rotated logs, and temporary files. The decision logic should be written as a configurable rule table rather than hardcoded into deletion statements:
CLEAN_RULES = [{"pattern": "**/cache/**", "kind": "build_cache", "keep_days": 7},{"pattern": "**/*.log.*", "kind": "log_rotate", "keep_days": 3},{"pattern": "**/tmp/**", "kind": "temp_file", "keep_days": 1},]
The third layer is execution and audit. It accepts only objects from the decision layer that carry an explicit kind label, and writes an audit log before deletion recording the time, path, size, and triggering rule for later traceability.
5. Safety Mechanisms: Driving the Probability of Wrong Deletion Toward Zero
The biggest risk of a cleanup script is not deleting slowly but deleting the wrong thing. At least five mechanisms are recommended:
- Dry-run by default: without a confirmation flag, only print the list of files to be deleted and the estimated space to be freed.
- Dual allowlist and blocklist validation: the blocklist takes higher priority and covers system directories and user data directories.
- Retention constraints: only clean files older than the retention period to avoid deleting intermediate artifacts still in use.
- Second confirmation before deletion: for a single item above a size threshold, require interactive confirmation.
- Audit and rollback clues: write the list to disk before deletion so files can be manually restored if something goes wrong.
Illustrative safety check code:
def is_safe_to_delete(path: Path, rules) -> bool:if any(block in path.parts for block in BLOCKED_PARTS):return Falseif not any(path.match(r["pattern"]) for r in rules):return Falsereturn age_days(path) >= min_keep_days(rules, path)
6. Performance and Experience: Do Not Ignore “Thinking Length”
In practice, an often-overlooked experience metric is response pacing. Some models perform lengthy internal reasoning before answering, which noticeably increases wait time, while models that respond concisely and produce runnable code directly offer a better experience for tool-writing tasks. For time-sensitive scenarios like a disk running out of space, waiting itself is a cost.
The engineering response is to write the prompt clearly and state the constraints completely to reduce back-and-forth clarification rounds. Also, write the generated result to a file first, then run a local dry-run and verify correctness with real output rather than judging by reading alone.
7. Service-Side Bottlenecks and the Case for Local Deployment
Beyond generation quality, the stability of the call path also affects the experience. When calling a model through a cloud API, you may encounter limited throughput or dropped connections, especially during peak hours. Common mitigations in the industry include request retries with backoff, streaming output to reduce time to first token, splitting long tasks into smaller batches, and caching results locally.
For these reasons, “can it run locally” has become a practical requirement for many developers. Local execution has natural advantages in keeping data within its boundary, controlling latency, and working offline, and is well suited to environment-sensitive information such as disk paths and directory structures. For such needs, the common industry practice is to adopt a privately deployable model service, or build a dedicated inference environment on cloud container platforms or model service offerings, keeping sensitive data within a controllable boundary.
8. Implementation Advice: From a One-Off Script to a Standing Capability
Getting the script running is only the starting point. To make it deliver value over the long term, three more steps are recommended:
- Configuration: move the scan root, retention periods, and thresholds into a configuration file to avoid editing code.
- Scheduling: use the system’s built-in scheduler to run dry-runs daily or weekly, output reports to a logging service, and use monitoring alerts to notify when free space drops below a threshold.
- Platformization: share the same rules and script across the team, incorporate the cleanup strategy into a unified operations workflow, archive cold data to object storage when needed, and run periodic tasks on a container platform.
9. Conclusion
The essence of disk space governance is turning “judgment based on experience” into “execution based on rules.” The value of smart coding tools is compressing the cost of writing these rules from hours to a single sentence, while the value of engineering discipline is ensuring the rules never delete the wrong thing. Combining the two is the reliable answer to problems like a 1TB disk filling up.
