repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

Replaced git-safe startup-wide find scans with lazy ancestor marker discovery on read; reload fell 67% Win32 and 36% WSL, all 25 extension tests passed independently

bb9a7d811dd0e112d504acb3be46f852fcda88d9

Oliver Krylow <o.krylow@isp-insoft.de> ·

SSH signature · not checked

Browse filesCompare with HEAD

Result: {"status":"keep","git_safe_reload_tax_ms":116.567,"elapsed_s":189,"win32_start_reload_ms":8422.974,"win32_extension_tax_ms":5094.013,"win32_startup_ms":6489.324,"win32_reload_ms":1933.65,"wsl_start_reload_ms":1483.698,"wsl_extension_tax_ms":634.232,"wsl_git_safe_reload_tax_ms":28.72}

Changed files (7)

extensions/git-safe/README.md

Modified
76 76 - writes `.pi-git-safe` marker after successful checkout
77 77 - returns canonical clone path, URL, optional branch, file count, total byte
78 78 count, symlink count, symlink paths, warnings, and optional sparse paths
79 -- recovers marked clone dirs on `session_start` by scanning cwd, temp dir,
80 - `~/.local/state/pi`, and home up to depth 4
81 -- cancels stale async recovery work on `session_shutdown`
82 -- notifies UI when recovered clone dirs are found
79 +- recovers marked clone dirs on demand by checking ancestors of each `read`
80 + path
83 81 - wraps text `read` results from tracked clone dirs in `<untrusted_external_data
84 82 marker="...">` markers with a git-specific warning preamble
85 83 - warns when `.git/config` contains `include` or `includeIf`

extensions/git-safe/__tests__/harness.test.ts

Modified
210 210 expect(t.session.extensionRunner.extensions).toHaveLength(1);
213 + it("recovers a marked clone lazily when read", async () => {
214 + root = mkdtempSync(path.join(tmpdir(), "pi-git-safe-read-"));
215 + const clone = path.join(root, "owner", "repo");
216 + const file = path.join(clone, "README.md");
217 + mkdirSync(clone, { recursive: true });
218 + writeFileSync(path.join(clone, ".pi-git-safe"), "{}", "utf8");
219 + writeFileSync(file, "untrusted instructions", "utf8");
220 + t = await createTestSession({ cwd: root, extensions: [gitSafePath()] });
222 + const result = await t.session.extensionRunner.emitToolResult({
223 + type: "tool_result",
224 + toolName: "read",
225 + toolCallId: crypto.randomUUID(),
226 + input: { path: file },
227 + content: [{ type: "text", text: "untrusted instructions" }],
228 + isError: false,
229 + } as never);
231 + expect(result?.content[0]).toMatchObject({ type: "text" });
232 + expect(
233 + result?.content[0]?.type === "text" && result.content[0].text,
234 + ).toContain("UNTRUSTED DATA");
235 + expect(
236 + result?.content[0]?.type === "text" && result.content[0].text,
237 + ).toContain("untrusted instructions");
238 + });
213 240 it("sets noninteractive editor variables while ordinary Git still runs", async () => {
214 241 await startWithFakeGit();

extensions/git-safe/clone.ts

Modified
15 15 writeFile,
16 16 } from "node:fs/promises";
17 -import { homedir, tmpdir } from "node:os";
17 +import { homedir } from "node:os";
18 18 import {
19 - dirname,
20 19 isAbsolute,
21 20 join,
22 21 normalize,
25 24 resolve,
27 26 } from "node:path";
28 -import {
29 - SpawnExitError,
30 - SpawnTimeoutError,
31 - spawnExpect,
32 - spawnWithTimeout,
33 -} from "./spawn.js";
27 +import { SpawnExitError, SpawnTimeoutError, spawnExpect } from "./spawn.js";
35 29 // ── Constants ──────────────────────────────────────────────────────────────
502 496 if (bytes >= 1_000) return `${(bytes / 1_000).toFixed(1)}KB`;
503 497 return `${bytes}B`;
506 -// ── Session recovery ───────────────────────────────────────────────────────
508 -/**
509 - * Walk known directories for .pi-git-safe marker files.
510 - * Returns canonical (realpath) paths to clone directories.
511 - */
512 -export async function recoverTrackedPaths(cwd: string): Promise<string[]> {
513 - const roots = [
514 - cwd,
515 - tmpdir(),
516 - join(homedir(), ".local", "state", "pi"),
517 - homedir(),
518 - ];
520 - const tracked: string[] = [];
522 - for (const root of roots) {
523 - if (!existsSync(root)) continue;
524 - try {
525 - const result = await spawnWithTimeout(
526 - "find",
527 - [root, "-name", MARKER_FILE, "-maxdepth", "4"],
528 - { timeout: 5_000 },
529 - );
531 - if (result.code === 0 && result.stdout.trim()) {
532 - for (const line of result.stdout.trim().split("\n")) {
533 - const markerPath = line.trim();
534 - if (!markerPath) continue;
535 - const cloneDir = dirname(markerPath);
536 - try {
537 - const canonical = realpathSync(cloneDir);
538 - tracked.push(canonical);
539 - } catch {
540 - // realpath may fail on deleted paths
541 - }
542 - }
543 - }
544 - } catch {
545 - // Permission denied, timeout, etc. — skip this root.
546 - }
547 - }
549 - // Deduplicate
550 - return [...new Set(tracked)];

extensions/git-safe/index.ts

Modified
14 14 * Architecture:
15 15 * git_clone_safe tool → 7-step safe clone process
16 - * tool_result hook on "read" → spotlight-wrap cloned content
17 - * session_start → recover tracked paths via marker files
16 + * tool_result hook on "read" → discover marker and spotlight-wrap content
20 19 import { realpath } from "node:fs/promises";
21 -import { resolve } from "node:path";
20 +import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
22 21 import {
23 22 type ExtensionAPI,
24 23 isToolCallEventType,
25 24 } from "@earendil-works/pi-coding-agent";
26 25 import { Text } from "@earendil-works/pi-tui";
27 26 import { Type } from "typebox";
28 -import {
29 - recoverTrackedPaths,
30 - type SafeCloneResult,
31 - safeClone,
32 -} from "./clone.js";
27 +import { isMarkerPresent, type SafeCloneResult, safeClone } from "./clone.js";
33 28 import {
34 29 applyGitPolicy,
35 30 blockedGitCommandReason,
53 48 // ── Module state ───────────────────────────────────────────────────────────
55 50 // Tracked clone paths (canonical realpath). Survives within session via
56 -// tool result details. Recovered across sessions via .pi-git-safe markers.
51 +// tool result details and is rediscovered from ancestor markers on demand.
57 52 const trackedClonePaths = new Set<string>();
59 54 function addTrackedPath(canonicalPath: string): void {
60 55 trackedClonePaths.add(canonicalPath);
58 +function isInsidePath(root: string, candidate: string): boolean {
59 + const path = relative(root, candidate);
60 + return (
61 + path === "" ||
62 + (path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path))
63 + );
63 66 function isInsideTrackedClone(canonicalFilePath: string): boolean {
64 67 for (const tracked of trackedClonePaths) {
65 - if (
66 - canonicalFilePath === tracked ||
67 - canonicalFilePath.startsWith(tracked + "/")
68 - ) {
69 - return true;
70 - }
68 + if (isInsidePath(tracked, canonicalFilePath)) return true;
72 70 return false;
73 +function discoverTrackedClone(canonicalFilePath: string): boolean {
74 + if (isInsideTrackedClone(canonicalFilePath)) return true;
75 + let directory = dirname(canonicalFilePath);
76 + while (true) {
77 + if (isMarkerPresent(directory)) {
78 + addTrackedPath(directory);
79 + return true;
80 + }
81 + const parent = dirname(directory);
82 + if (parent === directory) return false;
83 + directory = parent;
84 + }
75 87 // ── Extension ──────────────────────────────────────────────────────────────
77 89 export default function gitSafeExtension(pi: ExtensionAPI) {
78 90 // Session-scoped spotlight markers
79 91 const spotlightMarkers = createMarkers({ preamble: GIT_PREAMBLE });
80 - let generation = 0;
81 92 let gitPolicyRegistered = false;
82 93 let gitPolicyRuntime: GitPolicyRuntime | undefined;
114 - const ticket = ++generation;
115 - const paths = await recoverTrackedPaths(ctx.cwd);
116 - if (ticket !== generation) return;
117 - for (const p of paths) {
118 - addTrackedPath(p);
119 - }
120 - if (paths.length > 0 && ctx.hasUI) {
121 - ctx.ui.notify(
122 - `git-safe: recovered ${paths.length} tracked clone(s)`,
123 - "info",
124 - );
125 - }
128 126 pi.on("session_shutdown", async () => {
129 - generation++;
130 127 await removeGitPolicyRuntime(gitPolicyRuntime);
131 128 gitPolicyRuntime = undefined;
150 147 return;
153 - // Check if inside any tracked clone
154 - if (!isInsideTrackedClone(canonicalPath)) return;
150 + // Check in-session paths first, then lazily recover from ancestor markers.
151 + if (!discoverTrackedClone(canonicalPath)) return;
156 153 // Concatenate all text content, wrap once
157 154 const content = event.content as

extensions/rtk/index.ts

Modified
319 319 : outcome.kind === "fallback"
320 320 ? localFallbackRewrite(framed.command)
321 321 : undefined;
322 - if (
323 - rewritten &&
324 - (support.findPathSupported || !isFindRewrite(rewritten))
325 - )
322 + if (rewritten && (support.findPathSupported || !isFindRewrite(rewritten)))
326 323 event.input.command = framed.prefix + rewritten;

extensions/the-system/system-command-meta.ts

Modified
20 20 ): AutocompleteItem[] | null {
21 21 if (prefix.includes(" ")) return null;
22 22 if (SYSTEM_SUBCOMMANDS.some((item) => item === prefix)) return null;
23 - const items = SYSTEM_SUBCOMMANDS.filter((item) => item.startsWith(prefix)).map(
24 - (item) => ({ value: item, label: item }),
25 - );
23 + const items = SYSTEM_SUBCOMMANDS.filter((item) =>
24 + item.startsWith(prefix),
25 + ).map((item) => ({ value: item, label: item }));
26 26 return items.length ? items : null;

extensions/the-system/system.ts

Modified
410 410 : `The System ownership approval was cancelled for ${relative}.`,