AI-Assisted Programming in Practice: Designing a Disk Analysis and Safe Cleanup Tool

    This article walks through the design of a disk analysis and cleanup tool built with AI-assisted programming. It covers how to turn a one-line request into verifiable layered requirements (analysis, decision, execution), why disk usage statistics are more complex than summing file sizes, how to implement scanning with resource limits and explainability, how to design a controlled cleanup workflow instead of a raw delete button, how to measure the real efficiency of AI code generation, how to handle unstable remote model calls, the trade-offs of local deployment, and a three-phase testing strategy for high-risk filesystem tools.

    1. From a Full Disk to an Engineering Problem: Code Generation Is Only the Starting Point

    When a roughly one-terabyte disk is nearly full, users typically have one straightforward demand: find out what is consuming the space and free some of it quickly. AI-assisted programming can turn that demand into a working prototype—for example, scanning directories, aggregating file sizes, listing large files, and producing a candidate cleanup list.

    But there is a clear gap between “it runs” and “it is safe to use.” A disk tool touches the filesystem directly, and a single mistake in directory traversal, link handling, or deletion logic can cause data loss. The real challenge of this kind of task is not making the model write deletion logic as fast as possible, but making it generate a reviewable, verifiable, safe-by-default implementation under explicit constraints.

    When evaluating AI-assisted programming capability, we should not only look at whether the response is fluent or the code is long. What matters more is whether the program correctly understands the space-accounting semantics, separates analysis from deletion, handles insufficient permissions and file changes, and preserves enough information for troubleshooting when errors occur.

    2. Turning a One-Line Request into an Acceptable Task

    “Write a disk cleanup program in one line” is fine for starting exploration, but not as a final development specification. When the description is too broad, the generated program may infer its own cleanup rules—for example, treating files not modified for a long time as useless, or treating all temporary directories as deletable regions.

    A more reasonable approach is to split the requirement into three layers.

    2.1 Analysis Layer: Answering Where the Space Went

    The analysis layer only reads the filesystem and provides the following results:

    • Space usage of each subdirectory under a given directory;
    • A list of large files sorted by size;
    • Logical size aggregated by file type;
    • Paths that failed to scan, lacked permission, or were skipped;
    • Number of files processed, cumulative size, and scan progress.

    This layer should not depend on deletion permissions, nor should it request elevated privileges by default for convenience. Even if no cleanup is ever performed, the analysis report should deliver value on its own.

    2.2 Decision Layer: Explaining Why Something Can Be Considered for Cleanup

    The decision layer generates candidates, not deletions. Every candidate should carry an explicit reason, such as “located in a user-specified cache directory,” “older than the user-configured retention period,” or “belongs to intermediate export files the user explicitly allowed to be cleaned.”

    File size, extension, and modification time can only serve as filtering conditions; they cannot by themselves prove a file has no value. A large file untouched for years may be exactly the archive that needs long-term retention.

    2.3 Execution Layer: Only Performing Confirmed Operations

    The execution layer receives a confirmed list, re-checks the state of each target, executes item by item, and records the results. A file discovered during analysis may have been modified, moved, or replaced before confirmation, so an old report cannot be treated as current fact.

    This layered design avoids the dangerous pattern of “found a large file, so delete it on the spot,” and makes it easier to incrementally verify model-generated code.

    3. Why Disk Statistics Are More Complex Than Adding Up File Sizes

    Disk space analysis looks like nothing more than traversing directories and summing sizes, but it actually involves several different accounting semantics.

    3.1 Logical Size Is Not Actual Usage

    Logical size is the length a file presents to applications; actual usage depends on how the filesystem allocates storage. A sparse file may have a very large logical length while occupying only a small amount of real space. Conversely, large numbers of small files may occupy more space than their total content due to allocation units and metadata overhead.

    Therefore, reports should clearly state which accounting semantics are used. When the runtime environment reliably provides the relevant information, logical size and allocated space can be shown separately; when it cannot, the limitation should be stated rather than mixing the two together.

    3.2 Multiple Paths Do Not Necessarily Mean Multiple Copies of Data

    Hard links can make different paths point to the same underlying file data. Summing directly by path can overestimate actual usage. When unique-file accounting is needed, deduplication should use the file identifier together with device information, where the system supports it.

    At the same time, showing “visible file size by directory” and counting “unique data usage” are different requirements. The report should state which approach is used, so users do not assume that deleting a path will necessarily reclaim the corresponding amount of space.

    Not following symbolic links by default usually makes scan boundaries easier to control and reduces the risk of traversal loops. Whether to cross filesystems or mount points should also be an explicit user choice—otherwise a local directory scan may wander into external storage and suddenly take far longer.

    Insufficient permissions should not terminate the entire task. The program can record failed paths and continue with other directories, but the report must indicate that “results are incomplete” instead of packaging a partial scan as a complete statistic.

    4. Scan Implementation: Prioritize Resource Boundaries and Explainability

    With large numbers of files, the dominant cost usually comes from directory access and reading file metadata, not from arithmetic. The design should avoid unnecessary repeated access.

    Streaming scans are recommended: update the aggregate value of the corresponding directory as soon as a file is visited. If you only need to display the top N largest files, maintain a bounded candidate set rather than loading all file information into memory and sorting it afterward.

    The following is an illustrative flow, not runnable code:

    1. Initialize directory aggregates, candidate set, and error records
    2. Traverse the user-specified root directory:
    3. Check whether the allowed scan boundary would be crossed
    4. Skip links or special files according to policy
    5. Attempt to read file metadata
    6. If reading fails:
    7. Record the path and failure reason
    8. Continue with the next item
    9. Update directory statistics
    10. Update the large-file candidate set
    11. Periodically output scan progress
    12. Generate the report:
    13. State the accounting semantics
    14. Show directory usage and large files
    15. List skipped items and error counts
    16. Do not perform any deletion

    Concurrent scanning should also be used cautiously. More concurrency may improve throughput in some storage environments, but it can also cause access contention, increase system load, or even slow down other applications. Establish a single-threaded baseline first, then decide whether to add concurrency based on actual measurements, rather than assuming more threads are always faster.

    5. Safe Cleanup: From a “Delete Button” to a Controlled Workflow

    Cleanup functionality should be designed around “previewable, explainable, constrained, and traceable.”

    5.1 Preview by Default

    The first run should output the proposed action list, including target paths, filtering reasons, file sizes, and the planned operation. Without explicit user confirmation, no destructive action is performed.

    If a candidate directory contains important data, the user should be able to exclude it even when it meets the time and size conditions. Exclusion rules must be visible in the report so their effect can be verified.

    5.2 Use an Allowlist to Limit Scope

    Compared with trying to enumerate every path that must not be deleted, it is safer to restrict cleanup to an allowlist of directories and add extra protection for critical system directories. Candidates must also pass path boundary checks—membership in an allowed directory cannot be determined by string prefix matching alone.

    Be extra careful with operations on the cleanup directory itself. The directory may contain new files that did not exist during the scan, and recursive deletion would widen the scope of the operation. Prefer processing explicitly listed files.

    5.3 Re-verify Before Execution

    There is a time gap between scanning and deletion. Before execution, verify file identity, type, and necessary state; if anything has changed, skip the item and require re-analysis. In environments with higher security requirements, use the more reliable operation mechanisms supported by the system to reduce race conditions between checking and executing.

    5.4 Quarantine Is Not the Same as Freeing Space

    Moving files to a quarantine directory on the same filesystem lowers the difficulty of recovering from mistakes, but it usually does not free disk space immediately. Reclaiming capacity on the original disk through quarantine may involve transferring data to another storage device, followed by verifying the copy results and defining an explicit retention policy.

    Therefore, “recoverable” and “immediately frees space” sometimes involve a trade-off, and the interface and reports must say so—never promise that both come naturally together.

    6. How to Measure the Efficiency of AI-Assisted Programming

    Generation speed affects the user experience, but output volume per second is not the only metric. The total time of a code generation task can be broken down into request waiting, time to first output, sustained generation, and the subsequent review and correction time.

    If a model produces code quickly but misses safety boundaries, developers may spend more time reworking it. Conversely, a shorter implementation with clear structure and complete tests is often easier to put into production.

    It is recommended to evaluate along these dimensions:

    • Correctness: Do the statistics conform to the stated accounting semantics?
    • Safety: Is it read-only by default, and do dangerous operations require confirmation?
    • Completeness: Does it handle insufficient permissions, path changes, and interruptions?
    • Maintainability: Are scanning, rule evaluation, execution, and presentation decoupled?
    • Delivery efficiency: How many rounds of revision did it actually take from requirement to acceptance?

    For filesystem tasks, the most valuable prompt constraints are usually not “be as fast as possible” but “first produce a read-only version, state the assumptions, complete the tests, and only then implement the cleanup module separately.”

    7. How to Reduce Development Interruptions When Remote Calls Are Unstable

    Remote model calls may slow down, disconnect, or time out. A single experience is not enough to determine the cause—network conditions, service load, context length, and client behavior can all affect the outcome.

    On the engineering side, several general strategies apply: set reasonable timeouts; use bounded backoff retries for requests that are safe to retry; preserve already-received output and clearly mark whether it is complete; and split long tasks into stages such as interface design, scan implementation, test supplementation, and security review.

    Code generation and code execution must be separated. Incomplete output should never be run automatically, and missing parts must never be stitched together by guesswork into deletion commands. Even when generation completes smoothly, the program should pass inspection and testing before being granted permission to operate on real data.

    8. Local Deployment Is a Trade-off, Not an Automatically Better Experience

    Local deployment improves control over data flow and the runtime environment, and reduces dependence on external network connections, but it does not guarantee faster generation.

    Actual results depend on model size, hardware resources, context length, inference configuration, and concurrency requirements. Beyond hardware investment, you also need to consider deployment maintenance, version upgrades, resource monitoring, and access control.

    For a disk analysis tool, there is usually no need to send the entire directory listing or file contents to a model. Developers can describe requirements with fictional paths and test data, then validate the generated code locally. Only when the model genuinely needs to explain scan results should a filtered and de-identified summary be provided. Whether using remote calls or local deployment, minimizing unnecessary data exposure is the more fundamental principle.

    9. Turning Generated Code into a Reliable Tool Through Testing

    Tests should cover normal cases and proactively construct boundary conditions: empty directories, paths with special characters, oversized files, large numbers of small files, directories without permission, links, files deleted mid-scan, and candidates modified before cleanup.

    A three-phase acceptance process is recommended:

    Phase one validates only the analysis functionality, checking accounting semantics, directory boundaries, and error records.

    Phase two validates the cleanup preview, ensuring candidate reasons are clear, exclusion rules work, and the program does not actually modify any files.

    Phase three validates the execution functionality inside an isolated test directory, confirming that the program only processes approved targets and accurately reports succeeded, failed, and skipped items.

    Ultimately, the value of AI-assisted programming is not merely turning a sentence of natural language into a piece of code, but shortening the distance from problem discovery to delivery of a reliable tool. For a high-risk scenario like disk cleanup, what is truly worth pursuing is not the shortest generation time, but a program with clear boundaries, transparent behavior, and verified results—delivered within a reasonable timeframe.