pi-auto-reviewer 1.4.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -81,7 +81,7 @@ Works automatically, no configuration required.
81
81
  - Tier 3 handles destructive or unknown commands and pauses with `Reviewing: <command>...` (up to 60s per attempt, one automatic retry).
82
82
  - Allowed: command runs, `Auto-reviewer: ✓ <reason>` (set `notifyOnAllow` to `false` for quiet mode)
83
83
  - Blocked: command refused, `Auto-reviewer: ✗ <reason>`
84
- - Reviewer failed twice: interactive mode prompts you manually; non-interactive mode (`pi -p`, JSON mode) blocks the command.
84
+ - Reviewer failed twice: see *Handling a failed review*. By default (`agent` mode), the command is skipped and the agent continues with guidance. In `block` (with `onReviewFailure: "ask"`) and `manual` mode, interactive sessions ask **Block** / **Allow once**, with Block as the default choice.
85
85
 
86
86
  Each review attempt writes the command and full reviewer output to the OS temporary directory under `pi-reviewer-debug/` (`/tmp/pi-reviewer-debug/` on typical Linux systems). The newest 20 files are kept. Jev failures log the error message rather than provider error bodies.
87
87
 
@@ -108,6 +108,80 @@ Or persistently via `autoReviewer` in `~/.pi/agent/settings.json` (user) or `.pi
108
108
  Provider and model resolve as a pair (env → trusted project → user → pi default); a layer specifying only one of the two is ignored entirely.
109
109
 
110
110
 
111
+ ### Handling a denied command
112
+
113
+ Set `autoReviewer.onDeny` in user or trusted project settings:
114
+
115
+ ```json
116
+ { "autoReviewer": { "onDeny": "block" } }
117
+ ```
118
+
119
+ Or set `PI_REVIEWER_ON_DENY=block` for one launch. The modes are:
120
+
121
+ | Value | After the reviewer rejects a command |
122
+ | --- | --- |
123
+ | `agent` (default) | Return the error so the agent continues with guidance. |
124
+ | `block` | Stop the agent's turn; the command does not run. |
125
+ | `manual` | Ask the operator; Block stops the turn. Without a UI, or on cancellation, keep it blocked and stop the turn. |
126
+
127
+ No denied command executes in `block` or `agent` mode. In `manual` mode,
128
+ only an explicit **Allow once** permits that invocation. **Block** is the
129
+ first choice, so Enter stops the turn. Hard blocks cannot be overridden by
130
+ these settings. A failed review follows *Handling a failed review*.
131
+
132
+ The setting resolves independently of the provider/model pair:
133
+ environment → trusted project → user → `agent`. An invalid value selects
134
+ `agent`. Untrusted project settings are ignored. Use a launch-scoped
135
+ environment variable to limit this choice to a sandbox session.
136
+
137
+ `agent` mode does not grant permission to evade a refusal. The agent may
138
+ gather new evidence or choose a permitted alternative; retrying the denied
139
+ operation requires resolving the concern with evidence or explicit user
140
+ authorization. Do not replace a rejected command with another way of
141
+ performing the same unauthorized operation.
142
+
143
+ In `agent` mode, Pi receives the tool error and decides its next step. In
144
+ `block` and `manual` mode, a stopped command ends the turn. Pi stops the
145
+ turn only when every tool call in that model response asks to stop. If a
146
+ parallel call ran normally, the model gets one more step, sees this error,
147
+ and the next stopped call ends the turn. **Allow once** runs that one
148
+ command and the turn continues.
149
+
150
+ The reviewer emits `pi-auto-reviewer:denial` on `pi.events` only when the
151
+ mode is `agent` and the command stayed stopped. The payload is `sessionId`,
152
+ `toolCallId`, `handling: "agent"`, and `cause`. `cause: "denied"` means the
153
+ reviewer refused the command. `cause: "failed"` means the reviewer did not
154
+ answer; that is not a safety judgment. Earlier versions emitted this event
155
+ for every stopped command and had no `cause`. A continuation extension must
156
+ match both IDs. Manual **Block**, `block` mode, and **Allow once** emit no
157
+ denial event. Hard blocks do not emit recovery metadata.
158
+
159
+ ### Handling a failed review
160
+
161
+ Set `autoReviewer.onReviewFailure` when a review cannot get an answer
162
+ (network error, timeout, or a bad response). It does not apply to a refusal.
163
+
164
+ ```json
165
+ { "autoReviewer": { "onReviewFailure": "ask" } }
166
+ ```
167
+
168
+ Or set `PI_REVIEWER_ON_REVIEW_FAILURE` for one launch. `ask` is the default.
169
+ `follow-onDeny` uses the same stop-or-continue choice as `onDeny`. An invalid
170
+ value selects `ask`. Precedence is environment → trusted project → user →
171
+ `ask`. Untrusted project settings are ignored. The setting only changes
172
+ `block` mode: `manual` always asks, and `agent` never does.
173
+
174
+ | `onDeny` | Reviewer refuses | Reviewer fails, `ask` (default) | Reviewer fails, `follow-onDeny` |
175
+ | --- | --- | --- | --- |
176
+ | `agent` (default) | Agent continues, with refusal guidance. Event `cause: "denied"`. | Agent continues, with failure guidance. Event `cause: "failed"`. | Same as `ask`. |
177
+ | `block` | Turn stops. | Interactive session asks **Block** / **Allow once**. Block stops the turn. | Turn stops. |
178
+ | `manual` | Interactive session asks. Block stops the turn. | Interactive session asks. Block stops the turn. | Interactive session asks. Block stops the turn. |
179
+
180
+ Without a UI, `block` and `manual` stop the turn, and `agent` lets the agent
181
+ continue. A cancelled or closed dialog counts as Block. If the turn is already
182
+ aborted, no dialog is shown and the command stays stopped. **Allow once** runs
183
+ that one command.
184
+
111
185
  ### Allow notifications
112
186
 
113
187
  Allow notifications are enabled by default. To opt into quiet mode, set
@@ -197,7 +271,7 @@ The presets use TypeSafe’s [`/v1/systemone`](https://docs.typesafe.ai/api) and
197
271
 
198
272
  All reviewer options follow the provider/model pair’s precedence: env → trusted project → user. Include `backend` in that same layer. A complete environment pair replaces settings-file options; incomplete pairs and untrusted project settings are ignored. Omit `backend` or set it to `"pi"` to use the LLM reviewer; unknown backend names fail review.
199
273
 
200
- Tiers 1 and 2 are unchanged. Jev validates the choice, confidence, and probability distribution; malformed, inconsistent, or tied answers fail review. There is no additional confidence threshold. The existing 60-second deadline, one retry, and manual-prompt/noninteractive-block fallback apply.
274
+ Tiers 1 and 2 are unchanged. Jev validates the choice, confidence, and probability distribution; malformed, inconsistent, or tied answers fail review. There is no additional confidence threshold. The existing 60-second deadline and one retry apply. A failed review then follows *Handling a failed review*.
201
275
 
202
276
  ## Customizing rules
203
277
 
package/auto-reviewer.ts CHANGED
@@ -85,30 +85,78 @@ const DEBUG_KEEP = 20;
85
85
  // settings. Without this, an untrusted repository could influence which
86
86
  // model performs the security review.
87
87
 
88
+ export type DenialHandling = "block" | "manual" | "agent";
89
+ export type ReviewFailureHandling = "ask" | "follow-onDeny";
90
+
91
+ const REFUSAL_GUIDANCE = "\nThe command was not executed. Inspect the rejection and choose a permitted next step. Retry this operation only if new evidence or explicit user authorization resolves the concern. A safer alternative must not disguise the same denied operation. Do not blindly repeat the command.";
92
+ const FAILURE_GUIDANCE = "\nThe reviewer could not be reached, so the command was not reviewed or executed. Do not treat this as a safety judgment. Continue with work that does not need this command, or ask the user how to proceed. Do not rephrase the command to get around review.";
93
+
88
94
  interface ReviewerOverrides extends JevConfig {
89
95
  backend?: string;
90
96
  }
91
97
 
92
98
  // Read the extension-specific reviewer overrides from one settings file.
93
99
  // Malformed JSON or a missing autoReviewer object must never break review.
94
- function readReviewerSettingsFile(filePath: string): ReviewerOverrides {
100
+ function readAutoReviewerSettings(filePath: string): Record<string, unknown> | undefined {
95
101
  try {
96
- if (!fs.existsSync(filePath)) return {};
102
+ if (!fs.existsSync(filePath)) return undefined;
97
103
  const parsed: unknown = JSON.parse(fs.readFileSync(filePath, "utf8"));
98
- if (!parsed || typeof parsed !== "object") return {};
104
+ if (!parsed || typeof parsed !== "object") return undefined;
99
105
  const value = (parsed as Record<string, unknown>).autoReviewer;
100
- if (!value || typeof value !== "object") return {};
101
- const config = value as Record<string, unknown>;
102
- return {
103
- ...readBackendSettings(config),
104
- provider: typeof config.provider === "string" ? config.provider.trim() || undefined : undefined,
105
- model: typeof config.model === "string" ? config.model.trim() || undefined : undefined,
106
- };
106
+ return value && typeof value === "object" ? value as Record<string, unknown> : undefined;
107
107
  } catch {
108
- return {};
108
+ return undefined;
109
109
  }
110
110
  }
111
111
 
112
+ function readReviewerSettingsFile(filePath: string): ReviewerOverrides {
113
+ const config = readAutoReviewerSettings(filePath);
114
+ if (!config) return {};
115
+ return {
116
+ ...readBackendSettings(config),
117
+ provider: typeof config.provider === "string" ? config.provider.trim() || undefined : undefined,
118
+ model: typeof config.model === "string" ? config.model.trim() || undefined : undefined,
119
+ };
120
+ }
121
+
122
+ function resolveAutoReviewerChoice<T>(
123
+ cwd: string,
124
+ isProjectTrusted: boolean,
125
+ env: NodeJS.ProcessEnv,
126
+ homeDir: string,
127
+ envName: string,
128
+ settingsKey: string,
129
+ parse: (value: unknown) => T,
130
+ ): T {
131
+ if (env[envName] !== undefined) return parse(env[envName]);
132
+ if (isProjectTrusted) {
133
+ const project = readAutoReviewerSettings(path.join(cwd, CONFIG_DIR_NAME, "settings.json"));
134
+ if (project && Object.hasOwn(project, settingsKey)) return parse(project[settingsKey]);
135
+ }
136
+ const user = readAutoReviewerSettings(path.join(homeDir, ".pi", "agent", "settings.json"));
137
+ return parse(user?.[settingsKey]);
138
+ }
139
+
140
+ export function resolveDenialHandling(
141
+ cwd: string,
142
+ isProjectTrusted: boolean,
143
+ env: NodeJS.ProcessEnv = process.env,
144
+ homeDir: string = os.homedir(),
145
+ ): DenialHandling {
146
+ return resolveAutoReviewerChoice(cwd, isProjectTrusted, env, homeDir, "PI_REVIEWER_ON_DENY", "onDeny",
147
+ value => value === "block" || value === "manual" ? value : "agent");
148
+ }
149
+
150
+ export function resolveReviewFailureHandling(
151
+ cwd: string,
152
+ isProjectTrusted: boolean,
153
+ env: NodeJS.ProcessEnv = process.env,
154
+ homeDir: string = os.homedir(),
155
+ ): ReviewFailureHandling {
156
+ return resolveAutoReviewerChoice(cwd, isProjectTrusted, env, homeDir, "PI_REVIEWER_ON_REVIEW_FAILURE", "onReviewFailure",
157
+ value => value === "follow-onDeny" ? "follow-onDeny" : "ask");
158
+ }
159
+
112
160
  // Keep transport configuration in the same precedence layer as provider/model.
113
161
  function readBackendSettings(config: Record<string, unknown>): Pick<ReviewerOverrides, "backend" | "endpoint" | "apiKeyEnv"> {
114
162
  const settings: Pick<ReviewerOverrides, "backend" | "endpoint" | "apiKeyEnv"> = {};
@@ -1600,6 +1648,48 @@ export default function (pi: ExtensionAPI) {
1600
1648
  if (costs.summary().pending === 0) billingTrackers.delete(costs);
1601
1649
  };
1602
1650
 
1651
+ const finishStopped = async (input: {
1652
+ cause: "denied" | "failed";
1653
+ handling: DenialHandling;
1654
+ title: string;
1655
+ blockReason: string;
1656
+ agentFeedback: string;
1657
+ askOperator: boolean;
1658
+ }): Promise<{ block: true; reason: string; terminate?: true } | undefined> => {
1659
+ if (input.askOperator && ctx.hasUI && !ctx.signal?.aborted) {
1660
+ let allowedOnce = false;
1661
+ try {
1662
+ allowedOnce = await ctx.ui.select(
1663
+ `${input.title}\n\nCommand: ${command}\n\nAllow this command once?`,
1664
+ ["Block", "Allow once"],
1665
+ ) === "Allow once";
1666
+ } catch {
1667
+ // A cancelled or closed dialog counts as Block.
1668
+ }
1669
+ if (allowedOnce && !ctx.signal?.aborted) {
1670
+ const after = input.cause === "denied" ? "denial" : "a failed review";
1671
+ showResult(`Auto-reviewer: operator allowed this command once after ${after}`, "info");
1672
+ return undefined;
1673
+ }
1674
+ }
1675
+ if (input.handling === "agent") {
1676
+ try {
1677
+ pi.events.emit("pi-auto-reviewer:denial", {
1678
+ sessionId: parentSessionId,
1679
+ toolCallId: event.toolCallId,
1680
+ handling: "agent",
1681
+ cause: input.cause,
1682
+ });
1683
+ } catch {
1684
+ // Delivery failure must not reopen review or a dialog.
1685
+ }
1686
+ }
1687
+ const reason = input.blockReason + (input.handling === "agent" ? input.agentFeedback : "");
1688
+ if (input.handling === "agent") return { block: true, reason };
1689
+ return { block: true, reason, terminate: true };
1690
+ };
1691
+
1692
+ let denied: { reason: string } | undefined;
1603
1693
  for (let attempt = 1; attempt <= MAX_REVIEW_ATTEMPTS; attempt++) {
1604
1694
  try {
1605
1695
  if (ctx.hasUI) {
@@ -1624,36 +1714,54 @@ export default function (pi: ExtensionAPI) {
1624
1714
  if (decision.allowed) {
1625
1715
  showResult(`Auto-reviewer: ✓ ${decision.reason}`, "info");
1626
1716
  return undefined; // allow through
1627
- } else {
1628
- showResult(`Auto-reviewer: ✗ ${decision.reason}`, "warning");
1629
- return { block: true, reason: `Auto-reviewer blocked: ${decision.reason}` };
1630
1717
  }
1718
+ // A rejection is final. Finish it outside this try so a
1719
+ // notification or event error cannot start another review.
1720
+ denied = decision;
1721
+ break;
1631
1722
  } catch (err) {
1632
1723
  lastError = err instanceof Error ? err : new Error(String(err));
1724
+ if (ctx.signal?.aborted) break;
1633
1725
  if (ctx.hasUI && attempt < MAX_REVIEW_ATTEMPTS) {
1634
1726
  ctx.ui.notify(`Auto-review attempt ${attempt} failed: ${lastError.message.split("\n")[0].slice(0, 150)}`, "warning");
1635
1727
  }
1636
1728
  }
1637
1729
  }
1638
1730
 
1639
- if (ctx.hasUI) ctx.ui.setStatus("auto-reviewer", undefined);
1731
+ const handling = resolveDenialHandling(ctx.cwd, projectTrusted);
1732
+ if (denied) {
1733
+ showResult(`Auto-reviewer: ✗ ${denied.reason}`, "warning");
1734
+ return finishStopped({
1735
+ cause: "denied",
1736
+ handling,
1737
+ title: `Auto-reviewer denied: ${denied.reason}`,
1738
+ blockReason: `Auto-reviewer blocked: ${denied.reason}`,
1739
+ agentFeedback: REFUSAL_GUIDANCE,
1740
+ askOperator: handling === "manual",
1741
+ });
1742
+ }
1640
1743
 
1641
- showResult(`Auto-reviewer failed: ${lastError!.message.split("\n")[0].slice(0, 150)}`, "warning");
1744
+ if (ctx.hasUI) ctx.ui.setStatus("auto-reviewer", undefined);
1642
1745
 
1643
- if (ctx.hasUI) {
1644
- // All attempts failed — fall back to manual UI
1645
- const msg = lastError!.message;
1646
- const choice = await ctx.ui.select(
1647
- `⚠️ Auto-review failed (${MAX_REVIEW_ATTEMPTS} attempts): ${msg}\n\nCommand: ${command}\n\nAllow?`,
1648
- ["Yes", "No"],
1649
- );
1650
- if (choice !== "Yes") {
1651
- return { block: true, reason: "Auto-review failed and user declined" };
1652
- }
1653
- return undefined;
1746
+ // Esc aborts the review. That is a cancellation, not a failed review,
1747
+ // so the agent must not be told to continue the cancelled work.
1748
+ if (ctx.signal?.aborted) {
1749
+ reviewCompleted = true;
1750
+ if (costs.summary().pending === 0) billingTrackers.delete(costs);
1751
+ return { block: true, reason: "Auto-review cancelled. The command was not executed." };
1654
1752
  }
1655
1753
 
1656
- return { block: true, reason: `Auto-review failed (${MAX_REVIEW_ATTEMPTS} attempts): ${lastError!.message}` };
1754
+ const errorLine = lastError!.message.split("\n")[0].slice(0, 150);
1755
+ showResult(`Auto-reviewer failed: ${errorLine}`, "warning");
1756
+ const failureHandling = resolveReviewFailureHandling(ctx.cwd, projectTrusted);
1757
+ return finishStopped({
1758
+ cause: "failed",
1759
+ handling,
1760
+ title: `Auto-review failed (${MAX_REVIEW_ATTEMPTS} attempts): ${errorLine}`,
1761
+ blockReason: `Auto-review failed (${MAX_REVIEW_ATTEMPTS} attempts): ${errorLine}. The command was not executed.`,
1762
+ agentFeedback: FAILURE_GUIDANCE,
1763
+ askOperator: handling === "manual" || (handling === "block" && failureHandling === "ask"),
1764
+ });
1657
1765
  });
1658
1766
 
1659
1767
  // Clean up status on session end
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-auto-reviewer",
3
- "version": "1.4.0",
3
+ "version": "2.0.0",
4
4
  "description": "Auto-review bash commands before your pi agent executes them — akin to Codex Auto-review and Claude Code auto mode.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -0,0 +1,303 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import * as fs from "node:fs";
4
+ import * as os from "node:os";
5
+ import * as path from "node:path";
6
+ import * as reviewer from "../auto-reviewer.ts";
7
+
8
+ function fixture(t: any): string {
9
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "reviewer-denial-"));
10
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
11
+ return dir;
12
+ }
13
+
14
+ function configuredReview(t: any, mode: string, options: { hasUI?: boolean; choice?: string; cancel?: boolean; aborted?: boolean; preAborted?: boolean; takeFirstChoice?: boolean; denialEmitThrows?: boolean; allowOnRetry?: boolean; failReview?: boolean; failureMode?: string } = {}) {
15
+ const cwd = fixture(t);
16
+ const keys = ["PI_REVIEWER_PROVIDER", "PI_REVIEWER_MODEL", "PI_REVIEWER_BACKEND", "PI_REVIEWER_ENDPOINT", "PI_REVIEWER_API_KEY_ENV", "PI_REVIEWER_ON_DENY", "PI_REVIEWER_ON_REVIEW_FAILURE", "TYPESAFE_API_KEY"];
17
+ const original = Object.fromEntries(keys.map(key => [key, process.env[key]]));
18
+ const fetch = globalThis.fetch;
19
+ for (const key of keys) delete process.env[key];
20
+ Object.assign(process.env, { PI_REVIEWER_PROVIDER: "typesafe", PI_REVIEWER_MODEL: "jev-latest", PI_REVIEWER_BACKEND: "jev", PI_REVIEWER_ON_DENY: mode, TYPESAFE_API_KEY: "test-key" });
21
+ if (options.failureMode !== undefined) process.env.PI_REVIEWER_ON_REVIEW_FAILURE = options.failureMode;
22
+ t.after(() => {
23
+ globalThis.fetch = fetch;
24
+ for (const key of keys) {
25
+ if (original[key] === undefined) delete process.env[key];
26
+ else process.env[key] = original[key];
27
+ }
28
+ });
29
+ let requests = 0;
30
+ const prompts: any[] = [];
31
+ const events: any[] = [];
32
+ const notifications: string[] = [];
33
+ const handlers = new Map<string, any>();
34
+ globalThis.fetch = async (input: any, init?: any) => {
35
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input?.url;
36
+ if (typeof url === "string" && /^https?:\/\/(127\.0\.0\.1|localhost)(:|\/|$)/.test(url)) return fetch(input, init);
37
+ requests++;
38
+ if (options.failReview) return new Response("no", { status: 500 });
39
+ const choice = options.allowOnRetry && requests > 1 ? "allow" : "block";
40
+ const allow = choice === "allow";
41
+ return Response.json({ answers: { command_review: {
42
+ type: "choice", choice, confidence: 0.9,
43
+ probabilities: allow ? { allow: 0.9, block: 0.1 } : { allow: 0.1, block: 0.9 },
44
+ } } });
45
+ };
46
+ reviewer.default({
47
+ on: (name: string, handler: any) => handlers.set(name, handler),
48
+ appendEntry() {}, events: { emit: (name: string, data: any) => {
49
+ events.push({ name, data });
50
+ if (options.denialEmitThrows && name === "pi-auto-reviewer:denial") throw new Error("denial delivery failed");
51
+ } },
52
+ } as any);
53
+ const controller = new AbortController();
54
+ if (options.preAborted) controller.abort();
55
+ const ctx: any = {
56
+ signal: controller.signal,
57
+ cwd, hasUI: options.hasUI ?? false, isProjectTrusted: () => false,
58
+ sessionManager: { getSessionId: () => "denial-session", appendUsage() {}, getBranch: () => [] },
59
+ modelRegistry: { getApiKeyForProvider: async () => "test-key" },
60
+ ui: { setStatus() {}, notify(message: string) { notifications.push(String(message)); }, select: async (title: string, choices: string[]) => {
61
+ prompts.push({ title, choices });
62
+ if (options.aborted) controller.abort();
63
+ if (options.cancel) throw new Error("dialog cancelled");
64
+ if (options.takeFirstChoice) return choices[0];
65
+ return options.choice;
66
+ } },
67
+ };
68
+ return { events, prompts, notifications,
69
+ get requests() { return requests; },
70
+ review: (command = "git reset --hard HEAD^", id = "denied-call") => handlers.get("tool_call")({ toolName: "bash", toolCallId: id, input: { command } }, ctx),
71
+ };
72
+ }
73
+
74
+ test("agent mode returns a rejection for recovery without executing or manually allowing it", async t => {
75
+ const h = configuredReview(t, "agent", { hasUI: true, choice: "Allow once" });
76
+ const result = await h.review();
77
+ assert.equal(result.block, true);
78
+ assert.match(result.reason, /not executed/i);
79
+ assert.match(result.reason, /new evidence|safer/i);
80
+ assert.equal(h.prompts.length, 0);
81
+ assert.equal(h.requests, 1);
82
+ assert.equal(result.terminate, undefined);
83
+ assert.deepEqual(h.events.filter(e => e.name === "pi-auto-reviewer:denial").map(e => e.data), [{
84
+ sessionId: "denial-session", toolCallId: "denied-call", handling: "agent", cause: "denied",
85
+ }]);
86
+ });
87
+
88
+ test("manual mode allows exactly the displayed command only after explicit user confirmation", async t => {
89
+ const h = configuredReview(t, "manual", { hasUI: true, choice: "Allow once" });
90
+ assert.equal(await h.review(), undefined);
91
+ assert.equal(h.prompts.length, 1);
92
+ assert.match(h.prompts[0].title, /git reset --hard HEAD\^/);
93
+ assert.deepEqual(h.prompts[0].choices, ["Block", "Allow once"]);
94
+ assert.equal(h.events.filter(e => e.name === "pi-auto-reviewer:denial").length, 0);
95
+ await h.review("git reset --hard HEAD", "another-call");
96
+ assert.equal(h.prompts.length, 2);
97
+ });
98
+
99
+ test("manual decline stays blocked and emits no denial event", async t => {
100
+ const h = configuredReview(t, "manual", { hasUI: true, choice: "Block" });
101
+ const result = await h.review();
102
+ assert.equal(result.block, true);
103
+ assert.equal(result.terminate, true);
104
+ assert.equal(h.requests, 1);
105
+ assert.equal(h.events.filter(e => e.name === "pi-auto-reviewer:denial").length, 0);
106
+ });
107
+
108
+ test("manual mode without a UI fails closed", async t => {
109
+ const h = configuredReview(t, "manual");
110
+ const result = await h.review();
111
+ assert.equal(result.block, true);
112
+ assert.equal(result.terminate, true);
113
+ assert.equal(h.prompts.length, 0);
114
+ });
115
+
116
+ test("cancelled manual review blocks without rerunning the model review", async t => {
117
+ const h = configuredReview(t, "manual", { hasUI: true, cancel: true });
118
+ const result = await h.review();
119
+ assert.equal(result.block, true);
120
+ assert.equal(result.terminate, true);
121
+ assert.equal(h.requests, 1);
122
+ assert.equal(h.prompts.length, 1);
123
+ });
124
+
125
+ test("manual approval after cancellation cannot allow the command", async t => {
126
+ const h = configuredReview(t, "manual", { hasUI: true, choice: "Allow once", aborted: true });
127
+ const result = await h.review();
128
+ assert.equal(result.block, true);
129
+ assert.equal(result.terminate, true);
130
+ assert.equal(h.requests, 1);
131
+ });
132
+
133
+ test("hard blocks cannot be overridden by manual mode", async t => {
134
+ const h = configuredReview(t, "manual", { hasUI: true, choice: "Allow once" });
135
+ const result = await h.review("sudo shutdown");
136
+ assert.equal(result.block, true);
137
+ assert.match(result.reason, /Auto-blocked/);
138
+ assert.equal(h.requests, 0);
139
+ assert.equal(h.prompts.length, 0);
140
+ });
141
+
142
+ test("a denial delivery failure stays blocked and does not review again", async t => {
143
+ const h = configuredReview(t, "agent", { hasUI: true, denialEmitThrows: true, allowOnRetry: true });
144
+ const result = await h.review();
145
+ assert.equal(result.block, true);
146
+ assert.equal(result.terminate, undefined);
147
+ assert.match(result.reason, /^Auto-reviewer blocked:/);
148
+ assert.equal(h.requests, 1);
149
+ assert.equal(h.prompts.length, 0);
150
+ });
151
+
152
+ test("block mode preserves the existing denial behavior", async t => {
153
+ const h = configuredReview(t, "block", { hasUI: true, choice: "Allow once" });
154
+ const result = await h.review();
155
+ assert.equal(result.block, true);
156
+ assert.equal(result.terminate, true);
157
+ assert.match(result.reason, /^Auto-reviewer blocked:/);
158
+ assert.equal(h.prompts.length, 0);
159
+ assert.equal(h.events.filter(e => e.name === "pi-auto-reviewer:denial").length, 0);
160
+ });
161
+
162
+ test("denial policy resolves independently of provider settings and honors project trust", t => {
163
+ const cwd = fixture(t), home = fixture(t);
164
+ const write = (file: string, value: unknown) => {
165
+ fs.mkdirSync(path.dirname(file), { recursive: true });
166
+ fs.writeFileSync(file, JSON.stringify({ autoReviewer: value }));
167
+ };
168
+ const resolve = (reviewer as any).resolveDenialHandling;
169
+ assert.equal(typeof resolve, "function");
170
+ assert.equal(resolve(cwd, true, {}, home), "agent");
171
+ write(path.join(home, ".pi/agent/settings.json"), { onDeny: "manual" });
172
+ write(path.join(cwd, ".pi/settings.json"), { onDeny: "agent" });
173
+ assert.equal(resolve(cwd, false, {}, home), "manual");
174
+ assert.equal(resolve(cwd, true, {}, home), "agent");
175
+ assert.equal(resolve(cwd, true, { PI_REVIEWER_ON_DENY: "block" }, home), "block");
176
+ assert.equal(resolve(cwd, true, { PI_REVIEWER_ON_DENY: "typo" }, home), "agent");
177
+ write(path.join(cwd, ".pi/settings.json"), { onDeny: "typo" });
178
+ assert.equal(resolve(cwd, true, {}, home), "agent");
179
+ });
180
+
181
+ test("a failed review in block mode asks Block first and stopping ends the turn", async t => {
182
+ const h = configuredReview(t, "block", { hasUI: true, takeFirstChoice: true, failReview: true });
183
+ const result = await h.review();
184
+ assert.deepEqual(h.prompts.map(prompt => prompt.choices), [["Block", "Allow once"]]);
185
+ assert.match(h.prompts[0].title, /Auto-review failed \(2 attempts\)/);
186
+ assert.equal(result.block, true);
187
+ assert.equal(result.terminate, true);
188
+ assert.match(result.reason, /^Auto-review failed \(2 attempts\):/);
189
+ assert.match(result.reason, /not executed/i);
190
+ assert.equal(h.events.filter(e => e.name === "pi-auto-reviewer:denial").length, 0);
191
+ assert.equal(h.requests, 2);
192
+ });
193
+
194
+ test("a failed review in block mode runs the command only after Allow once", async t => {
195
+ const h = configuredReview(t, "block", { hasUI: true, choice: "Allow once", failReview: true });
196
+ assert.equal(await h.review(), undefined);
197
+ assert.equal(h.events.filter(e => e.name === "pi-auto-reviewer:denial").length, 0);
198
+ });
199
+
200
+ test("a failed review in agent mode skips the dialog and tells the agent to continue", async t => {
201
+ const h = configuredReview(t, "agent", { hasUI: true, choice: "Allow once", failReview: true });
202
+ const result = await h.review();
203
+ assert.equal(h.prompts.length, 0);
204
+ assert.equal(result.block, true);
205
+ assert.equal(result.terminate, undefined);
206
+ assert.match(result.reason, /could not be reached/i);
207
+ assert.match(result.reason, /safety judgment/i);
208
+ assert.deepEqual(h.events.filter(e => e.name === "pi-auto-reviewer:denial").map(e => e.data), [{
209
+ sessionId: "denial-session", toolCallId: "denied-call", handling: "agent", cause: "failed",
210
+ }]);
211
+ });
212
+
213
+ test("a failed review in manual mode uses the same Block and Allow once choices", async t => {
214
+ const h = configuredReview(t, "manual", { hasUI: true, choice: "Allow once", failReview: true });
215
+ assert.equal(await h.review(), undefined);
216
+ assert.deepEqual(h.prompts.map(prompt => prompt.choices), [["Block", "Allow once"]]);
217
+ assert.equal(h.events.filter(e => e.name === "pi-auto-reviewer:denial").length, 0);
218
+ });
219
+
220
+ test("a failed review without a UI stays stopped and only block and manual end the turn", async t => {
221
+ for (const mode of ["block", "manual", "agent"]) {
222
+ const h = configuredReview(t, mode, { failReview: true });
223
+ const result = await h.review();
224
+ assert.equal(result.block, true, mode);
225
+ assert.equal(h.prompts.length, 0, mode);
226
+ assert.equal(result.terminate, mode === "agent" ? undefined : true, mode);
227
+ assert.equal(h.events.filter(e => e.name === "pi-auto-reviewer:denial").length, mode === "agent" ? 1 : 0, mode);
228
+ }
229
+ });
230
+
231
+ test("an already aborted review is a cancellation, not a failed review", async t => {
232
+ for (const mode of ["manual", "block"]) {
233
+ const h = configuredReview(t, mode, { hasUI: true, choice: "Allow once", failReview: true, preAborted: true });
234
+ const result = await h.review();
235
+ assert.equal(result.block, true, mode);
236
+ assert.equal(result.terminate, undefined, mode);
237
+ assert.match(result.reason, /cancelled/i, mode);
238
+ assert.doesNotMatch(result.reason, /could not be reached/i, mode);
239
+ assert.equal(h.prompts.length, 0, mode);
240
+ assert.equal(h.requests, 0, mode);
241
+ assert.equal(h.notifications.some(message => message.includes("attempt")), false, mode);
242
+ assert.equal(h.events.filter(e => e.name === "pi-auto-reviewer:denial").length, 0, mode);
243
+ }
244
+ });
245
+
246
+ test("an already aborted review in agent mode does not continue the cancelled work", async t => {
247
+ const h = configuredReview(t, "agent", { hasUI: true, preAborted: true });
248
+ const result = await h.review();
249
+ assert.equal(result.block, true);
250
+ assert.equal(result.terminate, undefined);
251
+ assert.match(result.reason, /cancelled/i);
252
+ assert.doesNotMatch(result.reason, /could not be reached/i);
253
+ assert.equal(h.prompts.length, 0);
254
+ assert.equal(h.requests, 0);
255
+ assert.equal(h.notifications.some(message => message.includes("attempt")), false);
256
+ assert.equal(h.events.filter(e => e.name === "pi-auto-reviewer:denial").length, 0);
257
+ });
258
+
259
+ test("a cancelled failure dialog stays blocked and ends the turn", async t => {
260
+ const h = configuredReview(t, "manual", { hasUI: true, cancel: true, failReview: true });
261
+ const result = await h.review();
262
+ assert.equal(result.block, true);
263
+ assert.equal(result.terminate, true);
264
+ assert.equal(h.prompts.length, 1);
265
+ });
266
+
267
+ test("follow-onDeny skips the failure dialog in block mode and still asks in manual mode", async t => {
268
+ const blocked = configuredReview(t, "block", { hasUI: true, choice: "Allow once", failReview: true, failureMode: "follow-onDeny" });
269
+ const blockedResult = await blocked.review();
270
+ assert.equal(blocked.prompts.length, 0);
271
+ assert.equal(blockedResult.block, true);
272
+ assert.equal(blockedResult.terminate, true);
273
+ assert.equal(blocked.events.filter(e => e.name === "pi-auto-reviewer:denial").length, 0);
274
+
275
+ const manual = configuredReview(t, "manual", { hasUI: true, choice: "Allow once", failReview: true, failureMode: "follow-onDeny" });
276
+ assert.equal(await manual.review(), undefined);
277
+ assert.deepEqual(manual.prompts.map(prompt => prompt.choices), [["Block", "Allow once"]]);
278
+
279
+ const agent = configuredReview(t, "agent", { hasUI: true, choice: "Allow once", failReview: true, failureMode: "ask" });
280
+ const agentResult = await agent.review();
281
+ assert.equal(agent.prompts.length, 0);
282
+ assert.equal(agentResult.block, true);
283
+ assert.equal(agentResult.terminate, undefined);
284
+ });
285
+
286
+ test("review failure policy resolves independently of denial policy and honors project trust", t => {
287
+ const cwd = fixture(t), home = fixture(t);
288
+ const write = (file: string, value: unknown) => {
289
+ fs.mkdirSync(path.dirname(file), { recursive: true });
290
+ fs.writeFileSync(file, JSON.stringify({ autoReviewer: value }));
291
+ };
292
+ const resolve = (reviewer as any).resolveReviewFailureHandling;
293
+ assert.equal(typeof resolve, "function");
294
+ assert.equal(resolve(cwd, true, {}, home), "ask");
295
+ write(path.join(home, ".pi/agent/settings.json"), { onReviewFailure: "follow-onDeny", onDeny: "manual" });
296
+ write(path.join(cwd, ".pi/settings.json"), { onReviewFailure: "ask" });
297
+ assert.equal(resolve(cwd, false, {}, home), "follow-onDeny");
298
+ assert.equal(resolve(cwd, true, {}, home), "ask");
299
+ assert.equal(resolve(cwd, true, { PI_REVIEWER_ON_REVIEW_FAILURE: "follow-onDeny", PI_REVIEWER_ON_DENY: "agent" }, home), "follow-onDeny");
300
+ assert.equal(resolve(cwd, true, { PI_REVIEWER_ON_REVIEW_FAILURE: "typo" }, home), "ask");
301
+ write(path.join(cwd, ".pi/settings.json"), { onReviewFailure: "typo" });
302
+ assert.equal(resolve(cwd, true, {}, home), "ask");
303
+ });
@@ -54,7 +54,7 @@ function install(t: any, cwd: string, getProviderApiKey = async (_provider: stri
54
54
  }
55
55
  });
56
56
  let handler: any;
57
- extension({ on(name: string, callback: any) { if (name === "tool_call") handler = callback; } } as any);
57
+ extension({ events: { emit() {} }, on(name: string, callback: any) { if (name === "tool_call") handler = callback; } } as any);
58
58
  return command => handler({ toolName: "bash", input: { command }, toolCallId: "pending" }, {
59
59
  cwd, hasUI: false, isProjectTrusted: () => false,
60
60
  modelRegistry: { getApiKeyForProvider: getProviderApiKey },