@lenard9191/pi-edit-guard 0.2.0 → 0.3.1
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 +11 -0
- package/README.md +4 -4
- package/config.ts +1 -1
- package/guard/snapshot.ts +188 -70
- package/index.ts +3 -3
- package/package.json +3 -3
- package/skills/edit-guard/SKILL.md +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 0.3.1 — 2026-11-14
|
|
6
|
+
|
|
7
|
+
- Tested with π 1.5.0. The tests now run on `@earendil-works/pi-coding-agent` and `@earendil-works/pi-ai` 1.5.0 (0.3.0 was tested on 1.3.0) and pass, the run inside a real π session included. The oldest supported π is still 1.2.0. The extension code did not change.
|
|
8
|
+
|
|
9
|
+
## 0.3.0 — 2026-10-27
|
|
10
|
+
|
|
11
|
+
- **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.
|
|
12
|
+
- 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).
|
|
13
|
+
- 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.
|
|
14
|
+
- Fixed: `/undo` of an earlier run did not restore an ignored file that only a later checkpoint held, after a shell deleted it.
|
|
15
|
+
|
|
5
16
|
## 0.2.0 — 2026-10-22
|
|
6
17
|
|
|
7
18
|
- **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.
|
package/README.md
CHANGED
|
@@ -47,7 +47,7 @@ edit-guard: this command failed 2 times after changes. Stop. Re-read the relevan
|
|
|
47
47
|
|
|
48
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.
|
|
49
49
|
|
|
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. 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`.
|
|
51
51
|
|
|
52
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.
|
|
53
53
|
|
|
@@ -100,9 +100,9 @@ A run whose snapshot failed cannot be undone; `/undo` says so and names the run
|
|
|
100
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 }`. |
|
|
101
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. |
|
|
102
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. |
|
|
103
|
-
| `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. |
|
|
104
104
|
| `keepRuns` | `20` | Run checkpoints kept per session (and as many pre-undo checkpoints). |
|
|
105
|
-
| `storeMaxAgeDays` | `
|
|
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. |
|
|
106
106
|
|
|
107
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.
|
|
108
108
|
|
|
@@ -110,7 +110,7 @@ Outside git, the store also ignores `.git`, `node_modules`, `.pnpm-store`, `dist
|
|
|
110
110
|
|
|
111
111
|
## Secrets
|
|
112
112
|
|
|
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.
|
|
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.
|
|
114
114
|
|
|
115
115
|
## Decided out
|
|
116
116
|
|
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:
|
|
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
|
-
|
|
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
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
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
|
-
|
|
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(
|
|
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
|
-
|
|
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
|
-
/**
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
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)
|
|
496
|
+
if (c) add(ref!.split("/")[2]!, { ...c, commit, created: Number(created) * 1000 });
|
|
447
497
|
}
|
|
448
|
-
|
|
449
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
760
|
-
|
|
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
|
-
*
|
|
964
|
-
*
|
|
965
|
-
*
|
|
966
|
-
*
|
|
967
|
-
*
|
|
968
|
-
*
|
|
969
|
-
*
|
|
970
|
-
*
|
|
971
|
-
*
|
|
972
|
-
*
|
|
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,
|
|
975
|
-
const
|
|
976
|
-
const
|
|
977
|
-
const
|
|
978
|
-
const
|
|
979
|
-
const
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
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
|
|
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 (
|
|
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
|
|
1111
|
+
return refs.length;
|
|
995
1112
|
}
|
|
996
1113
|
|
|
997
1114
|
/**
|
|
998
|
-
* Delete stores not used for `
|
|
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,
|
|
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)
|
|
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 >
|
|
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,
|
|
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
|
|
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
|
|
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lenard9191/pi-edit-guard",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
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",
|
|
@@ -66,8 +66,8 @@
|
|
|
66
66
|
"@earendil-works/pi-coding-agent": ">=1.2.0"
|
|
67
67
|
},
|
|
68
68
|
"devDependencies": {
|
|
69
|
-
"@earendil-works/pi-ai": "1.
|
|
70
|
-
"@earendil-works/pi-coding-agent": "1.
|
|
69
|
+
"@earendil-works/pi-ai": "1.5.0",
|
|
70
|
+
"@earendil-works/pi-coding-agent": "1.5.0",
|
|
71
71
|
"@types/node": "^24.19.2",
|
|
72
72
|
"fast-check": "4.10.2",
|
|
73
73
|
"typescript": "^5.9.3"
|
|
@@ -71,8 +71,8 @@ The user configures the guard in `~/.pi/agent/pi-edit-guard/config.json`. Every
|
|
|
71
71
|
| `writeTools` | `{ "edit": "path", "write": "path" }` | Tools that change exactly one file, with the argument that names it. |
|
|
72
72
|
| `readOnlyTools` | `read`, `grep`, `find`, `ls` and other tools that never change files | Every other tool counts as changing files. |
|
|
73
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). |
|
|
74
|
+
| `exclude` | `[]` | More patterns the store ignores (`.gitignore` syntax). Files that match leave the next snapshot. |
|
|
75
75
|
| `keepRuns` | `20` | Run checkpoints kept per session. |
|
|
76
|
-
| `storeMaxAgeDays` | `
|
|
76
|
+
| `storeMaxAgeDays` | `7` | Checkpoints older than this are deleted in every session; stores unused for this long are deleted at session start. |
|
|
77
77
|
|
|
78
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>.
|