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

    This article explains how to use natural language prompts to generate disk space analysis and cleanup tools with coding LLMs. It covers a four-layer architecture (collection, aggregation, decision, and execution), three essential safety gates including allowlists, time-window checks, and dry-run mode, performance optimizations for large file volumes, and engineering practices for handling model API instability. Readers will learn how to build a reliable workflow that keeps risk controls ahead of any deletion action.

    1. Why Full Disks Are a Frequent Pain Point

    In local development, CI pipelines, and data processing workflows, running out of disk space is a common problem. Dependency caches, build artifacts, log files, container image layers, and model weight files can consume available capacity without anyone noticing. As free space approaches a critical threshold, compilation failures, database write errors, and service crashes start to appear, and troubleshooting them costs far more than routine maintenance would.

    The traditional approach is to enter directories manually and use built-in system commands to sort and locate large files. This works when there are only a few files, but with deep directory hierarchies and large file counts, manual inspection is slow and prone to accidental deletion. More importantly, developers often focus only on “what is taking up space” and overlook “which files can be safely deleted,” introducing the risk of data loss.

    2. Core Idea: Driving Code Generation with Natural Language

    Current mainstream AI coding tools already have strong code generation and engineering comprehension capabilities. A developer only needs to describe the goal in one sentence, for example, “analyze disk usage and generate a report of cleanable items,” and the model can output a complete script or program. Compared with lengthy chain-of-thought reasoning, short task-focused prompts often produce runnable results faster, which matters in urgent troubleshooting scenarios.

    It is worth emphasizing that the model produces a “candidate implementation,” not final production code. A sound workflow is to first have the model generate the scanning and classification logic, then have the developer add safety checks, logging, and rollback mechanisms, and finally run a trial in a small set of directories to verify behavior.

    3. Tool Design: A Four-Layer Architecture from Scanning to Cleanup

    A reliable disk governance tool should be split into four layers:

    1. Collection layer: Traverse the specified root directory and record each file’s path, size, modification time, owner, and permissions.
    2. Aggregation layer: Sum sizes by directory, output a Top N usage list, and identify large files, duplicate files, and long-unaccessed files.
    3. Decision layer: Use a rule engine to assign risk levels, separating items into “safe to clean,” “needs manual confirmation,” and “do not touch.”
    4. Execution layer: Delete or archive only low-risk items, keep a full audit trail, and support undo.

    Example code:

    1. import os
    2. from collections import defaultdict
    3. def scan(root, top_n=20):
    4. size_map = defaultdict(int)
    5. for dirpath, _, filenames in os.walk(root):
    6. for name in filenames:
    7. fp = os.path.join(dirpath, name)
    8. try:
    9. size_map[dirpath] += os.path.getsize(fp)
    10. except OSError:
    11. continue
    12. ranked = sorted(size_map.items(), key=lambda x: x[1], reverse=True)
    13. return ranked[:top_n]

    This code only handles collection and aggregation. The real value lies in how the decision layer defines safety boundaries.

    4. Safety Guardrails: Three Gates You Cannot Skip

    The first gate is an allowlist and denylist mechanism. System directories, database data directories, and files currently held by running processes must be explicitly excluded. The second gate is time-window and access-frequency checks: long-unaccessed caches can be cleaned first, while recently modified files require caution. The third gate is manual confirmation and dry-run mode, which by default only outputs a list of items to clean without performing real deletion.

    In addition, all deletion actions should first move files to a quarantine directory with a configurable rollback window, avoiding irreversible loss from mistakes.

    5. Performance and Usability Optimization

    With millions of files, single-threaded traversal becomes a bottleneck. Sharded scanning, incremental comparison, and result caching can help: persist the previous scan results and recompute only the changed parts. Long-running operations should run as background tasks, with progress tracked through logging and monitoring alerts so the interactive terminal is not blocked.

    On the interaction side, the tool should support filtering by directory, file type, and time range, and produce readable reports such as “a cache directory accounts for 42%, cleanup recommended.”

    6. Cloud Coordination: Extending Local Analysis

    When the local disk cannot handle the analysis workload, cold data can be archived to object storage, large-file scanning tasks can run elastically on a container platform, and a message queue can decouple task scheduling. General cloud product categories offered by Baidu AI Cloud, such as object storage, container platforms, logging services, and monitoring alerts, can serve as the backend for such tools, helping developers turn a one-off script into reusable governance capability.

    7. Engineering Advice on Model API Stability

    In practice, model services may see reduced throughput or dropped connections during peak hours. Three things should be done: set reasonable timeouts with exponential backoff retries; cache prompts and results to reduce repeated calls; and prepare a local fallback so the troubleshooting flow is not blocked by an external dependency. If conditions allow, deploying a lightweight model locally can significantly reduce latency and improve controllability.

    8. Summary

    The essence of disk space governance is closing the loop of “discover, decide, execute, and review.” By using a coding model to quickly generate skeleton code and layering on strict safety guardrails and cloud coordination, developers can obtain a usable tool within minutes. What matters is not how powerful the model is, but whether the process design keeps risk controls ahead of the deletion action.