Disk Space Analysis and Cleanup with AI Coding Models: A Practical Engineering Approach

    This article explains how engineers can use AI code generation models to build disk space analysis and cleanup tools for a single server. It covers splitting the work into a read-only analysis stage and a dry-run-first cleanup stage, organizing the tool into scanning, decision, execution, and audit layers, detecting duplicate files safely, and applying allowlist checks and rollback measures. It also covers prompt constraints, handling unstable managed APIs, and trade-offs of private deployment.

    When a single server’s data disk is close to full, operators usually need to answer three questions quickly: which files or directories are using the space, which files can be deleted safely, and how cleanup actions can be logged and reversed. The traditional approach is to combine several commands on the fly. It is fast, but the commands are hard to reuse, leave no audit trail, and carry a high risk of accidental deletion. The value of a code generation model is not in replacing engineers’ decisions. It turns a natural-language requirement into a clearly structured script skeleton, and engineers then add the safety boundaries, tests, and deployment process. This article does not evaluate any specific model or platform. It discusses the task from a general engineering perspective.

    1. Defining the Requirements: Setting Clear Boundaries for “Analysis” and “Cleanup”

    Asking a model to “write a program that cleans up the disk” is a high-risk prompt. A safer approach is to split the requirement into two stages. The analysis stage is read-only and outputs a list of candidates. The cleanup stage runs in dry-run mode by default. It only prints the paths that would be deleted, and it deletes nothing until someone explicitly confirms. The analysis stage should cover at least four capabilities: directory size summaries, large file detection, stale file detection, and duplicate file identification. Each capability needs clearly defined input parameters, such as the scan root directory, minimum file size threshold, time window, excluded paths, and output format. The cleanup stage needs an allowlist of root directories, a list of system paths that must never be deleted, a policy for symbolic links, a retry policy for failures, and a defined audit log format.

    Prompts should state constraints, not just goals. Useful constraints include: do not delete directories recursively, do not follow symbolic links, do not delete mount points, continue scanning when permission errors occur, output JSON by default, and verify that every deletion path lies inside an allowed root directory before deleting. The quality of model output depends heavily on whether these constraints can be verified. Engineers should also ask the model for pseudocode and test cases before the implementation. This makes it possible to catch logic gaps before any code is generated.

    2. Program Structure: Decoupling Scanning, Decision, Execution, and Auditing

    A maintainable disk tool should be organized into four layers. The scanner walks the file system and collects metadata. The decision component applies thresholds and policies to produce candidates. The executor handles dry-run output and actual deletion. The auditor records every decision. The scanner should iterate through the file system instead of loading all files into memory at once, which prevents memory growth in large directories. The metadata should include at least the path, size, modification time, whether the entry is a symbolic link, and the device number and inode. The decision component should report large files, stale files, and duplicate files separately, so that a single candidate matching several policies is not processed twice.

    The following simplified example shows how read-only scanning is separated from safe cleanup:

    1. import os, json, time
    2. from pathlib import Path
    3. def scan(root, min_size=100 * 1024 * 1024, old_days=30):
    4. now = time.time()
    5. large, old = [], []
    6. for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
    7. for name in filenames:
    8. p = Path(dirpath) / name
    9. try:
    10. st = p.stat()
    11. except OSError:
    12. continue
    13. item = {
    14. "path": str(p),
    15. "size": st.st_size,
    16. "mtime": st.st_mtime,
    17. "is_symlink": p.is_symlink(),
    18. }
    19. if st.st_size >= min_size:
    20. large.append(item)
    21. if (now - st.st_mtime) / 86400 >= old_days:
    22. old.append(item)
    23. return {"large": large, "old": old}
    24. def cleanup(candidates, allow_roots, dry_run=True, audit=print):
    25. roots = [Path(r).resolve() for r in allow_roots]
    26. for c in candidates:
    27. p = Path(c["path"]).resolve()
    28. if not any(p.is_relative_to(r) for r in roots):
    29. audit({"action": "skip", "reason": "outside_allow_roots", "path": str(p)})
    30. continue
    31. if p.is_symlink() or not p.is_file():
    32. audit({"action": "skip", "reason": "not_regular_file", "path": str(p)})
    33. continue
    34. audit({"action": "dry_run" if dry_run else "unlink", "path": str(p)})
    35. if not dry_run:
    36. p.unlink()

    A production version needs more work, including exclusion paths, file system boundary checks, concurrency control, exception handling, and persistent audit logs. A code generation model can produce these skeleton components quickly, but engineers must review the security policy.

    3. Duplicate File Detection: Lightweight Fingerprints First, Then Full Hash Verification

    Duplicate detection can easily become a performance bottleneck. A common approach is to group files by size first, compute a lightweight fingerprint only for files that share a size, and then compute a strong hash for the remaining candidate groups. Before computing a strong hash, check whether a file changed during the scan. This prevents false matches based on stale metadata. For hard links, deduplicate by device number and inode, so the same data is not counted as several copies. When removing duplicates, keep at least one copy. Prefer to keep the copy with the shorter path, the earlier modification time, or the copy in a backup directory. The exact policy should follow business rules.

    4. Safe Cleanup: Allowlists, Secondary Checks, and Rollback

    The first principle of a cleanup tool is to delete nothing by default. Dry-run output should include the estimated space to be freed, the number of candidates, and a Top list grouped by directory, so people can review it manually. Before any actual deletion, the tool should check again that the path is still inside an allowed root directory. It should also confirm that the path is not a mount point, not a symbolic link, and not a temporary file that is still being written. For critical business directories, consider moving files to a quarantine directory and keeping them for a period before asynchronously removing them under a retention policy.

    Audit logs should use line-delimited JSON. Each entry should record the time, operator, candidate source, path, size, decision result, and any error information. Audit logs can be sent to a log service, metrics can feed monitoring and alerting, and backup manifests can be written to object storage. Together, these form a traceable record of every cleanup action.

    5. Controlling Reasoning Length and Output Verbosity

    On complex tasks, code generation models may produce long reasoning or verbose output, which reduces interaction efficiency. Engineers can control this with layered prompts. The first round asks only for a plan and a risk list. The second round asks for interface definitions and pseudocode. The third round generates the implementation and tests. Each round should constrain the output structure, for example “output only the JSON field descriptions” or “output only the function signatures and boundary conditions.” For deterministic tool scripts, asking for unit test examples and a list of exception paths is more useful than asking for a long explanation. Engineers should treat model output as a draft. It moves to production only after static checks, unit tests, and a small-scope dry-run.

    6. Handling Throughput Fluctuations and Disconnections in Managed APIs

    When using a hosted code generation API, throughput fluctuations, timeouts, and connection interruptions are common problems. Clients should set reasonable timeouts, exponential backoff retries, a maximum retry count, and circuit-breaker thresholds. For long tasks, use segmented generation or an asynchronous task queue, so a single request does not carry too much context. In streaming scenarios, handle partial responses. Save the content generated so far and support manual continuation. For batch generation, control concurrency and record the latency, failure reason, and retry count of each request. These records help determine whether a failure comes from the network, rate limiting, or an overly long context. For critical production scripts, do not make online generation a runtime dependency. Store generated results, review them, and version them.

    7. Private Deployment: Use Cases and Trade-offs

    Private or local inference can reduce network dependency and keep data inside the internal network. However, it requires evaluating hardware resources, model licensing, version upgrades, inference service operations, and the cost of failure recovery. Data governance matters most when prompts contain sensitive paths, file inventories, or business directory structures. Whether you use a hosted API or a private deployment, follow the principle of least privilege. The generation tool should run under a restricted account that can access only the specified root directories. Deletion operations should require manual confirmation or an approval workflow.

    8. Acceptance Checklist

    Before release, complete at least the following checks: the scan is read-only and does not follow symbolic links; dry-run output can be reviewed; deletion paths are checked against the allowlist a second time; the audit log is complete; exception paths have tests; memory usage stays under control on large directories; duplicate detection guards against false matches; and the tool version and generation records are traceable. With this process in place, a code generation model can move from a one-off script helper to a reusable operations component. It speeds up delivery while keeping the engineering safety boundaries intact.