pi-file-write-guard

Read-before-write, staleness and truncation-write-back protection for pi's built-in write/edit tools

Packages

Package details

extension

Install pi-file-write-guard from npm and Pi will load the resources declared by the package manifest.

$ pi install npm:pi-file-write-guard
Package
pi-file-write-guard
Version
0.3.0
Published
Dec 4, 2026
Downloads
406/mo · 39/wk
Author
xuqianhui
License
MIT
Types
extension
Size
57 KB
Dependencies
0 dependencies · 1 peer
Pi manifest JSON
{
  "extensions": [
    "./extensions/write-guard.ts"
  ]
}

Security note

Pi packages can execute code and influence agent behavior. Review the source before installing third-party packages.

README

pi-file-write-guard

Stop pi's agent from destroying a file it only half-saw.

pi's built-in read returns at most 2000 lines / 50KB per call (hardcoded, no setting), and its write is a full overwrite with no checks in front of it. So the everyday pattern

read the whole file → splice something in → write the whole file back

silently deletes everything past line 2000 (or past the byte cap) — the tail was never in the model's hands. The same missing checks let an agent overwrite a file it never read, or write a copy back over someone else's later edit.

This extension adds that missing layer to the built-in write / edit tools, including calls nested inside codemode scripts.

pi install npm:pi-file-write-guard

What it blocks

code condition what it prevents
truncated_write target exists, new content is shorter, and it is still line-aligned at the same positions with the file (an exact prefix, or ≤2% positional mismatches) writing back a truncated read and silently dropping the tail
not_read target exists, was not read in this session, and the new content keeps less than keepRatio of its existing lines clobbering a file nobody looked at (path typo, config rewritten from memory)
modified_since_read file mtime moved past the watermark and its content hash differs (a pure touch is allowed) reverting an edit made by the user, another tool, or a previous turn
bash_mutation the bash command matches a file-mutating shape (>, >>, heredoc redirect, sed -i, perl -i, tee, dd of=, truncate) file changes sneaking around the gated tools, where neither the reviewable diff nor the gates apply

bash_mutation defaults to warn: it notifies and lets the command run. Flip it to "block" in codes once you trust the pattern list; the block message always offers the re-run escape (third identical attempt), so nothing deadlocks. Read-only forms (sed -n, 2>&1, /dev/null) are not flagged. Arbitrary shell is Turing-complete — this is a tripwire for the common accidental shapes, not a sandbox.

truncated_write is shape-based and needs no session state, so it keeps working after resume, /tree or compaction — which is why it is the first gate.

The read gates apply to write only (readGateTools). pi's edit re-reads the file and requires every oldText to match a unique region, so a successful edit is itself proof that the model saw the content — and a stale copy fails harmlessly. Gating edit costs a round trip and protects nothing.

not_read is self-evidencing: reproducing most of a file's existing lines without reading it is only possible if the model already knows them, so an overwrite that keeps ≥ keepRatio (default 50%) of the existing distinct lines passes. /tmp/x clobbered by unrelated content and a path typo still block. The check is a set comparison of trimmed non-blank lines, so it is position-independent and ignores reformatting/reordering.

The block reason carries the recovery path and ends with a machine-matchable line (write-guard: <code>).

Escapes (no deadlocks, but a blind retry does not pass)

  • Third attempt: the same code + path + content released on its third try. A blind identical retry once is still blocked.
  • Read what you drop: for truncated_write, a positional read at offset >= the last line the new content keeps releases the first attempt — the model has actually seen the part it is deleting.
  • Read fixes it: one read clears not_read; one re-read clears modified_since_read.
  • Use edit for a small change: it is not gated at all — the cheapest escape from not_read is a targeted replacement instead of a whole-file rewrite.
  • Replay on resume: session_start, session_tree and session_compact rebuild read state from the session branch (structured fields only; the watermark is the tool-result timestamp, which is the conservative direction).

Configuration

Global <agent-dir>/extensions/write-guard.json (default ~/.pi/agent/extensions/write-guard.json) is deep-merged with project <cwd>/.pi/write-guard.json, project winning. A malformed file falls back to the defaults.

{
  "enabled": true,
  "mode": "block",
  "codes": { "not_read": "block", "modified_since_read": "block", "truncated_write": "block" },
  "readGateTools": ["write"],
  "keepRatio": 0.5,
  "exempt": ["**/generated/**", "/var/log/**"]
}
key default meaning
enabled true turn the extension off entirely
mode "block" "warn" downgrades every gate to a notification (migration aid)
codes all "block" except bash_mutation: "warn" per-gate severity: block, warn, or off (off skips the gate and its work)
readGateTools ["write"] tools the read-state gates apply to; add "edit" for the strict behaviour
keepRatio 0.5 survival ratio above which an unread overwrite counts as self-evidencing
requireRead true legacy alias: false means codes.not_read: "off"
checkStaleness true legacy alias: false means codes.modified_since_read: "off"
exempt [] absolute-path globs; a relative pattern is anchored as **/<pattern>

An explicit codes key always wins over the legacy boolean.

Globs are matched by this package (src/glob.ts), not by node:path.matchesGlob: that matcher refuses to let ** cross a dot-prefixed segment, so **/generated/** silently fails under ~/.cache.

Limits

  • Only the built-in write / edit tools. bash redirection, MCP file tools and other extensions' file tools do not pass through here. In particular a file read through bash (cat, sed -n) does not count as a read: that is the main source of not_read false positives, and why not_read yields to the survival check instead of insisting on a read call.
  • Binary targets (containing NUL) and files over 32MB are skipped.
  • Content hashes are recorded for write and for full reads up to 1MB; edit records none, so a write right after an edit of the same file can only pass on an unchanged mtime.
  • Deliberate tradeoff: the truncation gate is content-shaped, so replacing a truncated read with entirely different content is allowed (a read-state gate would block it as a false positive), and an append on top of a truncated view is not flagged.

Development

npm install
npm run check     # tsc --noEmit + vitest
npm run pack:check

Layout: extensions/write-guard.ts wires pi's events; src/ is pure decision code (config, glob, shape, readstate, replay); test/ covers each rule plus end-to-end handler behaviour.

Release: npm publish (manual, from a tagged commit). See CHANGELOG.md.

License

MIT