Efficient Coding with LLMs and a Practical Disk Space Governance Plan

    This article explains how to use coding-focused large language models to build a read-only disk usage analyzer and a safe cleanup script when a development machine runs out of storage. It covers prompt design, layered directory aggregation, mandatory safety gates such as path whitelists and dry-run mode, governance strategies for common space consumers like build caches, logs, and container images, and the practical value of local inference for privacy-sensitive operations tasks. Readers will find working Python examples and a deployment checklist for turning one-off cleanup into repeatable, auditable capacity governance.

    1. The First Hour After the Disk Fills Up

    A full disk on a development machine, test box, or local workstation is rarely caused by a single thing. It is usually the result of long-term accumulation: build caches, dependency packages, container image layers, log files, dataset copies, editor indexes, and artifacts from older versions. Once free space approaches the limit, the first things to break are workloads that write continuously, such as compilation, database writes, log flushing, and temporary file creation. Build failures, service errors, and cache invalidation follow in a cascade.

    In this situation, developers do not need a feature-heavy “system optimization tool.” They need a script that answers three questions within minutes:

    1. Who is actually consuming the space;
    2. What can be safely deleted;
    3. How much space deletion is expected to free.

    When an AI coding tool is used for this, the key is to state the requirement precisely and constrain the shape of the model’s output. In practice, a well-behaved coding model has a few traits: it does not produce long, invisible reasoning before the actual output, it does not pile on abstractions unrelated to the task, and it returns code that is clearly structured, runnable, and auditable. Models like this fit operations and troubleshooting work, where time efficiency and deterministic results matter most.

    2. Prompt Design: Getting Engineering-Ready Code from One Sentence

    A “one-sentence prompt” does not mean a casual description. A good one contains four elements: goal, input, output, and constraints. For example:

    1. Write a cross-platform command-line script: scan space usage under a given
    2. directory, aggregate and sort by first-level subdirectory, output the top N
    3. entries by usage, and list files larger than 100MB; read-only analysis only,
    4. no automatic deletion.

    This works because it fixes the scan scope, the aggregation dimension, the threshold, the sort order, and the risk boundary. To extend it, add output format requirements, such as producing both a human-readable table and machine-parsable structured data:

    1. Also output JSON results with fields path, size_bytes, file_count, largest_files.

    Declaring “read-only” explicitly in the prompt matters a great deal. Many cleanup incidents do not originate from a wrong algorithm but from a tool that deletes by default. Splitting analysis and cleanup into two separate stages is the safest engineering practice.

    3. Implementing Space Analysis: Layered Aggregation Instead of a Full Sort

    Sorting every file on the disk looks straightforward, but it is expensive and hard to read when file counts are large. A more practical approach is layered aggregation: measure first-level directories first, then drill down into the heaviest ones. Example code:

    1. import os
    2. from collections import defaultdict
    3. def dir_usage(root):
    4. stats = defaultdict(lambda: [0, 0]) # size, count
    5. for cur, dirs, files in os.walk(root):
    6. for f in files:
    7. p = os.path.join(cur, f)
    8. try:
    9. s = os.path.getsize(p)
    10. except OSError:
    11. continue
    12. top = os.path.relpath(cur, root).split(os.sep)[0]
    13. stats[top][0] += s
    14. stats[top][1] += 1
    15. return sorted(stats.items(), key=lambda x: x[1][0], reverse=True)
    16. for name, (size, count) in dir_usage("/data")[:10]:
    17. print(f"{name:30s} {size/1024**3:8.2f} GB files={count}")

    The value of layered aggregation is that it turns a “space problem” into a “directory ownership problem.” When one directory looks abnormal, you can inspect its distribution over time, its file types, and its duplicate copies, rather than deleting anything outright.

    4. From Analysis to Cleanup: Safety Gates Must Be Built In

    Path handling is where cleanup scripts fail most often. A sound design includes at least these protections:

    • Path whitelist: operate only under a root directory the user explicitly specified;
    • Depth limit: avoid accidentally scanning system directories or mount points;
    • Symlink handling: do not follow links by default, to prevent escaping the boundary;
    • Time threshold: clean only caches or logs older than a given number of days;
    • Dry-run mode: first print what would be deleted and how much would be freed, then execute after confirmation;
    • Audit trail: record the path, size, and time of deleted objects for traceability.

    Illustrative safe cleanup logic:

    1. def safe_cleanup(root, older_than_days, dry_run=True):
    2. import time
    3. cutoff = time.time() - older_than_days * 86400
    4. freed = 0
    5. for cur, dirs, files in os.walk(root):
    6. for f in files:
    7. p = os.path.join(cur, f)
    8. try:
    9. st = os.stat(p)
    10. except OSError:
    11. continue
    12. if st.st_mtime < cutoff and p.startswith(root):
    13. freed += st.st_size
    14. if not dry_run:
    15. os.remove(p)
    16. return freed

    The core idea here is “do not delete by default.” In engineering practice, dry-run mode significantly reduces the chance of accidental deletion and gives users a realistic expectation of how much space will be freed.

    5. Common Space Consumers and Governance Strategies

    Different sources need different strategies; one “delete hammer” cannot solve everything:

    1. Build and dependency caches: rebuildable, but confirm no build is currently running;
    2. Log files: better handled with time-based rotation and compressed archiving than a one-time wipe;
    3. Container images and dangling layers: reclaim unreferenced resources on a schedule;
    4. Datasets and model copies: never delete casually; inventory them and track access frequency first;
    5. Editor and index caches: rebuildable, but rebuilding hurts interactive responsiveness;
    6. Temporary export files: often the largest and the most overlooked, so define naming and expiration conventions.

    The point of governance is not a single cleanup but a recurring capacity inspection routine. Feed script output into a monitoring and alerting system, set thresholds on directory-level growth rates, and intervene before capacity reaches the warning line.

    6. Beyond Model Capability: Localization and Controllability in Practice

    The coding model experience depends not only on generation quality but also on the stability and throughput of the inference service. When responses slow down or connections become unstable, interactive troubleshooting loses efficiency quickly. For high-frequency, low-complexity, privacy-sensitive operations script generation, local deployment or a private inference environment has real value: data stays within the boundary, latency is predictable, and behavior is auditable.

    To judge whether a coding model suits this kind of task, look at four dimensions: time to first token, sustained throughput, stability under long context, and whether it tends to emit redundant reasoning. The first three determine how fluid the interaction feels; the last determines the signal-to-noise ratio of the code produced. In a race-against-the-clock scenario like disk troubleshooting, concise and accurate output is usually worth more than an elaborate design.

    7. Implementation Checklist

    • State the goal, scope, output, and read-only constraint in one sentence;
    • Run layered aggregation analysis first, then apply threshold filtering;
    • Default cleanup logic to dry-run, and execute only after confirmation;
    • Enforce hard protections on paths, depth, symlinks, and time;
    • Connect inspection results to monitoring and alerting for a long-term capacity governance loop;
    • For high-frequency script generation, evaluate the feasibility and payoff of local inference.

    In short, a full disk is a classic time-sensitive engineering problem. A coding model with restrained reasoning and stable output, combined with a rigorous prompt and solid safety gates, can produce a usable tool in a very short time. The lasting payoff, however, comes from upgrading one-off cleanup into a repeatable, auditable, alertable capacity governance system.