Building a Disk Cleanup Tool with Code LLMs: A Practical Guide

    This article walks through using a code large language model to build a disk space analysis and cleanup tool. It covers how to write engineering-constrained prompts, a three-layer architecture that separates analysis, decision, and execution, safety principles such as dry-run-by-default and whitelisting, inference service considerations (throughput, streaming stability, cloud vs. local deployment), and a quality pipeline of static checks, testing, sandbox runs, and staged rollout.

    Building a Disk Cleanup Tool with Code LLMs: A Practical Guide

    When large disks fill up quickly with logs, caches, temp files, and build artifacts, operations and development teams need to quickly answer “what’s consuming the space?” and then safely remove what’s safe to delete. The traditional approach is to manually chain together commands and drill down directory by directory, which depends heavily on individual experience. The advantage of a code large language model (LLM) is that it can turn a natural-language requirement into a structured analysis script, complete with argument parsing, logging, exception handling, and dry-run modes. This article uses a “disk space analysis and cleanup tool” as an example to discuss how to bring code LLMs into a verifiable, governable development workflow.

    1. From “It Generates Code” to “It’s Deliverable”: Prompts Must Constrain Engineering Boundaries

    When asking a model to write an operations script, the worst thing you can do is say “clean up my disk” and let it delete files directly. A high-quality prompt should specify the runtime environment, output format, safety boundaries, and acceptance criteria. For example:

    1. Write a disk space analysis tool using only the Python standard library. Requirements:
    2. 1. Support a configurable root directory, a minimum file size threshold, and Top N output;
    3. 2. Analyze only by default; deletion must be explicitly enabled via --apply;
    4. 3. Filter against a whitelist of directories before deletion; never delete system
    5. directories, user home root paths, or mount points;
    6. 4. Output a JSON report including path, size, modification time, file type,
    7. and whether the file is deletable;
    8. 5. Write all deletion operations to an audit log, with failures recorded separately;
    9. 6. Provide unit test points and rollback suggestions.

    This kind of prompt turns “generate code” into “generate a reviewable engineering proposal.” The model must not only write the scanning logic but also account for edge cases: permissions, symbolic links, hard links, crossing filesystems, and files in use. For a team, what matters is not how many lines the model produces in one shot, but whether the output has well-defined inputs and outputs, failure paths, and rollback capability.

    2. Program Architecture: Separate Analysis, Decision, and Execution Layers

    A usable disk cleanup tool should be split into three layers: the analysis layer walks directories and collects size statistics; the decision layer applies the whitelist, file age, type, and size thresholds to produce a candidate list; the execution layer deletes only after explicit confirmation and records an audit log. The benefit of this separation is that analysis results can be reviewed, deletions are auditable, and the tool can later be integrated with approval workflows or scheduled jobs.

    Illustrative code:

    1. import argparse, json, os, time
    2. from pathlib import Path
    3. PROTECTED = {"/", "/etc", "/usr", "/var/lib", "/boot"}
    4. def scan(root: Path, min_size: int):
    5. results = []
    6. for p in root.rglob("*"):
    7. try:
    8. if p.is_symlink() or not p.is_file():
    9. continue
    10. st = p.stat()
    11. if st.st_size >= min_size:
    12. results.append({
    13. "path": str(p),
    14. "size": st.st_size,
    15. "mtime": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(st.st_mtime)),
    16. "protected": any(str(p).startswith(x) for x in PROTECTED),
    17. })
    18. except (PermissionError, OSError) as e:
    19. results.append({"path": str(p), "error": str(e)})
    20. return sorted(results, key=lambda x: x.get("size", 0), reverse=True)
    21. def main():
    22. ap = argparse.ArgumentParser()
    23. ap.add_argument("--root", required=True)
    24. ap.add_argument("--min-size", type=int, default=100 * 1024 * 1024)
    25. ap.add_argument("--top", type=int, default=50)
    26. ap.add_argument("--apply", action="store_true")
    27. ap.add_argument("--report", default="disk_report.json")
    28. args = ap.parse_args()
    29. root = Path(args.root).resolve()
    30. items = scan(root, args.min_size)
    31. report = {"root": str(root), "generated_at": time.time(), "items": items[:args.top]}
    32. Path(args.report).write_text(json.dumps(report, ensure_ascii=False, indent=2))
    33. if not args.apply:
    34. print("dry-run: report generated only, no files deleted")
    35. return
    36. for item in items[:args.top]:
    37. if item.get("protected"):
    38. continue
    39. try:
    40. os.remove(item["path"])
    41. print("deleted:", item["path"])
    42. except OSError as e:
    43. print("failed:", item["path"], e)

    This is only a skeleton. A production version should also include a whitelist configuration file, a second confirmation before deletion, batch rate limiting, persisted audit logs, file-lock detection, and a quarantine (recycle bin) mechanism. Model-generated code must go through code review and testing before it runs with elevated privileges.

    3. Safety Strategy: Dry-Run by Default, Whitelisting, Auditing, and Rollback

    Disk cleanup is a high-risk operation, so safety should take priority over feature richness. Four principles are recommended: dry-run by default, with deletion requiring an explicit flag; whitelist-first, where system directories, mount points, database directories, and user home roots are always protected; complete auditing, recording candidate files, deletion results, operator, and timestamps; and rollback capability—at minimum keeping reports and logs, and in critical environments moving files to a quarantine directory instead of deleting them outright.

    In addition, model-generated scripts should avoid being “too clever”: they should not automatically expand the scan scope, infer business meaning from file names, or recursively delete directories without confirmation. Symbolic links, hard links, and cross-filesystem mount points should be explicitly skipped or handled separately to avoid deleting link targets or affecting other mounted volumes.

    4. Inference Service Experience: Throughput, Disconnections, and Deployment Models

    In interactive coding with a code LLM, time to first token, output throughput, and connection stability directly affect the developer experience. If the inference service has insufficient throughput or occasional disconnects, developers will face repeated waiting and retries during long code generation, multi-round revisions, and batch refactoring—degrading the usability of the toolchain. When evaluating options, teams should look at: request timeout and retry policies, stability of streaming output, performance under long contexts, concurrency limits and quota management, and whether error codes are diagnosable.

    Regarding deployment, cloud APIs are well suited for quick integration and elastic concurrency, but require evaluating network dependency, call costs, and data compliance. Local deployment reduces the impact of network fluctuations and improves data control, but demands compute resources, model licensing, version upgrades, and operational investment. A reasonable approach is layering: sensitive code and high-frequency interactive scenarios can prioritize local or dedicated-environment deployment, while non-sensitive, bursty tasks can use cloud services, smoothed out with caching, batching, and queuing. On general-purpose cloud platforms such as Baidu AI Cloud, audit logs can be connected to logging services and runtime metrics to monitoring and alerting, but the final choice should follow the team’s security standards and cost model.

    5. Quality Assurance: Bringing Model Output into the Engineering Pipeline

    Model-generated code is only the starting point. A recommended pipeline is: prompt templates → static checks → unit tests → sandbox drills → human review → staged execution. Static checks focus on dangerous calls, path concatenation, and permission issues. Unit tests cover empty directories, permission-denied cases, symbolic links, oversized files, and deletion failures. Sandbox drills validate the dry-run report in an isolated environment. Human review focuses on deletion boundaries. Staged execution runs first on a small set of directories with report comparison.

    Only by positioning the code LLM as an “engineering assistant” rather than an “autonomous executor” can you improve efficiency while controlling risk. Disk analysis and cleanup is just one representative scenario; the same methodology applies to log rotation, build cache governance, and temp file reclamation: use clear prompts to constrain boundaries, a layered architecture to isolate risk, and auditing plus rollback as the safety net—ultimately turning model capability into reusable engineering productivity.