Quick Disk Analysis and Cleanup Scripts with a Lightweight Reasoning Model

    This article explains how to use a lightweight reasoning model to quickly generate disk analysis and cleanup scripts when storage space runs out. It covers prompt design, a structured JSON report format, layered cleanup strategies, safety rules for deletion, and a read-only Python script example that only uses the standard library.

    When disk space fills up in minutes—logs growing, build caches piling up, temp files never reclaimed—you need a script you can run right away, plus a cleanup flow you can control. A 1TB disk can trigger alerts within hours. Long theoretical explanations won’t help.

    Lightweight reasoning models take significantly less time to think when generating code. With one or two sentences, you can get a structurally complete disk analysis program, shrinking the gap between spotting the problem and taking action. The model’s value lies in turning vague needs into executable, auditable code. The results still need human review, especially for deletion operations.

    How to Write the Prompt

    The prompt doesn’t need to be complex, but the constraints must be explicit. The template below covers common constraint types and can be reused directly:

    1. Target system: Ubuntu 22.04 or macOS 14
    2. Scan root path: /data/workspace
    3. Recursion depth: 4
    4. Exclude directories: /data/workspace/.git, /data/workspace/keep
    5. Output: table, Top 10, including file count
    6. Cleanup strategy: dry-run only, double confirmation before deletion, move to /data/archive, write operation log
    7. Implementation constraints: only Python standard library, no sudo, no following symlinks

    The model’s returned report should be fixed to a JSON structure for easy integration with monitoring or logging systems:

    1. {
    2. "scan_root": "/data/workspace",
    3. "generated_at": "2026-11-19T21:00:00+00:00",
    4. "filesystem": {"total_bytes": 0, "used_bytes": 0, "free_bytes": 0},
    5. "top_dirs": [
    6. {"path": "string", "bytes": 0, "file_count": 0, "suggested_action": "keep or review or archive"}
    7. ],
    8. "unreadable_paths": 0
    9. }

    Field meanings:

    • scan_root records the scan root path for traceability.
    • filesystem records total capacity, used space, and free space.
    • top_dirs lists directories by size descending, with path, bytes, file count, and suggested action.
    • unreadable_paths counts paths skipped due to permission issues.

    Cleanup Must Be Layered

    Disk analysis typically involves scanning mount points, aggregating usage by directory, identifying oversized files and stale logs, and distinguishing deletable paths from those that must stay. Cleanup proceeds in three steps:

    1. Read-only statistics to get usage.
    2. Generate a suggested list grouped by type—build artifacts, package manager caches, expired logs, temp downloads.
    3. After manual confirmation, execute archiving or deletion.

    Separating statistics from deletion significantly reduces the risk of accidental data loss.

    Safety Rules for Cleanup

    • Dry-run by default. The script prints paths and sizes it would process, and only executes with an explicit --apply flag.
    • Archive before deletion. Keep archived directories for at least one change window, and periodically sample recovery drills to ensure files can be restored.
    • Hard-code exclusions for system paths such as /boot, /usr, /etc, and config files under the user home directory.
    • Do not follow symlinks. os.walk does not enter symlinked directories by default; use os.lstat to read file sizes to avoid counting files behind links.
    • Deduplicate hard links. If the same inode is referenced by multiple paths, deleting one path does not free space. Statistics should deduplicate by inode.
    • Bound mount points. If you need to stay within one filesystem, compare each directory’s st_dev with the root’s value and skip mismatches. The sample code does not include this check; add it if needed.
    • Distinguish layers in container environments. Overlay layers and volume-mounted data come from different sources; confirm which layer a path belongs to before cleanup.
    • Regular user scripts should not request administrator privileges. Record permission errors and skip them, then report the outcome via the exit code.
    • Leave a trace for second confirmation. Write the approver, time, path list, and file count into the log.

    Script Implementation

    The script below performs read-only directory usage statistics. It only requires Python 3.8+ standard library and runs with normal user permissions. It outputs filesystem capacity information and the largest N directories.

    1. #!/usr/bin/env python3
    2. # Read-only disk usage analysis. Requires Python 3.8+, standard library only.
    3. import os
    4. import sys
    5. import json
    6. import datetime
    7. from collections import defaultdict
    8. def get_fs_info(path):
    9. st = os.statvfs(path)
    10. total = st.f_blocks * st.f_frsize
    11. free = st.f_bavail * st.f_frsize
    12. used = total - free
    13. return total, used, free
    14. def scan_dir(root, max_depth, exclude_dirs, top_n=10):
    15. sizes = defaultdict(lambda: {"bytes": 0, "file_count": 0})
    16. unreadable = 0
    17. root_real = os.path.realpath(root)
    18. exclude_real = {os.path.realpath(p) for p in exclude_dirs}
    19. for dirpath, dirnames, filenames in os.walk(root_real):
    20. # skip excluded dirs
    21. rel = os.path.relpath(dirpath, root_real)
    22. depth = 0 if rel == "." else rel.count(os.sep) + 1
    23. if depth > max_depth:
    24. dirnames[:] = []
    25. continue
    26. # remove excluded and symlink dirs
    27. dirnames[:] = [d for d in dirnames
    28. if os.path.realpath(os.path.join(dirpath, d)) not in exclude_real
    29. and not os.path.islink(os.path.join(dirpath, d))]
    30. for name in filenames:
    31. fpath = os.path.join(dirpath, name)
    32. if os.path.islink(fpath):
    33. continue
    34. try:
    35. st = os.lstat(fpath)
    36. sizes[os.path.dirname(fpath)]["bytes"] += st.st_size
    37. sizes[os.path.dirname(fpath)]["file_count"] += 1
    38. except (OSError, PermissionError):
    39. unreadable += 1
    40. # aggregate to top N dirs
    41. top_dirs = []
    42. for path, info in sorted(sizes.items(), key=lambda x: -x[1]["bytes"])[:top_n]:
    43. top_dirs.append({
    44. "path": path,
    45. "bytes": info["bytes"],
    46. "file_count": info["file_count"],
    47. "suggested_action": "review" if info["bytes"] > 100_000_000 else "keep"
    48. })
    49. return top_dirs, unreadable
    50. def main():
    51. if len(sys.argv) < 2:
    52. print("Usage: disk_analyze.py <scan_root> [--max-depth N] [--exclude PATH1,PATH2]")
    53. sys.exit(1)
    54. root = sys.argv[1]
    55. max_depth = 4
    56. exclude = []
    57. i = 2
    58. while i < len(sys.argv):
    59. if sys.argv[i] == "--max-depth" and i+1 < len(sys.argv):
    60. max_depth = int(sys.argv[i+1])
    61. i += 2
    62. elif sys.argv[i] == "--exclude" and i+1 < len(sys.argv):
    63. exclude = sys.argv[i+1].split(",")
    64. i += 2
    65. else:
    66. i += 1
    67. total, used, free = get_fs_info(root)
    68. top, unreadable = scan_dir(root, max_depth, exclude)
    69. report = {
    70. "scan_root": root,
    71. "generated_at": datetime.datetime.utcnow().isoformat() + "Z",
    72. "filesystem": {"total_bytes": total, "used_bytes": used, "free_bytes": free},
    73. "top_dirs": top,
    74. "unreadable_paths": unreadable
    75. }
    76. print(json.dumps(report, indent=2))
    77. if __name__ == "__main__":
    78. main()

    The script outputs a JSON report directly, matching the earlier structure. It is read-only, so there is no risk of deletion. For cleanup, you would extend it with a separate --apply step that archives files first. Always review the generated list before running any destructive action.