import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { fauxAssistantMessage, fauxProvider, fauxToolCall, } from "@earendil-works/pi-ai"; import { afterEach, describe, expect, it, vi } from "vitest"; import { createTestSession, type TestSession } from "../../../test/harness"; function extPath(): string { return path.resolve(import.meta.dirname, "../index.ts"); } function projectSettings(cwd: string, verboten: Record): void { mkdirSync(path.join(cwd, ".pi"), { recursive: true }); writeFileSync( path.join(cwd, ".pi", "settings.json"), JSON.stringify({ verboten }), "utf8", ); } function toolCall(toolName: string, input: Record) { return { type: "tool_call", toolName, toolCallId: crypto.randomUUID(), input, }; } describe("Verboten Pi extension", () => { let t: TestSession | undefined; afterEach(() => { t?.dispose(); t = undefined; vi.restoreAllMocks(); }); it("loads through the real Pi runtime with one command and no tools", async () => { t = await createTestSession({ extensions: [extPath()] }); const extension = t.session.extensionRunner.extensions[0]; expect(extension.path).toBe(extPath()); expect([...extension.commands.keys()]).toEqual(["verboten"]); expect([...extension.tools.keys()]).toEqual([]); }); it("blocks protected read, write, edit, and direct grep calls", async () => { t = await createTestSession({ extensions: [extPath()] }); for (const [toolName, input] of [ ["read", { path: ".env" }], ["write", { path: ".env.local", content: "fixture" }], [ "edit", { path: ".env.production", edits: [{ oldText: "a", newText: "b" }], }, ], ["grep", { pattern: "token", path: ".env" }], ] as const) { const blocked = await t.session.extensionRunner.emitToolCall( toolCall(toolName, input) as never, ); expect(blocked, toolName).toMatchObject({ block: true }); expect(blocked?.reason, toolName).toContain(`blocked ${toolName}`); expect(blocked?.terminate).toBeUndefined(); } }); it("allows public templates, broad grep, ls, and find", async () => { t = await createTestSession({ extensions: [extPath()] }); for (const [toolName, input] of [ ["read", { path: ".env.example" }], ["grep", { pattern: "token", path: "." }], ["ls", { path: "." }], ["find", { pattern: ".env", path: "." }], ] as const) expect( await t.session.extensionRunner.emitToolCall( toolCall(toolName, input) as never, ), toolName, ).toBeUndefined(); }); it("injects terse instructions and every effective regex", async () => { t = await createTestSession({ extensions: [extPath()] }); const result = await t.session.extensionRunner.emitBeforeAgentStart( "prompt", undefined, "BASE", {} as never, ); expect(result?.systemPrompt).toContain("BASE"); expect(result?.systemPrompt).toContain( "Never expose protected-file contents", ); expect(result?.systemPrompt).toContain( "Trusted programs, hooks, filters, and credential helpers may consume protected files internally", ); expect(result?.systemPrompt).not.toContain( "Never read protected-file contents", ); expect(result?.systemPrompt).toContain("Broad grep searches"); expect(result?.systemPrompt).toContain(""); expect(result?.systemPrompt).toContain(" { t = await createTestSession({ extensions: [extPath()] }); const result = await t.session.extensionRunner.emitToolResult({ type: "tool_result", toolName: "grep", toolCallId: "grep-1", input: { pattern: "token", path: "." }, content: [ { type: "text", text: [ "safe.txt:1: allowed", ".env:2: protected-secret-fixture", ".env-3- protected-context-fixture", ].join("\n"), }, ], details: undefined, isError: false, } as never); const text = result?.content ?.filter((part) => part.type === "text") .map((part) => part.text) .join("\n"); expect(text).toContain("safe.txt:1: allowed"); expect(text).toContain("Verboten omitted 2 protected grep lines."); expect(text).not.toContain(".env"); expect(text).not.toContain("protected-secret-fixture"); expect(text).not.toContain("protected-context-fixture"); }); it("marks all-protected truncated grep output as an error", async () => { t = await createTestSession({ extensions: [extPath()] }); const result = await t.session.extensionRunner.emitToolResult({ type: "tool_result", toolName: "grep", toolCallId: "grep-2", input: { pattern: "token", path: "." }, content: [{ type: "text", text: ".env:1: protected" }], details: { matchLimitReached: 1 }, isError: false, } as never); expect(result?.isError).toBe(true); expect(result?.content[0]).toMatchObject({ type: "text", text: expect.stringContaining("consumed the result window"), }); expect(JSON.stringify(result)).not.toContain(".env"); }); it("shows a TUI-only source-grouped report", async () => { t = await createTestSession({ extensions: [extPath()] }); const extension = t.session.extensionRunner.extensions[0]; const baseContext = t.session.extensionRunner.createCommandContext(); const tuiContext = new Proxy(baseContext, { get(target, property, receiver) { if (property === "mode") return "tui"; return Reflect.get(target, property, receiver); }, }); await extension.commands.get("verboten")?.handler("", tuiContext); const entry = t.session.sessionManager .getEntries() .find( (item: { type: string; customType?: string }) => item.type === "custom" && item.customType === "verboten-report-v1", ); expect(entry).toBeTruthy(); expect(JSON.stringify(entry)).toContain("built-in static"); expect(JSON.stringify(entry)).toContain("built-in resolved"); }); }); describe("Verboten shell judge integration", () => { let t: TestSession | undefined; let root: string | undefined; afterEach(() => { t?.dispose(); if (root) rmSync(root, { recursive: true, force: true }); t = undefined; root = undefined; vi.restoreAllMocks(); }); async function startJudge( responses: ReturnType[], ) { root = mkdtempSync(path.join(tmpdir(), "verboten-judge-")); projectSettings(root, { judgeModel: "judge-test/guard" }); t = await createTestSession({ cwd: root, extensions: [extPath()] }); expect(t.session.extensionRunner.createContext().isProjectTrusted()).toBe( true, ); const faux = fauxProvider({ provider: "judge-test", models: [{ id: "guard", maxTokens: 4_096, reasoning: true }], }); faux.setResponses(responses); t.session.extensionRunner .createContext() .modelRegistry.registerProvider(faux.provider); return faux; } it("blocks a forbidden Bash command through one constrained verdict tool", async () => { const faux = await startJudge([ fauxAssistantMessage( fauxToolCall("record_verdict", { forbiddenOperationProbability: 0.98, reason: "Reads protected contents", }), { stopReason: "toolUse" }, ), ]); const stream = vi.spyOn(faux.provider, "streamSimple"); const blocked = await t?.session.extensionRunner.emitToolCall( toolCall("bash", { command: "cat .env" }) as never, ); expect(blocked).toMatchObject({ block: true }); expect(blocked?.reason).toContain("98%"); expect(stream).toHaveBeenCalledOnce(); const [, context, options] = stream.mock.calls[0] ?? []; expect(context?.tools).toHaveLength(1); expect(context?.tools?.[0]?.name).toBe("record_verdict"); expect(context?.systemPrompt).toContain( "Trusted programs, repository hooks, filters, and credential helpers may consume protected files internally", ); expect(options).toMatchObject({ maxTokens: 1_024, reasoning: "low", cacheRetention: "none", maxRetries: 0, }); expect(JSON.stringify(context?.messages)).toContain("cat .env"); }); it("allows metadata commands and caches successful verdicts", async () => { const faux = await startJudge([ fauxAssistantMessage( fauxToolCall("record_verdict", { forbiddenOperationProbability: 0.05, reason: "Lists metadata only", }), { stopReason: "toolUse" }, ), ]); const stream = vi.spyOn(faux.provider, "streamSimple"); for (let index = 0; index < 2; index++) expect( await t?.session.extensionRunner.emitToolCall( toolCall("bash", { command: "ls -la .env" }) as never, ), ).toBeUndefined(); expect(stream).toHaveBeenCalledOnce(); }); it("retries malformed output in the same provider context", async () => { const faux = await startJudge([ fauxAssistantMessage("I think this is forbidden."), fauxAssistantMessage( fauxToolCall("record_verdict", { forbiddenOperationProbability: 0.9, reason: "Reads protected contents", }), { stopReason: "toolUse" }, ), ]); const stream = vi.spyOn(faux.provider, "streamSimple"); const blocked = await t?.session.extensionRunner.emitToolCall( toolCall("powershell", { command: "Get-Content .env" }) as never, ); expect(blocked).toMatchObject({ block: true }); expect(stream).toHaveBeenCalledTimes(2); const secondContext = stream.mock.calls[1]?.[1]; expect(secondContext?.messages).toHaveLength(3); expect(JSON.stringify(secondContext?.messages)).toContain( "Call record_verdict exactly once", ); }); it("routes the permanent metadata, mutation, and embedded-script corpus", async () => { const corpus = [ { shell: "bash", command: "ls -la .env", forbidden: false }, { shell: "bash", command: "find . -name .env", forbidden: false }, { shell: "bash", command: "stat .env", forbidden: false }, { shell: "bash", command: "test -e .env", forbidden: false }, { shell: "bash", command: "git status --short .env", forbidden: false }, { shell: "bash", command: "rg token . --glob '!.env'", forbidden: false }, { shell: "bash", command: "printf 'Never read .env' > README.md", forbidden: false, }, { shell: "bash", command: "SCRIPT='cat .env'; printf '%s' \"$SCRIPT\"", forbidden: false, }, { shell: "bash", command: "cat <<'EOF' > README.md\\ncat .env\\nEOF", forbidden: false, }, { shell: "powershell", command: "$s = @'\\nGet-Content .env\\n'@; Write-Output $s", forbidden: false, }, { shell: "bash", command: "cat .env", forbidden: true }, { shell: "bash", command: "grep token .env", forbidden: true }, { shell: "bash", command: "git diff -- .env", forbidden: true }, { shell: "bash", command: "sha256sum .env", forbidden: true }, { shell: "bash", command: "cp .env backup", forbidden: true }, { shell: "bash", command: "tar -cf env.tar .env", forbidden: true }, { shell: "bash", command: "source .env", forbidden: true }, { shell: "bash", command: "chmod 600 .env", forbidden: true }, { shell: "bash", command: "rm .env", forbidden: true }, { shell: "bash", command: "python -c \"open('.env').read()\"", forbidden: true, }, { shell: "bash", command: "node -e \"require('fs').readFileSync('.env')\"", forbidden: true, }, { shell: "bash", command: "bash <<'EOF'\\ncat .env\\nEOF", forbidden: true, }, { shell: "powershell", command: "$s = @'\\nGet-Content .env\\n'@; Invoke-Expression $s", forbidden: true, }, { shell: "powershell", command: "Set-Content .env 'replacement'", forbidden: true, }, ] as const; const faux = await startJudge( corpus.map(({ forbidden }) => fauxAssistantMessage( fauxToolCall("record_verdict", { forbiddenOperationProbability: forbidden ? 0.95 : 0.05, reason: forbidden ? "Forbidden content operation" : "Metadata or inert data", }), { stopReason: "toolUse" }, ), ), ); const stream = vi.spyOn(faux.provider, "streamSimple"); for (const item of corpus) { const result = await t?.session.extensionRunner.emitToolCall( toolCall(item.shell, { command: item.command }) as never, ); expect(Boolean(result?.block), item.command).toBe(item.forbidden); } expect(stream).toHaveBeenCalledTimes(corpus.length); }); it("does not call a judge when no regex matches", async () => { const faux = await startJudge([]); const stream = vi.spyOn(faux.provider, "streamSimple"); expect( await t?.session.extensionRunner.emitToolCall( toolCall("bash", { command: "printf safe" }) as never, ), ).toBeUndefined(); expect(stream).not.toHaveBeenCalled(); }); });