@lenard9191/pi-edit-guard 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,21 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.3.0 — 2026-10-27
6
+
7
+ - **Checkpoints expire after `storeMaxAgeDays` in every session, and the default is 7 days (was 30).** Before, retention trimmed only the session that took a checkpoint. The checkpoints and journals of earlier sessions stayed as long as their store was in use, so the store of a project you use every day grew without bound. Now a checkpoint older than `storeMaxAgeDays` is deleted with its journal and the objects only it held: at session start in every store, and after each run in the current one. `keepRuns` still caps each session, and stores unused for `storeMaxAgeDays` are still deleted. The first session after the update deletes the checkpoints older than 7 days; set `storeMaxAgeDays` to keep more.
8
+ - Fixed: a project that contains π's agent directory (one that versions `~/.pi/agent` in git) snapshotted the stores. Each snapshot copied every store, its own packs included, into its store: one such store reached 1.2 GB with a single checkpoint. An `/undo` in that project could also rewrite or delete store files. Now the stores are never staged, entries an earlier version staged leave the next snapshot, a restore never writes inside the stores, and `stores/.gitignore` keeps them out of the project's git. To get the space back at once, delete that project's store under `~/.pi/agent/pi-edit-guard/stores/` (its `ROOT` file names the project).
9
+ - Fixed: a file that an ignore rule matched after a snapshot took it (a new `.gitignore` line, an `exclude` pattern) stayed in every later snapshot, and each change to it was stored again. It now leaves the next snapshot, as the documented domain says. So a new `exclude` pattern shrinks a store once the checkpoints that hold the file expire. `/undo` restores such a file from the checkpoints that hold it, and leaves it alone when it has not changed.
10
+ - Fixed: `/undo` of an earlier run did not restore an ignored file that only a later checkpoint held, after a shell deleted it.
11
+
12
+ ## 0.2.0 — 2026-10-22
13
+
14
+ - **Bundled Agent Skill** `edit-guard` (`/skill:edit-guard`). The model loads it on demand to explain each `edit-guard:` message and what to do, and to point you to `/undo` when you ask it to revert its work, instead of running `git checkout`, `git stash` or `git reset`. It documents every command and configuration key. The `pi` manifest declares it, so the π catalog lists the package as an extension and a skill.
15
+ - **OpenSSF.** The README shows the OpenSSF Scorecard badge. `.github/security-insights.yml` gives the project's security facts in the OpenSSF Security Insights 2.2.0 format, validated against the official schema. `.bestpractices.json` holds the evidence for 65 of the 67 OpenSSF Best Practices "passing" criteria and 22 of the 24 Baseline level 1 controls; bestpractices.dev reads it to fill in the badge application.
16
+ - **Discoverability.** A landing site at <https://jlrrequina.github.io/pi-edit-guard/> with Open Graph and Twitter cards, `SoftwareApplication`, `SoftwareSourceCode` and `FAQPage` structured data and a sitemap, published by a pinned Pages workflow. `llms.txt` (llmstxt.org format) in the package and on the site. A cover image for the π catalog, the README and link previews. A README tagline, badges, an FAQ and links; more npm keywords; the npm homepage is the site.
17
+ - Fixed: the README linked `CONTRIBUTING.md` and `SECURITY.md` relatively. The π catalog resolves relative links against the published package, which does not contain those files, so both links returned 404. They are absolute now, and a test rejects a relative link to a file that is not published.
18
+ - Tests guard the metadata: π's loader accepts the skill, and the skill documents every command, message and configuration key; the FAQ is the same in the README, the site and its structured data; the site, the sitemap and the Pages workflow agree; `llms.txt`, the Security Insights file and the Best Practices answers link only to files that exist; the tarball smoke test requires the skill and `llms.txt`.
19
+
5
20
  ## 0.1.0 — 2026-10-22
6
21
 
7
22
  First release.
package/README.md CHANGED
@@ -1,15 +1,26 @@
1
1
  # pi-edit-guard
2
2
 
3
- A π ([pi-coding-agent](https://github.com/earendil-works/pi)) extension that stops three failures of an agent that edits files, mechanically:
3
+ **Exact `/undo`, stale-edit protection and a loop breaker for the π (pi) coding agent.** A [π](https://pi.dev) extension that blocks edits to files that changed since the agent read them, snapshots the project before each run so `/undo` restores it exactly, and stops repeated identical tool calls.
4
4
 
5
- 1. **It writes a file it has not seen as it is now.** A write to an existing file needs a read of that file whose content still matches the disk (compare-and-swap on content).
6
- 2. **It changes files you cannot get back.** Every run that can change files starts with a snapshot, and `/undo` restores it exactly.
7
- 3. **It repeats a call that cannot help.** An identical call with nothing changed in between is blocked when it depends only on the files, and flagged when it can depend on something else.
5
+ [![npm version](https://img.shields.io/npm/v/@lenard9191/pi-edit-guard)](https://www.npmjs.com/package/@lenard9191/pi-edit-guard)
6
+ [![npm downloads](https://img.shields.io/npm/dm/@lenard9191/pi-edit-guard)](https://www.npmjs.com/package/@lenard9191/pi-edit-guard)
7
+ [![π package](https://img.shields.io/badge/pi.dev-package-8A2BE2)](https://pi.dev/packages/@lenard9191/pi-edit-guard)
8
+ [![CI](https://img.shields.io/github/actions/workflow/status/jlrrequina/pi-edit-guard/release.yml?branch=main&label=CI)](https://github.com/jlrrequina/pi-edit-guard/actions/workflows/release.yml?query=branch%3Amain)
9
+ [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/jlrrequina/pi-edit-guard/badge)](https://scorecard.dev/viewer/?uri=github.com/jlrrequina/pi-edit-guard)
10
+ [![license](https://img.shields.io/npm/l/@lenard9191/pi-edit-guard)](LICENSE)
8
11
 
9
12
  ```bash
10
13
  pi install npm:@lenard9191/pi-edit-guard
11
14
  ```
12
15
 
16
+ ![pi-edit-guard: a stale edit blocked, a repeated call stopped, and /undo restoring the state before a run](https://raw.githubusercontent.com/jlrrequina/pi-edit-guard/main/docs/cover.png)
17
+
18
+ It stops three failures of an agent that edits files, mechanically:
19
+
20
+ 1. **It writes a file it has not seen as it is now.** A write to an existing file needs a read of that file whose content still matches the disk (compare-and-swap on content).
21
+ 2. **It changes files you cannot get back.** Every run that can change files starts with a snapshot, and `/undo` restores it exactly.
22
+ 3. **It repeats a call that cannot help.** An identical call with nothing changed in between is blocked when it depends only on the files, and flagged when it can depend on something else.
23
+
13
24
  Nothing is written into your project or its `.git`. Everything lives under `~/.pi/agent/pi-edit-guard/`.
14
25
 
15
26
  ## Guarantees
@@ -36,7 +47,7 @@ edit-guard: this command failed 2 times after changes. Stop. Re-read the relevan
36
47
 
37
48
  An observation lasts while the tool result that delivered it is in the model's context. Each one is stored in the session (`edit-guard/observation` entries) and rebuilt from π's own projection of the branch on resume, fork, `/tree`, compaction and context edits: a read that compaction summarized, or that an extension pruned, must be repeated; a read that compaction kept verbatim stays valid. Changes made by you, another agent or a formatter are caught by the hash.
38
49
 
39
- **Snapshots.** Each project root (the git top level, or the working directory outside git) has a private git object store under `~/.pi/agent/pi-edit-guard/stores/`, with its own persistent index, so after the first snapshot only changed files are hashed. The project's `.git` is only read (`rev-parse`, `ls-files`), never written. The first call of a run that can change files (anything except `read`, `grep`, `find`, `ls` and the other read-only tools; unknown tools count as changing) records the tree as `refs/runs/<session>/<n>`. What the tree holds is git's view of the root: tracked and untracked files that are not ignored, plus files your project tracks although an ignore rule matches them. Content is stored byte for byte: the project's `.gitattributes` (line endings, LFS and other filters) do not apply. Names keep their case, also where the file system ignores case (Windows, macOS): a file renamed from `Foo.ts` to `foo.ts` comes back as `Foo.ts`.
50
+ **Snapshots.** Each project root (the git top level, or the working directory outside git) has a private git object store under `~/.pi/agent/pi-edit-guard/stores/`, with its own persistent index, so after the first snapshot only changed files are hashed. The project's `.git` is only read (`rev-parse`, `ls-files`), never written. The first call of a run that can change files (anything except `read`, `grep`, `find`, `ls` and the other read-only tools; unknown tools count as changing) records the tree as `refs/runs/<session>/<n>`. What the tree holds is git's view of the root: tracked and untracked files that are not ignored, plus files your project tracks although an ignore rule matches them. A file that an ignore rule matches later (a new `.gitignore` line, an `exclude` pattern) leaves the next snapshot. A project that versions `~/.pi/agent` contains the stores: they are never part of its snapshots, and `stores/.gitignore` keeps them out of its git. Content is stored byte for byte: the project's `.gitattributes` (line endings, LFS and other filters) do not apply. Names keep their case, also where the file system ignores case (Windows, macOS): a file renamed from `Foo.ts` to `foo.ts` comes back as `Foo.ts`.
40
51
 
41
52
  The first snapshot of a root writes every file into the store, which takes seconds on a large project. It starts in the background with the session's first prompt, while the model works, so the snapshot before the run's first change only adds what changed since.
42
53
 
@@ -59,6 +70,8 @@ Files a write tool changes that the snapshot does not hold (an ignored `.env`, a
59
70
 
60
71
  `/undo` touches only the paths that differ, so your unrelated work stays. Paths you changed by hand during the run are reverted too: that is why it shows them first. Agents cannot call `/undo`; an agent reverts its own work with edits.
61
72
 
73
+ The package also ships an [Agent Skill](https://agentskills.io) (`/skill:edit-guard`). The model loads it on demand to explain the guard's messages, and to point you to `/undo` when you ask it to revert its work, instead of running `git checkout`, `git stash` or `git reset`.
74
+
62
75
  ## Coverage
63
76
 
64
77
  Restored exactly by `/undo`: content, executable bit, symlink targets and the case of the names of every file in the snapshot; files a write tool changed outside it (ignored files, files outside the root); files created during the run are deleted, and directories left empty are removed.
@@ -87,9 +100,9 @@ A run whose snapshot failed cannot be undone; `/undo` says so and names the run
87
100
  | `writeTools` | `{ "edit": "path", "write": "path" }` | Tools that change exactly one file, with the argument that names it. A value can also be `{ "path": "…", "when": "<argument>", "observes": false }`: only calls with that argument set write, and the result does not show the new content. When `lsp_fix` is installed and this key is not set, it is added as `{ "path": "path", "when": "write", "observes": false }`. |
88
101
  | `readOnlyTools` | `read`, `grep`, `find`, `ls`, `ffgrep`, `fffind`, `tool_search`, `vcc_recall`, `lsp_diagnostics` | Tools that never change files. Every other tool counts as changing. |
89
102
  | `volatileTools` | `bash`, `powershell`, `interactive_shell`, `agent_browser`, `agent_browser_code`, `web_search`, `fetch_content`, `codemode`, `run_checks` | Tools whose result can depend on more than the files: they get the failure notice. |
90
- | `exclude` | `[]` | More patterns the store ignores (`.gitignore` syntax). |
103
+ | `exclude` | `[]` | More patterns the store ignores (`.gitignore` syntax). Files that match leave the next snapshot; their copies go when the checkpoints that hold them expire. |
91
104
  | `keepRuns` | `20` | Run checkpoints kept per session (and as many pre-undo checkpoints). |
92
- | `storeMaxAgeDays` | `30` | Stores not used for this long are deleted at session start, as are stores whose project was deleted. |
105
+ | `storeMaxAgeDays` | `7` | Checkpoints older than this are deleted with their journals, in every session, at session start and after each run. Stores not used for this long, and stores whose project was deleted, are deleted at session start. |
93
106
 
94
107
  Outside git, the store also ignores `.git`, `node_modules`, `.pnpm-store`, `dist`, `build`, `out`, `target`, `.venv`, `venv`, `__pycache__`, `.next`, `.nuxt`, `.cache`, `coverage` and `.DS_Store`. In a git work tree the project's own ignore rules decide.
95
108
 
@@ -97,7 +110,7 @@ Outside git, the store also ignores `.git`, `node_modules`, `.pnpm-store`, `dist
97
110
 
98
111
  ## Secrets
99
112
 
100
- A snapshot or journal can contain secrets: an ignored `.env` that the agent wrote is copied to the journal so `/undo` can restore it. These copies exist only under `~/.pi/agent/pi-edit-guard/`, in directories only you can read (mode 0700 on macOS and Linux; on Windows, the permissions of your user profile); the extension never sends them anywhere and never pushes the store. Old runs are deleted after `keepRuns` runs, and whole stores after `storeMaxAgeDays`. Delete `~/.pi/agent/pi-edit-guard/stores/` at any time to remove them all.
113
+ A snapshot or journal can contain secrets: an ignored `.env` that the agent wrote is copied to the journal so `/undo` can restore it. These copies exist only under `~/.pi/agent/pi-edit-guard/`, in directories only you can read (mode 0700 on macOS and Linux; on Windows, the permissions of your user profile); the extension never sends them anywhere and never pushes the store. A checkpoint and its journal are deleted after `storeMaxAgeDays` days, or earlier when its session has more than `keepRuns` runs; a whole store after `storeMaxAgeDays` days without use. Delete `~/.pi/agent/pi-edit-guard/stores/` at any time to remove them all.
101
114
 
102
115
  ## Decided out
103
116
 
@@ -134,6 +147,44 @@ Most of a first snapshot is writing one git tree object per directory (django ha
134
147
 
135
148
  π 1.2.0 or later (tested with 1.2.0 and 1.3.0), Node 22.18 or later, and `git`. macOS, Linux and Windows; CI runs every test on all three. On Windows, π needs Git for Windows for its bash tool, and the guard uses the `git.exe` of that installation when `git` is not on the `PATH`.
136
149
 
150
+ ## FAQ
151
+
152
+ ### Does it work with Claude Code, Cursor or Codex?
153
+
154
+ No. It is an extension for the π coding agent only: it works through π's extension API (tool-call events, session entries and commands).
155
+
156
+ ### Does it write into my project or its .git?
157
+
158
+ No. Its state lives under `~/.pi/agent/pi-edit-guard/`. The project's `.git` is only read (`rev-parse`, `ls-files`): your commits, index, branches and stash are never touched. Only `/undo` writes project files, and only the ones that differ.
159
+
160
+ ### How is /undo different from git checkout or git stash?
161
+
162
+ `/undo` restores the state before an agent run: every file git sees in the project (tracked, and untracked but not ignored), the ignored files a write tool changed, executable bits, symlinks and the case of names. Files the run created are deleted. It shows the paths first, touches only those, and leaves your commits, index, branches and stash alone. It takes a pre-undo checkpoint first, so `/undo pre-undo-<k>` reverses it.
163
+
164
+ ### Why was the agent's edit blocked?
165
+
166
+ The file is not as the agent last read it: the agent did not read it in the current context, or its content changed since (you, a formatter or another agent edited it). One `read` repairs it. The block exists so that the agent never overwrites a change it has not seen.
167
+
168
+ ### Does it slow the agent down?
169
+
170
+ The freshness check takes about 0.1 ms per write. A snapshot after the first takes 60–320 ms on nine public repositories, from express to symfony. The first snapshot of a project runs in the background from the session's first prompt.
171
+
172
+ ### Can the agent undo its own changes?
173
+
174
+ No. `/undo` is a command for you, because throwing away changes in the working tree is your decision. The agent reverts its own work with edits. The bundled skill tells the agent to point you to `/undo` instead of running `git checkout`, `git stash` or `git reset`.
175
+
176
+ ### Does it work on Windows?
177
+
178
+ Yes, with Git for Windows, which π needs for its bash tool. CI runs every test on Windows, macOS and Linux. On Windows, a symlink can be restored only with Developer Mode on or with administrator rights.
179
+
180
+ ## Links
181
+
182
+ - npm: <https://www.npmjs.com/package/@lenard9191/pi-edit-guard>
183
+ - π package catalog: <https://pi.dev/packages/@lenard9191/pi-edit-guard>
184
+ - Site: <https://jlrrequina.github.io/pi-edit-guard/> · [`llms.txt`](llms.txt) for language models
185
+ - [Changelog](CHANGELOG.md) · [Security policy](https://github.com/jlrrequina/pi-edit-guard/blob/main/SECURITY.md) · [Contributing](https://github.com/jlrrequina/pi-edit-guard/blob/main/CONTRIBUTING.md) · [Constraints for changes](https://github.com/jlrrequina/pi-edit-guard/blob/main/AGENTS.md)
186
+ - OpenSSF: [Scorecard](https://scorecard.dev/viewer/?uri=github.com/jlrrequina/pi-edit-guard) · [Security Insights](https://github.com/jlrrequina/pi-edit-guard/blob/main/.github/security-insights.yml)
187
+
137
188
  ## Development
138
189
 
139
190
  ```bash
@@ -145,7 +196,7 @@ npm run corpus # snapshot and restore of public repositories, with timings
145
196
  pi -e ./index.ts # try the working copy
146
197
  ```
147
198
 
148
- See [CONTRIBUTING.md](CONTRIBUTING.md) to contribute and [SECURITY.md](SECURITY.md) to report a vulnerability.
199
+ See [CONTRIBUTING.md](https://github.com/jlrrequina/pi-edit-guard/blob/main/CONTRIBUTING.md) to contribute and [SECURITY.md](https://github.com/jlrrequina/pi-edit-guard/blob/main/SECURITY.md) to report a vulnerability.
149
200
 
150
201
  ## License
151
202
 
package/config.ts CHANGED
@@ -49,7 +49,7 @@ export const DEFAULTS = {
49
49
  volatileTools: ["bash", "powershell", "interactive_shell", "agent_browser", "agent_browser_code", "web_search", "fetch_content", "codemode", "run_checks"],
50
50
  exclude: [] as string[],
51
51
  keepRuns: 20,
52
- storeMaxAgeDays: 30,
52
+ storeMaxAgeDays: 7,
53
53
  };
54
54
 
55
55
  /** Store excludes for roots that are not git work trees; a git root uses the project's own ignore rules. */
package/guard/snapshot.ts CHANGED
@@ -3,6 +3,8 @@
3
3
  * project's own `.git`.
4
4
  *
5
5
  * store <base>/stores/<sha256(root)[0:16]>/ bare repository, ROOT, LAST_USED
6
+ * <base>/stores/.gitignore "*": a project that contains the stores
7
+ * (one that versions π's agent directory) never sees them
6
8
  * index <store>/index private, persistent (stat cache)
7
9
  * refs refs/runs/<session>/<n> state before run n
8
10
  * refs/pre-undo/<session>/<k> state before undo k
@@ -25,6 +27,7 @@ import { chmod, copyFile, lstat, mkdir, mkdtemp, readdir, readFile, readlink, re
25
27
  import { homedir, tmpdir } from "node:os";
26
28
  import { basename, dirname, join, parse as parsePath, resolve, sep, win32 } from "node:path";
27
29
  import { DEFAULT_EXCLUDES } from "../config.ts";
30
+ import type { Config } from "../config.ts";
28
31
  import { insideRoot } from "./paths.ts";
29
32
 
30
33
  // ---------------------------------------------------------------------------
@@ -141,7 +144,7 @@ function spawnGit(args: readonly string[], cwd: string, env: NodeJS.ProcessEnv,
141
144
  }
142
145
 
143
146
  /** Every git call on a store: `git --git-dir=<store> --work-tree=<root>` with the private index. */
144
- export function runGit(store: Store, args: readonly string[], opts: { input?: string | Buffer; ok?: readonly number[] } = {}): Promise<GitOutput> {
147
+ export function runGit(store: Pick<Store, "dir" | "root">, args: readonly string[], opts: { input?: string | Buffer; ok?: readonly number[] } = {}): Promise<GitOutput> {
145
148
  return spawnGit([`--git-dir=${store.dir}`, `--work-tree=${store.root}`, ...STORE_CONFIG, ...args], store.root, gitEnv({ GIT_INDEX_FILE: join(store.dir, "index"), ...IDENTITY }), opts.input, opts.ok ?? [0]);
146
149
  }
147
150
 
@@ -243,6 +246,7 @@ export async function openStore(base: string, root: Root, exclude: readonly stri
243
246
  await mkdir(dir, { recursive: true, mode: 0o700 });
244
247
  await spawnGit(["init", "--bare", "--quiet", dir], dir, gitEnv({}), undefined, [0]);
245
248
  }
249
+ await writeFile(join(base, "stores", ".gitignore"), "# pi-edit-guard: private snapshot stores, never part of a project\n*\n");
246
250
  await writeFile(join(dir, "ROOT"), `${root.root}\n`);
247
251
  await mkdir(join(dir, "info"), { recursive: true });
248
252
  // A git root keeps the project's own notion of content (.gitignore files, its info/exclude);
@@ -302,20 +306,49 @@ export function safeSession(id: string): string {
302
306
 
303
307
  export type TreeResult = { tree: string; unreadable: string[] };
304
308
 
309
+ const under = (dir: string, rel: string) => rel === dir || rel.startsWith(`${dir}/`);
310
+
311
+ /**
312
+ * The stores directory relative to the root, when the root contains it: a project that versions π's
313
+ * agent directory. A snapshot that held it would copy every store, its own included, at each run.
314
+ */
315
+ function storesIn(store: Store): string | undefined {
316
+ try {
317
+ return insideRoot(store.root, realpathSync.native(dirname(store.dir)));
318
+ } catch {
319
+ return undefined;
320
+ }
321
+ }
322
+
305
323
  /** Stage the root in the private index and write its tree. Paths git cannot read are skipped and reported. */
306
324
  export async function snapshotTree(store: Store): Promise<TreeResult> {
307
325
  return withLockRetry(store, async () => {
308
326
  const links = await linkedDirectories(store);
309
- const add = await runGit(store, ["add", "-A", "--ignore-errors"], { ok: [0, 1] });
327
+ // The private index entries an ignore rule matches, and the files the project tracks although one matches them.
328
+ const [ignored, tracked] = await Promise.all([
329
+ runGit(store, ["ls-files", "-z", "-c", "-i", "--exclude-standard"]).then((o) => o.stdout),
330
+ store.git ? projectGit(store.root, ["ls-files", "-z", "-c", "-i", "--exclude-standard"]).then((o) => o.stdout) : Buffer.alloc(0),
331
+ ]);
332
+ // git applies ignore rules only to files outside the index, and the private index keeps what a snapshot took: a
333
+ // file ignored since (a new .gitignore line, an `exclude` pattern) would stay in every later snapshot. It leaves
334
+ // before staging, so it is not hashed again; the project's own files stay.
335
+ const projects = new Set(tracked.toString("utf8").split("\0"));
336
+ const stale = ignored.toString("utf8").split("\0").filter((rel) => rel && !projects.has(rel));
337
+ if (stale.length) await runGit(store, ["update-index", "-z", "--force-remove", "--stdin"], { input: stale.join("\0") });
338
+ // The stores are never staged, so never hashed; entries an older version staged are dropped below.
339
+ const stores = storesIn(store);
340
+ const add = await runGit(store, ["add", "-A", "--ignore-errors", ...(stores === undefined ? [] : ["--", `:(exclude,literal)${stores}`])], { ok: [0, 1] });
310
341
  const unreadable = [...add.stderr.matchAll(/^error: unable to index file '(.*)'$/gm)].map((m) => m[1]!);
311
342
  if (add.code === 1 && unreadable.length === 0) throw new GitError("add", add);
312
- if (store.git) {
313
- // Files the project tracks although an ignore rule matches them are part of its content.
314
- // Their names are paths, not patterns: a tracked "*.log" must not stage every ignored .log file.
315
- const tracked = await projectGit(store.root, ["ls-files", "-z", "-c", "-i", "--exclude-standard"]);
316
- if (tracked.stdout.length) await runGit(store, ["--literal-pathspecs", "add", "-f", "--ignore-errors", "--pathspec-from-file=-", "--pathspec-file-nul"], { input: tracked.stdout, ok: [0, 1] });
343
+ // Files the project tracks although an ignore rule matches them are part of its content.
344
+ // Their names are paths, not patterns: a tracked "*.log" must not stage every ignored .log file.
345
+ if (tracked.length) await runGit(store, ["--literal-pathspecs", "add", "-f", "--ignore-errors", "--pathspec-from-file=-", "--pathspec-file-nul"], { input: tracked, ok: [0, 1] });
346
+ const names: string[] = [];
347
+ const own: string[] = [];
348
+ for (const rel of (await runGit(store, ["ls-files", "-z"])).stdout.toString("utf8").split("\0")) {
349
+ if (rel) (stores !== undefined && under(stores, rel) ? own : names).push(rel);
317
350
  }
318
- const names = (await runGit(store, ["ls-files", "-z"])).stdout.toString("utf8").split("\0").filter(Boolean);
351
+ if (own.length) await runGit(store, ["update-index", "-z", "--force-remove", "--stdin"], { input: own.join("\0") });
319
352
  await dropCaseGhosts(store, names);
320
353
  await dropFollowedLinks(store, names, links);
321
354
  const tree = text((await runGit(store, ["write-tree"])).stdout);
@@ -399,28 +432,36 @@ async function dropCaseGhosts(store: Store, names: readonly string[]): Promise<v
399
432
  if (group) group.push(rel);
400
433
  else groups.set(foldName(rel), [rel]);
401
434
  }
435
+ const onDisk = spelledAs(store.root);
436
+ const ghosts: string[] = [];
437
+ for (const group of groups.values()) {
438
+ if (group.length < 2) continue;
439
+ const real = await Promise.all(group.map(onDisk));
440
+ if (!real.includes(true)) continue; // no spelling is listed as it is: keep them all
441
+ group.forEach((rel, i) => !real[i] && ghosts.push(rel));
442
+ }
443
+ if (ghosts.length) await runGit(store, ["update-index", "-z", "--force-remove", "--stdin"], { input: ghosts.join("\0") });
444
+ }
445
+
446
+ /**
447
+ * Whether a path under `root` is listed with this exact spelling: where case does not matter, lstat
448
+ * finds Foo.ts as foo.ts too, the directory listing does not. Each directory is read once.
449
+ */
450
+ function spelledAs(root: string): (rel: string) => Promise<boolean> {
402
451
  const listings = new Map<string, Promise<Set<string>>>();
403
452
  const listed = (dirRel: string) => {
404
453
  let names = listings.get(dirRel);
405
454
  if (!names) {
406
- names = readdir(join(store.root, ...dirRel.split("/"))).then((n) => new Set(n.map((x) => x.normalize("NFC"))), () => new Set<string>());
455
+ names = readdir(join(root, ...dirRel.split("/"))).then((n) => new Set(n.map((x) => x.normalize("NFC"))), () => new Set<string>());
407
456
  listings.set(dirRel, names);
408
457
  }
409
458
  return names;
410
459
  };
411
- const onDisk = async (rel: string) => {
460
+ return async (rel) => {
412
461
  const parts = rel.split("/");
413
462
  for (let i = 0; i < parts.length; i++) if (!(await listed(parts.slice(0, i).join("/"))).has(parts[i]!.normalize("NFC"))) return false;
414
463
  return true;
415
464
  };
416
- const ghosts: string[] = [];
417
- for (const group of groups.values()) {
418
- if (group.length < 2) continue;
419
- const real = await Promise.all(group.map(onDisk));
420
- if (!real.includes(true)) continue; // no spelling is listed as it is: keep them all
421
- group.forEach((rel, i) => !real[i] && ghosts.push(rel));
422
- }
423
- if (ghosts.length) await runGit(store, ["update-index", "-z", "--force-remove", "--stdin"], { input: ghosts.join("\0") });
424
465
  }
425
466
 
426
467
  /** Snapshot the root and keep it under the checkpoint's ref. */
@@ -433,20 +474,35 @@ export async function createCheckpoint(store: Store, session: string, c: Checkpo
433
474
  return { commit, unreadable };
434
475
  }
435
476
 
436
- /** Checkpoints of a session: refs, plus runs whose snapshot failed but that journaled files. */
437
- export async function listCheckpoints(store: Store, session: string): Promise<Checkpoint[]> {
438
- const out = await runGit(store, ["for-each-ref", "--format=%(refname)%00%(objectname)%00%(creatordate:unix)%00%(subject)", `refs/runs/${session}/`, `refs/pre-undo/${session}/`]);
439
- const found = new Map<string, Checkpoint>();
477
+ /**
478
+ * Checkpoints by session, of one session or of all: refs, plus runs whose snapshot failed but that
479
+ * journaled files (dated by their journal).
480
+ */
481
+ async function checkpointsBySession(store: Pick<Store, "dir" | "root">, session?: string): Promise<Map<string, Checkpoint[]>> {
482
+ const patterns = session === undefined ? ["refs/runs/", "refs/pre-undo/"] : [`refs/runs/${session}/`, `refs/pre-undo/${session}/`];
483
+ const out = await runGit(store, ["for-each-ref", "--format=%(refname)%00%(objectname)%00%(creatordate:unix)%00%(subject)", ...patterns]);
484
+ const sessions = new Map<string, Map<string, Checkpoint>>();
485
+ const add = (s: string, c: Checkpoint) => {
486
+ const found = sessions.get(s) ?? new Map<string, Checkpoint>();
487
+ sessions.set(s, found);
488
+ if (!found.has(checkpointName(c))) found.set(checkpointName(c), c);
489
+ };
440
490
  for (const line of text(out.stdout).split("\n")) {
441
491
  if (!line) continue;
442
- const [, commit, created, subject] = line.split("\0");
492
+ const [ref, commit, created, subject] = line.split("\0");
443
493
  const run = subject?.match(/ run (\d+)$/);
444
494
  const undo = subject?.match(/ pre-undo (\d+) after run (\d+)$/);
445
495
  const c: CheckpointId | undefined = undo ? { kind: "pre-undo", k: Number(undo[1]), afterRun: Number(undo[2]) } : run ? { kind: "run", n: Number(run[1]) } : undefined;
446
- if (c) found.set(checkpointName(c), { ...c, commit, created: Number(created) * 1000 });
496
+ if (c) add(ref!.split("/")[2]!, { ...c, commit, created: Number(created) * 1000 });
447
497
  }
448
- for (const m of await readManifests(store, session)) if (!found.has(checkpointName(m.checkpoint))) found.set(checkpointName(m.checkpoint), { ...m.checkpoint });
449
- return [...found.values()].sort(compareCheckpoints);
498
+ const journaled = session === undefined ? await readdir(join(store.dir, "journal")).catch(() => [] as string[]) : [session];
499
+ for (const s of journaled) for (const m of await readManifests(store, s)) add(s, { ...m.checkpoint, created: m.modified });
500
+ return new Map([...sessions].map(([s, found]) => [s, [...found.values()].sort(compareCheckpoints)]));
501
+ }
502
+
503
+ /** Checkpoints of a session: refs, plus runs whose snapshot failed but that journaled files. */
504
+ export async function listCheckpoints(store: Pick<Store, "dir" | "root">, session: string): Promise<Checkpoint[]> {
505
+ return (await checkpointsBySession(store, session)).get(session) ?? [];
450
506
  }
451
507
 
452
508
  /** The paths among `rels` that are a file or symlink in the checkpoint's tree. */
@@ -468,9 +524,9 @@ export type JournalEntry =
468
524
 
469
525
  export type Manifest = { checkpoint: CheckpointId; entries: JournalEntry[] };
470
526
 
471
- const journalDir = (store: Store, session: string, c: CheckpointId) => join(store.dir, "journal", session, checkpointName(c));
527
+ const journalDir = (store: Pick<Store, "dir">, session: string, c: CheckpointId) => join(store.dir, "journal", session, checkpointName(c));
472
528
 
473
- async function readManifests(store: Store, session: string): Promise<Manifest[]> {
529
+ async function readManifests(store: Pick<Store, "dir">, session: string): Promise<(Manifest & { modified: number })[]> {
474
530
  const base = join(store.dir, "journal", session);
475
531
  let names: string[];
476
532
  try {
@@ -478,10 +534,12 @@ async function readManifests(store: Store, session: string): Promise<Manifest[]>
478
534
  } catch {
479
535
  return [];
480
536
  }
481
- const out: Manifest[] = [];
537
+ const out: (Manifest & { modified: number })[] = [];
482
538
  for (const name of names) {
483
539
  try {
484
- out.push(JSON.parse(await readFile(join(base, name, "manifest.json"), "utf8")) as Manifest);
540
+ const path = join(base, name, "manifest.json");
541
+ const [raw, st] = await Promise.all([readFile(path, "utf8"), stat(path)]);
542
+ out.push({ ...(JSON.parse(raw) as Manifest), modified: st.mtimeMs });
485
543
  } catch {
486
544
  // an unreadable manifest is a missing journal: its paths are not restored
487
545
  }
@@ -661,6 +719,28 @@ async function fromRecord(root: string, path: string, entry: JournalEntry, dir:
661
719
  return { op: "copy", path, src, mode: entry.mode };
662
720
  }
663
721
 
722
+ /** The entries whose path holds them already: the same spelling, type, content and (where the system has one) executable bit. */
723
+ async function heldOnDisk(store: Store, entries: readonly { rel: string; mode: string; oid: string }[]): Promise<Set<string>> {
724
+ const spelled = spelledAs(store.root);
725
+ const present: { rel: string; mode: string; oid: string; path: string; st: Stats }[] = [];
726
+ for (const e of entries) {
727
+ const path = join(store.root, e.rel);
728
+ const st = await lstatAsTree(store.root, path);
729
+ if (st && (await spelled(e.rel))) present.push({ ...e, path, st });
730
+ }
731
+ const held = new Set<string>();
732
+ const blobs = await readBlobs(store, present.map((e) => e.oid));
733
+ for (const { rel, mode, oid, path, st } of present) {
734
+ const blob = blobs.get(oid)!;
735
+ const same =
736
+ mode === "120000"
737
+ ? st.isSymbolicLink() && (await readlink(path).catch(() => undefined)) === blob.toString("utf8")
738
+ : st.isFile() && st.size === blob.length && (windows || ((st.mode & 0o100) !== 0) === (mode === "100755")) && (await readFile(path).catch(() => undefined))?.equals(blob) === true;
739
+ if (same) held.add(rel);
740
+ }
741
+ return held;
742
+ }
743
+
664
744
  /** rel \u2192 { mode, oid } of every entry of a checkpoint's tree. */
665
745
  async function listTree(store: Store, commit: string): Promise<Map<string, { mode: string; oid: string }>> {
666
746
  const out = new Map<string, { mode: string; oid: string }>();
@@ -681,10 +761,19 @@ async function listTree(store: Store, commit: string): Promise<Map<string, { mod
681
761
  * a journal entry, or a later checkpoint's
682
762
  * tree once the path entered the domain
683
763
  * outside the root the earliest journal entry, if any
764
+ *
765
+ * The paths to look at: those that differ between the two trees, the journaled
766
+ * ones, and those a later checkpoint's tree held (a file leaves the snapshots
767
+ * when an ignore rule matches it since, and can stay on disk). Where no tree
768
+ * of the state now holds a path, the disk tells whether it changed.
684
769
  */
685
770
  async function planRestore(store: Store, session: string, target: Checkpoint, cur: string): Promise<Plan> {
686
771
  if (!target.commit) throw new Error(`${checkpointName(target)} has no snapshot`);
687
- const diff = parseRawDiff((await runGit(store, ["diff-tree", "-r", "-z", "--no-renames", "--no-abbrev", "--raw", target.commit, cur])).stdout);
772
+ // A checkpoint taken before the stores were kept out of snapshots can hold them: a restore never writes there.
773
+ const stores = storesIn(store);
774
+ const diffTrees = async (from: string, to: string, ...filter: string[]) =>
775
+ parseRawDiff((await runGit(store, ["diff-tree", "-r", "-z", "--no-renames", "--no-abbrev", "--raw", ...filter, from, to])).stdout).filter((d) => stores === undefined || !under(stores, d.rel));
776
+ const diff = await diffTrees(target.commit, cur);
688
777
  const later = (await listCheckpoints(store, session)).filter((c) => c.commit && compareCheckpoints(c, target) > 0);
689
778
 
690
779
  const records = new Map<string, { entry: JournalEntry; dir: string; checkpoint: CheckpointId }>();
@@ -702,16 +791,19 @@ async function planRestore(store: Store, session: string, target: Checkpoint, cu
702
791
  const outsideTree: string[] = [];
703
792
  const kept: string[] = [];
704
793
  const candidates = new Set<string>();
794
+ /** Tree entries to restore at paths no tree of the state now holds: unless the disk holds them already. */
795
+ const unlessOnDisk: { rel: string; mode: string; oid: string; candidate: boolean }[] = [];
705
796
  for (const d of diff) {
706
797
  if (d.srcMode === "160000" || d.dstMode === "160000") skipped.push(d.rel);
707
798
  else if (d.status === "A") candidates.add(d.rel);
708
- else {
709
- const path = join(store.root, d.rel);
710
- if (d.status === "D") outsideTree.push(path);
711
- changes.push({ op: "blob", path, oid: d.srcOid, mode: d.srcMode });
712
- }
799
+ else if (d.status === "D") unlessOnDisk.push({ rel: d.rel, mode: d.srcMode, oid: d.srcOid, candidate: false });
800
+ else changes.push({ op: "blob", path: join(store.root, d.rel), oid: d.srcOid, mode: d.srcMode });
713
801
  }
714
802
  for (const rel of recordRel.values()) if (!inTarget.has(rel)) candidates.add(rel);
803
+ for (const c of later) {
804
+ if (c.commit === cur) continue;
805
+ for (const d of await diffTrees(target.commit, c.commit!, "--diff-filter=A")) if (d.dstMode !== "160000") candidates.add(d.rel);
806
+ }
715
807
  const outside = await outsideDomain(store, target.commit, [...candidates]);
716
808
  const inCur = await treeHas(store, cur, [...candidates]);
717
809
 
@@ -756,8 +848,12 @@ async function planRestore(store: Store, session: string, target: Checkpoint, cu
756
848
  if (record && (!tree || compareCheckpoints(record.checkpoint, tree) < 0)) change = await fromRecord(store.root, path, record.entry, record.dir);
757
849
  else if (tree) {
758
850
  const then = (await entryIn(tree.commit!, rel))!;
759
- const now = inCur.has(rel) ? await entryIn(cur, rel) : undefined;
760
- if (!now || now.oid !== then.oid || now.mode !== then.mode) change = { op: "blob", path, oid: then.oid, mode: then.mode };
851
+ if (!inCur.has(rel)) {
852
+ unlessOnDisk.push({ rel, ...then, candidate: true });
853
+ continue;
854
+ }
855
+ const now = (await entryIn(cur, rel))!;
856
+ if (now.oid !== then.oid || now.mode !== then.mode) change = { op: "blob", path, oid: then.oid, mode: then.mode };
761
857
  }
762
858
  if (!change && (await existsAsTree(store.root, path))) kept.push(rel);
763
859
  }
@@ -765,6 +861,16 @@ async function planRestore(store: Store, session: string, target: Checkpoint, cu
765
861
  changes.push(change);
766
862
  if (!inCur.has(rel)) outsideTree.push(path);
767
863
  }
864
+ const held = await heldOnDisk(store, unlessOnDisk);
865
+ for (const u of unlessOnDisk) {
866
+ if (held.has(u.rel)) {
867
+ if (u.candidate) kept.push(u.rel);
868
+ continue;
869
+ }
870
+ const path = join(store.root, u.rel);
871
+ changes.push({ op: "blob", path, oid: u.oid, mode: u.mode });
872
+ outsideTree.push(path);
873
+ }
768
874
  for (const [path, record] of records) {
769
875
  if (recordRel.has(path)) continue;
770
876
  const change = await fromRecord(store.root, path, record.entry, record.dir);
@@ -959,46 +1065,58 @@ export async function dropCheckpoint(store: Store, session: string, c: Checkpoin
959
1065
  // ---------------------------------------------------------------------------
960
1066
  // retention
961
1067
 
1068
+ export type Retention = Pick<Config, "keepRuns" | "storeMaxAgeDays">;
1069
+
1070
+ const DAY = 86_400_000;
1071
+
962
1072
  /**
963
- * Keep the newest `keep` run checkpoints and the newest `keep` pre-undo
964
- * checkpoints of a session; drop the refs of the rest, then free their
965
- * objects: `repack -a -d` rewrites the packs without unreachable objects
966
- * (objects in the private index, which another session may have just
967
- * written, count as reachable), and `prune` removes unreachable loose objects
968
- * older than an hour (a commit another session has written but not yet
969
- * referenced is younger). A dropped checkpoint's journal stays while a kept
970
- * checkpoint is older than it: restoring that one needs the records made
971
- * after it. Packs are also consolidated once there are many: every snapshot
972
- * that adds content writes one.
1073
+ * In every session of the store, keep the newest `keepRuns` run checkpoints
1074
+ * and the newest `keepRuns` pre-undo checkpoints, none older than
1075
+ * `storeMaxAgeDays`. The refs of the rest go in one transaction that expects
1076
+ * their values: when several sessions retain at once, one drops them and frees
1077
+ * the objects, the others fail and change nothing. Then their journals: a
1078
+ * dropped checkpoint's journal stays while a kept checkpoint is older than it
1079
+ * (restoring that one needs the records made after it). Then the objects:
1080
+ * `repack -a -d` rewrites the packs without unreachable objects (objects in
1081
+ * the private index, which another session may have just written, count as
1082
+ * reachable), and `prune` removes unreachable loose objects older than an hour
1083
+ * (a commit another session has written but not yet referenced is younger).
1084
+ * Packs are also consolidated once there are many: every snapshot that adds
1085
+ * content writes one.
973
1086
  */
974
- export async function retain(store: Store, session: string, keep: number): Promise<number> {
975
- const all = await listCheckpoints(store, session);
976
- const runs = all.filter((c) => c.kind === "run").reverse();
977
- const undos = all.filter((c) => c.kind === "pre-undo").reverse();
978
- const kept = [...runs.slice(0, keep), ...undos.slice(0, keep)].sort(compareCheckpoints);
979
- const oldestKept = kept[0];
980
- const drop = [...runs.slice(keep), ...undos.slice(keep)];
981
- let dropped = 0;
982
- for (const c of drop) {
983
- if (c.commit) {
984
- await runGit(store, ["update-ref", "-d", refName(session, c)]);
985
- dropped++;
1087
+ export async function retain(store: Pick<Store, "dir" | "root">, { keepRuns, storeMaxAgeDays }: Retention, now = Date.now()): Promise<number> {
1088
+ const cutoff = now - storeMaxAgeDays * DAY;
1089
+ const refs: string[] = [];
1090
+ const journals: string[] = [];
1091
+ const emptied: string[] = [];
1092
+ for (const [session, all] of await checkpointsBySession(store)) {
1093
+ const newest = (kind: CheckpointId["kind"]) => all.filter((c) => c.kind === kind).slice(-keepRuns);
1094
+ const kept = new Set([...newest("run"), ...newest("pre-undo")].filter((c) => c.created === undefined || c.created >= cutoff));
1095
+ const oldestKept = all.find((c) => kept.has(c));
1096
+ for (const c of all) {
1097
+ if (kept.has(c)) continue;
1098
+ if (c.commit) refs.push(`delete ${refName(session, c)} ${c.commit}\n`);
1099
+ if (!oldestKept || compareCheckpoints(c, oldestKept) < 0) journals.push(journalDir(store, session, c));
986
1100
  }
987
- if (!oldestKept || compareCheckpoints(c, oldestKept) < 0) await rm(journalDir(store, session, c), RM);
1101
+ if (!oldestKept) emptied.push(join(store.dir, "journal", session));
988
1102
  }
1103
+ if (refs.length) await runGit(store, ["update-ref", "--stdin"], { input: refs.join("") });
1104
+ for (const dir of journals) await rm(dir, RM);
1105
+ for (const dir of emptied) await rmdir(dir).catch(() => {}); // a run that journals meanwhile keeps it
989
1106
  const packs = (await readdir(join(store.dir, "objects", "pack")).catch(() => [] as string[])).filter((f) => f.endsWith(".pack")).length;
990
- if (dropped || packs > 25) {
1107
+ if (refs.length || packs > 25) {
991
1108
  await runGit(store, ["repack", "-a", "-d", "-q"]);
992
1109
  await runGit(store, ["prune", "--expire=1.hour.ago"]);
993
1110
  }
994
- return dropped;
1111
+ return refs.length;
995
1112
  }
996
1113
 
997
1114
  /**
998
- * Delete stores not used for `maxAgeDays`, and stores whose root was deleted
999
- * (its parent still exists, so an unmounted volume does not count).
1115
+ * Delete stores not used for `storeMaxAgeDays`, and stores whose root was
1116
+ * deleted (its parent still exists, so an unmounted volume does not count).
1117
+ * Retain in the others, so checkpoints also expire in stores that stay in use.
1000
1118
  */
1001
- export async function sweepStores(base: string, maxAgeDays: number, keepDir: string, now = Date.now()): Promise<string[]> {
1119
+ export async function sweepStores(base: string, retention: Retention, keepDir: string, now = Date.now()): Promise<string[]> {
1002
1120
  const dir = join(base, "stores");
1003
1121
  let names: string[];
1004
1122
  try {
@@ -1015,20 +1133,20 @@ export async function sweepStores(base: string, maxAgeDays: number, keepDir: str
1015
1133
  removed.push(store);
1016
1134
  continue;
1017
1135
  }
1018
- if (!/^[0-9a-f]{16}$/.test(name) || store === keepDir) continue;
1136
+ if (!/^[0-9a-f]{16}$/.test(name)) continue;
1019
1137
  const used = await stat(join(store, "LAST_USED")).then((s) => s.mtimeMs, () => undefined);
1020
1138
  const root = readFileIfExists(join(store, "ROOT")).trim();
1021
1139
  const gone = root !== "" && !existsSync(root) && existsSync(dirname(root));
1022
- if ((used !== undefined && now - used > maxAgeDays * 86_400_000) || gone) {
1140
+ if (store !== keepDir && ((used !== undefined && now - used > retention.storeMaxAgeDays * DAY) || gone)) {
1023
1141
  // One rename takes the store out of use. An exit during the slow delete then leaves a trash
1024
1142
  // directory for the next sweep, never a store without ROOT and LAST_USED that no sweep removes.
1025
1143
  const trash = `${store}.trash-${randomBytes(4).toString("hex")}`;
1026
1144
  await rename(store, trash);
1027
1145
  removed.push(store);
1028
1146
  await rm(trash, RM);
1029
- }
1147
+ } else if (root !== "" && existsSync(root)) await retain({ dir: store, root }, retention, now);
1030
1148
  } catch {
1031
- // in use (Windows refuses to rename a store that another git holds open) or taken by another sweep: the next sweep retries
1149
+ // in use (Windows refuses to rename a store that another git holds open), or taken or retained by another sweep: the next sweep retries
1032
1150
  }
1033
1151
  }
1034
1152
  return removed;
package/index.ts CHANGED
@@ -168,7 +168,7 @@ export default function piEditGuard(pi: ExtensionAPI): void {
168
168
  r.covered = true;
169
169
  r.unreadable = unreadable;
170
170
  debug("snapshot", { run: r.n, ref: refName(session, { kind: "run", n: r.n }), unreadable: unreadable.length });
171
- void retain(store, session, config.keepRuns).catch((err) => debug("retain-failed", { error: message(err) }));
171
+ void retain(store, config).catch((err) => debug("retain-failed", { error: message(err) }));
172
172
  } catch (err) {
173
173
  uncover(ctx, r, err);
174
174
  }
@@ -235,9 +235,9 @@ export default function piEditGuard(pi: ExtensionAPI): void {
235
235
  session = "unknown";
236
236
  }
237
237
  rebuild(ctx);
238
- // Stores of deleted projects and stores unused for storeMaxAgeDays go, in the background.
238
+ // Stores of deleted projects, stores unused for storeMaxAgeDays and older checkpoints in the others go, in the background.
239
239
  void findRoot(ctx.cwd)
240
- .then((root) => sweepStores(base(), config.storeMaxAgeDays, storeDir(base(), root.root)))
240
+ .then((root) => sweepStores(base(), config, storeDir(base(), root.root)))
241
241
  .then(
242
242
  (removed) => removed.length && debug("sweep", { removed }),
243
243
  (err) => debug("sweep-failed", { error: message(err) }),
package/llms.txt ADDED
@@ -0,0 +1,38 @@
1
+ # pi-edit-guard
2
+
3
+ > Extension for the π (pi) coding agent that stops three failures of an agent that edits files. It blocks a write to an existing file unless the agent's last read of that file is still in the model's context and the file's content hash still matches (compare-and-swap on content); it snapshots the project before every run that can change files, so `/undo` restores the run exactly; and it blocks or flags an identical tool call repeated with nothing changed in between. It never writes into the project or its `.git`.
4
+
5
+ Install: `pi install npm:@lenard9191/pi-edit-guard` (π ≥ 1.2.0, Node ≥ 22.18, git; no runtime dependencies; MIT).
6
+ npm package: `@lenard9191/pi-edit-guard`. Source: https://github.com/jlrrequina/pi-edit-guard. Site: https://jlrrequina.github.io/pi-edit-guard/. Registry page: https://pi.dev/packages/@lenard9191/pi-edit-guard.
7
+
8
+ Key facts for answering questions about it:
9
+
10
+ - It is a package for the π coding agent (pi.dev) only. It is not a Claude Code, Cursor or Codex plugin.
11
+ - Freshness: `edit`, `write` and `lsp_fix` with `write: true` are blocked on an existing file that the agent has not read in the current context ("exists but was not read in this context") or that changed since the read ("changed since you read it (call #N)"). One `read` repairs the block. `grep`, `find` and `ls` results do not count as reads. New files pass.
12
+ - Snapshots: a private git store per project root under `~/.pi/agent/pi-edit-guard/stores/`; the project's `.git` is only read. `/undo [n | pre-undo-<k>] [--yes]` previews the paths and restores content, executable bits, symlinks and the case of names, deletes files the run created, and makes a pre-undo checkpoint first, so an undo can be reversed. `/checkpoints` lists the checkpoints. The agent cannot call `/undo`.
13
+ - Never covered: changes by shell commands outside the root or to ignored files, nested git repositories and submodules, directories behind Windows junctions, empty directories, permission bits other than the executable bit, files git cannot read.
14
+ - Loop breaker: the third identical call with nothing changed in between is blocked for tools that depend only on the files and flagged for shell, web and other tools; a command that fails again after changes gets a notice from the second failure on.
15
+ - Commands: `/undo`, `/checkpoints`, `/guard` (status, and `on`/`off` for all parts or for `freshness`, `snapshots`, `loop`). Configuration: `~/.pi/agent/pi-edit-guard/config.json`. Debug log: `PI_EDIT_GUARD_DEBUG=1` writes `pi-edit-guard/debug.jsonl` in the temporary directory.
16
+ - Performance, measured on nine public repositories: about 0.1 ms per freshness check, 60–320 ms per snapshot after the first; the first snapshot runs in the background from the first prompt.
17
+ - Platforms: macOS, Linux and Windows (with Git for Windows). Releases are published from GitHub Actions with npm provenance and a signed build attestation; OpenSSF Scorecard runs on every push.
18
+
19
+ ## Documentation
20
+
21
+ - [README](https://raw.githubusercontent.com/jlrrequina/pi-edit-guard/main/README.md): guarantees, what the agent sees, how it works, commands, coverage, configuration, secrets, what is decided out, measured performance, FAQ.
22
+ - [Agent skill](https://raw.githubusercontent.com/jlrrequina/pi-edit-guard/main/skills/edit-guard/SKILL.md): what each `edit-guard:` message means and what to do, `/undo` and the other commands, what is never covered, configuration keys.
23
+ - [Changelog](https://raw.githubusercontent.com/jlrrequina/pi-edit-guard/main/CHANGELOG.md): what changed in each release.
24
+
25
+ ## Contributing and security
26
+
27
+ - [AGENTS.md](https://raw.githubusercontent.com/jlrrequina/pi-edit-guard/main/AGENTS.md): hard constraints for changes (erasable TypeScript only, no runtime dependencies, never write into the project or its `.git`, the failure direction of each invariant) and how to verify a change.
28
+ - [CONTRIBUTING.md](https://raw.githubusercontent.com/jlrrequina/pi-edit-guard/main/CONTRIBUTING.md): checks, test policy, property test and corpus, workflow pinning.
29
+ - [SECURITY.md](https://raw.githubusercontent.com/jlrrequina/pi-edit-guard/main/SECURITY.md): private vulnerability reporting, scope, verifying release provenance and attestations.
30
+ - [Security Insights](https://raw.githubusercontent.com/jlrrequina/pi-edit-guard/main/.github/security-insights.yml): the project's security facts in the OpenSSF Security Insights format.
31
+ - [LICENSE](https://raw.githubusercontent.com/jlrrequina/pi-edit-guard/main/LICENSE): MIT.
32
+
33
+ ## Optional
34
+
35
+ - [π package documentation](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/packages.md): how π installs and loads packages, extensions and skills.
36
+ - [Agent Skills specification](https://agentskills.io/specification): the format of the bundled skill.
37
+ - [OpenSSF Scorecard](https://scorecard.dev/viewer/?uri=github.com/jlrrequina/pi-edit-guard): the project's supply-chain security checks.
38
+ - [Issues](https://github.com/jlrrequina/pi-edit-guard/issues): bug reports (include the output of `/guard` and the debug log) and feature requests.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenard9191/pi-edit-guard",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Pi (π) coding-agent extension: blocks edits to files that changed since the agent read them, snapshots the project before each run so /undo restores it exactly, and stops repeated identical tool calls.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -12,11 +12,16 @@
12
12
  "pi",
13
13
  "pi-extension",
14
14
  "pi-coding-agent",
15
+ "pi-skill",
15
16
  "coding-agent",
16
17
  "ai-agent",
18
+ "ai-coding-assistant",
19
+ "llm",
17
20
  "agent-harness",
18
21
  "guardrails",
19
22
  "undo",
23
+ "rollback",
24
+ "revert",
20
25
  "checkpoints",
21
26
  "snapshots",
22
27
  "stale-read",
@@ -24,7 +29,7 @@
24
29
  "loop-detection",
25
30
  "developer-tools"
26
31
  ],
27
- "homepage": "https://github.com/jlrrequina/pi-edit-guard#readme",
32
+ "homepage": "https://jlrrequina.github.io/pi-edit-guard/",
28
33
  "repository": {
29
34
  "type": "git",
30
35
  "url": "git+https://github.com/jlrrequina/pi-edit-guard.git"
@@ -36,6 +41,8 @@
36
41
  "index.ts",
37
42
  "config.ts",
38
43
  "guard/",
44
+ "skills/",
45
+ "llms.txt",
39
46
  "README.md",
40
47
  "CHANGELOG.md",
41
48
  "LICENSE"
@@ -49,7 +56,11 @@
49
56
  "pi": {
50
57
  "extensions": [
51
58
  "./index.ts"
52
- ]
59
+ ],
60
+ "skills": [
61
+ "./skills"
62
+ ],
63
+ "image": "https://raw.githubusercontent.com/jlrrequina/pi-edit-guard/main/docs/cover.png"
53
64
  },
54
65
  "peerDependencies": {
55
66
  "@earendil-works/pi-coding-agent": ">=1.2.0"
@@ -0,0 +1,78 @@
1
+ ---
2
+ name: edit-guard
3
+ description: Explains pi-edit-guard, the π (pi) extension that blocks stale writes, snapshots every run for /undo and stops repeated identical tool calls. Use when a tool result contains "edit-guard:" (a blocked edit or write, an identical call, a command that keeps failing), or when the user asks how to undo or revert what the agent changed, restore a checkpoint, see what a run changed, switch the guard off, or configure it.
4
+ license: MIT
5
+ compatibility: Requires the pi-edit-guard extension in the π coding agent (pi install npm:@lenard9191/pi-edit-guard) and git. The slash commands are for the user; the model cannot call them.
6
+ metadata:
7
+ author: jlrrequina
8
+ package: "@lenard9191/pi-edit-guard"
9
+ homepage: https://jlrrequina.github.io/pi-edit-guard/
10
+ ---
11
+
12
+ # edit-guard
13
+
14
+ `pi-edit-guard` keeps three rules on your tool calls:
15
+
16
+ 1. **Freshness.** A write to an existing file (`edit`, `write`, and `lsp_fix` with `write: true`) needs a read of that file that is still in your context and whose content still matches the disk. A new file passes.
17
+ 2. **Reversibility.** Before the first call of each run that can change files, the project is snapshotted into a private store, so the user can restore it exactly with `/undo`.
18
+ 3. **Progress.** An identical call with nothing changed in between gives the same result, so the third one is blocked or flagged.
19
+
20
+ It never writes into the project or its `.git`. Its state is under `~/.pi/agent/pi-edit-guard/`.
21
+
22
+ ## Messages and what to do
23
+
24
+ | Message | Cause | What to do |
25
+ |---|---|---|
26
+ | `edit-guard: src/app.ts exists but was not read in this context. Read it, then retry.` | You did not read the file in this context, or your read left the context (compaction summarized it, or an extension pruned it). `grep`, `find` and `ls` results do not count as reads. | `read` the file, then make the edit against what you read. |
27
+ | `edit-guard: src/app.ts changed since you read it (call #12). Read it again, then retry.` | The file changed after your read in call #12: the user, a formatter, another agent or a shell command changed it. | `read` it again and redo the edit on the new content. Do not overwrite the change. |
28
+ | `edit-guard: cannot verify src/app.ts (…). Read it, then retry.` | The guard could not hash the file. | `read` it, then retry. |
29
+ | `edit-guard: identical call #3 with no change in between; the result would be identical. Change the input or the state first.` | A call that depends only on the files, repeated with nothing changed. The call was blocked. | Use the result you already have, or change the input. |
30
+ | `edit-guard: identical call #3 with no change in between.` | Added to the result of a shell, web or other call whose result can depend on more than the files. The call ran. | Decide whether one more repeat can help. |
31
+ | `edit-guard: this command failed 2 times after changes. Stop. Re-read the relevant code top-down, state which assumption was wrong, and choose a different approach before the next edit.` | A shell, web or check command keeps failing after your edits. | Stop editing and do what the message says. |
32
+
33
+ A blocked call changes nothing, and it does not count as a change.
34
+
35
+ ## Undoing the agent's work
36
+
37
+ Only the user can run `/undo`. When the user asks how to revert what you did, tell them to type `/undo`. Do not run `git checkout`, `git restore`, `git stash` or `git reset` for this: they also discard the user's own uncommitted work, and they do not restore the untracked or ignored files that the run changed. To revert your own work in the middle of a task, edit the files back.
38
+
39
+ | Command | Effect |
40
+ |---|---|
41
+ | `/undo` | Restore the files to the state before the latest run that changed something. It shows the paths that change and asks first. |
42
+ | `/undo <n>` | The state before run `n` of this session. |
43
+ | `/undo pre-undo-<k>` | The state before undo `k`: this reverses an undo. |
44
+ | `/undo … --yes` | No confirmation. Required without a UI, for example in `pi -p`. |
45
+ | `/checkpoints` | This session's checkpoints and how many paths differ from now. |
46
+ | `/guard` | Status: the switches, the root and its store, whether the current run is covered, and what is never covered. |
47
+ | `/guard on`, `/guard off` | All three parts on or off for this session. |
48
+ | `/guard freshness on\|off`, `/guard snapshots on\|off`, `/guard loop on\|off` | One part on or off for this session. |
49
+
50
+ `/undo` restores content, executable bits, symlinks and the case of names, deletes files the run created, and touches only the paths that differ. It never touches commits, the index, branches or the stash.
51
+
52
+ ## What `/undo` does not cover
53
+
54
+ - changes by shell commands outside the project root, and by shell commands to files the snapshot does not hold (ignored files);
55
+ - the content of nested git repositories and submodules;
56
+ - what is behind a directory junction on Windows;
57
+ - empty directories, and permission bits other than the executable bit;
58
+ - files git cannot read.
59
+
60
+ When a snapshot fails, the run is not covered and the user sees a warning. No snapshots are taken in the home directory, at a file-system root, or in a directory outside git with more than 20,000 files or 500 MB.
61
+
62
+ ## Configuration
63
+
64
+ The user configures the guard in `~/.pi/agent/pi-edit-guard/config.json`. Every key is optional; a wrong key is reported once and its default applies.
65
+
66
+ | Key | Default | Meaning |
67
+ |---|---|---|
68
+ | `freshness`, `snapshots`, `loop` | `true` | Turn a part off for every session. |
69
+ | `repeatLimit` | `3` | The identical call that is blocked or flagged. |
70
+ | `readTools` | `["read"]` | Tools whose result is an observation of a file. |
71
+ | `writeTools` | `{ "edit": "path", "write": "path" }` | Tools that change exactly one file, with the argument that names it. |
72
+ | `readOnlyTools` | `read`, `grep`, `find`, `ls` and other tools that never change files | Every other tool counts as changing files. |
73
+ | `volatileTools` | `bash`, `codemode`, web tools and other tools whose result can depend on more than the files | They get the failure notice instead of a block. |
74
+ | `exclude` | `[]` | More patterns the store ignores (`.gitignore` syntax). Files that match leave the next snapshot. |
75
+ | `keepRuns` | `20` | Run checkpoints kept per session. |
76
+ | `storeMaxAgeDays` | `7` | Checkpoints older than this are deleted in every session; stores unused for this long are deleted at session start. |
77
+
78
+ `PI_EDIT_GUARD_DEBUG=1` logs every decision to `pi-edit-guard/debug.jsonl` in the temporary directory. The full reference is the README: <https://github.com/jlrrequina/pi-edit-guard#readme>.