Disk Space Analysis and Cleanup with LLMs: A Practical Guide
This article explains how to use code-generating large language models to build a disk space analysis and cleanup tool. It covers what a reusable prompt should include, a four-layer architecture for traversal, aggregation, policy, and auditing, and the safety boundaries that cleanup tools must enforce, such as read-only defaults, path validation, and symlink handling. It also discusses performance tuning for large file sets, practical model-usage considerations, and a step-by-step rollout checklist. Readers will learn how to turn a vague requirement into an auditable, repeatable utility while keeping deletion decisions under human control.
1. The Real Challenge Behind a Full Disk
A developer’s local disk rarely fills up for a single reason. It is usually the combined result of accumulated logs, build caches, container image layers, dependency caches, temporary swap files, and historical archives. The traditional approach is to enter directories one level at a time, repeatedly run directory size commands, and then manually decide which files can be deleted. The problem with this process is that it relies heavily on personal experience and applies inconsistent criteria, which makes it easy to delete data that is still referenced.
Handing this kind of task to a model with code generation capabilities is not about replacing human judgment. The value is that it quickly produces a clear, auditable, and repeatable tool skeleton. Models are good at translating vague requirements into runnable program structures, but whether to delete anything, and what to delete, should still be controlled by the user through parameters and confirmation steps.
2. What a One-Line Prompt Should Include
In practice, a shorter prompt does not necessarily produce better results. What matters is whether it covers four elements: the goal, the scope, the output format, and the safety boundary. A reusable template looks like this:
Write a disk space analysis and cleanup helper program:1) Scan a specified root directory, aggregate sizes by first- and second-leveldirectories, and output them in descending order;2) Find the top N largest files and show their paths, sizes, and last modified times;3) Support two modes: "analyze only" and "clean up after confirmation", withanalyze-only as the default;4) Limit cleanup targets to a configurable whitelist of directories (such as cacheand temporary directories);5) Output a structured report for later archiving.
This description does not name any specific product or tool, yet it states the key constraints clearly: read-only by default, cleanup must be explicitly enabled, scope is configurable, and results leave a trace. Code generated from such a prompt is typically usable out of the box.
3. Recommended Architecture for the Generated Code
A robust implementation is usually split into four decoupled layers, which makes them easy to replace and test.
The first layer is traversal and statistics. Use the language’s built-in file traversal capability, catch exceptions when a directory cannot be accessed due to permissions, and skip it so the whole task is not interrupted. Statistics should record the path, size in bytes, and modification time rather than returning only a total.
The second layer is aggregation and sorting. Aggregate file-level data into directory-level data by path prefix, then sort by size in descending order. Example code:
def aggregate(root, depth=2):buckets = {}for path, size, mtime in walk_files(root):parts = path.split(sep)[:depth]key = sep.join(parts)buckets.setdefault(key, 0)buckets[key] += sizereturn sorted(buckets.items(), key=lambda kv: kv[1], reverse=True)
The third layer is policy and whitelist. Cleanup rules should not be hard-coded; they should be provided as configuration, such as allowed directory suffixes, a file age threshold, and a minimum file size threshold. An object enters the candidate list only when it meets all three conditions: it is inside the whitelist, it is older than the retention period, and its size exceeds the threshold.
The fourth layer is execution and auditing. By default, it outputs the candidate list and the estimated space that can be freed, without deleting anything. When the user explicitly enables cleanup mode, it first prints each path to be deleted and waits for confirmation, then performs the deletion and writes an operation log recording the time, path, size, and result for later review.
4. Safety Boundaries: The First Principle of Cleanup Tools
A cleanup program carries far more risk than an analysis program, so a few ground rules are essential. First, read-only by default: any deletion capability requires an explicit switch. Second, path validation must be normalized: resolve relative paths to absolute paths, then check whether they are inside the allowed root directories, so path traversal cannot escape the scope into system directories. Third, do not follow symbolic links, to avoid statistics and deletion reaching real data through a link. Fourth, keep minimum age and minimum size thresholds to avoid deleting files that were just created and are still in use. Fifth, record deletion failures separately instead of silently ignoring them.
def is_allowed(target, allowed_roots):real = normalize_absolute(target)return any(real.startswith(root) for root in allowed_roots)
5. Performance and Usability Improvements
When the scan scope reaches millions of files, a naive implementation slows down noticeably. Practical optimizations include: limiting traversal depth, going coarse first and fine later; scanning known large directories first; persisting statistics to an intermediate file to support resumable scans; and showing two sections in the report, “safe to free” and “needs manual confirmation”, to reduce the user’s decision cost. In addition, output should follow a stable sorting rule so that two scan results can be compared as a diff, which verifies whether the cleanup actually took effect.
6. Practical Notes on Using the Model
Two issues that are unrelated to the model itself can still affect the experience. One is uncontrollable output length: some models perform lengthy internal reasoning before generating, which increases waiting time and consumes a large amount of context. Explicitly stating in the prompt “give runnable code and a brief explanation directly” often improves this significantly. The other is the stability and rate fluctuation of the server-side API, which can interrupt long tasks. The way to handle this is to break the task into smaller pieces: generate only the statistics module first, verify it, then generate the cleanup module; also write key results to a local file to avoid duplicated work if the session is interrupted.
If local compute is available, deploying the model in your own environment avoids network fluctuation and rate limits, and the data does not have to leave the machine, which is especially suitable for sensitive scenarios such as processing local files. If you use a cloud service, pay attention to general rate limits, timeout retries, and log monitoring to keep uncertainty within a controllable range.
7. Rollout Checklist
- Run a full scan in read-only mode first and confirm the report format matches expectations;
- Tighten the whitelist and thresholds, keeping only directories that are clearly safe to clean;
- Trial the cleanup on a small set of directories, and check the logs and freed space;
- Gradually expand the scope, and keep the report from each run for comparison;
- Add the tool to regular inspections to form a loop of scan, confirm, clean, and review.
8. Conclusion
A one-line prompt can quickly produce a usable tool not because the model “guesses”, but because the requirement has been expressed as a clear structure with boundaries. Writing safety constraints into the prompt, leaving deletion authority to the user, and turning results into auditable logs are what make this kind of automation script truly usable in the long run.
