Disk Space Analysis and Automated Cleanup with LLMs: A Practical Guide

    This article walks through building a reliable disk space analysis and cleanup tool with help from code-generating LLMs. It covers how to turn a one-line request into an executable specification, the four-layer design (traversal and aggregation, scoring, execution, and observability), key safety rules such as dry-run defaults and path whitelists, prompt and latency considerations, API reliability fallbacks, and the test cases to cover before rollout.

    1. Background: The First Response When Capacity Runs Low

    A full system disk on a development machine, build server, or test environment is a frequent and high-impact failure in day-to-day operations. Typical symptoms include build jobs failing because they cannot write temporary files, interrupted log writes that leave troubleshooting information missing, dependency downloads and cache directories that keep growing, and container runtimes unable to create new instances due to lack of space. At this point, the first response is not “delete something immediately,” but to establish a trustworthy understanding of space usage first, and then perform reclamation within a controlled scope.

    The traditional approach relies on manually entering directories one level at a time to inspect usage. It is inefficient and prone to missing special cases such as mount points, sparse files, and hard links. Handing this kind of task to an intelligent coding tool with code generation capabilities can produce a structured analysis script within minutes, turning “guesswork” into “measurement.”

    2. Requirement Breakdown: Turning a One-Line Request into an Executable Spec

    A one-line prompt like “write me a disk space analysis and cleanup program” works because the task itself has clear boundaries and well-defined inputs and outputs. To make the generated result stable and usable, it helps to fill in the following elements in the prompt:

    • Runtime environment: operating system type, target paths, and whether cross-platform support is needed.
    • Analysis goals: usage aggregated by first-/second-level directories, Top N rankings, large file location, and a time dimension (such as files not accessed for a long time).
    • Cleanup strategy: whitelist protection, minimum file age threshold, dry-run first, and confirmation before deletion.
    • Output format: terminal tables, structured report files, or machine-readable formats (such as JSON/CSV) for later integration with monitoring and alerting.
    • Failure handling: fallback behavior for insufficient permissions, symbolic link loops, and files in use.

    A reusable prompt skeleton example:

    1. Goal: Analyze and safely clean up a specified disk directory.
    2. Constraints:
    3. 1) Default to dry-run; only output the deletion candidate list and estimated space to be freed;
    4. 2) Protect system and configuration directories; normalize paths before prefix matching;
    5. 3) Exclude files smaller than the threshold or accessed within the last N days from candidates;
    6. 4) Skip and log permission errors without interrupting the overall flow;
    7. 5) Output the Top 20 directories by usage plus a machine-readable list.

    3. Key Design Points for Generated Code

    Regardless of the implementation language, a reliable disk governance program should contain four layers that are decoupled from each other for easy unit testing and replacement.

    1) Traversal and aggregation layer. The core is to avoid double counting and loops. A common mistake is naive recursion that repeatedly follows symbolic links, causing runtime to spike or even stack overflow. In practice, record visited device numbers and inodes (or use an equivalent mechanism) for deduplication, and explicitly decide whether to cross device boundaries at mount points.

    1. import os
    2. def walk_once(root, seen=None):
    3. seen = set() if seen is None else seen
    4. for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
    5. for name in filenames:
    6. path = os.path.join(dirpath, name)
    7. try:
    8. st = os.stat(path)
    9. except OSError:
    10. continue
    11. key = (st.st_dev, st.st_ino)
    12. if key in seen:
    13. continue
    14. seen.add(key)
    15. yield path, st.st_size

    2) Decision and scoring layer. Combine “usage size,” “access time,” and “path risk level” into a candidate set, where the risk level is determined by a path prefix whitelist. This layer should be completely side-effect free and is the focus of unit testing.

    3) Execution layer. Separate deletion actions from decision logic. Before deleting, re-validate that the normalized path is still within the allowed scope, preventing path concatenation from being bypassed by crafted input.

    4) Observability layer. Output structured results so they can integrate with common cloud capabilities such as logging services and monitoring alerts, forming a closed loop of “discover—reclaim—review.”

    4. Reasoning Chain and Response Efficiency: Don’t Let “Thinking Too Long” Cancel Out the Gains

    These tasks are latency-sensitive, and users expect output within seconds to minutes. Some models perform very long internal reasoning chains before responding, showing up as long periods with no output and significantly higher token consumption, which also drives up costs in pay-as-you-go scenarios. In contrast, code generation tasks usually have clear structure and mature patterns, and a moderate reasoning budget is enough to obtain high-quality results.

    The practical recommendation is to explicitly specify in the prompt “give the key solution points first, then the complete code, and finally the verification steps,” compressing long-chain thinking into a short, reviewable list. Also split complex requirements into multiple rounds of small tasks to avoid piling up too many constraints at once and causing repeated rework.

    5. Interface Stability and Engineering Fallbacks

    When calling model capabilities through external interfaces, throughput fluctuations and connection interruptions are variables that must be considered. Production-grade fallbacks include: setting reasonable timeouts and retry limits on the client, using exponential backoff, enabling streaming reception for long outputs to reduce the loss from a single failure, and caching generated code and prompt templates locally. If latency and controllability requirements are extremely high, you can evaluate deploying open-weight models in your own environment, but you must also plan for compute resources, concurrency capacity, and version upgrade paths, rather than looking only at single-inference speed.

    6. Safety Red Lines: Four Rules for Cleanup Programs

    1. Dry-run by default; real deletion requires an explicit switch.
    2. Path whitelists take priority over blacklists; normalize before matching.
    3. Minimum age threshold to avoid accidentally deleting temporary files that are being written.
    4. Full audit trail; output an auditable list that supports rollback by list or manual review.

    7. Verification and Rollout

    Before going live, cover at least four types of cases: empty directories, very large directories, directories with symbolic link loops, and permission-restricted directories. Validation metrics include the error between total usage statistics and actual disk usage, execution time, and the number of false judgments. After rollout, it is recommended to run the analysis part on a low-frequency schedule, keep the cleanup part manually triggered, and gradually adjust thresholds based on reports.

    8. Conclusion

    A one-line prompt can yield a usable tool because the requirement is correctly structured and the pattern-based capabilities of generative models on coding tasks are fully leveraged. By focusing on prompt constraints, layered design, safety fallbacks, and observability, disk governance can evolve from “ad-hoc firefighting” into a “reusable routine capability.”