Skip to content

Move became rewrite

Ask an agent to move code and it often doesn’t carry it — it reads what the code does and regenerates something equivalent at the destination. On large code that silently drops whatever it judged incidental: a comment kept on purpose, an exact type, an edge case. Nothing errors; the diff reads as a clean move. The fix is to make a move be a move — the destination must carry the origin’s bytes, not a reconstruction of them.

Watch a move regenerate — then get refused

The agent declares intent (#refactor) and a scope — the moves it commits to. Then two things are checked independently:

  1. A move that regenerated instead of carrying the bytes — refused by a gate before the write lands, and re-checked by a file-guard on the committed files at turn-end.

  2. A declared move that never happened — caught at turn-end by the completeness gate, which refuses the Stop.

A context ties them together, tracking the scope until every move lands. A context can only track; only a gate blocks a turn.

This is the real, working example shipped in the sloprail repo at examples/deterministic-refactoring-mode/. Three natures (a context, two gates and a file-guard), each a directory under .sloprail/ — a *.yaml declaration plus the scripts it names:

  • Directory.sloprail/
    • Directorycontext/
      • Directoryrefactoring/
        • context.yaml
        • enter.sh
        • exit.sh
    • Directoryfile-guard/
      • Directorymoved-content-reconciles/
        • file-guard.yaml
        • reconciles-against-origin.sh
    • Directorygate/
      • Directoryrefactor-complete/
        • gate.yaml
        • verify-declared-moves-landed.sh
      • Directorymoved-content-reconciles/
        • gate.yaml
        • reconciles-against-origin.sh
  • README.md

Tracks the refactor; never refuses. On a marked write it activates the scope; at Stop its enter reads the #refactor scope=… declaration and records the declared moves. Its exit closes the context once the gate says the refactor is complete — which is what carries a multi-turn refactor.

.sloprail/context/refactoring/context.yaml
# Tracks a declared refactor; never blocks (the blocking is the paired Stop
# gate `refactor-complete`, which reads the declared_markers this context's
# enter writes). Two triggers:
# - PreToolUse: activate the scope before a marked write, so the reconcile
# file-guard's `match: context["refactoring"].active` is true at that write.
# - PostTagWrite: fires at Stop once the turn is settled, so enter can read the
# `#refactor scope=...` declaration and populate declared_markers before the
# gate reads it (enters run before gates).
on:
- event: PreToolUse
- event: PostTagWrite
enter: ./enter.sh
exit: ./exit.sh
.sloprail/context/refactoring/enter.sh
#!/usr/bin/env bash
# Extract the declared refactor scope from the trajectory and print it as this
# context's payload. Each scope token is the fqn a landed `sr:moved-from` marker
# will carry — `<path>@<sha>:<start>-<end>` — so the gate can later check for a
# literal match. Printing nothing keeps the prior payload (it does not decline);
# the gate permits on an empty scope, so a turn with no #refactor is harmless.
set -uo pipefail
input="$(cat)"
transcript_path="$(printf '%s' "$input" | jq -r '.transcriptPath')"
# The declaration is one message with the #refactor tag and a scope list, e.g.
# #refactor scope=src/beta.go@<sha>:10-24,src/gamma.go@<sha>:3-9
# Take the last entry carrying the tag and read its text. The tag lives at
# .events[].tags[].label on a normalized entry (events are flat).
decl="$(sr-session trajectory normalize \
--path "$transcript_path" \
--events PostTagWrite \
| jq -r '
def msgtext:
if type == "string" then .
elif type == "array" then [.[] | select(.type? == "text") | .text] | join("")
elif type == "object" then [(.content // [])[] | select(.type? == "text") | .text] | join("")
else "" end;
[ .[]
| select(any(.events[]?;
.kind == "PostTagWrite" and any(.tags[]?; .label == "refactor")))
][-1] // {}
| .message | msgtext')"
if [ -z "$decl" ]; then
exit 0
fi
scope="$(printf '%s' "$decl" | grep -oE 'scope=[^ ]+' | head -1 | cut -d= -f2)"
jq -n --arg scope "$scope" \
'{declared_markers: ($scope | split(",")), declared_at: "trajectory"}'
.sloprail/context/refactoring/exit.sh
#!/usr/bin/env bash
# Pure lifecycle: consulted on a Stop while the context is active, this only
# decides whether to close the context — it cannot block (that's the gate's job).
# The refactor is finished exactly when the completeness gate passed this Stop,
# so read that verdict rather than re-deriving it. Staying open across a failing
# Stop is what carries a multi-cycle refactor.
set -uo pipefail
input="$(cat)"
# Nothing declared -> nothing to stay open for.
declared="$(printf '%s' "$input" | jq -r '.currentContext.payload.declared_markers[]?' 2>/dev/null)"
if [ -z "$declared" ]; then
exit 0
fi
# Default "fail" (context stays open) when the gate has no recorded verdict —
# the more-guarding direction.
status="$(printf '%s' "$input" | jq -r '.gates["refactor-complete"].status // "fail"' 2>/dev/null)"
if [ "$status" = "pass" ]; then
exit 0
fi
exit 1

Runs before a marked write lands, only while the context is active. It reconciles the pending bytes against their pinned origin; anything that doesn’t reconcile is a rewrite, and a rewrite is refused before it reaches the file. A write whose result can’t be computed (sed -i on a moved file) is refused too, since a gate does not fail closed on that by itself.

.sloprail/gate/moved-content-reconciles/gate.yaml
# Reconcile a moved file against its origin BEFORE the write lands — but only
# inside a declared refactor (the context link is a variable in the match, not a
# flat active_in) and only for a file carrying an sr:moved-from marker. The same
# marker outside the context is not this gate's business.
#
# A move that regenerated instead of carrying the bytes is the loss to prevent,
# so the check is a gate on PreFileCreate/PreFileUpdate: the write is refused and
# never lands. The file-guard of the same name keeps the Stop-time reconcile on the
# settled file. The gate's match reads the event nested (`event.newMarkers`); the
# file-guard's reads `markers` bare.
#
# Two triggers, not the PreFileWrite alias, because the second reads a field only
# an update carries. On an update whose result the engine cannot compute (`sed -i`)
# the pending markers are unknown, so the trigger also selects a file that ALREADY
# carries the marker (`oldMarkers`): an in-place edit of a moved file cannot be
# reconciled, and the script refuses it rather than let it through unseen.
on:
- event: PreFileCreate
match: 'context["refactoring"].active and any(event.newMarkers, .kind == "moved-from")'
- event: PreFileUpdate
match: 'context["refactoring"].active and (any(event.newMarkers, .kind == "moved-from") or (not event.resultKnown and any(event.oldMarkers, .kind == "moved-from")))'
checks:
- script: ./reconciles-against-origin.sh
.sloprail/gate/moved-content-reconciles/reconciles-against-origin.sh
#!/usr/bin/env bash
# A file carrying an sr:moved-from marker must be byte-identical to its origin at
# the pinned commit, minus imports and whitespace. The marker's fqn carries
# <path>@<sha>:<start>-<end>.
#
# This is the PRE-WRITE copy (the gate): it reads the pending bytes off a
# PreFileCreate/PreFileUpdate. The file-guard of the same name keeps the Stop-time
# copy, which reads the settled bytes.
lib_dir="$(cd "$(dirname "$0")/../../file-guard/moved-content-reconciles" && pwd)"
unset reconciles_against_origin_lib_loaded
. "$lib_dir/reconciles-against-origin-lib.sh" || exit 2
[ "${reconciles_against_origin_lib_loaded:-}" = 1 ] || exit 2
lib_init
# resultKnown, not has("newContent") — newContent is ALWAYS a present key on
# PreFileCreate/PreFileUpdate, so has("newContent") is always true and an absent
# value reads as "", indistinguishable from a write that genuinely empties the
# file. The "engine could not predict the result" signal is resultKnown. A gate
# does not fail closed on it by itself, and a reconcile against bytes nobody saw
# would be no check at all, so refuse: a write whose result cannot be computed
# (sed -i, an unresolvable sr-file line) is not admitted.
known="$(printf '%s' "$input" | jq -r '.event.resultKnown // false')"
if [ "$known" != "true" ]; then
jq -n '{reason: "This write carries an sr:moved-from marker but the bytes it would leave in the file cannot be worked out from the command, so it cannot be reconciled against its origin. Write the moved content directly (the whole file) instead of editing it in place. If you use sr-file, run it alone in its own Bash call, with nothing before or after it on the line: another command beside it (sr-file ...; cat X) is what makes the bytes unknowable, and the edit itself is allowed."}'
exit 1
fi
new="$(printf '%s' "$input" | jq -r '.event.newContent')"
lib_check

The after-check of the same name. A file-guard judges commits, so at Stop (once the moves are committed) it runs the same reconcile on each moved file of the changeset — the backstop for a write the gate could not see.

.sloprail/file-guard/moved-content-reconciles/file-guard.yaml
# Reconcile a moved file against its origin at Stop, for every file of the committed
# range carrying an sr:moved-from marker.
#
# The match reads no context: a file-guard judges committed bytes (in CI, with no
# session), and a context is session state. Whether a refactor is DECLARED is the
# gates' business (gate/moved-content-reconciles and gate/refactor-complete read
# the refactoring context live); this backstop only reconciles what the commits
# hold.
#
# This judges the committed changeset: each file the range touched that carries the
# marker is reconciled as committed. The PREVENTION — refusing a move that
# regenerated instead of carrying the bytes, before the write lands — is the
# PreFileWrite gate of the same name (gate/moved-content-reconciles); this is the
# backstop for a write the gate could not see (a command the engine does not parse).
match: any(markers, .kind == "moved-from")
checks:
- script: ./reconciles-against-origin.sh
.sloprail/file-guard/moved-content-reconciles/reconciles-against-origin.sh
#!/usr/bin/env bash
# A file carrying an sr:moved-from marker must be byte-identical to its origin at
# the pinned commit, minus imports and whitespace. The marker's fqn carries
# <path>@<sha>:<start>-<end>.
#
# This is the FILE-GUARD copy: it reads each moved file's committed bytes from the
# Changeset, always known (committed blobs have no "could not be read" case), and
# reconciles every file in it. The gate of the same name keeps the pre-write copy,
# which reads the pending bytes and consults `resultKnown`.
lib_dir="$(cd "$(dirname "$0")" && pwd)"
unset reconciles_against_origin_lib_loaded
. "$lib_dir/reconciles-against-origin-lib.sh" || exit 2
[ "${reconciles_against_origin_lib_loaded:-}" = 1 ] || exit 2
lib_init
[ "$(printf '%s' "$input" | jq -r '.event.kind // ""')" = "Changeset" ] || {
jq -n '{reason: "reconciles-against-origin: expected a Changeset event, so the moved files could not be reconciled."}'
exit 1
}
n="$(printf '%s' "$input" | jq -r '.changeset.files | length')" || n=""
case "$n" in '' | *[!0-9]*)
jq -n '{reason: "reconciles-against-origin: the changeset'"'"'s files could not be read, so nothing was reconciled."}'
exit 1
;;
esac
i=0
while [ "$i" -lt "$n" ]; do
path="$(printf '%s' "$input" | jq -r --argjson i "$i" '.changeset.files[$i].path // ""')" || exit 1
# A file whose committed content or markers are missing from the payload was not
# reconciled: refuse, naming it, rather than read the gap as "no moved-from marker".
new="$(printf '%s' "$input" | jq -r --argjson i "$i" '.changeset.files[$i].newContent | if type == "string" then . else error("missing") end' 2>/dev/null)" &&
markers="$(printf '%s' "$input" | jq -c --argjson i "$i" '.changeset.files[$i].newMarkers | if type == "array" then . else error("missing") end' 2>/dev/null)" || {
jq -n --arg path "$path" '{reason: ($path + ": its committed content or markers are missing from the changeset, so it could not be reconciled against its origin.")}'
exit 1
}
i=$((i + 1))
lib_reconcile
done
exit 0

The piece that blocks. It wakes at Stop when a refactor is active, reads the declared scope, and searches the tree for the sr:moved-from marker each move should have left. Any missing → the turn is refused.

.sloprail/gate/refactor-complete/gate.yaml
# The completeness half: every declared move must actually land. This is the
# piece that blocks — a context cannot, only a gate does. Match on the context's
# active flag skips the check when no refactor was declared; `require` orders the
# context first, so the gate reads its settled declared_markers.
on:
- event: Stop
match: context["refactoring"].active
require:
- context: refactoring
checks:
- script: ./verify-declared-moves-landed.sh
.sloprail/gate/refactor-complete/verify-declared-moves-landed.sh
#!/usr/bin/env bash
# Every declared move must have landed. The declared scope is the paired
# context's payload (.context.refactoring.payload.declared_markers); `require`
# guarantees it's settled before this runs. Each token is the fqn a landed
# `sr:moved-from` marker carries, so "did this move land" is a literal search of
# the tree for that marker — the file-guard has already checked the bytes.
#
# Portability: no mapfile/readarray (bash 3.2 lacks them); sets are carried as
# newline-delimited strings walked with `while read`.
set -uo pipefail
input="$(cat)"
# Empty -> nothing declared -> permit (a missing scope must not be a false refusal).
declared="$(printf '%s' "$input" \
| jq -r '.context.refactoring.payload.declared_markers[]? | select(. != "")' 2>/dev/null)"
if [ -z "$declared" ]; then
exit 0
fi
root="${SR_WORKSPACE:-.}"
# grep -F: the fqn is a literal (contains . @ : -). Leader-agnostic; .git skipped.
missing=""
while IFS= read -r fqn; do
[ -z "$fqn" ] && continue
if ! grep -rIF --exclude-dir=.git -- "sr:moved-from $fqn" "$root" >/dev/null 2>&1; then
if [ -z "$missing" ]; then
missing="$fqn"
else
missing="$missing, $fqn"
fi
fi
done <<EOF
$declared
EOF
if [ -n "$missing" ]; then
jq -n --arg detail "$missing" \
'{reason: ("Refactor declared but not complete — these declared moves never landed as an sr:moved-from marker: " + $detail + ". Finish the moves you declared, or the turn cannot end.")}'
exit 1
fi
exit 0