@hank-warren/pi-auto-permissions 0.12.1 → 0.14.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/index.ts CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  } from "./loop-revise-budget.js";
11
11
  import * as PiCodingAgent from "@earendil-works/pi-coding-agent";
12
12
  import {
13
+ getAgentDir,
13
14
  getSelectListTheme,
14
15
  getSettingsListTheme,
15
16
  type ExtensionAPI,
@@ -29,22 +30,52 @@ import { patchAutoPermissionsConfig } from "./config-writer.js";
29
30
  import {
30
31
  applySettingChange,
31
32
  buildSettingItems,
33
+ createDenialsSubmenu,
32
34
  createModelSubmenu,
35
+ createStandingApprovalsSubmenu,
33
36
  createTimeoutSubmenu,
37
+ type DenialsSubmenuHost,
38
+ type DenialSummary,
39
+ type StandingApprovalsSubmenuHost,
40
+ type StandingApprovalSummary,
34
41
  type MenuModel,
35
42
  type ReviewerSettings,
36
43
  type SettingChange,
37
44
  type SubmenuHost,
38
45
  } from "./settings-menu.js";
46
+ import {
47
+ appendDenialRecord,
48
+ buildDenialRecord,
49
+ readRecentDenials,
50
+ type DenialSource,
51
+ type DenialVerdict,
52
+ } from "./denial-log.js";
53
+ import {
54
+ buildSetupDraftRequest,
55
+ parseSetupDraft,
56
+ scanProject,
57
+ scanRecentSessionCommands,
58
+ setupEntrySources,
59
+ SETUP_DRAFT_SYSTEM_PROMPT,
60
+ SETUP_SESSION_SCAN_LIMIT,
61
+ } from "./setup-scan.js";
39
62
  import {
40
63
  appendPromptEvaluation,
41
64
  classifyPromptChoice,
42
65
  expectedDecisionForChoice,
43
66
  permissionPromptOptions,
67
+ shouldOfferStandingApproval,
44
68
  type PromptEvaluationUserChoice,
45
69
  } from "./evaluation-log.js";
46
- import { findGates, type Gate } from "./gates.js";
70
+ import { ALL_SHELL_GATE, findGates, type Gate } from "./gates.js";
47
71
  import { appendUsageRecord, buildUsageLogRecord } from "./usage-log.js";
72
+ import {
73
+ grantStandingApproval,
74
+ readStandingApprovals,
75
+ revokeStandingApproval,
76
+ STANDING_APPROVAL_LIMIT,
77
+ standingApprovalsToPermissionOverrides,
78
+ } from "./standing-overrides.js";
48
79
  import {
49
80
  reviewFrameIntervalMs,
50
81
  reviewStatusFrame,
@@ -54,18 +85,26 @@ import {
54
85
  } from "./widget-status.js";
55
86
  import {
56
87
  applyFullRebuildEviction,
88
+ buildGuardianPolicySection,
57
89
  buildReviewEnvelope,
58
90
  collectReviewEvidence,
59
91
  LOOP_CONTEXT_SYSTEM_PROMPT,
60
92
  INJECTED_USER_MESSAGE_SYSTEM_PROMPT,
61
93
  OVERRIDE_FEEDBACK_SYSTEM_PROMPT,
62
94
  parsePermissionVerdict,
95
+ parsePrefilterVerdict,
96
+ PREFILTER_INSTRUCTION,
63
97
  SUBAGENT_CONTEXT_SYSTEM_PROMPT,
64
98
  type EvidenceCaps,
65
99
  type PermissionVerdict,
66
100
  type ReviewEvidenceRecord,
67
101
  } from "./review.js";
68
102
  import { mergeOverrideEvidence, type PermissionOverride } from "./override-evidence.js";
103
+ import {
104
+ buildSessionEnvironmentSection,
105
+ captureSessionEnvironment,
106
+ type SessionEnvironmentSnapshot,
107
+ } from "./session-environment.js";
69
108
  import { OptionSelector } from "@hank-warren/pi-permission-selector/selector.ts";
70
109
  import { PulsingApprovalIndicator } from "./approval-pulse.js";
71
110
 
@@ -243,6 +282,10 @@ function loadTrustedGroups(cwd: string): Set<string> {
243
282
  return groups;
244
283
  }
245
284
 
285
+ function denyReason(gate: Gate): string {
286
+ return `Blocked by policy: ${gate.label}\n\n${gate.message ?? "This operation is denied by rule."}\n\nThis is a deny rule: it cannot be overridden with request_override, trusted groups, or user approval. Choose a different approach.`;
287
+ }
288
+
246
289
  function conventionReason(gate: Gate, command: string): string {
247
290
  let reason = `Convention violation: ${gate.label}\n\n${gate.message ?? "Use the configured project tooling."}`;
248
291
  const suggestion = gate.suggest?.(command);
@@ -277,6 +320,131 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
277
320
  let activeReviewerSessionId: string | undefined;
278
321
  const permissionOverrides: PermissionOverride[] = [];
279
322
  let overrideSeq = 0;
323
+ let standingApprovalCapNotified = false;
324
+ /** Captured once per session; see session-environment.ts for why once. */
325
+ let sessionEnvironment: SessionEnvironmentSnapshot | undefined;
326
+
327
+ /**
328
+ * Overrides persist as custom session entries the way the loop budget does,
329
+ * so a resumed session keeps the user's prompt decisions instead of
330
+ * forgetting every allow and standing block constraint.
331
+ */
332
+ const OVERRIDES_ENTRY_TYPE = "auto-permissions-overrides";
333
+
334
+ function persistOverrides(): void {
335
+ try {
336
+ pi.appendEntry(OVERRIDES_ENTRY_TYPE, {
337
+ seq: overrideSeq,
338
+ overrides: permissionOverrides
339
+ .filter((override) => !override.standing)
340
+ .map((override) => ({ ...override })),
341
+ });
342
+ } catch {
343
+ // Persistence is best-effort; the in-memory records still apply now.
344
+ }
345
+ }
346
+
347
+ /** Fail-open like the loop budget: unreadable state means no overrides. */
348
+ function restoreOverrides(entries: readonly unknown[]): void {
349
+ permissionOverrides.length = 0;
350
+ overrideSeq = 0;
351
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
352
+ const entry = entries[index] as { type?: string; customType?: string; data?: unknown } | undefined;
353
+ if (entry?.type !== "custom" || entry.customType !== OVERRIDES_ENTRY_TYPE) continue;
354
+ const data = entry.data as { seq?: unknown; overrides?: unknown } | undefined;
355
+ if (Array.isArray(data?.overrides)) {
356
+ for (const raw of data.overrides) {
357
+ if (!raw || typeof raw !== "object") continue;
358
+ const candidate = raw as PermissionOverride;
359
+ if (
360
+ typeof candidate.seq !== "number"
361
+ || typeof candidate.gateLabel !== "string"
362
+ || typeof candidate.command !== "string"
363
+ || typeof candidate.reviewerReason !== "string"
364
+ || !["allow", "allow_unnecessary", "allow_appropriate", "block"].includes(candidate.choice)
365
+ ) {
366
+ continue;
367
+ }
368
+ permissionOverrides.push({
369
+ seq: candidate.seq,
370
+ ...(typeof candidate.anchorKey === "string" ? { anchorKey: candidate.anchorKey } : {}),
371
+ gateLabel: candidate.gateLabel,
372
+ command: candidate.command,
373
+ reviewerReason: candidate.reviewerReason,
374
+ choice: candidate.choice,
375
+ });
376
+ }
377
+ }
378
+ if (typeof data?.seq === "number" && Number.isSafeInteger(data.seq) && data.seq >= 0) {
379
+ overrideSeq = data.seq;
380
+ }
381
+ return;
382
+ }
383
+ }
384
+
385
+ /** Drop matching ledger-backed evidence in place; `permissionOverrides` is shared by reference. */
386
+ function removeStandingOverrides(matches: (override: PermissionOverride) => boolean): void {
387
+ const kept = permissionOverrides.filter((override) => !override.standing || !matches(override));
388
+ permissionOverrides.splice(0, permissionOverrides.length, ...kept);
389
+ }
390
+
391
+ /** Replace only ledger-backed evidence; session prompt decisions stay put. */
392
+ function loadStandingPermissionOverrides(config: AutoPermissionsConfig, ctx: ExtensionContext): void {
393
+ removeStandingOverrides(() => true);
394
+ if (!config.standingApprovals.enabled) return;
395
+ try {
396
+ const records = readStandingApprovals(config.standingApprovals.path);
397
+ permissionOverrides.push(...standingApprovalsToPermissionOverrides(records));
398
+ } catch (error) {
399
+ const message = error instanceof Error ? error.message : String(error);
400
+ ctx.ui.notify(`Could not load standing Auto Permissions approvals: ${message}`, "warning");
401
+ }
402
+ }
403
+
404
+ /**
405
+ * Record a non-approved outcome: a `pi.events` emit (the PermissionDenied
406
+ * hook equivalent) always, plus a denial-log line when enabled. Never blocks
407
+ * the decision itself.
408
+ */
409
+ function recordDenial(
410
+ config: AutoPermissionsConfig,
411
+ ctx: ExtensionContext,
412
+ target: ReviewTarget,
413
+ gate: Gate,
414
+ command: string,
415
+ verdict: DenialVerdict,
416
+ reason: string,
417
+ decisionSource: DenialSource,
418
+ ): void {
419
+ try {
420
+ pi.events.emit("auto-permissions:denied", {
421
+ tool: target.toolName,
422
+ command,
423
+ gate: gate.label,
424
+ group: gate.group,
425
+ verdict,
426
+ reason,
427
+ decisionSource,
428
+ });
429
+ } catch {
430
+ // Event fan-out is observability, never part of the decision.
431
+ }
432
+ if (!config.denialLog.enabled) return;
433
+ try {
434
+ appendDenialRecord(config.denialLog.path, buildDenialRecord({
435
+ sessionId: ctx.sessionManager.getSessionId(),
436
+ cwd: ctx.cwd,
437
+ tool: target.toolName,
438
+ gate: { label: gate.label, group: gate.group },
439
+ command,
440
+ verdict,
441
+ reason,
442
+ decisionSource,
443
+ }));
444
+ } catch {
445
+ // The denial log is best-effort observability.
446
+ }
447
+ }
280
448
  let reviewerGeneration = 0;
281
449
  let reviewerLifecycleController = new AbortController();
282
450
 
@@ -384,8 +552,13 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
384
552
  // allowlist rather than on whether this turn's evidence happens to contain
385
553
  // one: the system prompt has to be identical across the turns of a review
386
554
  // lineage, and "did an injected record appear yet" is not.
555
+ const guardianPolicySection = buildGuardianPolicySection(config.guardianPolicy);
556
+ // Lazy in case a review lands before session_start ran; still once only.
557
+ sessionEnvironment ??= captureSessionEnvironment(ctx.cwd);
387
558
  const policyPrompt = [
388
559
  basePolicyPrompt,
560
+ ...(guardianPolicySection ? [guardianPolicySection] : []),
561
+ buildSessionEnvironmentSection(sessionEnvironment),
389
562
  OVERRIDE_FEEDBACK_SYSTEM_PROMPT,
390
563
  ...(config.reviewEvidence.userMessageTypes.length ? [INJECTED_USER_MESSAGE_SYSTEM_PROMPT] : []),
391
564
  ].join("\n\n");
@@ -434,6 +607,84 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
434
607
  });
435
608
 
436
609
  const fullEvidence = () => applyFullRebuildEviction(evidence, config.reviewEvidence.fullRebuildKeepToolRecords);
610
+
611
+ // Stage one: an optional stateless single-token prefilter at minimal
612
+ // reasoning. SAFE approves; REVIEW and every failure fall through to the
613
+ // full lineage review below, which is untouched — the prefilter uses its
614
+ // own throwaway session, so the append-only lineage invariant holds. The
615
+ // envelope text matches a full-rebuild review's, so when the full review
616
+ // does run without a lineage base its prompt is largely a provider cache
617
+ // hit of this call.
618
+ if (config.reviewer?.prefilter) {
619
+ const prefilterSessionId = reviewerSessionId(model);
620
+ const prefilterSignal = AbortSignal.any([
621
+ AbortSignal.timeout(config.reviewer.timeoutMs),
622
+ reviewerLifecycleController.signal,
623
+ ...(signal ? [signal] : []),
624
+ ]);
625
+ let safe = false;
626
+ try {
627
+ const auth = await waitForSignal(ctx.modelRegistry.getApiKeyAndHeaders(model), prefilterSignal);
628
+ if (!auth.ok) throw new Error(auth.error);
629
+ const response = await resolveGuardianCompleteSimple(ctx.modelRegistry, "pi-auto-permissions")(
630
+ model,
631
+ {
632
+ systemPrompt,
633
+ messages: [{
634
+ role: "user",
635
+ content: [{ type: "text", text: `${buildReviewEnvelope(fullEvidence(), request, "full")}\n\n${PREFILTER_INSTRUCTION}` }],
636
+ timestamp: Date.now(),
637
+ }],
638
+ },
639
+ {
640
+ apiKey: auth.apiKey,
641
+ headers: auth.headers,
642
+ env: auth.env,
643
+ signal: prefilterSignal,
644
+ reasoning: "minimal",
645
+ sessionId: prefilterSessionId,
646
+ transport: isOpenAICodexModel(model) ? "websocket" : "auto",
647
+ cacheRetention: "long",
648
+ },
649
+ );
650
+ if (response.stopReason !== "aborted" && response.stopReason !== "error" && !prefilterSignal.aborted) {
651
+ recordReviewerUsage(config, model, response.usage, subagentContext !== undefined, "prefilter");
652
+ safe = parsePrefilterVerdict(assistantText(response.content)) === "safe";
653
+ }
654
+ } catch {
655
+ // Fail closed into the full review: a prefilter that cannot answer
656
+ // flags for review, it never approves and never blocks by itself.
657
+ } finally {
658
+ cleanupReviewerSession(prefilterSessionId);
659
+ }
660
+ if (!sessionActive || signal?.aborted) throw new Error("review timed out or was cancelled");
661
+ if (safe) {
662
+ if (config.evaluationLog.enabled) {
663
+ try {
664
+ appendPromptEvaluation(config.evaluationLog.path, {
665
+ version: 2,
666
+ timestamp: new Date().toISOString(),
667
+ sessionId: mainSessionId,
668
+ cwd: ctx.cwd,
669
+ tool: toolName,
670
+ gate: { label: gate.label, group: gate.group },
671
+ userRequest: evidence
672
+ .filter((record) => record.source === "user")
673
+ .map((record) => record.text)
674
+ .join("\n"),
675
+ command: typeof input.command === "string" ? input.command : JSON.stringify(input),
676
+ relevantContext: [...evidence],
677
+ actualDecision: "approve",
678
+ actualReason: "prefilter",
679
+ decisionSource: "prefilter",
680
+ });
681
+ } catch {
682
+ // Evaluation logging must never block a permission decision.
683
+ }
684
+ }
685
+ return { decision: "approve", reason: "prefilter" };
686
+ }
687
+ }
437
688
  let userMessage = makeUserMessage(base ? evidence.slice(base.evidenceKeys.length) : fullEvidence(), base ? "delta" : "full");
438
689
  let messages = base ? [...base.messages, userMessage] : [userMessage];
439
690
  if (base && estimateReviewTokens(systemPrompt, messages) >= budget) {
@@ -513,17 +764,22 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
513
764
  * Reviewer calls never reach the session transcript, so their usage is invisible to
514
765
  * tooling that reads session files. Record content-free counters in a sidecar instead.
515
766
  */
516
- function recordReviewerUsage(config: AutoPermissionsConfig, model: { provider: string; id: string }, usage: unknown, subagent: boolean): void {
767
+ function recordReviewerUsage(config: AutoPermissionsConfig, model: { provider: string; id: string }, usage: unknown, subagent: boolean, label: "guardian" | "prefilter" | "setup" = "guardian"): void {
517
768
  if (!config.usageLog.enabled) return;
518
769
  try {
519
- appendUsageRecord(config.usageLog.path, buildUsageLogRecord(model.provider, model.id, usage, "guardian", "auto-permissions", subagent));
770
+ appendUsageRecord(config.usageLog.path, buildUsageLogRecord(model.provider, model.id, usage, label, "auto-permissions", subagent));
520
771
  } catch {
521
772
  // Usage accounting is optional and must never block a permission decision.
522
773
  }
523
774
  }
524
775
 
525
776
  function untrustedMatches(command: string, config: AutoPermissionsConfig): Gate[] {
526
- return findGates(command, config.rules).filter((gate) => !trustedGroups.has(gate.group));
777
+ // Deny rules are hard policy boundaries: a project-scoped trusted-ops file
778
+ // must not be able to lift one, or a checked-in file could disarm the
779
+ // circuit breaker. Only guarded and convention matches honor the bypass.
780
+ return findGates(command, config.rules).filter(
781
+ (gate) => gate.level === "deny" || !trustedGroups.has(gate.group),
782
+ );
527
783
  }
528
784
 
529
785
  function evidenceCaps(config: AutoPermissionsConfig): EvidenceCaps {
@@ -856,6 +1112,16 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
856
1112
  }
857
1113
  showReviewDisplay(ctx, config, gate, command, target, "ask_user", detail);
858
1114
  if (!ctx.hasUI) {
1115
+ recordDenial(
1116
+ config,
1117
+ ctx,
1118
+ target,
1119
+ gate,
1120
+ command,
1121
+ "block",
1122
+ detail,
1123
+ decisionSource === "guardian" ? "guardian" : "review_failure",
1124
+ );
859
1125
  showReviewDisplay(ctx, config, gate, command, target, "blocked", detail, true);
860
1126
  return {
861
1127
  block: true,
@@ -882,7 +1148,10 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
882
1148
  choice = await promptSelect(
883
1149
  ctx,
884
1150
  `${gate.label} — Auto Permissions needs approval\n\n${detail}\n\n${command}`,
885
- permissionPromptOptions(config.evaluationLog.enabled),
1151
+ permissionPromptOptions(
1152
+ config.evaluationLog.enabled,
1153
+ shouldOfferStandingApproval(decisionSource, config.standingApprovals.enabled),
1154
+ ),
886
1155
  promptSignal,
887
1156
  { allowComment: true },
888
1157
  );
@@ -904,14 +1173,48 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
904
1173
  if (decisionSource === "guardian" && classification) {
905
1174
  const overrideChoice = classification.userChoice ?? (classification.allowsExecution ? "allow" as const : undefined);
906
1175
  if (overrideChoice) {
907
- permissionOverrides.push({
908
- seq: overrideSeq++,
909
- anchorKey: reviewerLineage?.evidenceKeys.at(-1),
910
- gateLabel: gate.label,
911
- command,
912
- reviewerReason: detail,
913
- choice: overrideChoice,
914
- });
1176
+ let recordedStanding = false;
1177
+ if (classification.standingApproval && config.standingApprovals.enabled) {
1178
+ try {
1179
+ const { evicted, override } = grantStandingApproval(
1180
+ config.standingApprovals.path,
1181
+ {
1182
+ gate: { label: gate.label, group: gate.group },
1183
+ command,
1184
+ project: ctx.cwd,
1185
+ reason: detail,
1186
+ },
1187
+ overrideSeq++,
1188
+ reviewerLineage?.evidenceKeys.at(-1),
1189
+ );
1190
+ removeStandingOverrides(
1191
+ (existing) => existing.standing?.gateGroup === gate.group && existing.command === command,
1192
+ );
1193
+ permissionOverrides.push(override);
1194
+ recordedStanding = true;
1195
+ if (evicted > 0 && !standingApprovalCapNotified) {
1196
+ standingApprovalCapNotified = true;
1197
+ ctx.ui.notify(
1198
+ `Standing approvals reached ${STANDING_APPROVAL_LIMIT} entries; the oldest approval was removed.`,
1199
+ "warning",
1200
+ );
1201
+ }
1202
+ } catch (error) {
1203
+ const message = error instanceof Error ? error.message : String(error);
1204
+ ctx.ui.notify(`Could not save standing approval: ${message}`, "warning");
1205
+ }
1206
+ }
1207
+ if (!recordedStanding) {
1208
+ permissionOverrides.push({
1209
+ seq: overrideSeq++,
1210
+ anchorKey: reviewerLineage?.evidenceKeys.at(-1),
1211
+ gateLabel: gate.label,
1212
+ command,
1213
+ reviewerReason: detail,
1214
+ choice: overrideChoice,
1215
+ });
1216
+ }
1217
+ persistOverrides();
915
1218
  }
916
1219
  }
917
1220
  if (config.evaluationLog.enabled && classification?.userChoice) {
@@ -931,6 +1234,16 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
931
1234
  showReviewDisplay(ctx, config, gate, command, target, "approved", "approved by user", true);
932
1235
  return undefined;
933
1236
  }
1237
+ recordDenial(
1238
+ config,
1239
+ ctx,
1240
+ target,
1241
+ gate,
1242
+ command,
1243
+ "block",
1244
+ detail,
1245
+ decisionSource === "guardian" ? "user" : "review_failure",
1246
+ );
934
1247
  showReviewDisplay(ctx, config, gate, command, target, "blocked", "blocked by user", true);
935
1248
  return { block: true, reason: "Blocked by user" };
936
1249
  } finally {
@@ -952,17 +1265,44 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
952
1265
  return { block: true, reason: error instanceof Error ? error.message : String(error) };
953
1266
  }
954
1267
  if (!config.enabled) return;
955
- const matches = untrustedMatches(command, config);
956
- if (!matches.length) return;
1268
+ const target: ReviewTarget = { toolName: event.toolName, toolCallId: event.toolCallId };
1269
+ const ruleMatches = findGates(command, config.rules);
1270
+ const matches = ruleMatches.filter(
1271
+ (gate) => gate.level === "deny" || !trustedGroups.has(gate.group),
1272
+ );
1273
+ // Level priority across all matches, never first-match: a convention or
1274
+ // guarded rule earlier in config order must not shadow a deny rule later.
1275
+ const deny = matches.find((gate) => gate.level === "deny");
1276
+ if (deny) {
1277
+ recordDenial(config, ctx, target, deny, command, "block", deny.message ?? deny.label, "deny");
1278
+ return { block: true, reason: denyReason(deny) };
1279
+ }
957
1280
  const convention = matches.find((gate) => gate.level === "convention");
958
1281
  if (convention && !allowedConventionCommands.has(command)) {
1282
+ recordDenial(
1283
+ config,
1284
+ ctx,
1285
+ target,
1286
+ convention,
1287
+ command,
1288
+ "block",
1289
+ convention.message ?? convention.label,
1290
+ "convention",
1291
+ );
959
1292
  return { block: true, reason: conventionReason(convention, command) };
960
1293
  }
961
- const gate = matches.find((candidate) => candidate.level === "guarded");
1294
+ let gate = matches.find((candidate) => candidate.level === "guarded");
1295
+ // With reviewAllShell on, a command no rule names at all still gets a
1296
+ // guardian review under the generic gate. "No rule" is judged before the
1297
+ // trusted-groups filter: a command whose matching group the project
1298
+ // trusts was explicitly waved through, not left unnamed, and must not be
1299
+ // re-captured by the blanket gate.
1300
+ if (!gate && !ruleMatches.length && config.reviewAllShell && !trustedGroups.has(ALL_SHELL_GATE.group)) {
1301
+ gate = ALL_SHELL_GATE;
1302
+ }
962
1303
  if (!gate) return;
963
1304
 
964
1305
  const signal = ctx.signal;
965
- const target = { toolName: event.toolName, toolCallId: event.toolCallId };
966
1306
  showReviewDisplay(ctx, config, gate, command, target, "waiting");
967
1307
  try {
968
1308
  const verdict = await reviewCommand(
@@ -996,6 +1336,16 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
996
1336
  const loopContext = detectLoopContext();
997
1337
  if (loopContext) {
998
1338
  const charge = chargeLoopRevision(loopContext.loopId, gate.label, verdict.reason);
1339
+ recordDenial(
1340
+ config,
1341
+ ctx,
1342
+ target,
1343
+ gate,
1344
+ command,
1345
+ verdict.decision === "revise" ? "revise" : "block",
1346
+ verdict.reason,
1347
+ "loop",
1348
+ );
999
1349
  showReviewDisplay(
1000
1350
  ctx,
1001
1351
  config,
@@ -1017,6 +1367,7 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
1017
1367
  };
1018
1368
  }
1019
1369
  if (verdict.decision === "revise") {
1370
+ recordDenial(config, ctx, target, gate, command, "revise", verdict.reason, "guardian");
1020
1371
  showReviewDisplay(ctx, config, gate, command, target, "revise", verdict.reason, true);
1021
1372
  return {
1022
1373
  block: true,
@@ -1034,6 +1385,7 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
1034
1385
  // judgment, so it charges no revision round — but it still must not open
1035
1386
  // a modal in a session with nobody to answer it.
1036
1387
  if (detectLoopContext()) {
1388
+ recordDenial(config, ctx, target, gate, command, "block", reason, "review_failure");
1037
1389
  showReviewDisplay(ctx, config, gate, command, target, "blocked", reason, true);
1038
1390
  return {
1039
1391
  block: true,
@@ -1063,7 +1415,7 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
1063
1415
  name: "request_override",
1064
1416
  executionMode: "sequential",
1065
1417
  label: "Request Override",
1066
- description: "Request a one-session exception for a command that violates a tooling convention. This cannot bypass guarded commands.",
1418
+ description: "Request a one-session exception for a command that violates a tooling convention. This cannot bypass guarded commands or deny rules.",
1067
1419
  parameters: Type.Object({
1068
1420
  command: Type.String({ description: "Exact command to allow" }),
1069
1421
  reason: Type.String({ description: "Why the convention does not apply" }),
@@ -1079,6 +1431,12 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
1079
1431
  };
1080
1432
  }
1081
1433
  const matches = untrustedMatches(params.command, config);
1434
+ if (matches.some((gate) => gate.level === "deny")) {
1435
+ return {
1436
+ content: [{ type: "text", text: "The command matches a deny rule, which is a hard policy boundary. Deny rules cannot be bypassed with request_override; choose a different approach." }],
1437
+ details: { success: false },
1438
+ };
1439
+ }
1082
1440
  if (!matches.length || matches.some((gate) => gate.level === "guarded")) {
1083
1441
  return {
1084
1442
  content: [{ type: "text", text: "The command is not a convention violation. Guarded commands cannot be bypassed with request_override." }],
@@ -1145,16 +1503,162 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
1145
1503
  * and in every other one. reviewerFingerprint() covers provider, model and
1146
1504
  * reasoning effort, so the cached reviewer lineage self-invalidates too.
1147
1505
  */
1506
+ /**
1507
+ * `/auto-permissions setup`: scan the project (git remotes, AGENTS.md or
1508
+ * README.md, lockfiles) and recent session files — command strings only,
1509
+ * never user messages — then draft guardianPolicy.environment and softDeny
1510
+ * entries plus suggested trusted-ops groups with one model call. The draft
1511
+ * is accepted or discarded as a whole; accepting appends both policy tiers
1512
+ * via the narrow config writer. Trusted-ops suggestions are displayed only:
1513
+ * a wizard must not widen a project-level bypass file on its own.
1514
+ */
1515
+ async function runSetupWizard(ctx: ExtensionContext): Promise<void> {
1516
+ const path = autoPermissionsConfigPath();
1517
+ let config: AutoPermissionsConfig;
1518
+ try {
1519
+ config = loadAutoPermissionsConfig(path);
1520
+ } catch (error) {
1521
+ const message = error instanceof Error ? error.message : String(error);
1522
+ ctx.ui.notify(`Auto Permissions config error: ${message} — fix ${path} first`, "warning");
1523
+ return;
1524
+ }
1525
+ const model = config.reviewer
1526
+ ? ctx.modelRegistry.find(config.reviewer.provider, config.reviewer.model)
1527
+ : ctx.model;
1528
+ if (!model) {
1529
+ ctx.ui.notify("Auto Permissions setup needs a reviewer model (or an active session model).", "warning");
1530
+ return;
1531
+ }
1532
+
1533
+ ctx.ui.notify("Auto Permissions setup: scanning project facts and recent session commands…", "info");
1534
+ const project = scanProject(ctx.cwd);
1535
+ const commands = scanRecentSessionCommands(join(getAgentDir(), "sessions"), SETUP_SESSION_SCAN_LIMIT);
1536
+ const availableGroups = [...new Set(config.rules.map((rule) => rule.group))].sort();
1537
+
1538
+ const sessionId = reviewerSessionId(model);
1539
+ let draftText: string;
1540
+ try {
1541
+ const setupSignal = AbortSignal.any([AbortSignal.timeout(60_000), reviewerLifecycleController.signal]);
1542
+ const auth = await waitForSignal(ctx.modelRegistry.getApiKeyAndHeaders(model), setupSignal);
1543
+ if (!auth.ok) throw new Error(auth.error);
1544
+ const response = await resolveGuardianCompleteSimple(ctx.modelRegistry, "pi-auto-permissions")(
1545
+ model,
1546
+ {
1547
+ systemPrompt: SETUP_DRAFT_SYSTEM_PROMPT,
1548
+ messages: [{
1549
+ role: "user",
1550
+ content: [{ type: "text", text: buildSetupDraftRequest(project, commands, availableGroups) }],
1551
+ timestamp: Date.now(),
1552
+ }],
1553
+ },
1554
+ {
1555
+ apiKey: auth.apiKey,
1556
+ headers: auth.headers,
1557
+ env: auth.env,
1558
+ signal: setupSignal,
1559
+ reasoning: "low",
1560
+ sessionId,
1561
+ transport: isOpenAICodexModel(model) ? "websocket" : "auto",
1562
+ },
1563
+ );
1564
+ if (response.stopReason === "aborted") throw new Error("setup draft timed out or was cancelled");
1565
+ if (response.stopReason === "error") throw new Error(response.errorMessage ?? "setup draft request failed");
1566
+ recordReviewerUsage(config, model, response.usage, false, "setup");
1567
+ draftText = assistantText(response.content);
1568
+ } catch (error) {
1569
+ const message = error instanceof Error ? error.message : String(error);
1570
+ ctx.ui.notify(`Auto Permissions setup failed: ${message}`, "warning");
1571
+ return;
1572
+ } finally {
1573
+ cleanupReviewerSession(sessionId);
1574
+ }
1575
+
1576
+ let draft: ReturnType<typeof parseSetupDraft>;
1577
+ try {
1578
+ draft = parseSetupDraft(draftText, availableGroups);
1579
+ } catch (error) {
1580
+ const message = error instanceof Error ? error.message : String(error);
1581
+ ctx.ui.notify(`Auto Permissions setup failed: ${message}`, "warning");
1582
+ return;
1583
+ }
1584
+ const existingEnvironment = new Set(config.guardianPolicy.environment);
1585
+ const existingSoftDeny = new Set(config.guardianPolicy.softDeny);
1586
+ const environment = draft.environment
1587
+ .filter((text) => !existingEnvironment.has(text))
1588
+ .map((text) => ({ text, sources: setupEntrySources(text, project, commands) }))
1589
+ .filter((entry) => entry.sources.length > 0);
1590
+ const softDeny = draft.softDeny
1591
+ .filter((text) => !existingSoftDeny.has(text))
1592
+ .map((text) => ({ text, sources: setupEntrySources(text, project, commands) }))
1593
+ .filter((entry) => entry.sources.length > 0);
1594
+ if (!environment.length && !softDeny.length && !draft.trustedGroups.length) {
1595
+ ctx.ui.notify("Auto Permissions setup found nothing verifiably sourced to suggest for this project.", "info");
1596
+ return;
1597
+ }
1598
+
1599
+ const lines = [
1600
+ `Auto Permissions setup — based on your ${SETUP_SESSION_SCAN_LIMIT} most recent sessions`,
1601
+ "For a thorough interactive setup, ask your agent to use the auto-permissions-setup skill.",
1602
+ "",
1603
+ ];
1604
+ if (environment.length) {
1605
+ lines.push("guardianPolicy.environment entries to append:");
1606
+ for (const entry of environment) {
1607
+ lines.push(` - ${entry.text}`, ` from: ${entry.sources.join(", ")}`);
1608
+ }
1609
+ }
1610
+ if (softDeny.length) {
1611
+ if (environment.length) lines.push("");
1612
+ lines.push("guardianPolicy.softDeny entries to append:");
1613
+ for (const entry of softDeny) {
1614
+ lines.push(` - ${entry.text}`, ` from: ${entry.sources.join(", ")}`);
1615
+ }
1616
+ }
1617
+ if (draft.trustedGroups.length) {
1618
+ if (environment.length || softDeny.length) lines.push("");
1619
+ lines.push("Suggested .pi/trusted-ops groups (shown only — add them to the project file yourself):");
1620
+ for (const group of draft.trustedGroups) {
1621
+ lines.push(` - ${group}`, " from: recent session commands");
1622
+ }
1623
+ }
1624
+
1625
+ const savableCount = environment.length + softDeny.length;
1626
+ const choice = await promptSelect(
1627
+ ctx,
1628
+ lines.join("\n"),
1629
+ savableCount ? ["Accept and save", "Discard"] : ["Done"],
1630
+ reviewerLifecycleController.signal,
1631
+ { allowComment: false },
1632
+ );
1633
+ if (choice !== "Accept and save" || !savableCount) return;
1634
+ try {
1635
+ patchAutoPermissionsConfig(path, {
1636
+ appendEnvironment: environment.map((entry) => entry.text),
1637
+ appendSoftDeny: softDeny.map((entry) => entry.text),
1638
+ });
1639
+ ctx.ui.notify(`Saved ${savableCount} tiered trust entr${savableCount === 1 ? "y" : "ies"} to guardianPolicy.`, "info");
1640
+ } catch (error) {
1641
+ const message = error instanceof Error ? error.message : String(error);
1642
+ ctx.ui.notify(`Could not save Auto Permissions setup draft: ${message}`, "warning");
1643
+ }
1644
+ }
1645
+
1148
1646
  pi.registerCommand("auto-permissions", {
1149
- description: "Configure Auto Permissions",
1150
- handler: async (_args, ctx) => {
1647
+ description: "Configure Auto Permissions (\"setup\" drafts trust configuration from your project)",
1648
+ handler: async (args, ctx) => {
1151
1649
  if (ctx.mode !== "tui") {
1152
1650
  ctx.ui.notify("/auto-permissions requires interactive TUI mode", "warning");
1153
1651
  return;
1154
1652
  }
1653
+ if ((args ?? "").trim() === "setup") {
1654
+ await runSetupWizard(ctx);
1655
+ return;
1656
+ }
1155
1657
 
1156
1658
  const path = autoPermissionsConfigPath();
1157
1659
  let settings: ReviewerSettings;
1660
+ let denialLog: AutoPermissionsConfig["denialLog"];
1661
+ let standingApprovalsConfig: AutoPermissionsConfig["standingApprovals"];
1158
1662
  try {
1159
1663
  const config = loadAutoPermissionsConfig(path);
1160
1664
  settings = {
@@ -1162,6 +1666,8 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
1162
1666
  reviewer: config.reviewer,
1163
1667
  systemPromptSource: config.systemPromptSource,
1164
1668
  };
1669
+ denialLog = config.denialLog;
1670
+ standingApprovalsConfig = config.standingApprovals;
1165
1671
  } catch (error) {
1166
1672
  // Editing a file we cannot validate is the one way this writer could
1167
1673
  // quietly make things worse, so refuse rather than open.
@@ -1203,6 +1709,80 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
1203
1709
  return ctx.modelRegistry.find(settings.reviewer.provider, settings.reviewer.model) as MenuModel | undefined;
1204
1710
  };
1205
1711
 
1712
+ const recentDenials = (): DenialSummary[] => {
1713
+ if (!denialLog.enabled) return [];
1714
+ try {
1715
+ return readRecentDenials(denialLog.path, 20).map((record) => ({
1716
+ id: record.id,
1717
+ ts: record.ts,
1718
+ gateLabel: record.gate.label,
1719
+ command: record.command,
1720
+ verdict: record.verdict,
1721
+ reason: record.reason,
1722
+ }));
1723
+ } catch {
1724
+ return [];
1725
+ }
1726
+ };
1727
+
1728
+ const standingApprovalSummaries = (): StandingApprovalSummary[] => {
1729
+ if (!standingApprovalsConfig.enabled) return [];
1730
+ try {
1731
+ return readStandingApprovals(standingApprovalsConfig.path).map((record, index) => ({
1732
+ id: `${index}:${record.ts}:${record.gate.label}`,
1733
+ record,
1734
+ }));
1735
+ } catch {
1736
+ return [];
1737
+ }
1738
+ };
1739
+
1740
+ const revokeApproval = (approval: StandingApprovalSummary): void => {
1741
+ try {
1742
+ if (!revokeStandingApproval(standingApprovalsConfig.path, approval.record)) {
1743
+ ctx.ui.notify("That standing approval is no longer in the ledger.", "warning");
1744
+ return;
1745
+ }
1746
+ const config = loadAutoPermissionsConfig(path);
1747
+ loadStandingPermissionOverrides(config, ctx);
1748
+ discardReviewerLineage();
1749
+ ctx.ui.notify("Standing approval revoked.", "info");
1750
+ } catch (error) {
1751
+ const message = error instanceof Error ? error.message : String(error);
1752
+ ctx.ui.notify(`Could not revoke standing approval: ${message}`, "warning");
1753
+ }
1754
+ };
1755
+
1756
+ /**
1757
+ * "Allow on retry": the existing override machinery, driven from the
1758
+ * denial ledger. An exact-command allow override (which already
1759
+ * generalizes correctly and survives via evidence re-injection and the
1760
+ * session entry), plus a visible injected message telling the agent it
1761
+ * may retry. No new authorization pathway.
1762
+ */
1763
+ const allowRetry = (denial: DenialSummary): void => {
1764
+ permissionOverrides.push({
1765
+ seq: overrideSeq++,
1766
+ anchorKey: reviewerLineage?.evidenceKeys.at(-1),
1767
+ gateLabel: denial.gateLabel,
1768
+ command: denial.command,
1769
+ reviewerReason: denial.reason,
1770
+ choice: "allow",
1771
+ });
1772
+ persistOverrides();
1773
+ try {
1774
+ // The same channel a prompt note uses. This is a real user decision
1775
+ // made in the menu, so a user message is honest provenance — and it
1776
+ // gives the agent a turn to actually retry.
1777
+ pi.sendUserMessage(
1778
+ `Auto Permissions: I reviewed the denied command in /auto-permissions and allowed it on retry:\n\n ${denial.command}\n\nYou may run this exact command again; a session override now authorizes it.`,
1779
+ );
1780
+ } catch {
1781
+ // The override itself is already in force; the nudge is best-effort.
1782
+ }
1783
+ ctx.ui.notify("Override added for the exact command; the agent may retry it.", "info");
1784
+ };
1785
+
1206
1786
  await ctx.ui.custom<void>((tui, _theme, _keybindings, done) => {
1207
1787
  const host: SubmenuHost = {
1208
1788
  getSettings: () => settings,
@@ -1212,11 +1792,35 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
1212
1792
  settingsTheme: getSettingsListTheme(),
1213
1793
  selectTheme: getSelectListTheme(),
1214
1794
  };
1795
+ const denialsHost: DenialsSubmenuHost = {
1796
+ recentDenials,
1797
+ allowRetry,
1798
+ settingsTheme: getSettingsListTheme(),
1799
+ selectTheme: getSelectListTheme(),
1800
+ requestRender: () => tui.requestRender(),
1801
+ };
1802
+ const standingHost: StandingApprovalsSubmenuHost = {
1803
+ standingApprovals: standingApprovalSummaries,
1804
+ revokeStandingApproval: revokeApproval,
1805
+ settingsTheme: getSettingsListTheme(),
1806
+ selectTheme: getSelectListTheme(),
1807
+ requestRender: () => tui.requestRender(),
1808
+ };
1215
1809
  const list = new SettingsList(
1216
- buildSettingItems(settings, {
1217
- reviewerModel: createModelSubmenu(host),
1218
- timeout: createTimeoutSubmenu(host),
1219
- }),
1810
+ buildSettingItems(
1811
+ settings,
1812
+ {
1813
+ reviewerModel: createModelSubmenu(host),
1814
+ timeout: createTimeoutSubmenu(host),
1815
+ ...(denialLog.enabled ? { recentDenials: createDenialsSubmenu(denialsHost) } : {}),
1816
+ ...(standingApprovalsConfig.enabled
1817
+ ? { standingApprovals: createStandingApprovalsSubmenu(standingHost) }
1818
+ : {}),
1819
+ },
1820
+ undefined,
1821
+ denialLog.enabled ? recentDenials().length : undefined,
1822
+ standingApprovalsConfig.enabled ? standingApprovalSummaries().length : undefined,
1823
+ ),
1220
1824
  10,
1221
1825
  host.settingsTheme,
1222
1826
  (id, value) => {
@@ -1259,9 +1863,11 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
1259
1863
  discardReviewerLineage();
1260
1864
  reviewerLifecycleController = new AbortController();
1261
1865
  sessionActive = true;
1866
+ standingApprovalCapNotified = false;
1262
1867
  allowedConventionCommands.clear();
1263
- permissionOverrides.length = 0;
1264
- overrideSeq = 0;
1868
+ // Restore prompt decisions from the branch: a resumed session keeps its
1869
+ // allows and standing block constraints (parity with the loop budget).
1870
+ restoreOverrides(ctx.sessionManager.getBranch());
1265
1871
  // Rebuild the revise budget before the first tool call: a resumed session
1266
1872
  // that forgot its spent rounds would hand the agent a fresh set of them.
1267
1873
  loopReviseBudget.restore(ctx.sessionManager.getBranch());
@@ -1273,8 +1879,14 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
1273
1879
  if (details?.success && details.command) allowedConventionCommands.add(details.command);
1274
1880
  }
1275
1881
  trustedGroups = ctx.isProjectTrusted() ? loadTrustedGroups(ctx.cwd) : new Set();
1882
+ // Snapshot the trust baseline at session start: remotes configured now are
1883
+ // inside the boundary, anything added or repointed later is not. Re-capture
1884
+ // on every session_start (resume, branch switch) so the baseline follows
1885
+ // the session the reviews belong to; the fingerprint covers the change.
1886
+ sessionEnvironment = captureSessionEnvironment(ctx.cwd);
1276
1887
  try {
1277
1888
  const config = currentConfig(ctx);
1889
+ loadStandingPermissionOverrides(config, ctx);
1278
1890
  if (config.ui.placement === "toolRow") registerGuardedBash(ctx);
1279
1891
  } catch {
1280
1892
  // The first bash call will fail closed with the configuration error.