Practical Guide to Disk Space Analysis and Cleanup Using Lightweight Code Models

    Disk space exhaustion often involves complex troubleshooting across multiple directories, file types, and time windows. This article explores how lightweight code models can accelerate the creation of auditable, iterable disk analysis and cleanup tools. It covers positioning the model as a scaffolding accelerator rather than a replacement for human review, designing prompts with explicit safety boundaries, structuring the program into scanning, analysis, and cleanup phases, and implementing critical guardrails such as dry-run defaults and path validation. It also addresses inference service stability, local deployment considerations, and strategies for validation and iteration.

    1. Problem Background: Why Disk Space Alerts Need “Tooling”

    Disk space shortage may seem like a simple operational issue, but troubleshooting often involves multiple directories, file types, time windows, and large file localization. Developers usually need to answer several questions first: Who is occupying the space? Is it logs or cache? Are there duplicate files? Which files can be safely deleted? Will deletion affect the business? Relying solely on manual directory traversal leads to long troubleshooting paths, repetitive labor, and a high risk of accidental file deletion under high-pressure scenarios.

    The value of code generation models lies not in replacing developer judgment, but in rapidly generating an auditable, iterable scanning and analysis tool. By delegating repetitive logic—such as directory traversal, size statistics, extension aggregation, Top N large file output, and duplicate file hash comparison—to the model to generate scaffolding, developers can focus their energy on cleanup strategies, safety boundaries, and rollback validation. Rather than having the model output a “universal cleanup script” all at once, a more robust approach is to have the model generate a phased tool: read-only scanning first, then an analysis report, and finally cleanup execution only after explicit confirmation.

    2. Model Positioning: Accelerating Scaffolding, Not Replacing Review

    In coding tasks, some general-purpose models may output lengthy reasoning processes, which can hinder interaction efficiency. Lightweight code models that reduce irrelevant reasoning and directly provide structured code are better suited for tool-oriented tasks. However, no matter how smooth the model’s output is, the generated code must undergo human review and sandbox validation. Disk cleanup programs, in particular, carry irreversible risks; they must default to read-only, default to dry-run, and require explicit execution for deletion operations.

    A reasonable positioning is: the model is responsible for generating a “readable, modifiable, testable” initial script, while developers are responsible for adding safety guardrails and business constraints. The model output should meet requirements such as being a single file, having few dependencies, clear parameters, complete logging, and recoverable errors. This leverages generation efficiency while preventing uncontrolled logic from being directly introduced into the production environment.

    3. Prompt Design: Writing Safety Boundaries into Requirements

    To get the model to generate a usable disk analysis and cleanup program, the prompt cannot simply be “write a program to clean up disk space.” It should clearly specify inputs, outputs, constraints, and failure handling. The following template can be used:

    1. Please generate a single-file disk space analysis script with the following requirements:
    2. 1. Input parameters: root directory, minimum file threshold, Top N, output JSON path;
    3. 2. Default to read-only scanning, do not delete any files;
    4. 3. Do not follow symbolic links, skip directories without permissions and log errors;
    5. 4. Calculate total size, aggregate by extension, output Top N large files;
    6. 5. The cleanup function must be explicitly enabled via --apply and require --confirm for secondary confirmation;
    7. 6. Before deletion, verify that the path is within the user-specified root directory; deleting the root directory itself is prohibited;
    8. 7. Output structured logs, including scan count, error count, and estimated reclaimable space;
    9. 8. The code must include exception handling to prevent a single file failure from causing an overall interruption.

    This type of prompt translates “safety boundaries” into executable constraints, making it easier for the model to generate a well-structured program. If the first output lacks a dry-run mode or path validation, you can continue by asking it to “only modify the cleanup function, add whitelist validation and soft delete logs,” rather than having the model rewrite the entire code.

    4. Program Structure: Three Phases of Scanning, Analysis, and Cleanup

    A deployable tool should be divided into three phases. The scanning phase only reads metadata, tallying file size, modification time, extension, and directory distribution. The analysis phase generates a Top N large file list, an extension usage ranking, a list of suspected temporary files, and an estimated reclaimable space. The cleanup phase only processes files that match whitelist rules and outputs a “will be deleted” list by default.

    Below is a simplified example focusing on the read-only scanning, aggregation, and dry-run cleanup logic:

    1. import argparse
    2. import json
    3. import os
    4. import time
    5. from pathlib import Path
    6. from collections import defaultdict
    7. def human_size(num):
    8. for unit in ["B", "KB", "MB", "GB", "TB"]:
    9. if num < 1024:
    10. return f"{num:.1f}{unit}"
    11. num /= 1024
    12. return f"{num:.1f}PB"
    13. def scan(root, min_size, top_n):
    14. root = Path(root).resolve()
    15. total = 0
    16. file_count = 0
    17. by_ext = defaultdict(int)
    18. large_files = []
    19. errors = []
    20. for p in root.rglob("*"):
    21. try:
    22. if p.is_symlink() or not p.is_file():
    23. continue
    24. st = p.stat()
    25. except OSError as e:
    26. errors.append({"path": str(p), "error": str(e)})
    27. continue
    28. size = st.st_size
    29. total += size
    30. file_count += 1
    31. ext = p.suffix.lower() or "<no_ext>"
    32. by_ext[ext] += size
    33. if size >= min_size:
    34. large_files.append({
    35. "path": str(p),
    36. "size": size,
    37. "mtime": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(st.st_mtime)),
    38. })
    39. large_files.sort(key=lambda x: x["size"], reverse=True)
    40. ext_rank = sorted(by_ext.items(), key=lambda x: x[1], reverse=True)
    41. return {
    42. "root": str(root),
    43. "total_size": total,
    44. "total_human": human_size(total),
    45. "file_count": file_count,
    46. "top_files": large_files[:top_n],
    47. "by_ext": [{"ext": k, "size": v, "human": human_size(v)} for k, v in ext_rank],
    48. "errors": errors[:100],
    49. }
    50. def cleanup_candidates(root, suffix_set, older_than_days):
    51. root = Path(root).resolve()
    52. now = time.time()
    53. candidates = []
    54. for p in root.rglob("*"):
    55. try:
    56. if p.is_symlink() or not p.is_file():
    57. continue
    58. if p.suffix.lower() not in suffix_set:
    59. continue
    60. st = p.stat()
    61. if now - st.st_mtime < older_than_days * 86400:
    62. continue
    63. candidates.append({"path": str(p), "size": st.st_size})
    64. except OSError:
    65. continue
    66. return candidates
    67. def main():
    68. parser = argparse.ArgumentParser()
    69. parser.add_argument("--root", required=True)
    70. parser.add_argument("--min-size", type=int, default=10 * 1024 * 1024)
    71. parser.add_argument("--top-n", type=int, default=50)
    72. parser.add_argument("--output", default="disk_report.json")
    73. parser.add_argument("--apply", action="store_true")
    74. parser.add_argument("--confirm", action="store_true")
    75. args = parser.parse_args()
    76. report = scan(args.root, args.min_size, args.top_n)
    77. with open(args.output, "w", encoding="utf-8") as f:
    78. json.dump(report, f, ensure_ascii=False, indent=2)
    79. print("Total size:", report["total_human"])
    80. print("File count:", report["file_count"])
    81. print("Report written to:", args.output)
    82. candidates = cleanup_candidates(args.root, {".tmp", ".log", ".cache"}, 7)
    83. print("Cleanup candidate count:", len(candidates))
    84. if args.apply and args.confirm:
    85. root = Path(args.root).resolve()
    86. for item in candidates:
    87. p = Path(item["path"]).resolve()
    88. if root not in p.parents:
    89. print("Skipping out-of-bounds path:", p)
    90. continue
    91. print("Will delete:", p)
    92. # In production, it is recommended to move to an isolated directory first, then delete later
    93. else:
    94. for item in candidates[:20]:
    95. print("dry-run:", item["path"], human_size(item["size"]))
    96. if __name__ == "__main__":
    97. main()

    In the example, the cleanup logic remains conservative: it defaults to dry-run, only enters the deletion branch if both --apply and --confirm are present, and re-validates that the path is under the root directory. In a production environment, this can be further modified to “move to an isolated directory + scheduled cleanup” to reduce the risk of irreversible accidental deletion.

    5. Safety Guardrails: Deleting Correctly Matters More Than Just Being Able to Delete

    Safety guardrails for a disk cleanup tool should at least include: running with least privilege, whitelist directories, path normalization, no symlink following, secondary validation before deletion, operation logging, soft delete or quarantine zone, and rollback on failure. Hardcoding critical system directories, default recursive deletion, and executing destructive operations without confirmation are strictly prohibited.

    Additionally, the tool should output an auditable report, including the scan root directory, file count, error list, candidate list, estimated reclaimable space, and actual execution results. Directories without permissions, mount points, and actively written log files should be skipped and logged to prevent overall failure or misjudgment caused by a single anomaly.

    6. Inference Service Stability and Local Deployment Considerations

    When integrating code generation into the development toolchain, the throughput and stability of the inference service directly impact the user experience. External services may be affected by concurrency, network, quotas, and long-connection policies, resulting in slow responses or interruptions. Engineering-wise, you should add timeouts, retries, fallbacks, and caching: cache generation results for identical prompts; generate in chunks for long tasks; provide clear error messages for failed requests and allow manual takeover.

    If conditions permit, local deployment can reduce the risk of data exfiltration, mitigate network jitter, and make it easier to fix model versions according to team standards. However, local deployment also requires evaluating the costs of VRAM, concurrency, cold starts, model updates, and monitoring. Regardless of the deployment method chosen, “generated code must be reviewed, and cleanup operations must be confirmed” should remain a fixed process.

    7. Validation and Iteration: Start with Small Directories

    After generating the script, first construct sample files in a test directory, covering large files, temporary files, no-permission files, symbolic links, and out-of-bounds paths, to validate scanning statistics, candidate filtering, and path validation. Then run it in a read-only mode in a real environment and compare it with manual statistics. Verify the cleanup function in an isolated environment first; confirm that logging, soft deletion, and rollback processes work before gradually opening it up.

    In summary, lightweight code models are well-suited to take on the scaffolding generation task for disk analysis and cleanup tools, but they must be paired with clear prompt constraints, a phased program structure, default read-only and dry-run modes, safe path validation, and stable inference service governance. By leaving efficiency to the model and retaining final control for the developer, you can achieve both speed and stability in disk space troubleshooting.