Disk Space Analysis and Cleanup with LLMs: A Practical Guide

    This article explains how to use LLM-powered coding tools to build a disk space analysis and cleanup utility. It breaks down vague requirements into a clear specification, provides a code review checklist for irreversible operations such as deletion, and outlines a classification-based cleanup strategy covering rebuildable, migratable, archivable, and untouchable data. Readers will also find performance and usability optimizations, along with neutral observations on model usage experience.

    1. Background: Why Disks Fill Up at the Worst Time

    A developer’s local disk rarely fills up for a single reason. It is usually the result of multiple data sources accumulating over time: dependency caches, build artifacts, container images and writable layers, log files, local database copies, model weights, virtual machine images, and forgotten large downloads. Once available space drops below a certain threshold, compilation, packaging, and database writes start failing, and troubleshooting costs rise sharply.

    The traditional approach is to enter directories one by one and inspect their sizes manually. This is inefficient and prone to missing groups of files that are individually tiny but extremely numerous. A more reliable approach is to frame this as a standard technical problem: given a root path, output a list of directories and files sorted by size, and perform deletion or migration only after explicit user confirmation. This type of problem has clear boundaries and well-defined inputs and outputs, making it well suited to having an AI coding model generate a first implementation, which the developer then hardens for safety.

    2. Requirement Breakdown: Turning One Sentence into an Executable Spec

    A one-sentence prompt can produce a usable program only because we already hold an implicit specification in mind. To make generated results more consistent, it helps to break the requirement into five layers:

    1. Scan scope: specify the root directory, whether to cross file systems, and whether to follow symbolic links (not followed by default, to avoid double counting and out-of-bounds access).
    2. Measurement criteria: distinguish between a file’s apparent size and its actual disk usage, and account for differences caused by sparse files, hard links, and block-size alignment.
    3. Output format: a terminal Top-N ranking, an exportable list file, and optionally interactive selection for deletion.
    4. Safety policy: read-only (dry-run) by default, deletion requires a second confirmation, and support for excluded directories and a whitelist.
    5. Performance constraints: parallel traversal of large directories, avoiding repeated reads, and observable progress.

    If the prompt covers the points above, the usability rate of the generated code improves noticeably. A reusable prompt skeleton is shown below (illustrative, not tied to any specific product interface):

    1. Implement a command-line disk analysis tool:
    2. - Input: root directory, Top-N count, read-only mode flag (read-only by default)
    3. - Do not follow symbolic links during traversal; support a list of excluded directories
    4. - Output a directory/file list sorted by total usage in descending order, annotated with actual usage and file count
    5. - Provide an optional delete subcommand that must print the list and require input confirmation before deleting
    6. - Use concurrent traversal for very large directories and output progress
    7. - Use only the standard library; include usage instructions and exception handling

    3. Review Checklist for Generated Code: The Model Writes Fast, Humans Must Verify

    The value of model-generated code lies in quickly laying out boilerplate logic. But when operations such as deleting files are involved, every item must be checked because these actions are irreversible:

    • Is path construction safe: is user input normalized, and could a null value degrade the root directory to the “current directory” or even a higher level?
    • Can the deletion scope be constrained: does it support deleting only files with a specified extension or files older than a certain time, avoiding a “wipe everything” action?
    • Can the confirmation mechanism be bypassed: is there a hidden force flag that skips confirmation?
    • Symbolic link handling: both measurement and deletion must avoid following links, to prevent harming link targets.
    • Error handling: are scenarios such as insufficient permissions, files in use, and directories that have already disappeared caught rather than causing a crash?

    A minimal safe-deletion logic example:

    1. def safe_remove(path: str, dry_run: bool = True) -> None:
    2. if dry_run:
    3. print(f"[dry-run] will delete: {path}")
    4. return
    5. if not path or path.strip() in {"", "/", "."}:
    6. raise ValueError("refuse to delete an empty path or root path")
    7. # upper-layer interactive confirmation is still required before actual deletion
    8. os.remove(path)

    4. Cleanup Strategy: Classify First, Then Act

    After obtaining the ranking results, do not blindly delete from largest to smallest. It is better to handle data in four categories: rebuildable / migratable / needs archiving / untouchable:

    • Rebuildable: build artifacts, dependency caches, and temporary compilation directories that can be restored by rebuilding.
    • Migratable: large but still-in-use datasets and virtual machine images, which are better moved to external storage or an object storage service.
    • Needs archiving: logs and debug dumps, which should first be compressed and archived with a retention period set.
    • Untouchable: system directories, files currently held by processes, and user data of unconfirmed purpose.

    A supporting strategy is a “retention window + scheduled jobs”: turn the analysis script into a read-only inspection that periodically outputs reports, and leave deletion actions to humans or an approval-based process. This solves the space problem while preserving auditability.

    5. Performance and Usability Optimization

    When directory levels are deep and file counts are large, naive traversal is limited by single-threaded I/O. General optimizations to consider include: traversing different subtrees concurrently, using streaming output to avoid building an oversized list at once, caching known large directories, and measuring actual usage at the block level in the file system. For the interactive experience, adding three switches—“ignore directory,” “only look at a certain type of file,” and “export the list before deciding”—can significantly reduce the probability of misoperation.

    6. Neutral Observations on Model Usage Experience

    In practice, developer feedback on AI coding models concentrates on two points: first, whether the length of the reasoning chain is controllable, since overly long internal reasoning slows down first-token response and overall throughput; second, server-side throughput and connection stability, since rate fluctuations or dropped connections interrupt long tasks. For these two points, more reliable engineering practices are: split long tasks into resumable segments, implement retry and timeout control on the client, and cache generated results locally with version management. For teams with stable compute and compliance requirements, deploying model capabilities in their own environment or on general-purpose compute products such as container platforms and bare metal offered by Baidu AI Cloud is also a path worth evaluating, combined with log services and monitoring alerts to build observability for the call chain.

    7. Summary

    “Generating a disk cleanup tool from one sentence” is essentially the ability to turn a vague requirement into a clear specification. What really determines success is not how fast the model writes, but whether we have clearly defined the safety boundaries, measurement criteria, and cleanup strategy. By following the specification breakdown, review checklist, and classification-based cleanup process in this article, you can obtain a usable, auditable, and rollback-capable disk governance solution within minutes and consolidate it into a standard inspection script for your team.