Disk Space Analysis and Cleanup with LLM-Generated Python Tools
This article explains how to use AI coding assistants to build a disk space analysis and cleanup tool. It covers breaking capacity requirements into verifiable constraints, structuring prompts for stable output, a three-layer implementation with sample Python code, and the safety guardrails that cleanup tools require, including dry-run defaults, path validation, and audit logging. It also discusses performance tuning and the practical limits of model inference and API calls.
1. Background: What Engineering Teams Need When Disks Fill Up
A full system disk on a development machine, test server, or edge node is a routine operational problem. The typical symptoms are failed builds, logs that cannot be written, interrupted dependency downloads, and even services crashing because they cannot persist data. The traditional approach is to enter directories one level at a time, check their sizes manually, and delete caches and temporary files based on experience. This is slow and prone to accidental deletion.
Handing this task to an AI coding assistant can significantly shorten the time from “discovering the problem” to “having a usable script.” However, a reliable result depends on more than a vague instruction. The requirements must be broken down into verifiable engineering constraints.
2. Requirement Breakdown: Turning One Sentence into an Executable Spec
A qualified disk analysis and cleanup program should cover at least the following capabilities:
- Capacity overview: show the total, used, available, and percentage for each mount point.
- Drill-down analysis: recursively calculate directory sizes, with configurable depth and sorted output.
- Large file detection: find files above a threshold and output their paths and sizes.
- Cleanup execution: support both “dry-run” and “actual deletion” modes, reporting only by default.
- Safety guardrails: path allowlists, retention checks, confirmation before deletion, and operation logs.
Writing these constraints clearly makes the generated result far more predictable.
3. Prompt Design: The More Specific the Constraints, the More Stable the Output
A structured prompt following the pattern “role + goal + constraints + output format” is recommended, for example:
Write a command-line disk analysis and cleanup tool in Python with the following requirements:1. Use only the standard library and run cross-platform;2. Default to dry-run: print cleanup candidates only, do not delete;3. Support --depth to control recursion depth and --min-size to filter large files;4. Validate that the path is within allowed directories before deletion, and write an operation log;5. Output a mount point overview, Top N large directories, and Top N large files.
The key is to state “no deletion by default,” “path validation,” and “audit logging” as hard requirements, so the model does not produce high-risk default behavior.
4. Core Implementation and Sample Code
The design can be split into three layers: a collection layer for traversal and statistics, a decision layer for filtering and evaluation, and an execution layer for deletion and logging. Decoupling these layers makes them easier to test and replace individually.
import osfrom pathlib import Pathdef dir_size(root: Path, depth: int) -> list[tuple[str, int]]:result = []for cur, _, files in os.walk(root):rel = Path(cur).relative_to(root)if len(rel.parts) > depth:continuetotal = sum((Path(cur) / f).stat().st_size for f in filesif (Path(cur) / f).is_file())result.append((str(rel), total))return sorted(result, key=lambda x: x[1], reverse=True)def is_safe(target: Path, allow_roots: list[Path]) -> bool:resolved = target.resolve()return any(resolved.is_relative_to(r.resolve()) for r in allow_roots)
During the statistics phase, build an index first and then sort it to avoid repeated traversal. During the deletion phase, always resolve the path before comparing it against the allowlist, so that symlinks or relative paths cannot bypass validation.
5. Safety Guardrails: The First Principle of Cleanup Tools
Cleanup programs carry far more risk than analysis programs and must include multiple layers of protection:
- Default to dry-run; deletion happens only when an explicit parameter is passed.
- Combine a directory allowlist with a retention check, for example, cleaning only caches not accessed for more than N days.
- Print the list and require confirmation before deletion, and write key operations to a structured log.
- Hard-code rejection of system directories and mount point roots.
6. Performance and Engineering Optimizations
When directory levels are deep and file counts are large, traversal itself is the main cost. Strategies such as incremental scanning, result caching, and on-demand drill-down can help. Outputting the Top N results instead of the full set reduces terminal flooding and memory usage. For engineering maturity, add unit tests covering path validation and boundary depths, and connect logs to a common logging service for later auditing.
7. Practical Limits of Model Capability and the Call Path
AI coding assistants perform well on tasks like “generating a runnable script from one sentence,” especially when the prompt contains explicit constraints, which leads to more consistent output quality. It is worth recognizing objectively that overly long chains of thought slow down delivery, and the bandwidth and stability of the call path also affect the experience. If latency and predictability are critical, consider a self-hosted deployment, or use general-purpose model capabilities from a cloud platform with a stable inference service, and monitor call success rate and latency with alerting.
8. Conclusion
Disk cleanup may look simple, but it is a complete loop of “analyze, decide, execute, audit.” Only by specifying requirements, moving risk guardrails to the front, and accounting for call-path performance can AI coding assistants become a genuine productivity tool rather than a new source of risk.
