Efficient Coding with Large Language Models and a Disk Cleanup Workflow

    This article covers a practical approach to using large language models for coding and a layered design for a disk analysis and cleanup tool. It defines measurable criteria for evaluating coding models, including time to first token, reasoning budget, API stability, and local deployability. It then walks through a four-layer architecture (collection, aggregation, reporting, and remediation), sample Python code, prompt engineering tips, performance and security practices, and a path from local scripts to a platform-based workflow.

    1. Background: Emergency Response When the Disk Is Full

    A developer’s local disk gradually filling up with logs, build artifacts, caches, and container image layers is a common problem with little tolerance for error. Once free space drops below a threshold, compilation, dependency installation, and database writes can fail, sometimes causing system-level issues. The traditional approach is to inspect directories manually, which is slow and prone to accidental deletion. A better approach is to use a single natural-language requirement to drive an AI coding tool to generate a small “scan, report, and clean up” utility, turning emergency response into a repeatable process.

    2. Evaluation Criteria: How to Decide Whether a Coding Model Is Good

    The original practice mentioned three impressions: fast generation, a reasoning process that is not overly verbose, and stable execution. Abstracting these into measurable engineering metrics makes evaluation more rigorous:

    1. Time to first token and throughput: These determine the interactive experience and affect the “change one line, run once” iteration rhythm.
    2. Reasoning budget control: An overly long chain of thought increases waiting time and consumes context window space, reducing effective information density.
    3. API stability: Long-lived connection drops, rate limiting, and fluctuations can interrupt generation tasks directly, so retry and fallback strategies are needed.
    4. Local deployability: When data compliance and offline scenarios are involved, local inference capability is an important advantage.

    These four points are closer to real development needs than “is it fast” and make horizontal comparisons within a team easier.

    3. Design: A Layered Structure for the Disk Analysis and Cleanup Tool

    Split the tool into four layers, each with a single responsibility and easy to test:

    • Collection layer: Traverse directories and record the byte size and modification time of each file.
    • Aggregation layer: Accumulate usage bottom-up along the directory tree to get usage at each level.
    • Reporting layer: Output the top N largest directories, largest files, and files not accessed for a long time.
    • Remediation layer: Support three safety levels: “report only”, “move to quarantine”, and “delete by rule”.

    Illustrative interface design (language-agnostic):

    1. scan(root, depth) -> directory usage tree
    2. top_dirs(tree, n) -> the n directories with the highest usage
    3. stale_files(root, days) -> files not accessed for more than the given number of days
    4. quarantine(paths, dest) -> move into a quarantine directory, rollback supported
    5. purge(paths, confirm=true) -> delete after a second confirmation

    Key constraint: read-only by default; any deletion action must be explicitly enabled and confirmed twice; the quarantine area keeps a rollback window to avoid irreversible loss from accidental deletion.

    4. Implementation Highlights and Sample Code

    During traversal, avoid duplicate counting and symbolic link traps, and collect file size and access time in a single pass:

    1. import os, time
    2. def scan(root):
    3. tree = {}
    4. for cur, dirs, files in os.walk(root, followlinks=False):
    5. total = 0
    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. total += st.st_size
    13. tree[cur] = total
    14. # Accumulate bottom-up into parent directories
    15. for cur in sorted(tree, key=len, reverse=True):
    16. parent = os.path.dirname(cur.rstrip(os.sep))
    17. if parent in tree:
    18. tree[parent] += tree[cur]
    19. return tree

    In the reporting stage, sort by usage and format human-readable units to quickly locate the “culprit”:

    1. def human(n):
    2. for unit in ("B", "KB", "MB", "GB", "TB"):
    3. if n < 1024:
    4. return f"{n:.1f}{unit}"
    5. n /= 1024
    6. return f"{n:.1f}PB"
    7. def report(tree, n=20):
    8. for path, size in sorted(tree.items(), key=lambda x: -x[1])[:n]:
    9. print(f"{human(size):>10} {path}")

    In the cleanup stage, prefer “move to quarantine” and defer irreversible operations:

    1. import shutil
    2. def quarantine(paths, dest, days=7):
    3. os.makedirs(dest, exist_ok=True)
    4. for p in paths:
    5. shutil.move(p, os.path.join(dest, os.path.basename(p)))
    6. print(f"Quarantined {len(paths)} items; they can be cleaned up together after {days} days")

    5. Prompt Engineering: Writing a One-Line Requirement More Reliably

    When generating code from natural language, the closer the requirement description is to “acceptance criteria”, the more usable the output. Recommended elements: goal, input, output, and constraints. Example:

    1. Write a cross-platform disk analysis and cleanup script:
    2. Input is the root directory and a depth threshold;
    3. Output is the 20 directories with the highest usage and a list of files not accessed for more than 30 days;
    4. Read-only by default; deletion requires an explicit parameter and a second confirmation, and files are moved to a quarantine directory before deletion.

    Additional constraints can significantly reduce rework, for example specifying “do not follow symbolic links”, “skip abnormal files instead of aborting”, and “support non-ASCII paths”.

    6. Performance and Stability Optimization

    • For large directories, prefer streaming statistics to avoid building a huge list at once and causing a memory spike.
    • Set timeouts and skip policies for network drives and mount points to prevent long blocking.
    • Incremental mode records the previous scan result and compares only the changed parts.
    • When calling an AI coding tool, prepare exponential backoff retries for timeouts and rate limiting, and split long tasks into small-step generation to reduce the cost of a single interruption.

    7. Security and Compliance Red Lines

    A cleanup tool is a high-risk script and should follow the principle of least privilege: access only user-authorized directories; generate a manifest snapshot before deletion; set an expiration reminder for the quarantine area instead of automatic forced deletion; in enterprise environments, integrate with logging services and monitoring alerts, and record every remediation action for auditing. If sensitive data directories are involved, exclude them by default.

    8. From Local to Platform-Based

    When the need expands from a personal machine to a team, scan results can be written to object storage, a container platform can run the job on a schedule, tasks can be distributed through a message queue, and monitoring alerts can notify on disk usage thresholds. Baidu AI Cloud typically provides combinations of general-purpose capabilities for this kind of scenario, which can be selected as needed, while the tool itself stays decoupled from the specific environment for easier migration.

    9. Conclusion

    Evaluating a coding model should not focus only on “generates fast”; it should combine four metrics: time to first token, reasoning budget, API stability, and deployability. Abstracting disk governance into four layers (collection, aggregation, reporting, and remediation), together with safe defaults and the four prompt elements, makes it possible to reliably produce a reusable tool from a single natural-language requirement, turning a one-off emergency response into a long-term operable capability.