Disk Space Analysis and Cleanup with LLMs: A Practical Guide

    This article presents a practical approach to using large language models (LLMs) to generate disk space analysis and cleanup tools. It covers how to turn a one-line prompt into an executable specification, a four-stage design of scanning, aggregation, reporting, and controlled deletion, and the safety boundaries required for high-risk cleanup operations, including read-only defaults, confirmation prompts, and protected-path whitelists. It also discusses controlling reasoning length, retry and rate-limit handling when calling model APIs, and local deployment for sensitive data, showing how to turn an emergency response into a reusable engineering capability.

    1. Background: Emergency Response When the Disk Is Full

    In development, testing, and data analysis environments, running out of disk space unexpectedly is a frequent failure. Failed log rotation, accumulated build caches, uncleaned temporary files, and bloated container image layers can all exhaust available capacity in a short time. Once the root partition is full, the consequences range from failed builds and services that cannot write, to databases that cannot flush to disk and processes that exit unexpectedly.

    Traditional troubleshooting relies on manually entering directories one level at a time, running capacity statistics commands, and then judging from experience which files can be deleted. This process involves many steps, is prone to accidental deletion, and comes with heavy time pressure in urgent situations. In such moments, using an AI coding tool to describe the goal in a single natural-language sentence and having the model directly produce a “disk space analysis + cleanup” program is a worthwhile engineering practice.

    It is worth emphasizing that this article does not evaluate any specific model or platform. Instead, it abstracts the original experience into a general technical question: how to use an LLM to quickly generate a safe, controllable, and reusable disk governance tool.

    2. Requirement Breakdown: Turning a One-Line Prompt into an Executable Specification

    To get high-quality code from a model, the prompt cannot be just “write me a cleanup program”; it should include constraints. A recommended prompt structure is:

    • Goal: Scan a specified directory and output the Top N entries in descending order of space usage;
    • Scope: Support excluding critical system directories to avoid collateral damage;
    • Safety: Analyze only by default; deletion requires explicit confirmation;
    • Output: Terminal table plus an optional JSON report;
    • Runtime environment: Cross-platform first, with as few dependencies as possible.

    Example prompt (illustrative):

    1. Write a disk space analysis tool:
    2. 1. Recursively calculate the usage of each subdirectory under a given root directory;
    3. 2. Display the top 20 items in descending order of size, with human-readable units;
    4. 3. Default to dry-run; delete only when --delete is passed and a second confirmation is given;
    5. 4. Exclude system directories such as /proc and /sys;
    6. 5. Support output to both the terminal and a JSON file.

    Such a specification-style description can significantly reduce the model’s “overthinking” and repeated rewrites, making the output closer to usable code.

    3. Core Implementation: A Four-Stage Design of Scan, Aggregate, Present, and Clean Up

    A reliable disk analysis program is typically divided into four layers:

    1. Traversal layer: Recursively read directory entries and measure file and directory usage;
    2. Aggregation layer: Summarize subdirectory sizes bottom-up to avoid double counting;
    3. Presentation layer: Sort, format units, and generate reports;
    4. Action layer: Perform deletion under explicit authorization and record an audit log.

    Illustrative core logic (pseudocode):

    1. def scan(path, exclude):
    2. total = 0
    3. for entry in os.scandir(path):
    4. if entry.path in exclude:
    5. continue
    6. if entry.is_file():
    7. total += entry.stat().st_size
    8. else:
    9. total += scan(entry.path, exclude)
    10. return total
    11. def human(n):
    12. for unit in ["B","KB","MB","GB","TB"]:
    13. if n < 1024: return f"{n:.1f}{unit}"
    14. n /= 1024

    The key points are: hard links and symbolic links must be handled separately, otherwise the statistics will be duplicated or go out of bounds; permission errors must be caught and skipped to ensure the scan is not interrupted.

    4. Safety Boundaries: Cleanup Capability Must Be “Off by Default”

    Disk cleanup is a high-risk operation. Engineering practice should follow three iron rules:

    • Read-only by default: Never delete without explicit parameters;
    • Second confirmation: Print the target list before deletion and require input confirmation;
    • Whitelist protection: Hard-code protection for system directories, mount points, and database data directories.

    It is recommended to maintain a protection list in the program:

    1. PROTECTED = {"/", "/boot", "/etc", "/usr", "/var/lib"}

    At the same time, deletion actions should be written to a log recording the time, path, size, and operator, for later traceability. This way, even if the model-generated code has defects, it will not cause irreversible loss.

    5. Performance and Experience: The Engineering Value of Controlling “Reasoning Length”

    The original experience mentions a common pain point: some models have overly long reasoning chains in coding tasks, leading to slow responses and high context consumption. From an engineering perspective, this is not purely a model problem; rather, unclear task specifications amplify uncertainty. Improvement measures include:

    • Specify input and output formats in the prompt to reduce ambiguity;
    • Provide boundary conditions all at once to avoid multiple rounds of rework;
    • Require generated code to be “single-file, few dependencies, dry-run capable”;
    • Split large tasks into three small requests: scanning, reporting, and cleanup.

    These practices can significantly reduce ineffective reasoning and make the interaction pace more controllable.

    6. API-Side Stability: Rate, Stream Interruption, and Retry Strategies

    Even if the code is generated correctly, calling an LLM service may still encounter reduced throughput or connection interruptions. General mitigation strategies are:

    • Streaming output + timeout control: Avoid long periods of no response;
    • Exponential backoff retries: Back off about 3 times for retryable errors;
    • Cache prompts and results locally: Do not repeat requests for the same task;
    • Fallback plan: Keep a manual fallback version of critical scripts.

    These are common engineering practices when calling intelligent services, regardless of the specific vendor.

    7. Local Deployment: An Inevitable Choice for Data-Sensitive Scenarios

    When disk contents involve sensitive data, placing the code generation step in a local inference environment is a more prudent direction. The advantages of local deployment are that data does not leave the domain, latency is controllable, and it can run offline; the challenges lie in compute cost and model size. In practice, a combination of “a small-parameter model for code completion and a rule engine for validation” can balance efficiency and security.

    8. Summary

    A full disk is not scary; what is scary is lacking a reusable remediation tool. By using specification-style prompts to guide an AI coding tool to generate a four-stage program of “scan—aggregate—present—controlled cleanup,” combined with read-only defaults, whitelist protection, and audit logs, an emergency troubleshooting session can be turned into a long-term capability. At the same time, controlling reasoning length and improving retry and localization strategies can keep the entire workflow running stably in real production environments.