Disk Cleanup Automation with Large Language Models: A Practical Guide

    This article shows how to use LLM-driven coding tools to build a disk space analysis and cleanup program from a single natural-language prompt. It covers the key elements of an effective prompt, a four-stage pipeline architecture, safety-first design principles, validation and tuning steps, and optional scheduled automation with observability. The goal is to turn ad-hoc emergency scripts into reusable, well-tested operations tooling.

    1. Background: Emergency Response When the Disk Is Full

    A full disk on a development machine, test server, or local workstation is a frequent operational scenario in day-to-day engineering. Common causes include continuously growing build caches and dependency packages, accumulated container images and log files, local database copies and export files that are never archived, and temporary files that are never cleaned up. When available space approaches zero, builds, packaging, and database writes start failing one after another, making troubleshooting expensive and likely to disrupt delivery schedules.

    The traditional approach is to inspect directory sizes manually and delete files based on experience. This is inefficient and carries a risk of deleting the wrong files. With LLM-driven intelligent coding tools, you can describe the requirement in a single natural-language sentence and quickly generate a runnable disk space analysis and cleanup program. The core value of these tools is turning “operational experience” into “executable code,” shortening emergency response from half an hour to a few minutes.

    2. Requirements: Key Elements of a One-Sentence Prompt

    To get a usable program from the model in one pass, the prompt should not be just “clean up my disk.” It should include constraints and acceptance criteria. The recommended elements are:

    • Target platform and runtime: specify the operating system and runtime version;
    • Scan scope: specify the starting directory and excluded directories;
    • Output: aggregate size by directory and list the top space consumers;
    • Cleanup strategy: report first, delete later, with no automatic deletion by default;
    • Safety requirements: support a dry-run mode, require confirmation before deletion, and write an operation log.

    Example prompt (illustrative):

    1. Generate a command-line program that scans disk usage under a specified directory,
    2. aggregates size by first-level subdirectory, and outputs the top 20 in descending order;
    3. support --dry-run to report only without deleting;
    4. deletion operations require confirmation and must be written to a log file;
    5. exclude system directories and the current working directory.

    The more complete the elements, the closer the generated result is to production-ready, and the lower the cost of subsequent adjustments.

    3. Program Architecture: A Four-Stage Pipeline

    A robust disk analysis and cleanup program should be split into four stages, each with a single responsibility and easy to test:

    1. Collection stage: traverse the directory tree, accumulate file sizes, and handle symbolic links and permission errors;
    2. Aggregation stage: summarize by directory level and produce a sorted usage ranking;
    3. Decision stage: filter cleanup candidates based on thresholds and rules;
    4. Execution stage: perform deletion or archival under confirmation and logging safeguards.

    Illustrative structure code:

    1. def scan(root, exclude):
    2. stats = {}
    3. for dirpath, dirnames, filenames in os.walk(root):
    4. dirnames[:] = [d for d in dirnames if d not in exclude]
    5. size = sum(get_size(os.path.join(dirpath, f)) for f in filenames)
    6. stats[dirpath] = size
    7. return sorted(stats.items(), key=lambda x: x[1], reverse=True)
    8. def cleanup(candidates, dry_run=True):
    9. for path, size in candidates:
    10. if dry_run:
    11. print(f"[dry-run] will delete {path} ({human(size)})")
    12. continue
    13. if confirm(path):
    14. safe_remove(path)
    15. log_action(path, size)

    4. Safety Design: The First Principle of Cleanup Tools

    Cleanup programs carry far more risk than ordinary scripts, so safety must come before functionality:

    • Read-only by default: unless the deletion switch is explicitly enabled, the program only outputs a report;
    • Allowlist and denylist: explicitly exclude system directories, mount points, the current working directory, and version control directories;
    • Path validation: validate the real path before deletion, rejecting symlink escapes and out-of-bounds paths;
    • Confirmation: require manual confirmation for targets that exceed a size threshold or reside in critical directories;
    • Rollback capability: prefer moving to a quarantine directory over direct deletion, preserving a recovery window;
    • Audit log: record time, path, size, and operator for later traceability.

    5. From Generated to Usable: Validation and Tuning

    Code generated by the model usually needs three rounds of validation: first run syntax and static checks, then create large files in a test directory to verify aggregation results, and finally use dry-run mode to confirm the candidate list matches expectations. Tuning priorities include traversal performance for large directories (concurrent or incremental scanning), deduplicating counts for symbolic and hard links, graceful degradation when permissions are insufficient, and output readability (human-readable size units, progress bars, summary).

    6. Advanced Integration: Scheduled Tasks and Observability

    To upgrade a one-off script into a persistent capability, combine it with system-level scheduling to run automatic scans during daily off-peak hours and output reports; write results to a logging service, and use monitoring alerts to notify the responsible person when available space falls below a threshold. In container or cloud host environments, you can reuse object storage for cold data archival and use a container platform to run periodic tasks, forming a closed loop of “scan, report, archive, clean up.”

    7. An Objective Note on Model Capability and the Invocation Chain

    This kind of practice places three requirements on the model: stable instruction following, a reasoning process that is not overly verbose, and generated code that runs directly. Different models and different integration methods vary in response speed and stability, and network links, concurrency quotas, and platform load all affect the experience. The engineering response is to templatize prompts, write key logic as reusable local modules, and enforce a test and dry-run process on generated results, reducing dependence on a single invocation chain. For scenarios with data compliance and stable latency requirements, you can evaluate running self-hosted inference services and task scheduling on general cloud product capabilities from Baidu AI Cloud, such as a container platform, logging service, and monitoring alerts, for a more controllable runtime environment.

    8. Conclusion

    Generating a disk cleanup program from a single sentence is essentially expressing operational experience in a structured way to an intelligent coding tool. What really determines success is not the model itself, but the clarity of the requirements, the safety design of the program, and the validation process before release. Following the four-stage architecture and safety checklist in this article lets you quickly recover usable space when the disk is critical, and turn temporary scripts into reusable automated operations assets.