Disk Space Analysis and Cleanup with LLMs: A Practical Guide
This article explains how to use large language models to generate disk space analysis and cleanup tools for dev machines, test machines, and edge nodes. It covers why disk-full incidents are usually multi-factor problems, why this task fits LLM code generation, how to write prompts that make implicit constraints explicit, a recommended layered code structure, safety boundaries that keep deletion disabled by default, a three-step validation process, runtime and model service considerations, and a checklist of common pitfalls.
1. Background: The Real Engineering Challenge Behind a Full Disk
A full system disk on a dev machine, test machine, or edge node is a frequent failure with a wide blast radius. It is rarely caused by a single oversized file. More often, it is the result of several factors stacking up: log rotation that no longer works, accumulated build caches, bloated container image layers, temporary files that are never reclaimed, and database preallocated files that keep growing. As the disk approaches 100%, the first things to break are the ones that need to write: logs cannot be flushed so troubleshooting information is lost, database writes fail and raise exceptions, compilation and packaging stop midway, and services fail to start because they cannot create temporary files.
Traditional troubleshooting relies on manually walking into directories layer by layer and running statistics commands, then judging from experience what can be deleted. This process has three pain points. First, it is slow: when directories are deep and file counts are large, the statistics themselves take a long time. Second, it is error-prone: manual judgment easily mistakes files still held by running processes, or data the business actually needs, for garbage. Third, it is not reusable: every incident means going through the whole flow again. Handing this kind of task—clear goal, fixed steps, but highly repetitive—to an LLM to generate a script is an entry point with obvious payoff.
2. Why This Task Fits an LLM
Disk analysis and cleanup programs have a few characteristics that match LLM strengths well: clear input and output boundaries (scan a root path, output a usage ranking plus cleanup suggestions), logic that is mostly traversal and aggregation, low requirements for third-party dependencies, and verifiable results (reconcile the total against system tool output).
At the same time, the inherent risk of this task must be acknowledged: cleanup actions are irreversible. So the correct engineering posture is not “have the model write a deletion script and run it.” Instead, position the generated artifact as a tool that is analysis-first, cleanup-second, and read-only by default, with deletion designed as an option that must be explicitly enabled. The reason a one-line prompt mentioned in the original text worked on the first try is essentially that the requirement was specific enough and the scenario common enough that the model already had plenty of similar patterns to reuse. And the so-called “overly long thinking process” problem, in this kind of task, usually comes from a prompt that lacks constraint boundaries, leaving the model to guess at unstated premises.
3. Prompt Design: Making Implicit Constraints Explicit
A high-quality prompt should contain six elements: goal, runtime environment, input parameters, output format, safety constraints, and exception handling. Example:
Implement a command-line disk space analysis tool with the following requirements:1) Language and runtime: a scripting language, standard library only, no external dependencies;2) Input: a root path argument and a depth argument, read-only scanning by default;3) Output: list the top N directories and files by usage, largest first, annotated with modification time, size, and whether it is a symbolic link;4) Cleanup capability: disabled by default, executed only when an explicit confirmation argument is passed, and limited to whitelist patterns (such as temporary files with a specified suffix, or logs older than a retention period);5) Safety: do not follow symbolic links, do not cross file systems, skip and log permission errors, print the deletion list and require a second confirmation before deleting;6) Output a summary: total usage, estimated reclaimable space, and the number of skipped paths.
The more specific the constraints, the less the model has to fill in on its own, and both output length and rework rate go down. This is also the most effective way to control generation quality—cheaper in time than repeatedly asking follow-up questions after the fact.
4. Recommended Structure and Key Implementation of the Generated Code
A reliable analysis tool is usually split into four layers: traversal, aggregation, decision, and execution. The benefit of layering is that read-only analysis is decoupled from cleanup actions, so each can be tested separately.
import os, time, argparsedef human(n):for u in ("B","KB","MB","GB","TB"):if n < 1024: return f"{n:.1f}{u}"n /= 1024return f"{n:.1f}PB"def scan(root, max_depth=3, follow_links=False):stats, skipped = {}, 0root = os.path.abspath(root)for cur, dirs, files in os.walk(root, followlinks=follow_links, onerror=lambda e: None):depth = cur[len(root):].count(os.sep)if depth >= max_depth:dirs[:] = []total = 0for f in files:p = os.path.join(cur, f)try:if os.path.islink(p) and not follow_links:skipped += 1; continuetotal += os.path.getsize(p)except OSError:skipped += 1stats[cur] = stats.get(cur, 0) + totalreturn stats, skippeddef top_dirs(stats, n=20):return sorted(stats.items(), key=lambda x: x[1], reverse=True)[:n]if __name__ == "__main__":ap = argparse.ArgumentParser()ap.add_argument("root"); ap.add_argument("--depth", type=int, default=3)ap.add_argument("--top", type=int, default=20)a = ap.parse_args()t0 = time.time()s, sk = scan(a.root, a.depth)for p, size in top_dirs(s, a.top):print(f"{human(size):>10} {p}")print(f"Total {human(sum(s.values()))}, skipped {sk} items, elapsed {time.time()-t0:.1f}s")
A few details that are easy to overlook but affect reliability: not following symbolic links avoids double counting and out-of-bounds deletion; swallowing permission exceptions in the traversal callback and counting them keeps the scan from aborting on a single failure; depth truncation controls elapsed time; and aggregating results by accumulating per directory rather than taking single-file sizes is what reflects real usage.
5. Safety Boundaries: Cleanup Must Be “Off by Default”
Cleanup logic should follow the principles of least privilege and rollback capability: whitelist matching takes priority over blacklist; only files that are clearly expired (based on modification time and retention days) are processed; before deletion, output the list, total size, and file count and require confirmation; provide a dry-run mode that only prints without executing; for files held by running processes, give a hint rather than force deletion; and exclude critical paths (system directories, mount point roots, business data directories) outright.
def candidates(root, suffix, keep_days, now=None):now = now or time.time()for cur, _, files in os.walk(root):for f in files:if not f.endswith(suffix): continuep = os.path.join(cur, f)try:if now - os.path.getmtime(p) > keep_days*86400:yield p, os.path.getsize(p)except OSError:continue
6. Validation and Evaluation
Generated artifacts cannot go straight to production. Three validation steps are needed. First, reconciliation: the deviation between the tool’s total and the system-wide statistics should be within an acceptable range; a large deviation usually means missed or double counting. Second, dry run: build samples in a test directory—large files, expired logs, symbolic links, files without permissions—and check whether skipping and decision-making behave as expected. Third, canary rollout: run cleanup on non-critical nodes first, watch business metrics and log integrity, then gradually widen the scope. Recommended evaluation metrics to keep fixed: reclaimable space, scan time, number of skipped items, and number of misjudgments.
7. Runtime Environment and Model Service Selection
This kind of script has minimal runtime requirements and can run locally or on any reachable machine. If you use a cloud model service to generate the code, three general capabilities matter: stability of call latency, output completeness under long context, and rate limiting plus retry strategy. In engineering terms, wrap model calls in a client with timeouts and exponential backoff retries, and persist both prompts and generated results for reproducibility and auditing. If data egress is a concern, evaluate deploying open-weight models in your own environment, or use the general-purpose container platforms and inference services offered in the cloud, keeping the data path fully under your control.
8. Common Pitfalls Checklist
- A prompt that lacks runtime environment and dependency constraints, causing generated code to pull in unusable components;
- No limit on depth or on crossing file systems, making scan time uncontrollable;
- Deletion logic coupled with decision logic, so the read-only part cannot be tested on its own;
- Ignoring modification time and in-use checks, deleting files that are still in use;
- Inconsistent counting rules (whether hard links and sparse files are included), causing reconciliation to fail;
- Generating once and going live immediately, with no dry run or canary stage.
9. Summary
Handing a high-frequency operations problem like “the disk is full” to an LLM to generate a tool turns repetitive troubleshooting into a reusable asset. What really determines success is not the length of the model’s output, but the constraint quality of the prompt, the layered design of the generated code, and the safety boundaries around cleanup actions. Proceed in the order of “read-only analysis first, explicit opt-in for cleanup, validation and canary as a safety net,” and you can quickly get a stable, usable storage governance script running locally or in the cloud.
