Reliable Editing and Stale Preconditions
Change a file after an edit is proposed and check that stale preconditions prevent application.
An agent reads lines 12–16 of a file, reasons for forty seconds, and proposes replacing line 15. In those forty seconds, a formatter rewraps the file, a colleague’s editor saves a change, or a second agent inserts an import at the top. Every line moves down by one. The proposed edit is still well formed and still names line 15, and it now lands on the wrong statement. Nothing in the agent’s reasoning was wrong. The world it reasoned about no longer exists.
This chapter is about that gap between when a change is proposed and when it is applied. The mechanism that closes it is old and unglamorous: a precondition, a fact that must still hold at the moment the operation is applied, checked by the component that applies it. Databases call the pattern optimistic concurrency control. Version-control systems use it to refuse non-fast-forward pushes. Agent harnesses need it more than either, because an agent’s latency between reading and writing is long and variable, and because the reader is a model that cannot notice the change for itself.
Evidence status. Draft manuscript. Formal Project 02 (Reliable Editor) has not started, and the Project 01 review’s sequencing condition still gates the formal study: the blocking findings (RER-02, RER-04, P01R-02, P01R-27) must be corrected and the corrected candidate must pass independent re-review (REVIEW-02 returned REJECT, 2026-11-23). The educational edit-gate demonstration D06-EDIT-01 is implemented and executed (
examples/pi-harness-lab/src/edit-gates.ts;test/edit-gates.test.ts, 15/15 pass offline on real temporary workspaces). It runs on disposable fixtures with no dependency on Project 01 acceptance. External sources are DOCUMENTED and are not replicated here. The formal arm comparison (§6.8) is the remaining EXPERIMENT PENDING study.
6.1 Why the problem exists
Three properties of agent editing create the stale-precondition problem. None of them is a model defect.
The model’s view is a snapshot. Whatever the model knows about a file is what some earlier tool call returned. Nothing updates that view when the file changes. A human editor shows a live buffer, and a model’s context does not.
Proposal and application are separated by unbounded time. A model request can take seconds or minutes. A run can include retries, approval pauses (Chapter 12) and, in a durable harness, a crash and resume (Chapter 10). The longer the gap, the more likely it is that the world has moved.
There are other writers. In a real repository, the agent is rarely the only writer. Formatters, build steps, the user’s own editor and, from Project 08, other agents all write to the same files. Even a single agent can be its own concurrent writer, when an earlier edit in the same run shifts the lines that a later proposal was computed against.
A harness that applies edits without checking the basis on which they were proposed is relying on luck. And luck fails silently. The edit “succeeds”: the tool returns success, the trace records success, and the error shows up later, if at all, as a test failure or a bug in someone else’s code. This is Chapter 4’s trace-versus-outcome gap appearing at the level of a single effect.
6.2 What a precondition is
A precondition is a predicate over the target’s state that must be true at application time for the operation to have the meaning its proposer intended. Three questions describe any particular precondition:
- What does it bind to? It might bind to a whole file, a line range, individual lines, a syntactic unit, or a path name.
- How is it expressed? It might be a digest of the bytes, a version number, the literal expected text, or a structural description.
- Who checks it, and when? The check might be made by the model (it cannot), by a host check before dispatch, or by the effect boundary atomically with the write.
Different edit formats answer these questions differently, often without saying so. The comparison below is a PROPOSED analysis for this book. It is not a measured ranking.
| Edit format | Implicit precondition | Typical silent failure | Typical spurious rejection |
|---|---|---|---|
| Line-number replace (“replace line 15”) | None beyond “line 15 exists” | Lines shifted, so the edit lands on the wrong statement | Rare. The format almost never refuses (unmeasured; decided by §6.8) |
| Search/replace (old text → new text) | Old text occurs, ideally exactly once | Old text occurs more than once and the wrong occurrence is changed; or the matching rule is loose | Whitespace or formatting changes break an otherwise correct match |
| Unified diff with fuzzy application | Context lines match approximately | Fuzz applies the hunk somewhere plausible but wrong | Few, which is exactly the danger (unmeasured; decided by §6.8) |
| Hash-anchored lines (each target line cited with a content hash) | Each cited line still has the cited content | Small, if anchors are verified | Any change to a cited line, including a harmless one |
| Whole-file base digest | The entire file is byte-identical to what was read | None, for that file | Any change anywhere in the file, including unrelated ones |
The table shows a basic trade-off. Strict preconditions turn silent corruption into visible refusals, and some of those refusals are unnecessary. A whole-file digest never applies an edit to a moved target, but it also refuses an edit to line 15 because someone fixed a typo on line 200. Anchored lines refuse less often but protect less: they verify what was cited and nothing else, so a semantically relevant change to an uncited line goes undetected. Neither is correct in general. The choice depends on what spurious refusals cost and what silent corruption costs, and that is an empirical question (§6.8).
Hash-anchored editing has public evidence behind it, with caveats.
Stencil’s edit-format study included an anchoring variant that the article
calls “hashline”, alongside other edit formats, across sixteen models on synthetic React inverse-mutation tasks
(R03-HARNESS-RESEARCH.md R03-C08; DOCUMENTED). The R03 dossier reads
the published chart as showing model × format interactions rather than a
universal winner. It notes that exact formatted-file comparison may reject
semantically correct alternatives, and that the benchmark’s code pin could
not be resolved, which blocks a faithful replication. Stencil measured
editing success. It did not measure stale-base rejection, which is this
chapter’s concern.
6.3 Where the check must happen
The model cannot check a precondition. It has no access to the current state of the file except through another tool call, and that call returns a new snapshot that may itself be stale by the time the edit is applied. The check belongs to the component that performs the write, at the moment it performs the write.
The naïve implementation is check-then-act. The host reads the file,
compares the digest, and then writes. This leaves a window in which
another writer can change the file after the comparison and before the
write. The R04 security dossier makes the same point about paths: checking
a pathname and then reopening it permits concurrent replacement, and a
handle stabilizes which object is accessed but not its bytes
(R04-SECURITY-RECOVERY.md R04-P03; PROPOSED, grounded in documented
Windows semantics R04-C01–C03). For editing, this means:
- Bind identity first. Open the target once and work through that handle, so that a rename or replacement of the path cannot swap in a different object between check and write. Full Windows treatment (junctions, hard links, casing, namespaces) belongs to Chapters 11–12. A Project 02 fixture should avoid those cases deliberately and say so.
- Stage, then publish under the guard. Write the new content to a
staging location, verify that the base precondition still holds, then
publish. R04 recommends staged output and guarded publication for local
file work, with recovery tied to the observed destination identity and
hash (R04-P06; PROPOSED). The Project 01 candidate already uses the
staging half of this pattern for its own evidence. It writes
bundle.json.partialand renames it into place, and it creates each run directory exclusively so that a historical attempt is never overwritten (supervisor.ts,writeBundle; source inspection). That code protects the harness’s record, not a user’s file, and it has no base-digest check because it never edits an existing file. It is the right shape, not yet the right mechanism. - State what the guard does not cover. Without operating-system locking or a transactional filesystem, a writer that does not cooperate can still race between the final verification and the rename. On a single-user development machine that window may be acceptable. If so, the contract should name it as a known gap, not leave it unmentioned. Proving a race-free publication protocol on Windows is not a Project 02 claim.
The precondition check also has to sit after every transformation of the
proposal. Pi 1.6.0 lets extension hooks block or mutate tool calls, and
mutated input is not revalidated (R02-PI.md C12; OBSERVED source inspection for the
inspected artifact, TEST NOT RUN). If the base digest is checked in a hook and a later
hook rewrites the target, the check described a proposal that no longer
exists. As in Chapter 5, the schema and hooks describe, and the handler at
the effect boundary decides.
6.4 The interface must carry the precondition
Chapter 5’s producibility principle applies with new force here. If the
edit tool requires a base digest, the model must be able to see that
digest in what it read. The Project 01 read interface already provides
this. Every fixture_read result header carries the file’s full content
digest and the exact range returned. A Project 02 edit tool can therefore
require, as part of its arguments, the digest the model was shown. That
turns a hidden race into an explicit contract: I propose this change to
the version of the file whose digest was X.
The Project 01 review’s recommendation for Project 02 says the same thing
directly. A write or patch must name the base content hash or version it
read. A stale base must be rejected. Before and after hashes must be
recorded (REVIEW.md §12; PROPOSED by the reviewer).
The interface must also make refusal informative. A stale-precondition error should name the cause with a distinct code and, where safe, return the current digest, so that the model knows it must re-read before re-proposing. Following Chapter 5, it must not quietly apply the edit to the new version. Rebasing an edit is a decision, and the model or a human must make it with the new content in view.
6.5 Reliable is not the same as correct
A precondition guarantees that an edit is applied to the content it was computed against. It says nothing about whether the edit is any good. A perfectly guarded edit can introduce a bug, delete a test, or change twelve files when one was asked for. These are different failures, and they need different checks:
| Failure | Check | Owner |
|---|---|---|
| Edit applied to the wrong base | Base precondition at application | Effect boundary |
| Edit changes more than was admitted | Expected file set and diff scope; no deletions outside the allowed set | Host policy and independent checker |
| Edit is syntactically invalid | Post-condition gate, such as a parser or linter, before publication | Effect boundary or host |
| Edit is semantically wrong | Independent tests or an oracle over the resulting file set | Evaluator |
The Project 01 reviewer’s Project 02 recommendations include the second
and fourth rows: verify patches with an independent checker, not the
model’s claim, checking the expected file set, the expected diff, no extra
changes and no deletions outside the allowed set (REVIEW.md §12). An
example of the third row is documented in SWE-agent. Its project notes
describe a linter that runs when an edit command is issued and refuses the
edit if the code is not syntactically correct
(SWE-agent ACI notes;
DOCUMENTED). This book does not measure what that gate contributes.
Keeping the rows separate matters for evaluation. If a Project 02 run is scored only on whether the final tests pass, a guarded editor and an unguarded one may look identical on runs without concurrent writers. The difference appears only when a stale base is deliberately injected. That is why the brief for this chapter is phrased as a fault-injection test, and not as a success-rate comparison.
6.6 Edits as state transitions
In the vocabulary of Chapter 3, an edit is a small state machine nested
inside the run’s RUNNING state. Writing it out shows which transitions
belong to whom. This is PROPOSED for Project 02.
| From | To | Trigger | Decided by |
|---|---|---|---|
| — | PROPOSED | Model emits an edit with base digest, target and replacement | Model (proposal only) |
| PROPOSED | REJECTED_INVALID | Schema or handler validation fails | Handler (deterministic) |
| PROPOSED | REJECTED_SCOPE | Target is outside the admitted file set | Host policy (deterministic) |
| PROPOSED | STAGED | New content written to staging; post-condition gate passes | Effect boundary |
| STAGED | REJECTED_STALE | Base precondition no longer holds | Effect boundary (deterministic) |
| STAGED | APPLIED | Precondition holds; content published; after-digest recorded | Effect boundary |
| APPLIED | VERIFIED / FAILED | Independent checker and oracle | Evaluator |
As in Chapter 3, the model acts on exactly one edge, the first. Every
refusal edge is deterministic and records its reason. The terminal
judgment (VERIFIED or FAILED) is made by the evaluator, after the
fact, from the resulting files. A Project 02 trace that shows APPLIED
has, as Chapter 4 insists, still not shown an outcome.
6.7 Worked example: a stale base, step by step
This section is an executed educational demonstration, D06-EDIT-01
(examples/pi-harness-lab/src/edit-gates.ts; test/edit-gates.test.ts,
15/15 pass offline). It edits a disposable copy of a fixture file in
a real temporary workspace, never the frozen Project 01 fixture. The
contract below is the implemented one, not a sketch:
// Implemented in examples/pi-harness-lab/src/edit-gates.ts (D06-EDIT-01, executed).
type EditProposal = {
proposalId: string; // replay protection: never applied twice
taskId: string; // must match the admitted task
target: string; // task-relative path; lexical policy + link binding
baseSha256: string; // full digest the proposer claims to have read
startLine: number; // 1-based inclusive range to replace
endLine: number;
replacement: string; // exact new text for that range
approval: { approver: string } | null; // separate approver, checked by the gate
};
type EditResult =
| { ok: true; afterSha256: string; changedLines: [number, number] }
| { ok: false; code: "TASK_MISMATCH" | "OUT_OF_SCOPE" | "STALE_BASE"
| "INVALID_ARGUMENTS" | "INVALID_RANGE" | "UNAUTHORIZED"
| "POSTCONDITION_FAILED" | "CONFLICT" | "REPLAYED";
detail: string; currentSha256?: string };
Timeline (executed).
- t₀. The model reads
src/a.tslines 1–6 and receives the header with digestD1. - t₁. The model proposes an edit with
baseSha256: D1, replacing lines 2–3, with arelease-captainapproval. - t₁ + δ. The fault hook, standing in for a formatter or another
writer, inserts a line at the top. The file’s digest is now
D2. - t₂. The effect boundary stages the replacement, re-reads the target
through the bound path, computes
D2 ≠ D1, discards the staging, and returns{ ok: false, code: "STALE_BASE", currentSha256: D2 }. Nothing is published. The receipt log records the proposal, the injected change, the refusal and both digests. - t₃. The model re-reads, receives
D2, and proposes against the new lines withbaseSha256: D2. The edit is staged, verified, passes its postcondition, published by atomic rename, andafterSha256is recorded with anACCEPTEDreceipt. - After the run. The test compares the resulting file with the expected content, confirms that no other file changed, and confirms that the injected line survived. An editor that “fixed” the conflict by overwriting the formatter’s change would fail this check even though its edit applied cleanly.
The same timeline against a line-number replace tool with no base carries no step 4: at t₂ it writes over the new lines 2–3 — the wrong lines — and reports success. Only step 6 discovers the damage. That contrast is the experiment, and both halves of it run in the suite.
The adversarial cases also run, each asserting the file is untouched
after refusal: parent-traversal, absolute and device-namespace targets;
a symlink inside the workspace pointing at an outside canary (refused by
real-path binding; canary byte-identical); wrong-task proposals;
out-of-scope files; malformed ranges and oversized replacements; a
postcondition failure that discards staging with the original intact; a
rival writer between staging and publish (CONFLICT); a replayed
proposal ID (REPLAYED, applied exactly once); self-issued and missing
approvals (UNAUTHORIZED); and a genuine approval presented against a
moved base — refused as STALE_BASE, because an approval never rebases
an edit by itself. Reproduce all of it with
npm --prefix examples/pi-harness-lab test.
6.8 Project 02 checkpoint: Reliable Editor
Blueprint requirement: apply a targeted code change; the new mechanisms are stable edit anchors, guarded tool schemas and precondition checks; the verification compares basic replace/patch with guarded edits under a matched model and task, and stale edits must be rejected.
Status: formal study not started. The Project 01 review’s §12 sequencing conditions still gate the formal study: resolve and re-review Project 01’s blocking findings first, use disposable fixtures, enforce per-task tools and budgets, verify patches independently, and fix trace, replay and joint-acceptance defects before adding effects. The educational demonstration D06-EDIT-01 already follows the disposable part of that contract (real temporary workspaces, per-task file sets, recorded receipts) with no dependency on Project 01 acceptance. Keep the scope small: no broker, database, ECK or adaptive routing unless a concrete defect requires it.
Proposed study design. All of the following is PROPOSED; EXPERIMENT PENDING.
| Arm | Edit interface | Precondition |
|---|---|---|
| E0 | Line-number replace | None |
| E1 | Search/replace with exact-once match | Implicit (old text present and unique) |
| E2 | Range replace with whole-file baseSha256 |
Explicit, strict |
| E3 | Hash-anchored lines | Explicit, per cited line |
| E-neg | E2 with the guard disabled (base accepted and ignored) | Ablation of the check alone |
The tasks are small targeted changes on disposable copies of synthetic fixtures, each with an independent expected result. The fault schedule is fixed in advance and identical across arms, and it injects concurrent modifications at scheduled points. Each modification is classified as overlapping (it touches the target lines), shifting (it moves them without touching them) or unrelated (elsewhere in the file). Endpoints:
- Stale applications: edits applied to a base that changed. These must be zero for E2 and E3 on overlapping and shifting faults.
- Spurious rejections: refusals on unrelated changes.
- Verified task completion by the independent oracle.
- Collateral damage: changes outside the target, including overwritten concurrent changes.
- Retries, calls, tokens and elapsed time, at a matched total budget.
The registered predictions are these. E0 shows stale applications on shifting faults. E1 shows fewer, but fails on duplicated text. E2 shows no stale applications and the most spurious rejections on unrelated faults. E3 sits between them on spurious rejections. E-neg reproduces E0’s failures, which confirms that the check, not the extra argument, is the cause. Any stale application under E2 or E3 falsifies the mechanism claim outright, whatever the completion rate. Following the Stencil interaction finding, any completion difference is expected to be model-specific and will be reported as such.
6.9 Failure modes
- Checking in the wrong place. The precondition is checked in a hook or by the model, and the write happens elsewhere later. Defence: check at the effect boundary, after every transformation (R02 C12).
- Check-then-act gap. The digest is compared, then the path is reopened for writing. Defence: bind the object once, stage, verify, publish, and name any remaining race in the contract.
- Silent rebase. On a stale base the tool “helpfully” reapplies the edit to the new content. Defence: refuse and return the current digest; the model or a human decides.
- Precondition without producibility. The tool demands a digest that the read interface does not show (Chapter 5). Defence: the read result carries the full digest.
- Guarded but wrong. A clean application of a bad edit. Defence: independent post-conditions and an oracle (§6.5).
- Overwriting a concurrent writer. The edit applies, and the injected change disappears. Defence: the oracle checks that unrelated changes survived.
6.10 What you can build and test now
D06-EDIT-01 already implements the core loop: the EditProposal handler
with task identity, lexical + link-bound path checks, base-digest
preconditions, shape validation, a separate-approval authority gate,
staged publish with re-verification, postcondition validation, replay
protection and recorded receipts — all against real temporary
workspaces. Extend it with the remaining §6.8 arms (E0 line-number
replace as the negative control, E1 search/replace, E3 hash anchors,
E-neg guard-disabled) and the fault schedule (overlapping, shifting,
unrelated) as shared data, so every arm receives exactly the same
faults.
6.11 What remains unverified
- Formal Project 02 acceptance (the §6.8 arm comparison with a matched model and task). The Project 01 prerequisites are not accepted.
- Pi 1.6.0’s built-in
edittool semantics: how it matches, whether it carries any precondition, and how it reports failure. R02 records that the factory exists (C03) but does not characterize its matching behaviour (UNKNOWN). This chapter makes no claim about it, and the demonstration uses a custom tool. - A race-free publication protocol on Windows (R04; Chapters 11–12). The demonstration names its residual race in the contract; it does not eliminate it.
- Whether stricter preconditions help or hurt any particular model’s completion rate (§6.8).
EXPERIMENT PENDING. The formal Project 02 arm comparison has not run; D06-EDIT-01 is an executed educational demonstration of the guard mechanism, not that study.
Part I has treated the model’s view of the world as something the harness can make correct: producible, current and guarded. It has quietly assumed that the view also fits. Project 01’s fixture is limited to 64 KiB of admitted text and its reads to 8 KiB, and that is exactly why the question never came up. Part II drops the assumption. Chapter 7 treats the context window as a bounded resource and asks what a harness should do when the evidence a task needs is larger than the space available to show it.