Building a Rollback Plugin for an AI Coding Tool: Lessons Learned and Pitfalls

    This article walks through the real-world pitfalls of building a rollback plugin for a DSH-style AI coding host that supports extensions. It explains why treating snapshots as file copies fails, why the rollback unit should be an attempt rather than a file, how plugin lifecycle mismatches with host state cause orphaned data, and how to prevent rollback storms under automation. It includes practical code for content-addressed snapshots and guarded edits, five reusable design principles, and a deployment checklist.

    1. Where It Started: A Plugin Idea That Seemed Obvious

    The motivation was simple. We wanted our AI coding tool to revert both file contents and the conversation context to their pre-edit state after it modified the wrong file. That would let us abandon a dead-end path and retry with a different approach.

    During implementation, the logic responsible for file snapshots and restoration gradually separated into a reusable capability module. Since it was already decoupled from the specific tool, a natural idea followed: a DSH-style AI coding host (referred to as the DSH-style host below) that supports a plugin mechanism allows extensions, so why not package the rollback capability as a plugin?

    On paper, the plan was smooth. In practice, it hit one pitfall after another. Below, the whole process is abstracted into four categories of problems, examined layer by layer.

    2. Pitfall One: Treating a “Snapshot” as “Copying a File”

    The first implementation was naive: before each edit, copy the entire target file to a temporary directory, and copy it back on rollback. It ran fast on small files, but problems surfaced immediately with large resource files or dependency directories.

    • Time and space costs spiraled out of control: every change triggered a full copy, and disk usage grew linearly with the number of operations.
    • Non-text assets were missed: only the edited files were backed up, ignoring hidden state such as build caches, generated artifacts, and temporary configs.
    • Rollback was incomplete: files returned to the past, but in-process caches, indexes, and the in-memory views of language services were still new.

    A more reasonable approach is to abstract snapshots as “content addressing + delta storage”: use a content digest as the unique identifier, store identical content only once, and produce no new copy for unchanged files.

    1. import hashlib, os, json
    2. class SnapshotStore:
    3. def __init__(self, root):
    4. self.root = root
    5. os.makedirs(os.path.join(root, "objects"), exist_ok=True)
    6. def _digest(self, path):
    7. h = hashlib.sha256()
    8. with open(path, "rb") as f:
    9. for chunk in iter(lambda: f.read(1 << 20), b""):
    10. h.update(chunk)
    11. return h.hexdigest()
    12. def put(self, path):
    13. d = self._digest(path)
    14. target = os.path.join(self.root, "objects", d)
    15. if not os.path.exists(target):
    16. with open(path, "rb") as src, open(target, "wb") as dst:
    17. dst.write(src.read())
    18. return {"path": path, "digest": d}
    19. def manifest(self, entries):
    20. p = os.path.join(self.root, "manifest.json")
    21. with open(p, "w", encoding="utf-8") as f:
    22. json.dump(entries, f, ensure_ascii=False, indent=2)

    3. Pitfall Two: Reverting Files but Not the “Conversation and Intent”

    The second pitfall was more subtle. The files did return to their pre-edit state, but the conversation history still contained the conclusion “I’ve already fixed it.” The model kept reasoning from there and carried the wrong conclusion forward as an established fact. That canceled out most of the value of the rollback.

    The correct abstraction is that the minimum unit of rollback is not a file but an attempt. An attempt should contain three parts at once: the file snapshot, the conversation and reasoning trace, and the attempt’s metadata (trigger reason, intended goal, elapsed time, and verdict). All three share the same monotonically increasing version number, and rollback switches them as a whole by that version number.

    1. {
    2. "version": 17,
    3. "reason": "unit-test-failed",
    4. "goal": "fix-boundary-condition",
    5. "files": [{"path": "src/core.py", "digest": "9f2c..."}],
    6. "transcript_ref": "transcripts/17.jsonl",
    7. "verdict": "rejected"
    8. }

    An additional benefit is auditability: any rollback can answer “why it was rolled back, what it rolled back to, and what was rolled back.”

    4. Pitfall Three: Plugin Lifecycle Out of Sync with Host State

    The third pitfall came from the plugin mechanism itself. Plugins are typically designed as short-lived units that follow a “load-execute-unload” lifecycle, whereas rollback capability is inherently long-lived and spans sessions. This mismatch leads to:

    • After a plugin is unloaded, the snapshot directory becomes orphaned data that no one claims;
    • After the host restarts, the version pointer held in the plugin’s memory is lost, so it cannot tell which version is current;
    • When multiple plugins modify the same file, the snapshot order does not match the actual write order, leaving state scrambled after rollback.

    The way to handle this is to externalize and make state explicit: persist the version pointer, snapshot index, and lock information to disk, and let the plugin act only as a stateless execution shell. Also introduce a serialized write queue to guarantee that “snapshot-modify” happen in pairs and in order.

    1. def guarded_edit(store, path, mutate, version):
    2. entry = store.put(path) # snapshot first
    3. try:
    4. mutate(path) # then modify
    5. except Exception:
    6. store.restore(entry) # restore in place on failure
    7. raise
    8. return version + 1

    5. Pitfall Four: “Rollback Storms” Under Exceptions and Concurrency

    The last pitfall appeared in automation scenarios. When rollback was set to “automatically roll back on test failure,” the model could oscillate repeatedly between two approaches, producing high-frequency rollbacks that wasted compute and polluted history. Rollback must be constrained:

    • Attempt limit: if consecutive rollbacks for the same goal exceed a threshold, pause and escalate for human confirmation;
    • Deduplication: if a new attempt’s content digest overlaps heavily with an already-rejected attempt, reject it outright to avoid spinning in place;
    • Idempotent rollback: repeating the rollback for the same version number must produce the same result;
    • Keep an audit log: write every rollback to a logging service to make it easy to analyze failure patterns afterward.

    6. Design Principles After Abstraction

    The experience above converges into five reusable principles:

    1. The rollback unit is an attempt, not a file;
    2. Snapshots use content addressing and delta storage to avoid full copies;
    3. State is externalized and the plugin is stateless, so the host can recover after a restart;
    4. Writes are serialized, with snapshots and modifications strictly paired;
    5. Rollback must have budget and idempotency constraints and be fully auditable.

    7. Deployment Checklist

    • Does it cover non-text assets and generated artifacts?
    • Does rollback switch the conversation and reasoning trace at the same time?
    • Is the version pointer persisted and recoverable across sessions?
    • Are concurrent writes ordered, and is there any snapshot inversion?
    • Are both a rollback-count threshold and a similarity threshold set?
    • Are there two paths: in-place recovery on failure and full rollback?

    8. Conclusion

    The real difficulty of a rollback plugin is not “copying the file back,” but completely, orderly, and auditably undoing a failed attempt. Elevating rollback from a file operation to a versioned transactional operation is the dividing line between a toy and something usable. If the host runs on a container platform, object storage can hold snapshots, a logging service can hold audit records, and monitoring and alerting can track rollback frequency, keeping the whole mechanism stable and controllable at scale.