Disk Space Analysis and Cleanup with LLM Assistance: A Practical Guide

    This article presents a practical workflow for diagnosing and resolving full disks on development machines, test servers, and edge nodes using LLM-assisted code generation. It covers turning a one-sentence prompt into an executable specification with a read-only default, four code review checkpoints for filesystem operations (path handling, symlinks and mounts, deletion semantics, and observability), a three-tier cleanup strategy, ways to control inference overhead and throughput bottlenecks, and validation steps to prevent recurrence.

    1. Background: A Full Disk Is a Chronic Failure

    When a development machine, test server, or edge node runs out of disk space, it is rarely a single event. It is usually the result of long-term accumulation. Common sources include build artifacts, dependency caches, container image layers, application logs, temporary export files, and local database backups.

    Once the space is exhausted, the first symptom is not the obvious “write failed” error. Instead, a chain reaction appears: logs can no longer be written to disk, so troubleshooting clues are lost; temporary directories become unwritable, so tasks are interrupted; and some services fail to start because they cannot create lock files.

    The goal, therefore, should not stop at “delete a few files to free up space.” It should be a repeatable process: quantify first, attribute second, clean up third, and prevent recurrence last. With an intelligent coding tool, the most repetitive and error-prone part of this process—writing the scripts—can be delegated to the model, while the human focuses on strategy decisions and risk control.

    2. Requirement Abstraction: Turning a One-Sentence Prompt into an Executable Specification

    The most valuable part of the original practice was getting a usable tool from a single natural-language description. To make the generated result stable and reliable, however, the prompt needs four kinds of information: the goal, the constraints, the output format, and the boundaries.

    A reusable template looks like this:

    1. Implement a command-line disk space analysis and cleanup helper with the following requirements:
    2. 1. Accept a target directory and a depth threshold, and output a list of directories/files sorted by usage;
    3. 2. Default to read-only analysis and do not perform any deletion;
    4. 3. Cleanup capability must be explicitly enabled and support a dry run (only print the paths that would be deleted and an estimate of the space freed);
    5. 4. Protect critical system directories, symbolic links, and mount points; recursive deletion is forbidden;
    6. 5. Output both a human-readable summary and a machine-parseable result.

    The key design here is “read-only by default.” Most accidental disk deletions happen because the tool has write permission by default and lacks a confirmation step. Writing safety into the requirements rather than patching it in afterward is a shared point of prompt engineering and requirements analysis.

    3. Reviewing Generated Code: Four Checkpoints

    Code produced by intelligent coding tools is usually well structured, but review cannot be skipped when filesystem operations are involved.

    The first checkpoint is path handling. Confirm that path concatenation consistently uses absolute path normalization, and that user input is validated, so that an empty variable cannot cause traversal to start from the root directory.

    The second checkpoint is links and mounts. The analysis tool should traverse without following symbolic links and should warn when crossing filesystem boundaries. Otherwise, the statistics will be inaccurate, and cleanup actions may damage other partitions.

    The third checkpoint is deletion semantics. An acceptable implementation collects a candidate set first and confirms it in one place, rather than deleting while traversing. A schematic safe skeleton is shown below:

    1. def collect_targets(root, min_size_mb=100):
    2. targets = []
    3. for dirpath, _, files in os.walk(root, followlinks=False):
    4. for name in files:
    5. p = os.path.join(dirpath, name)
    6. try:
    7. size = os.path.getsize(p)
    8. except OSError:
    9. continue
    10. if size >= min_size_mb * 1024 * 1024:
    11. targets.append((p, size))
    12. return sorted(targets, key=lambda x: -x[1])
    13. def preview(targets):
    14. total = 0
    15. for p, s in targets:
    16. print(f"{s/1048576:.1f} MB {p}")
    17. total += s
    18. print(f"Estimated reclaimable: {total/1073741824:.2f} GB")

    The fourth checkpoint is observability. The tool should output structured results so that it can be integrated with logging services or monitoring alerts, forming a closed loop of “space level - threshold - notification” instead of relying on manual investigation every time.

    4. Cleanup Strategy: Tiered Handling Instead of One-Size-Fits-All

    It is recommended to classify candidates into three tiers. Tier one is data that can be safely rebuilt, such as build caches, dependency download caches, and temporary export files; these can be cleaned directly. Tier two is data that requires confirmation, such as historical logs and artifacts from old versions; these should be handled with a retention policy, for example rolling retention by time with compressed archiving. Tier three is data that must never be handled automatically, such as business data directories, database files, and mounted external storage; only alerts and manual intervention are allowed.

    In containers and virtual environments, note that the usage of image layers and volumes is often not reflected in the apparent size of a single directory. In such cases, governance should be combined with the resource views of the container platform and the cleanup policies of the image registry, avoiding blind deletion of internal files on the host.

    5. Performance and Experience: Controlling Reasoning Overhead and Throughput Bottlenecks

    One often-overlooked point in practice is interaction efficiency. Some models perform lengthy internal reasoning before generating code, which slows the first-token response; meanwhile, the throughput and stability of the call path determine whether long-file generation will be interrupted. There are three engineering responses: first, state explicitly in the prompt “give the implementation and key notes directly, without lengthy analysis” to reduce unnecessary reasoning overhead; second, split large tasks into small steps, for example generating the analysis part first and the cleanup part only after validation passes; third, set timeouts and retries for the generation process and persist the output to disk, so that a mid-way failure does not force a restart from scratch.

    If there are higher requirements for data compliance and response latency, consider deploying the model capability in a private environment or accessing it through a general model service category in the cloud, so that data stays within its domain, while elastic compute handles peak loads.

    6. Validation and Recurrence Prevention

    After the tool is complete, be sure to rehearse in a temporary directory with large files first, verifying that the statistics match actual usage, that the dry run deletes nothing, and that the protection rules take effect. Then connect scheduled jobs and level alerts to turn one-off troubleshooting into routine governance.

    In summary, the value of a one-sentence prompt is not “letting the model write scripts for us,” but moving the analysis framework, safety boundaries, and validation criteria forward into the requirement description. Once read-only by default, tiered handling, and an observable closed loop are fixed in place, disk space problems change from reactive firefighting into measurable day-to-day operations metrics.