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:
Target system: Ubuntu 22.04 or macOS 14Scan root path: /data/workspaceRecursion depth: 4Exclude directories: /data/workspace/.git, /data/workspace/keepOutput: table, Top 10, including file countCleanup strategy: dry-run only, double confirmation before deletion, move to /data/archive, write operation logImplementation 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:
{"scan_root": "/data/workspace","generated_at": "2026-11-19T21:00:00+00:00","filesystem": {"total_bytes": 0, "used_bytes": 0, "free_bytes": 0},"top_dirs": [{"path": "string", "bytes": 0, "file_count": 0, "suggested_action": "keep or review or archive"}],"unreadable_paths": 0}
Field meanings:
scan_rootrecords the scan root path for traceability.filesystemrecords total capacity, used space, and free space.top_dirslists directories by size descending, with path, bytes, file count, and suggested action.unreadable_pathscounts 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:
- Read-only statistics to get usage.
- Generate a suggested list grouped by type—build artifacts, package manager caches, expired logs, temp downloads.
- 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
--applyflag. - 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.walkdoes not enter symlinked directories by default; useos.lstatto 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_devwith 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.
#!/usr/bin/env python3# Read-only disk usage analysis. Requires Python 3.8+, standard library only.import osimport sysimport jsonimport datetimefrom collections import defaultdictdef get_fs_info(path):st = os.statvfs(path)total = st.f_blocks * st.f_frsizefree = st.f_bavail * st.f_frsizeused = total - freereturn total, used, freedef scan_dir(root, max_depth, exclude_dirs, top_n=10):sizes = defaultdict(lambda: {"bytes": 0, "file_count": 0})unreadable = 0root_real = os.path.realpath(root)exclude_real = {os.path.realpath(p) for p in exclude_dirs}for dirpath, dirnames, filenames in os.walk(root_real):# skip excluded dirsrel = os.path.relpath(dirpath, root_real)depth = 0 if rel == "." else rel.count(os.sep) + 1if depth > max_depth:dirnames[:] = []continue# remove excluded and symlink dirsdirnames[:] = [d for d in dirnamesif os.path.realpath(os.path.join(dirpath, d)) not in exclude_realand not os.path.islink(os.path.join(dirpath, d))]for name in filenames:fpath = os.path.join(dirpath, name)if os.path.islink(fpath):continuetry:st = os.lstat(fpath)sizes[os.path.dirname(fpath)]["bytes"] += st.st_sizesizes[os.path.dirname(fpath)]["file_count"] += 1except (OSError, PermissionError):unreadable += 1# aggregate to top N dirstop_dirs = []for path, info in sorted(sizes.items(), key=lambda x: -x[1]["bytes"])[:top_n]:top_dirs.append({"path": path,"bytes": info["bytes"],"file_count": info["file_count"],"suggested_action": "review" if info["bytes"] > 100_000_000 else "keep"})return top_dirs, unreadabledef main():if len(sys.argv) < 2:print("Usage: disk_analyze.py <scan_root> [--max-depth N] [--exclude PATH1,PATH2]")sys.exit(1)root = sys.argv[1]max_depth = 4exclude = []i = 2while i < len(sys.argv):if sys.argv[i] == "--max-depth" and i+1 < len(sys.argv):max_depth = int(sys.argv[i+1])i += 2elif sys.argv[i] == "--exclude" and i+1 < len(sys.argv):exclude = sys.argv[i+1].split(",")i += 2else:i += 1total, used, free = get_fs_info(root)top, unreadable = scan_dir(root, max_depth, exclude)report = {"scan_root": root,"generated_at": datetime.datetime.utcnow().isoformat() + "Z","filesystem": {"total_bytes": total, "used_bytes": used, "free_bytes": free},"top_dirs": top,"unreadable_paths": unreadable}print(json.dumps(report, indent=2))if __name__ == "__main__":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.
