repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

fix(git-safe): guard agent Git execution

a6436748ad05e71c2d7ea86d938c2bd07c198e0c

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (9)

extensions/git-safe/CHANGELOG.md

Modified
1 1 # Changelog
3 +## Unreleased
5 +- Prevent agent-issued Git commands from opening interactive editors
6 +- Reject hook-skipping `--no-verify` options through normal Git, aliases, shell indirection, nested Bash, `xargs`, child-process PATH lookup, and literal bypasses
7 +- Convert temporary wrapper paths for Git Bash on Windows
8 +- Document explicit `git.exe` child-process and unrestricted-Bash residual bypasses
9 +- Keep safe-clone behavior unchanged
3 11 ## 0.0.3
5 13 - Add sparse safe clone support.

extensions/git-safe/README.md

Modified
24 24 - Hooks:
25 25 - `session_start`
26 26 - `session_shutdown`
27 + - `tool_call` for agent-issued `bash`
27 28 - `tool_result` for `read`
28 29 - Settings:
29 30 none
31 32 ## Behavior
34 +Agent-issued Bash commands receive noninteractive Git editor settings:
36 +- `GIT_EDITOR=true`
37 +- `GIT_SEQUENCE_EDITOR=true`
38 +- `GIT_MERGE_AUTOEDIT=no`
40 +A session-scoped Git executable wrapper receives parsed arguments from normal Bash calls, `command git`, `env git`, `xargs git`, nested Bash, and unqualified child-process PATH lookup.
41 +It rejects hook-skipping `--no-verify` options, including accepted abbreviations, short `commit -n`, and non-shell alias chains.
42 +It resets the editor environment immediately before invoking real Git and delegates ordinary commands unchanged.
43 +Bash `git()` and `git.exe()` functions route direct calls to that wrapper, while narrow preflight checks cover simple literal bypasses.
44 +Windows paths are converted for Git Bash, and common `git.exe` shell forms route through the wrapper.
45 +The layers are defense in depth, not a security boundary; unrestricted Bash can still address or construct alternate executable paths.
46 +On Windows, a non-Bash child process that explicitly launches `git.exe` can bypass the script wrapper because the extension does not ship a native PE launcher.
33 48 `git_clone_safe` clones a repository with checks around hook execution,
34 49 symlinks, LFS filters, disk use, and credential prompts.

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

Added
new file mode 100644
1 +import { describe, expect, it } from "vitest";
2 +import { applyGitPolicy, blockedGitCommandReason } from "../git-policy";
4 +describe("git-safe agent Git policy", () => {
5 + it("blocks literal command-git no-verify bypasses", () => {
6 + for (const command of [
7 + "command git commit --no-verify",
8 + "command -p git push --no-verify",
9 + " command -- git rebase --no-verify",
10 + ]) {
11 + expect(blockedGitCommandReason(command)).toContain("blocked --no-verify");
12 + }
13 + });
15 + it("does not classify ordinary Git or quoted documentation as command bypasses", () => {
16 + for (const command of [
17 + "git commit --no-verify",
18 + "printf '%s' 'command git commit --no-verify'",
19 + "command git status",
20 + "command git commit -m 'Document --no-verify usage'",
21 + "command git merge --no-verify-signatures topic",
22 + ]) {
23 + expect(blockedGitCommandReason(command)).toBeUndefined();
24 + }
25 + });
27 + it("routes Git, command, and env through the executable wrapper", () => {
28 + const runtime = { wrapperDir: "/tmp/git policy", realGit: "/usr/bin/git" };
29 + const wrapped = applyGitPolicy("git status", runtime);
31 + expect(wrapped).toContain("'/tmp/git policy'");
32 + expect(wrapped).toContain("'/tmp/git policy/git'");
33 + expect(wrapped).not.toContain("PI_GIT_SAFE_REAL_GIT");
34 + expect(applyGitPolicy(wrapped, runtime)).not.toBe(wrapped);
35 + });
37 + it("converts Windows paths for Git Bash", () => {
38 + const wrapped = applyGitPolicy("git status", {
39 + wrapperDir: "C:\\Users\\me\\AppData\\Local\\Temp\\git-safe",
40 + realGit: "C:\\Program Files\\Git\\cmd\\git.exe",
41 + });
43 + expect(wrapped).toContain(
44 + "export PATH='/c/Users/me/AppData/Local/Temp/git-safe':\"$PATH\"",
45 + );
46 + expect(wrapped).toContain(
47 + "'/c/Users/me/AppData/Local/Temp/git-safe/git' \"$@\"",
48 + );
49 + });
51 + it("does not trust an agent-supplied policy marker", () => {
52 + const command = "# pi-git-safe-policy-v1\ngit commit --no-verify";
53 + const wrapped = applyGitPolicy(command, {
54 + wrapperDir: "/tmp/wrapper",
55 + realGit: "/usr/bin/git",
56 + });
58 + expect(wrapped).not.toBe(command);
59 + expect(wrapped.endsWith(command)).toBe(true);
60 + });
61 +});

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

Modified
1 +import {
2 + chmodSync,
3 + mkdirSync,
4 + mkdtempSync,
5 + readFileSync,
6 + rmSync,
7 + writeFileSync,
8 +} from "node:fs";
9 +import { tmpdir } from "node:os";
10 +import path from "node:path";
11 +import { createBashTool } from "@earendil-works/pi-coding-agent";
1 12 import { afterEach, describe, expect, it } from "vitest";
2 -import { createTestSession, type TestSession } from "../../../test/harness";
3 -import gitSafeExtension from "../index";
13 +import {
14 + createTestSession,
15 + type TestSession,
16 + withProcessEnv,
17 +} from "../../../test/harness";
19 +type BashEvent = {
20 + type: "tool_call";
21 + toolName: "bash";
22 + toolCallId: string;
23 + input: { command: string };
24 +};
26 +function gitSafePath(): string {
27 + return path.resolve(import.meta.dirname, "../index.ts");
30 +function rtkPath(): string {
31 + return path.resolve(import.meta.dirname, "../../rtk/index.ts");
34 +function installFakeGit(root: string): string {
35 + const bin = path.join(root, "fake-bin");
36 + mkdirSync(bin);
37 + const git = path.join(bin, "git");
38 + writeFileSync(
39 + git,
40 + [
41 + "#!/usr/bin/env bash",
42 + "if [[ \"$*\" == '--list-cmds=builtins' ]]; then printf 'status\\n'; exit 0; fi",
43 + "if [[ \"$*\" == *'config --get alias.'* ]]; then exit 1; fi",
44 + "printf 'FAKE_GIT\\n'",
45 + "printf 'ARGS:'",
46 + "printf '<%s>' \"$@\"",
47 + 'printf \'\\nEDITOR=<%s> SEQUENCE=<%s> MERGE=<%s>\\n\' "$GIT_EDITOR" "$GIT_SEQUENCE_EDITOR" "$GIT_MERGE_AUTOEDIT"',
48 + "",
49 + ].join("\n"),
50 + "utf8",
51 + );
52 + chmodSync(git, 0o755);
53 + const gitExe = path.join(bin, "git.exe");
54 + writeFileSync(gitExe, readFileSync(git));
55 + chmodSync(gitExe, 0o755);
56 + return bin;
59 +function installFakeRtk(bin: string): void {
60 + const rtk = path.join(bin, "rtk");
61 + writeFileSync(
62 + rtk,
63 + [
64 + "#!/usr/bin/env bash",
65 + "if [[ \"$1\" == '--version' ]]; then printf 'rtk 0.42.4\\n'; exit 0; fi",
66 + "if [[ \"$1\" == 'rewrite' && \"$2\" == 'git commit --no-verify' ]]; then printf 'rtk git commit --no-verify\\n'; exit 0; fi",
67 + "if [[ \"$1\" == 'rewrite' && \"$2\" == 'git status' ]]; then printf 'rtk git status\\n'; exit 0; fi",
68 + 'if [[ "$1" == \'git\' ]]; then shift; exec git "$@"; fi',
69 + "exit 1",
70 + "",
71 + ].join("\n"),
72 + "utf8",
73 + );
74 + chmodSync(rtk, 0o755);
77 +function bashEvent(command: string): BashEvent {
78 + return {
79 + type: "tool_call",
80 + toolName: "bash",
81 + toolCallId: crypto.randomUUID(),
82 + input: { command },
83 + };
5 86 describe("git-safe pi-test-harness", () => {
6 87 let t: TestSession | undefined;
88 + let root: string | undefined;
89 + let fakeGit: string | undefined;
8 91 afterEach(() => {
9 92 t?.dispose();
93 + if (root) rmSync(root, { recursive: true, force: true });
10 94 t = undefined;
95 + root = undefined;
96 + fakeGit = undefined;
99 + async function startWithFakeGit(useRtk = false): Promise<void> {
100 + root = mkdtempSync(path.join(tmpdir(), "pi-git-safe-test-"));
101 + const fakeBin = installFakeGit(root);
102 + if (useRtk) installFakeRtk(fakeBin);
103 + fakeGit = path.join(fakeBin, "git");
104 + t = await createTestSession({
105 + cwd: root,
106 + env: { PATH: `${fakeBin}${path.delimiter}${process.env.PATH}` },
107 + extensions: useRtk ? [gitSafePath(), rtkPath()] : [gitSafePath()],
108 + });
111 + async function execute(command: string) {
112 + if (!t) throw new Error("missing test session");
113 + const event = bashEvent(command);
114 + const blocked = await t.session.extensionRunner.emitToolCall(
115 + event as never,
116 + );
117 + if (blocked) return { blocked, output: "" };
118 + const tool = createBashTool(t.cwd);
119 + try {
120 + const result = await withProcessEnv(t.env, () =>
121 + tool.execute(
122 + event.toolCallId,
123 + event.input,
124 + new AbortController().signal,
125 + undefined,
126 + ),
127 + );
128 + const output = result.content
129 + .flatMap((part) => (part.type === "text" ? [part.text] : []))
130 + .join("\n");
131 + return { blocked, output };
132 + } catch (error) {
133 + return {
134 + blocked,
135 + output: error instanceof Error ? error.message : String(error),
136 + };
140 + async function expectRejected(command: string): Promise<void> {
141 + const result = await execute(command);
142 + expect(result.output).toContain("git-safe blocked --no-verify");
143 + expect(result.output).not.toContain("FAKE_GIT");
13 146 it("loads in real Pi extension runtime", async () => {
14 - t = await createTestSession({ extensionFactories: [gitSafeExtension] });
147 + t = await createTestSession({ extensions: [gitSafePath()] });
16 149 expect(t.session.extensionRunner.extensions).toHaveLength(1);
152 + it("sets noninteractive editor variables while ordinary Git still runs", async () => {
153 + await startWithFakeGit();
155 + const result = await execute("git status");
157 + expect(result.blocked).toBeUndefined();
158 + expect(result.output).toContain("FAKE_GIT");
159 + expect(result.output).toContain("ARGS:<status>");
160 + expect(result.output).toContain("EDITOR=<true> SEQUENCE=<true> MERGE=<no>");
161 + });
163 + it("rejects no-verify after shell expansion and indirect PATH lookup", async () => {
164 + await startWithFakeGit();
166 + for (const command of [
167 + 'flag=--no-verify; git commit "$flag"',
168 + "git am --no-v patch.mbox",
169 + "git am -n patch.mbox",
170 + 'command git commit --no-"verify"',
171 + "command -p git -C . commit --no-verify",
172 + "env git push --no-verify",
173 + "env --uns PATH git commit --no-verify",
174 + "bash -p -c 'git rebase --no-verify'",
175 + "bash -c 'command git commit --no-verify'",
176 + "unset -f git; git commit --no-verify",
177 + "printf '%s\\0' commit --no-verify | xargs -0 git",
178 + "printf '%s\\0' commit --no-verify | xargs -0 git.exe",
179 + "printf '%s\\0' commit --no-verify | xargs -0 --max-a 2 git.exe",
180 + "git commit -n",
181 + "git commit --no-verif",
182 + "git commit --untracked-files --no-verify",
183 + "git push --signed --no-verify",
184 + "git rebase --rebase-merges --no-verify main",
185 + "git pull --no-verify",
186 + ]) {
187 + await expectRejected(command);
189 + });
191 + it("rejects temporary aliases that create no-verify inside Git", async () => {
192 + await startWithFakeGit();
194 + for (const command of [
195 + "git -c 'alias.nv=commit --no-verify' nv",
196 + `git -c "alias.nv=commit -m '' --no-verify" nv`,
197 + "git -c 'alias.nv=--no-pager commit --no-verify' nv",
198 + "git -c 'alias.x=-c alias.y=commit y --no-verify' x",
199 + "git -calias.nv='commit --no-verify' nv",
200 + "git -c 'alias.nv=commit -n' nv",
201 + "git -c 'alias.nv=commit \"--no-verify\"' nv",
202 + "git -c alias.ci=commit ci --no-verify",
203 + "NV='commit --no-verify' git --config-env=alias.nv=NV nv",
204 + "GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=alias.nv GIT_CONFIG_VALUE_0='commit --no-verify' git nv",
205 + ]) {
206 + await expectRejected(command);
209 + const chain = Array.from(
210 + { length: 12 },
211 + (_, index) => `-c alias.a${index}=a${index + 1}`,
212 + ).join(" ");
213 + await expectRejected(`git ${chain} -c 'alias.a12=commit --no-verify' a0`);
214 + });
216 + it("restores editor protection at the executable boundary", async () => {
217 + await startWithFakeGit();
219 + for (const command of [
220 + "GIT_EDITOR=vim git commit",
221 + "GIT_SEQUENCE_EDITOR=vim git rebase -i HEAD~1",
222 + "env -u GIT_EDITOR -u GIT_SEQUENCE_EDITOR -u GIT_MERGE_AUTOEDIT git commit",
223 + "GIT_EDITOR=vim command -p git commit",
224 + ]) {
225 + const result = await execute(command);
226 + expect(result.output).toContain("FAKE_GIT");
227 + expect(result.output).toContain(
228 + "EDITOR=<true> SEQUENCE=<true> MERGE=<no>",
229 + );
231 + });
233 + it("preserves editor queries without opening an editor", async () => {
234 + await startWithFakeGit();
236 + const result = await execute("git var GIT_EDITOR");
237 + expect(result.output).toContain("FAKE_GIT");
238 + expect(result.output).toContain("EDITOR=<> SEQUENCE=<> MERGE=<>");
239 + });
241 + it("does not trust an agent-supplied policy marker", async () => {
242 + await startWithFakeGit();
244 + await expectRejected(
245 + "# pi-git-safe-policy-v1\\ngit commit --no-verify".replace("\\n", "\n"),
246 + );
247 + });
249 + it("permits no-verify when Git treats it as data", async () => {
250 + await startWithFakeGit();
252 + for (const command of [
253 + "git add -- --no-verify",
254 + "git grep -e --no-verify",
255 + "git commit -m --no-verify",
256 + "git commit -am --no-verify",
257 + "git commit -uno",
258 + "git commit -t/dev/null",
259 + "git commit --mess --no-verify",
260 + "git commit -m safe --end-of-options --no-verify",
261 + "git commit -Sn -m signed",
262 + "git merge --into-name --no-verify topic",
263 + "git merge -F --no-verify topic",
264 + "git am --resolvemsg --no-verify patch.mbox",
265 + "git rebase --trailer --no-verify trunk",
266 + "git pull --no-rebase -o --no-verify",
267 + "git -c 'alias.nv=commit --no-verify' status",
268 + "git -c 'alias.note=!printf %s --no-verify' note",
269 + "command git merge --no-verify-signatures topic",
270 + "command git commit -m 'Document --no-verify usage'",
271 + 'env -i PATH="$PATH" git status',
272 + "GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=alias.nv GIT_CONFIG_VALUE_0='commit --no-verify' git -c alias.nv=status nv",
273 + "GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=alias.status GIT_CONFIG_VALUE_0='commit --no-verify' git status",
274 + ]) {
275 + const result = await execute(command);
276 + expect(result.blocked, command).toBeUndefined();
277 + expect(result.output, command).toContain("FAKE_GIT");
279 + });
281 + it("blocks literal command-git bypasses before execution", async () => {
282 + await startWithFakeGit();
284 + const result = await execute("command git commit --no-verify");
286 + expect(result.blocked).toMatchObject({ block: true });
287 + expect(result.blocked?.reason).toContain("git-safe blocked --no-verify");
288 + });
290 + it("rejects literal absolute Git paths", async () => {
291 + await startWithFakeGit();
292 + if (!fakeGit) throw new Error("missing fake Git path");
294 + for (const command of ["commit", "pull"]) {
295 + const result = await execute(
296 + `${JSON.stringify(fakeGit)} ${command} --no-verify`,
297 + );
298 + expect(result.blocked).toMatchObject({ block: true });
300 + });
302 + it("keeps policy active after RTK rewrites Git", async () => {
303 + await startWithFakeGit(true);
305 + await expectRejected("git commit --no-verify");
306 + const ordinary = await execute("git status");
307 + expect(ordinary.output).toContain("FAKE_GIT");
308 + expect(ordinary.output).toContain("ARGS:<status>");
309 + });

extensions/git-safe/git-policy.ts

Added
new file mode 100644
1 +import { constants } from "node:fs";
2 +import {
3 + access,
4 + chmod,
5 + mkdtemp,
6 + readFile,
7 + realpath,
8 + rm,
9 + writeFile,
10 +} from "node:fs/promises";
11 +import { tmpdir } from "node:os";
12 +import { delimiter, join } from "node:path";
14 +const POLICY_MARKER = "# pi-git-safe-policy-v1";
15 +const COMMAND_PREFIX_END = "# pi-command-prefix-end";
17 +const BLOCK_REASON =
18 + "git-safe blocked --no-verify. Fix the hook failure or ask the user for help.";
20 +const DIRECT_COMMAND_GIT_NO_VERIFY_RE =
21 + /^\s*command\s+(?:(?:-p|--)\s+)*git(?:\.exe)?\s+(?:am|commit|merge|pull|push|rebase)\s+--no-verify(?:\s|$)/u;
23 +export interface GitPolicyRuntime {
24 + wrapperDir: string;
25 + realGit: string;
28 +function pathKey(env: NodeJS.ProcessEnv): string {
29 + return Object.keys(env).find((key) => key.toLowerCase() === "path") ?? "PATH";
32 +export async function findGitExecutable(
33 + env: NodeJS.ProcessEnv = process.env,
34 + platform = process.platform,
35 +): Promise<string | undefined> {
36 + const path = env[pathKey(env)] ?? "";
37 + const names = platform === "win32" ? ["git.exe"] : ["git"];
38 + for (const dir of path.split(delimiter).filter(Boolean)) {
39 + for (const name of names) {
40 + const candidate = join(dir.replace(/^"|"$/gu, ""), name);
41 + try {
42 + await access(
43 + candidate,
44 + platform === "win32" ? constants.F_OK : constants.X_OK,
45 + );
46 + return await realpath(candidate);
47 + } catch {}
48 + }
49 + }
50 + return undefined;
53 +export async function createGitPolicyRuntime(): Promise<GitPolicyRuntime> {
54 + const realGit = await findGitExecutable();
55 + if (!realGit) throw new Error("Git executable not found on PATH");
56 + const wrapperDir = await mkdtemp(join(tmpdir(), "pi-git-safe-policy-"));
57 + const wrapper = join(wrapperDir, "git");
58 + try {
59 + const template = await readFile(
60 + new URL("./git-wrapper.cjs", import.meta.url),
61 + "utf8",
62 + );
63 + await writeFile(
64 + wrapper,
65 + template.replace('"__PI_GIT_SAFE_REAL_GIT__"', JSON.stringify(realGit)),
66 + "utf8",
67 + );
68 + await chmod(wrapper, 0o755);
69 + await writeFile(
70 + join(wrapperDir, "git.cmd"),
71 + `@echo off\r\n"${process.execPath}" "%~dp0git" %*\r\n`,
72 + "utf8",
73 + );
74 + return { wrapperDir, realGit };
75 + } catch (error) {
76 + await rm(wrapperDir, { recursive: true, force: true }).catch(() => {});
77 + throw error;
78 + }
81 +export async function removeGitPolicyRuntime(
82 + runtime: GitPolicyRuntime | undefined,
83 +): Promise<void> {
84 + if (runtime)
85 + await rm(runtime.wrapperDir, { recursive: true, force: true }).catch(
86 + () => {},
87 + );
90 +function shellQuote(value: string): string {
91 + return `'${value.replaceAll("'", `'\\''`)}'`;
94 +function bashPath(value: string): string {
95 + const normalized = value.replaceAll("\\", "/");
96 + const drive = normalized.match(/^([A-Za-z]):\/(.*)$/u);
97 + return drive ? `/${drive[1].toLowerCase()}/${drive[2]}` : normalized;
100 +export function blockedGitCommandReason(
101 + command: string,
102 + runtime?: GitPolicyRuntime,
103 +): string | undefined {
104 + if (DIRECT_COMMAND_GIT_NO_VERIFY_RE.test(command)) return BLOCK_REASON;
105 + if (!runtime) return undefined;
106 + const trimmed = command.trimStart();
107 + const literalPaths = [
108 + runtime.realGit,
109 + bashPath(runtime.realGit),
110 + shellQuote(runtime.realGit),
111 + shellQuote(bashPath(runtime.realGit)),
112 + JSON.stringify(runtime.realGit),
113 + ];
114 + for (const path of literalPaths) {
115 + if (!trimmed.startsWith(`${path} `)) continue;
116 + const args = trimmed.slice(path.length).trimStart();
117 + if (
118 + /^(?:am|commit|merge|pull|push|rebase)\s+--no-verify(?:\s|$)/u.test(args)
120 + return BLOCK_REASON;
122 + return undefined;
125 +export function applyGitPolicy(
126 + command: string,
127 + runtime: GitPolicyRuntime,
128 +): string {
129 + const wrapper = shellQuote(bashPath(join(runtime.wrapperDir, "git")));
130 + return `${POLICY_MARKER}
131 +export PATH=${shellQuote(bashPath(runtime.wrapperDir))}:"$PATH"
132 +git() {
133 + ${wrapper} "$@"
135 +git.exe() {
136 + ${wrapper} "$@"
138 +command() {
139 + local -a __pi_git_safe_args=("$@")
140 + local __pi_git_safe_index=0
141 + while [[ "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "-p" || "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "--" ]]; do
142 + ((__pi_git_safe_index++))
143 + done
144 + if [[ "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "git" || "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "git.exe" ]]; then
145 + ${wrapper} "\${__pi_git_safe_args[@]:$((__pi_git_safe_index + 1))}"
146 + else
147 + builtin command "$@"
148 + fi
150 +env() {
151 + local -a __pi_git_safe_args=("$@")
152 + local __pi_git_safe_index=0
153 + while (( __pi_git_safe_index < \${#__pi_git_safe_args[@]} )); do
154 + case "\${__pi_git_safe_args[$__pi_git_safe_index]}" in
155 + --)
156 + ((__pi_git_safe_index++))
157 + break
158 + ;;
159 + --u*=*|--c*=*|--s*=*|--a*=*)
160 + ((__pi_git_safe_index++))
161 + ;;
162 + -u|--u*|-C|--c*|-S|--s*|--a*)
163 + ((__pi_git_safe_index += 2))
164 + ;;
165 + -*|*=*)
166 + ((__pi_git_safe_index++))
167 + ;;
168 + *)
169 + break
170 + ;;
171 + esac
172 + done
173 + if [[ "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "git" || "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "git.exe" ]]; then
174 + __pi_git_safe_args[$__pi_git_safe_index]=${wrapper}
175 + fi
176 + builtin command env "\${__pi_git_safe_args[@]}"
178 +xargs() {
179 + local -a __pi_git_safe_args=("$@")
180 + local __pi_git_safe_index=0
181 + while (( __pi_git_safe_index < \${#__pi_git_safe_args[@]} )); do
182 + case "\${__pi_git_safe_args[$__pi_git_safe_index]}" in
183 + --)
184 + ((__pi_git_safe_index++))
185 + break
186 + ;;
187 + --arg*=*|--e*=*|--r*=*|--m*=*|--d*=*)
188 + ((__pi_git_safe_index++))
189 + ;;
190 + -a|-E|-I|-L|-n|-P|-s|-d|--arg*|--e*|--r*|--m*|--d*)
191 + ((__pi_git_safe_index += 2))
192 + ;;
193 + -*)
194 + ((__pi_git_safe_index++))
195 + ;;
196 + *)
197 + break
198 + ;;
199 + esac
200 + done
201 + if [[ "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "git" || "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "git.exe" ]]; then
202 + __pi_git_safe_args[$__pi_git_safe_index]=${wrapper}
203 + fi
204 + builtin command xargs "\${__pi_git_safe_args[@]}"
206 +export -f git git.exe command env xargs
207 +${COMMAND_PREFIX_END}
208 +${command}`;

extensions/git-safe/git-wrapper.cjs

Added
new file mode 100644
1 +#!/usr/bin/env node
3 +const { spawnSync } = require("node:child_process");
5 +const realGit = "__PI_GIT_SAFE_REAL_GIT__";
6 +const protectedCommands = new Set([
7 + "am",
8 + "commit",
9 + "merge",
10 + "pull",
11 + "push",
12 + "rebase",
13 +]);
14 +const globalValueOptions = new Set([
15 + "-C",
16 + "-c",
17 + "--config-env",
18 + "--exec-path",
19 + "--git-dir",
20 + "--namespace",
21 + "--super-prefix",
22 + "--work-tree",
23 +]);
24 +const commandValueOptions = {
25 + am: new Set([
26 + "-C",
27 + "-p",
28 + "--directory",
29 + "--empty",
30 + "--exclude",
31 + "--include",
32 + "--patch-format",
33 + "--quoted-cr",
34 + "--resolvemsg",
35 + "--whitespace",
36 + ]),
37 + commit: new Set([
38 + "-C",
39 + "-F",
40 + "-c",
41 + "-m",
42 + "--author",
43 + "--cleanup",
44 + "--date",
45 + "--file",
46 + "--fixup",
47 + "--message",
48 + "--pathspec-from-file",
49 + "--reedit-message",
50 + "--reuse-message",
51 + "--squash",
52 + "--template",
53 + "--trailer",
54 + ]),
55 + merge: new Set([
56 + "-F",
57 + "-m",
58 + "-s",
59 + "-X",
60 + "--cleanup",
61 + "--file",
62 + "--into-name",
63 + "--message",
64 + "--strategy",
65 + "--strategy-option",
66 + ]),
67 + pull: new Set([
68 + "-s",
69 + "-X",
70 + "--cleanup",
71 + "--depth",
72 + "--deepen",
73 + "--negotiation-tip",
74 + "--server-option",
75 + "--shallow-exclude",
76 + "--shallow-since",
77 + "--strategy",
78 + "--strategy-option",
79 + "--upload-pack",
80 + ]),
81 + push: new Set(["-o", "--exec", "--push-option", "--receive-pack", "--repo"]),
82 + rebase: new Set([
83 + "-s",
84 + "-X",
85 + "-x",
86 + "--empty",
87 + "--exec",
88 + "--onto",
89 + "--strategy",
90 + "--strategy-option",
91 + "--trailer",
92 + "--whitespace",
93 + ]),
94 +};
95 +const shortValueOptions = {
96 + am: new Set(["C", "p"]),
97 + commit: new Set(["C", "F", "c", "m", "t"]),
98 + merge: new Set(["F", "m", "s", "X"]),
99 + pull: new Set(["o", "s", "X"]),
100 + push: new Set(["o"]),
101 + rebase: new Set(["s", "X", "x"]),
103 +const shortAttachedValueOptions = {
104 + am: new Set(),
105 + commit: new Set(["S", "u"]),
106 + merge: new Set(),
107 + pull: new Set(),
108 + push: new Set(),
109 + rebase: new Set(),
112 +function optionName(argument) {
113 + const equals = argument.indexOf("=");
114 + return equals < 0 ? argument : argument.slice(0, equals);
117 +function consumesNext(argument, options) {
118 + return !argument.includes("=") && options.has(optionName(argument));
121 +function consumesCommandValue(argument, options) {
122 + if (argument.includes("=")) return false;
123 + if (options.has(argument)) return true;
124 + if (!argument.startsWith("--")) return false;
125 + return [...options].filter((option) => option.startsWith(argument)).length === 1;
128 +function commandPosition(args) {
129 + for (let index = 0; index < args.length; index++) {
130 + const argument = args[index];
131 + if (argument === "--") return index + 1;
132 + if (!argument.startsWith("-")) return index;
133 + if (consumesNext(argument, globalValueOptions)) index++;
135 + return -1;
138 +function addAlias(aliases, config) {
139 + const match = config.match(/^alias\.([^=]+)=(.*)$/isu);
140 + if (match) aliases.set(match[1].toLowerCase(), match[2]);
143 +function addArgumentAliases(aliases, args, commandIndex) {
144 + for (let index = 0; index < commandIndex; index++) {
145 + const argument = args[index];
146 + if (argument === "-c") {
147 + addAlias(aliases, args[++index] ?? "");
148 + continue;
150 + if (argument.startsWith("-c") && argument.length > 2) {
151 + addAlias(aliases, argument.slice(2));
152 + continue;
154 + const configEnv = argument.startsWith("--config-env=")
155 + ? argument.slice("--config-env=".length)
156 + : argument === "--config-env"
157 + ? (args[++index] ?? "")
158 + : undefined;
159 + if (configEnv !== undefined) {
160 + const equals = configEnv.indexOf("=");
161 + if (equals >= 0) {
162 + const name = configEnv.slice(0, equals);
163 + const variable = configEnv.slice(equals + 1);
164 + addAlias(aliases, `${name}=${process.env[variable] ?? ""}`);
170 +function temporaryAliases(args, commandIndex) {
171 + const aliases = new Map();
172 + const count = Number.parseInt(process.env.GIT_CONFIG_COUNT ?? "0", 10);
173 + for (let index = 0; index < count; index++) {
174 + const key = process.env[`GIT_CONFIG_KEY_${index}`] ?? "";
175 + const value = process.env[`GIT_CONFIG_VALUE_${index}`] ?? "";
176 + addAlias(aliases, `${key}=${value}`);
178 + addArgumentAliases(aliases, args, commandIndex);
179 + return aliases;
182 +function splitAlias(value) {
183 + const words = [];
184 + let word = "";
185 + let quote = "";
186 + let escaped = false;
187 + let started = false;
188 + for (const character of value.trim()) {
189 + if (escaped) {
190 + word += character;
191 + escaped = false;
192 + started = true;
193 + continue;
195 + if (character === "\\" && quote !== "'") {
196 + escaped = true;
197 + continue;
199 + if ((character === "'" || character === '"') && !quote) {
200 + quote = character;
201 + started = true;
202 + continue;
204 + if (character === quote) {
205 + quote = "";
206 + continue;
208 + if (/\s/u.test(character) && !quote) {
209 + if (started) words.push(word);
210 + word = "";
211 + started = false;
212 + continue;
214 + word += character;
215 + started = true;
217 + if (escaped) {
218 + word += "\\";
219 + started = true;
221 + if (started) words.push(word);
222 + return words;
225 +function configuredAlias(globalArgs, command) {
226 + const result = spawnSync(
227 + realGit,
228 + [...globalArgs, "config", "--get", `alias.${command}`],
230 + encoding: "utf8",
231 + env: process.env,
232 + },
233 + );
234 + return result.status === 0 ? result.stdout.trim() : undefined;
237 +function isBuiltinCommand(command) {
238 + const result = spawnSync(realGit, ["--list-cmds=builtins"], {
239 + encoding: "utf8",
240 + env: process.env,
241 + });
242 + return result.status === 0 && result.stdout.split(/\s+/u).includes(command);
245 +function resolveCommand(args) {
246 + const position = commandPosition(args);
247 + if (position < 0 || position >= args.length) return undefined;
248 + const globalArgs = args.slice(0, position);
249 + const aliases = temporaryAliases(args, position);
250 + const seen = new Set();
251 + let command = args[position];
252 + let commandArgs = args.slice(position + 1);
253 + while (!protectedCommands.has(command)) {
254 + const key = command.toLowerCase();
255 + if (seen.has(key)) break;
256 + seen.add(key);
257 + const alias = aliases.get(key) ?? configuredAlias(globalArgs, command);
258 + if (!alias || alias.startsWith("!") || isBuiltinCommand(command)) break;
259 + const expansion = [...splitAlias(alias), ...commandArgs];
260 + const expandedPosition = commandPosition(expansion);
261 + if (expandedPosition < 0 || expandedPosition >= expansion.length) break;
262 + addArgumentAliases(aliases, expansion, expandedPosition);
263 + globalArgs.push(...expansion.slice(0, expandedPosition));
264 + command = expansion[expandedPosition];
265 + commandArgs = expansion.slice(expandedPosition + 1);
267 + return { command, args: commandArgs };
270 +function isNoVerifyLongOption(command, argument) {
271 + const minimum = command === "am" ? "--no-v" : "--no-veri";
272 + return argument.length >= minimum.length && "--no-verify".startsWith(argument);
275 +function inspectShortOptions(command, argument) {
276 + if (!/^-[^-]/u.test(argument)) return { blocked: false, consumesNext: false };
277 + const options = argument.slice(1);
278 + const values = shortValueOptions[command];
279 + const attachedValues = shortAttachedValueOptions[command];
280 + for (let index = 0; index < options.length; index++) {
281 + const option = options[index];
282 + if ((command === "am" || command === "commit") && option === "n") {
283 + return { blocked: true, consumesNext: false };
285 + if (values.has(option)) {
286 + return {
287 + blocked: false,
288 + consumesNext: index === options.length - 1,
289 + };
291 + if (attachedValues.has(option)) {
292 + return { blocked: false, consumesNext: false };
295 + return { blocked: false, consumesNext: false };
298 +function hasNoVerifyOption(args) {
299 + const resolved = resolveCommand(args);
300 + if (!resolved || !protectedCommands.has(resolved.command)) return false;
301 + const valueOptions = commandValueOptions[resolved.command];
302 + for (let index = 0; index < resolved.args.length; index++) {
303 + const argument = resolved.args[index];
304 + if (argument === "--" || argument === "--end-of-options") return false;
305 + if (isNoVerifyLongOption(resolved.command, argument)) return true;
306 + const short = inspectShortOptions(resolved.command, argument);
307 + if (short.blocked) return true;
308 + if (short.consumesNext || consumesCommandValue(argument, valueOptions)) index++;
310 + return false;
313 +const args = process.argv.slice(2);
314 +if (hasNoVerifyOption(args)) {
315 + console.error(
316 + "git-safe blocked --no-verify. Fix the hook failure or ask the user for help.",
317 + );
318 + process.exit(126);
321 +const editorQuery =
322 + args[commandPosition(args)] === "var" &&
323 + (args[commandPosition(args) + 1] === "GIT_EDITOR" ||
324 + args[commandPosition(args) + 1] === "GIT_SEQUENCE_EDITOR");
325 +const env = { ...process.env };
326 +if (!editorQuery) {
327 + env.GIT_EDITOR = "true";
328 + env.GIT_SEQUENCE_EDITOR = "true";
329 + env.GIT_MERGE_AUTOEDIT = "no";
331 +const result = spawnSync(realGit, args, { stdio: "inherit", env });
332 +if (result.error) {
333 + console.error(result.error.message);
334 + process.exit(127);
336 +if (result.signal) process.kill(process.pid, result.signal);
337 +process.exit(result.status ?? 1);

extensions/git-safe/index.ts

Modified
20 20 import { realpath } from "node:fs/promises";
21 21 import { resolve } from "node:path";
22 -import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
22 +import {
23 + type ExtensionAPI,
24 + isToolCallEventType,
25 +} from "@earendil-works/pi-coding-agent";
23 26 import { Text } from "@earendil-works/pi-tui";
24 27 import { Type } from "typebox";
25 28 import {
27 30 type SafeCloneResult,
28 31 safeClone,
29 32 } from "./clone.js";
33 +import {
34 + applyGitPolicy,
35 + blockedGitCommandReason,
36 + createGitPolicyRuntime,
37 + type GitPolicyRuntime,
38 + removeGitPolicyRuntime,
39 +} from "./git-policy.js";
30 40 import { createMarkers, wrapUntrusted } from "./spotlight.js";
32 42 // ── Git-specific spotlight preamble ────────────────────────────────────────
68 78 // Session-scoped spotlight markers
69 79 const spotlightMarkers = createMarkers({ preamble: GIT_PREAMBLE });
70 80 let generation = 0;
81 + let gitPolicyRegistered = false;
82 + let gitPolicyRuntime: GitPolicyRuntime | undefined;
72 - // ── session_start: recover tracked paths ─────────────────────────────
84 + // ── session_start: install agent Git policy ──────────────────────────
74 86 pi.on("session_start", async (_event, ctx) => {
87 + if (!gitPolicyRuntime) {
88 + try {
89 + gitPolicyRuntime = await createGitPolicyRuntime();
90 + } catch (error) {
91 + if (ctx.hasUI)
92 + ctx.ui.notify(
93 + `git-safe policy disabled: ${error instanceof Error ? error.message : String(error)}`,
94 + "warning",
95 + );
96 + }
97 + }
98 + if (gitPolicyRuntime && !gitPolicyRegistered) {
99 + gitPolicyRegistered = true;
100 + pi.on("tool_call", (event) => {
101 + if (!isToolCallEventType("bash", event) || !gitPolicyRuntime) return;
102 + const reason = blockedGitCommandReason(
103 + event.input.command,
104 + gitPolicyRuntime,
105 + );
106 + if (reason) return { block: true, reason };
107 + event.input.command = applyGitPolicy(
108 + event.input.command,
109 + gitPolicyRuntime,
110 + );
111 + });
75 114 const ticket = ++generation;
76 115 const paths = await recoverTrackedPaths(ctx.cwd);
77 116 if (ticket !== generation) return;
89 128 pi.on("session_shutdown", async () => {
90 129 generation++;
130 + await removeGitPolicyRuntime(gitPolicyRuntime);
131 + gitPolicyRuntime = undefined;
93 134 // ── tool_result hook on "read": spotlight-wrap cloned content ────────

extensions/rtk/__tests__/rtk.test.ts

Modified
6 6 localFallbackRewrite,
7 7 parseRtkVersion,
8 8 shouldSkipCommand,
9 + splitCommandPrefix,
9 10 } = __test;
11 12 type Handler = (event: any, ctx: any) => unknown | Promise<unknown>;
65 66 expect(isFindRewrite("rtk git status")).toBe(false);
69 + test("preserves registered command prefixes around rewrites", async () => {
70 + const prefix = "# policy\n# pi-command-prefix-end\n";
71 + expect(splitCommandPrefix(`${prefix}git status`)).toEqual({
72 + prefix,
73 + command: "git status",
74 + });
75 + expect(
76 + await emit(
77 + await loadWithRewrite(0, "rtk git status\n"),
78 + `${prefix}git status`,
79 + ),
80 + ).toBe(`${prefix}rtk git status`);
81 + });
68 83 test("maps local noisy-output misses only", () => {
69 84 expect(localFallbackRewrite("journalctl --user -n 100 --no-pager")).toBe(
70 85 "rtk summary journalctl --user -n 100 --no-pager",

extensions/rtk/index.ts

Modified
10 10 import { isToolCallEventType } from "@earendil-works/pi-coding-agent";
12 12 const TIMEOUT_MS = 2_000;
13 +const COMMAND_PREFIX_END = "# pi-command-prefix-end\n";
13 14 const MIN_MAJOR = 0;
14 15 const MIN_MINOR = 23;
45 46 return /^(?:env\s+)?RTK_DISABLED=1(?:\s|$)/u.test(trimmed);
49 +export function splitCommandPrefix(command: string): {
50 + prefix: string;
51 + command: string;
52 +} {
53 + const end = command.indexOf(COMMAND_PREFIX_END);
54 + if (end < 0) return { prefix: "", command };
55 + const bodyStart = end + COMMAND_PREFIX_END.length;
56 + return {
57 + prefix: command.slice(0, bodyStart),
58 + command: command.slice(bodyStart),
59 + };
48 62 function hasShellOperators(command: string): boolean {
49 63 return /[|;<>`]|\$\(|&&|\|\|/u.test(command);
217 231 localFallbackRewrite,
218 232 parseRtkVersion,
219 233 shouldSkipCommand,
234 + splitCommandPrefix,
222 237 export default async function rtk(pi: ExtensionAPI, ctx?: ExtensionContext) {
242 257 pi.on("tool_call", async (event, ctx) => {
243 258 if (!isToolCallEventType("bash", event)) return;
244 - const command = event.input.command;
245 - if (typeof command !== "string" || shouldSkipCommand(command)) return;
246 - const outcome = await rewriteCommand(pi, command, ctx.signal);
259 + const framed = splitCommandPrefix(event.input.command);
260 + if (shouldSkipCommand(framed.command)) return;
261 + const outcome = await rewriteCommand(pi, framed.command, ctx.signal);
247 262 const rewritten =
248 263 outcome.kind === "rewrite"
249 264 ? outcome.command
250 265 : outcome.kind === "fallback"
251 - ? localFallbackRewrite(command)
266 + ? localFallbackRewrite(framed.command)
252 267 : undefined;
253 268 if (rewritten && (findPathSupported || !isFindRewrite(rewritten)))
254 - event.input.command = rewritten;
269 + event.input.command = framed.prefix + rewritten;