260 Safe File Write Protocol

The “Safe File Write” Protocol

This document describes the mandatory “Safe File Write” protocol for modifying files to prevent data corruption.

The Problem

Modifying files in place (e.g., with the replace tool) can lead to corruption if the operation fails or is interrupted. This is especially dangerous when modifying critical files like process documents or shared state. The now-deprecated “ROT13 Point-Fix Pattern” was an attempt to solve this, but it proved unreliable.

The Solution: The safe_apply_change.py Script

The canonical and mandatory implementation of the Safe File Write protocol is the scripts/safe_apply_change.py script. This script automates the protocol, providing a robust, testable, and verifiable method for applying complex file changes.

The script’s workflow is as follows:

  1. It takes the original file path and the proposed new content as input.
  2. It writes the new content to a temporary file.
  3. It generates a diff between the original and the temporary file.
  4. It presents this diff to the user for approval.
  5. Upon approval, it atomically replaces the original file with the temporary file.

This script must be used for all non-trivial file modifications, especially on critical files.

Warning: The replace Tool and In-Place Modification

The replace tool is particularly hazardous because it modifies files directly in-place. This violates the “Safe File Write” protocol and carries a high risk of file corruption, especially if the old_string is not perfectly unique or if the tool fails mid-operation.

Mandatory Procedure:

  • DO NOT use the replace tool on critical files (process documents, source code, configuration).
  • For any file modification, the preferred method is to use the scripts/safe_apply_change.py script.

The replace tool should only be considered for low-risk, cosmetic changes on non-critical files.