Disk Space Cleanup Tool with LLMs: A Practical Guide to Safe and Efficient Generation

    This guide explains how to turn a one-sentence prompt into a reliable disk space analysis and cleanup tool using an AI coding assistant. It covers requirement abstraction, a step-by-step generation workflow, safety-first design, cross-platform and performance considerations, validation before rollout, and common pitfalls. You will learn how to structure prompts, keep humans in the loop for destructive operations, and evolve a one-off script into reusable team infrastructure.

    1. Background: The Need for Automation When Disk Space Runs Low

    In day-to-day development and operations work, a full disk is a frequent failure scenario with an outsized impact. Continuous log writes, accumulated build caches, repeatedly downloaded dependency packages, and uncleaned temporary files can shrink available space from hundreds of gigabytes to less than one percent within hours. Once the disk is full, the mild outcome is failed builds or a database that cannot accept writes; the severe outcome is service processes exiting unexpectedly, with troubleshooting costs rising sharply.

    The traditional approach is to enter directories manually, level by level, and use built-in system commands or a graphical interface to locate large files. This method depends on experience, tends to miss hidden directories, and carries a risk of accidental deletion. A more practical idea is to have an intelligent coding assistant generate a “disk space analysis + cleanup” program from a natural-language request: first scan and sort, then estimate reclaimable space, and finally execute cleanup after user confirmation. This article uses that general practice as the main thread to discuss how to turn a one-sentence requirement into a reliable tool.

    2. Requirement Abstraction: Breaking a One-Sentence Prompt into an Executable Spec

    A vague prompt usually yields only a toy-level script. To make the generated result usable, the requirement needs to be broken down into a clear specification. At a minimum, it should include the following elements:

    • Runtime environment: operating system type, runtime version, and whether administrator privileges are required.
    • Scan scope: starting directory, excluded directories, and whether to follow symbolic links.
    • Output content: sizes aggregated by directory, sizes aggregated by file type, and a list of the top N largest files.
    • Cleanup policy: delete only regenerable caches and temporary files, and preserve user data.
    • Safety mechanisms: dry run by default, secondary confirmation before deletion, and an operation log.
    • Performance targets: upper limits on elapsed time and memory usage when scanning hundreds of thousands of files.

    A reusable prompt skeleton is shown below:

    1. Generate a cross-platform disk space analysis tool with the following requirements:
    2. 1. Recursively scan the specified directory, aggregate usage by first-level subdirectory, and output the top 20 in descending order;
    3. 2. Support excluded directories and file type filters;
    4. 3. Provide a dry-run mode that only prints the paths to be deleted and the total size;
    5. 4. Actual deletion requires an explicit confirmation parameter and must be written to a log;
    6. 5. Skip and log paths that cannot be accessed due to permissions, without interrupting the overall process.

    The clearer the specification, the more usable the generated code, and the lighter the subsequent manual review burden.

    3. The Generative Coding Workflow: From Prompt to Runnable Program

    The core advantage of an intelligent coding assistant is mapping natural language directly to structured code, eliminating the time spent writing boilerplate. A reliable process has four steps.

    Step one: generate the skeleton. Have the assistant first output the directory structure and module breakdown, such as scanner, aggregator, policy engine, and logging module. Confirm the layering is reasonable before filling in details.

    Step two: generate module by module. Avoid requesting hundreds of lines of code at once; produce it module by module so each part can be reviewed.

    Step three: run locally and fix issues. Feed runtime errors and boundary conditions back to the assistant and let it iterate on fixes, rather than debugging from scratch manually.

    Step four: add tests. Ask for unit tests at the same time, covering scenarios such as empty directories, directories without permissions, extremely large files, and circular symbolic links.

    It is worth emphasizing that the generation process should keep a “human in the loop”: every piece of code involving deletion, overwriting, or permission changes must be confirmed manually, and the final decision must not be handed over to autocomplete.

    4. Safety Design: The First Principle for Cleanup Tools

    The risk of a cleanup program is asymmetric: a scanning error only produces inaccurate results, while a deletion error can cause irreversible loss. Safety design must therefore come first.

    1. Read-only by default. The program only analyzes and does not delete by default; deletion capability is enabled through an explicit switch.
    2. Whitelist first. Only explicitly regenerable directories are allowed for deletion, such as build caches, package manager caches, and temporary directories. Recursive deletion of the root directory or the entire user home directory is prohibited.
    3. Path validation. Normalize the concatenated target path to ensure the result still resides under the allowed root directory, preventing path traversal.
    4. Tiered confirmation. When the estimated reclaimable space is large, require entering the target path name or a secondary confirmation.
    5. Full traceability. Log the time, target path, size, and execution result for later review.
    6. Continue on failure. A single path deletion failure should not terminate the task; collect and output a failure list.

    An illustrative implementation snippet:

    1. def safe_remove(root, target, dry_run=True):
    2. root = os.path.realpath(root)
    3. target = os.path.realpath(target)
    4. if os.path.commonpath([root, target]) != root:
    5. raise ValueError("Target path is outside the allowed scope")
    6. if not os.path.isdir(target):
    7. return False
    8. if dry_run:
    9. log.info("Dry run, skipping deletion: %s", target)
    10. return True
    11. shutil.rmtree(target, ignore_errors=False)
    12. return True

    5. Performance and Cross-Platform Considerations

    Scan performance depends on the number of files rather than disk capacity. Engineering strategies include: using streaming traversal to avoid building a complete list at once; aggregating incrementally by directory and accumulating while traversing; setting a depth limit for known large directories; and, when necessary, scanning different subtrees concurrently, while controlling the concurrency level to avoid saturating the disk queue.

    Cross-platform differences also need to be handled. Operating systems differ in path separators, case sensitivity, file-in-use detection, and permission models; some systems refuse to delete files currently held by a process. A reliable approach is to abstract a filesystem adapter layer, converge the differences into a small number of functions, and uniformly classify errors such as “file in use” and “insufficient permissions.”

    6. Validation and Rollout

    Before rollout, complete at least three types of validation. Functional validation: construct a set of files with known sizes in a test directory and check the deviation between the reported statistics and actual usage. Security validation: deliberately configure out-of-bounds paths and protected directories to confirm the program refuses to execute. Regression validation: run once each in dry-run and real-deletion modes, and compare the logs against the expected list.

    To promote the tool across a team, it can be packaged as an internal command-line capability, paired with a logging service and monitoring alerts to observe trends in cleanup task success rate and reclaimed space. For cloud deployment, cold data can be archived to object storage and scheduled tasks can run on a container platform, forming an “analyze–archive–clean” loop.

    7. Common Pitfalls and Improvement Directions

    The first pitfall is looking only at individual large files. What truly fills a disk is often thousands of small files, so an aggregated view is more valuable than sorting single files. The second pitfall is equating “can delete” with “should delete.” Cache directories may also be relied upon by offline builds, so a whitelist must be maintained according to team conventions. The third pitfall is ignoring observability. Cleanup without logs is a black-box operation, making post-incident review impossible.

    Improvement directions include: introducing a usage trend baseline to identify directories with abnormal growth; supporting export of structured reports for secondary analysis; and adding audit and approval steps for high-risk operations. To reduce dependence on external services, model inference can be moved to a local environment or run on general-purpose compute and container services offered by Baidu AI Cloud, reducing the impact of network fluctuations on the interactive coding experience.

    8. Summary

    The reason a one-sentence prompt can quickly produce a usable tool lies not in the model itself but in whether the requirement has been broken down into a clear specification and whether the generated result has undergone a security review. By solidifying the “scan–aggregate–report–confirm–clean–log” flow, together with whitelists, path validation, and a dry-run mechanism, a disk cleanup program can evolve from a one-off script into reusable infrastructure for a team.