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

    This article presents a reusable engineering approach to using general-purpose large language models (LLMs) to turn a one-sentence requirement into a working disk space analysis and cleanup tool. It covers what a good prompt should include, a review checklist to run before executing generated code, engineering constraints for safe deletion, performance and stability considerations on the model service side, and how to turn one-off scripts into team standards. The focus is on default dry-run behavior, logging and rollback, exclusion whitelists, and observability to reclaim space quickly without risking data loss.

    1. Background: The “Golden Ten Minutes” After a Disk Fills Up

    A full system disk on a development machine, test machine, or edge node is a frequent failure scenario in engineering practice. Common triggers include continuously growing build caches and dependency packages, container images and log files that are never rotated, large temporary files produced during debugging, and database export files that are not archived in time. Once a disk approaches full capacity, it can directly cause write failures, truncated logs, and services that fail to start, leaving a very narrow window for troubleshooting.

    The traditional approach relies on manually navigating directories layer by layer, checking large files by hand, and then deleting them carefully. This process is both slow and prone to accidental deletion. In recent years, general-purpose LLMs with code generation capabilities can convert a “one-sentence requirement” directly into a runnable disk space analysis and cleanup program, significantly compressing the time from discovering the problem to producing a tool. This article uses that practice as its main thread and provides a reusable, engineering-oriented method.

    2. Requirements: What a One-Sentence Prompt Should Include

    The effectiveness of natural-language-driven code generation depends heavily on how complete the requirement description is. Overly vague prompts tend to produce uncontrollable implementations. It is recommended to cover at least the following elements:

    • Runtime environment and language: specify the operating system and runtime version to avoid generating incompatible system calls.
    • Scan scope: specify the starting directory, whether to cross mount points, and whether to follow symbolic links.
    • Sorting and aggregation rules: sort by file usage while aggregating by directory, making it easier to locate the “big items.”
    • Output format: terminal table, structured file, or both.
    • Cleanup strategy: report only, require secondary confirmation, or execute automatically; whether excluded directories are supported.
    • Safety constraints: prohibit touching critical system paths, and require a trace to be left before deletion.

    Example prompt (illustrative):

    1. Write a disk space analysis and cleanup command-line program for a general Linux environment:
    2. 1. Recursively calculate usage from a specified root directory, aggregate by directory, and output the top 30 items in descending order by size;
    3. 2. Support --dry-run, which only prints the candidate files to be deleted and the total reclaimable space;
    4. 3. Deletion operations require secondary confirmation and are written to a local log recording the time, path, and size;
    5. 4. Exclude critical system directories and version control metadata of the current working directory by default;
    6. 5. Do not depend on any third-party proprietary services; use only the standard library.

    3. Review Checklist for Generated Code: Read First, Then Run

    Generated results are not “ready to use out of the box.” Before running, it is recommended to confirm the following items one by one:

    1. Whether path handling is sound: whether user input is normalized and boundary-checked, and whether relative path ambiguity is avoided.
    2. Whether deletion decisions are conservative: whether only clearly matched candidates are deleted, and whether a whitelist mechanism is retained.
    3. Whether a dry-run capability exists: whether dry-run is the default behavior, and whether real deletion requires an explicit switch.
    4. Whether logging is sufficient: whether it can reconstruct “what was deleted, when it was deleted, and how much was freed.”
    5. Whether exception handling is complete: whether scenarios such as insufficient permissions, files in use, and directories changing during scanning are caught.
    6. Whether resource usage is controllable: whether scanning large directories will occupy memory for a long time, and whether streaming processing is needed.

    Illustrative core statistics logic (pseudocode):

    1. def walk_and_sum(root, exclude):
    2. total = 0
    3. for dirpath, dirnames, filenames in os.walk(root):
    4. dirnames[:] = [d for d in dirnames if not excluded(dirpath, d, exclude)]
    5. for name in filenames:
    6. path = os.path.join(dirpath, name)
    7. try:
    8. total += os.path.getsize(path)
    9. except OSError:
    10. continue
    11. return total

    4. Engineering Constraints for Safe Cleanup: Caging the “Drop the Database” Risk

    The biggest risk of automated cleanup is accidental deletion. Engineering practice should adhere to the principle of “no deletion by default, deletion only when explicit, leave a trace before deletion, and be rollback-capable”:

    • Default dry-run: the first run only outputs the candidate list and total reclaimable space, and is executed only after human confirmation.
    • Tiered confirmation: apply different confirmation strengths to system directories, user data directories, and build caches.
    • Exclusion list: include version control metadata, logs being written, database files, and so on in the protection scope.
    • Time window protection: files accessed within a recent period are excluded from cleanup candidates by default.
    • Operation tracing and rollback: before deletion, files can first be moved to a quarantine directory or archive storage, and thoroughly cleaned up only after confirming no anomalies.
    • Quotas and rate limiting: control concurrency during bulk deletion to avoid I/O jitter affecting other services on the same machine.

    5. Performance and Stability: Don’t Ignore Variables on the Model Service Side

    What is often underestimated in practice is the stability of the generation and invocation pipeline. Some developers report that responses are fast when the model is used with a free quota, while output speed drops noticeably when accessed through certain intelligent coding tools, and connection interruptions even occur. Such phenomena are usually related to inference resource scheduling, concurrency quotas, network links, and client retry strategies, and are variables that result from the combined effect of the service side and the engineering side.

    Ways to respond include:

    • Decouple “generation” from “execution”: it is acceptable for the generation stage to be a bit slower, but the execution stage must be controllable and auditable.
    • Set reasonable timeouts and resumable breakpoints for long outputs to avoid starting over from scratch after a single failure.
    • Accumulate repetitive tasks into local script templates to reduce dependence on the online generation pipeline.
    • Pay attention to observability: record invocation duration and failure rate to help determine whether the bottleneck is in the network or on the server side.

    6. Turning the Capability into Team Standards

    One-off firefighting tools should gradually be solidified into team assets:

    • Establish “disk health” inspections: periodically output usage trends to provide early warning rather than firefighting after the fact.
    • Bring cleanup scripts into code review and version control, with clear maintainers and change records.
    • Define tiered handling plans: cache-type data can be cleaned automatically, while data-type data must be confirmed manually.
    • Combine monitoring alerts and log services to set threshold reminders for disk usage.
    • Establish boundaries for the use of generative tools: operations involving deletion or permission changes must be reviewed by a person.

    7. Conclusion

    Using natural language to quickly generate a disk analysis and cleanup program is essentially compressing “requirement expression, code generation, human review, and safe execution” into a short workflow. What truly determines success or failure is not generation speed, but the clarity of the requirement description, the rigor of the review checklist, and the conservativeness of the deletion strategy. By solidifying default dry-run, trace-and-rollback, exclusion whitelists, and observability, supplemented by reasonable expectations for latency and stability on the model service side, you can reclaim space quickly and steadily when the disk is in critical condition while holding the bottom line of data security.