From e4048ffb3ccf67b3364ebea570454e71d1937587 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Wed, 25 Nov 2026 19:04:33 -0500 Subject: [PATCH 1/6] Remember the setup command the user allowed per repo create_worktree asks when the repo's .ness.json has a setupCommand, so anyone whose repo has one was prompted on every agent create_worktree, which nudges them toward a blanket 'Always allow'. Now allowing one of those prompts records that repo's command in the permissions slice (persisted next to the grants), and later calls go through while the command is unchanged. A changed command asks again. Only a human Allow records it: the reviewer's auto-approvals don't go through resolveApproval. The command is snapshotted when the card opens, so an edit to .ness.json while it's open isn't what gets approved. It's recorded only when the setup command was the sole reason to ask, so allowing a PR checkout remembers nothing. 'Remove all' clears approved commands too, and permissions:forgetSetupCommand drops one; there's no UI for listing them yet. Co-Authored-By: Claude Opus 5.5 --- src/main/approval-bridge-rules.test.ts | 50 +++++++++++++++++++++- src/main/approval-bridge.ts | 58 ++++++++++++++++++++++---- src/main/build-initial-state.test.ts | 17 +++++++- src/main/build-initial-state.ts | 20 +++++++-- src/main/index.ts | 23 ++++++++-- src/main/persistence.ts | 2 + src/renderer/build-backend.ts | 1 + src/renderer/types.ts | 1 + src/shared/ness-tool-policy.test.ts | 12 ++++++ src/shared/ness-tool-policy.ts | 13 ++++-- src/shared/state/permissions.test.ts | 44 +++++++++++++++++++ src/shared/state/permissions.ts | 32 ++++++++++++-- 12 files changed, 249 insertions(+), 24 deletions(-) diff --git a/src/main/approval-bridge-rules.test.ts b/src/main/approval-bridge-rules.test.ts index f20c28651..757e91dba 100644 --- a/src/main/approval-bridge-rules.test.ts +++ b/src/main/approval-bridge-rules.test.ts @@ -70,7 +70,14 @@ async function harness( // Haiku reviewer — this suite is only about the rule path. isAutoApproveEnabled: () => false, getAutoApproveSteerInstructions: () => '', - repoSetupCommandFor, + repoSetupFor: repoSetupCommandFor + ? (sid, root) => { + const command = repoSetupCommandFor(sid, root) + return command === null ? null : { repoRoot: root ?? '/repo', command } + } + : undefined, + onSetupCommandApproved: (repoRoot, command) => + store.dispatch({ type: 'permissions/setupCommandApproved', payload: { repoRoot, command } }), isOpenRepo: (root) => root === '/repo' }) openBridges.push(bridge) @@ -180,6 +187,47 @@ describe('ApprovalBridge — Ness tools', () => { ).toBe('mcp__ness-control__create_worktree') }) + it('remembers a setup command the user allowed, and asks again when it changes', async () => { + let command = 'npm install' + const h = await harness([], () => command) + const cw = (id: string, input: Record = { branchName: 'x' }) => + h.send({ id, tool_name: 'mcp__ness-control__create_worktree', input, tool_use_id: `tu-${id}` }) + + expect(await cw('sc-1')).toBeNull() + // While the card is open, the repo's command changes; the card still + // approves what it showed, not the new one. + command = 'npm ci' + expect(h.bridge.resolveApproval('sc-1', { behavior: 'allow' })).toBe(true) + expect(h.store.getSnapshot().state.permissions.approvedSetupCommands).toEqual({ + '/repo': 'npm install' + }) + expect(await cw('sc-2')).toBeNull() + + command = 'npm install' + const ok = await cw('sc-3') + expect((ok as { result: { behavior: string } }).result.behavior).toBe('allow') + + // A PR checkout asks for its own reason, so allowing it remembers nothing. + command = 'make setup' + expect(await cw('sc-4', { prNumber: 7 })).toBeNull() + h.bridge.resolveApproval('sc-4', { behavior: 'allow' }) + expect(h.store.getSnapshot().state.permissions.approvedSetupCommands['/repo']).toBe('npm install') + }) + + it('does not remember a setup command the user denied', async () => { + const h = await harness([], () => 'npm install') + expect( + await h.send({ + id: 'sc-deny', + tool_name: 'mcp__ness-control__create_worktree', + input: { branchName: 'x' }, + tool_use_id: 'tu-sc-deny' + }) + ).toBeNull() + h.bridge.resolveApproval('sc-deny', { behavior: 'deny', message: 'no' }) + expect(h.store.getSnapshot().state.permissions.approvedSetupCommands).toEqual({}) + }) + it('asks for create_worktree on a PR checkout or an unopened repo', async () => { const h = await harness([], () => '') const pr = await h.send({ diff --git a/src/main/approval-bridge.ts b/src/main/approval-bridge.ts index ea9b8b0fa..5f381b0eb 100644 --- a/src/main/approval-bridge.ts +++ b/src/main/approval-bridge.ts @@ -66,6 +66,10 @@ interface PendingResponse { * approval card after the user edits steering guidance) can rebuild * the prompt without crossing slice boundaries. */ payload: JsonClaudePendingApproval + /** Set when this create_worktree asked only because of the repo's setup + * command; allowing it remembers that command. Snapshotted at request + * time so an edit to .ness.json while the card is open isn't approved. */ + approvesSetup?: { repoRoot: string; command: string } } interface SessionEntry { @@ -86,9 +90,16 @@ export interface ApprovalBridgeDeps { * guidance. Empty string when unset. */ getAutoApproveSteerInstructions: () => string /** The repo's own (.ness.json) setup command an MCP create_worktree from - * this session would run (repoRoot undefined = the session's own repo): - * '' for none, null when unknown. */ - repoSetupCommandFor?: (sessionId: string, repoRoot: string | undefined) => string | null + * this session would run, with the repo it resolved to (repoRoot + * undefined = the session's own repo). command is '' for none; null + * when the repo can't be resolved. */ + repoSetupFor?: ( + sessionId: string, + repoRoot: string | undefined + ) => { repoRoot: string; command: string } | null + /** The user allowed a create_worktree whose only reason to ask was this + * repo setup command. The host records and persists it. */ + onSetupCommandApproved?: (repoRoot: string, command: string) => void /** True when `repoRoot` is a repo already open in Ness. */ isOpenRepo?: (repoRoot: string) => boolean } @@ -244,6 +255,10 @@ export class ApprovalBridge { type: 'jsonClaude/approvalResolved', payload: { requestId } }) + if (result.behavior === 'allow' && pending.approvesSetup) { + const { repoRoot, command } = pending.approvesSetup + this.deps?.onSetupCommandApproved?.(repoRoot, command) + } return true } @@ -405,13 +420,25 @@ export class ApprovalBridge { // a human; see shared/ness-tool-policy.ts for what's excluded and why. // No approvalSessionAllowed dispatch either: these calls fire every // turn, and an "auto-allowed" chip on each would be noise. - const repoSetupCommandFor = this.deps?.repoSetupCommandFor + const repoSetupFor = this.deps?.repoSetupFor + let setup: { repoRoot: string; command: string } | null = null + const nessCtx = { + repoSetupCommandFor: repoSetupFor + ? (repoRoot: string | undefined): string | null => { + setup = repoSetupFor(basePayload.sessionId, repoRoot) + return setup?.command ?? null + } + : undefined, + isOpenRepo: this.deps?.isOpenRepo + } + const approved = this.store.getSnapshot().state.permissions.approvedSetupCommands if ( isAutoAllowedNessCall(basePayload.toolName, basePayload.input, { - repoSetupCommandFor: repoSetupCommandFor - ? (repoRoot) => repoSetupCommandFor(basePayload.sessionId, repoRoot) - : undefined, - isOpenRepo: this.deps?.isOpenRepo + ...nessCtx, + isSetupCommandApproved: () => { + const s = setup as { repoRoot: string; command: string } | null + return s !== null && approved[s.repoRoot] === s.command + } }) ) { respond({ behavior: 'allow', updatedInput: basePayload.input }) @@ -476,11 +503,24 @@ export class ApprovalBridge { } const payload: JsonClaudePendingApproval = { ...basePayload, autoReview } + // Would this call have gone through with its setup command approved? + // Then the command is the only thing the user is being asked about. + const pendingSetup = setup as { repoRoot: string; command: string } | null + const approvesSetup = + pendingSetup && + pendingSetup.command !== '' && + isAutoAllowedNessCall(basePayload.toolName, basePayload.input, { + ...nessCtx, + isSetupCommandApproved: () => true + }) + ? pendingSetup + : undefined this.pendingResponses.set(payload.requestId, { respond, socket, sessionId: payload.sessionId, - payload + payload, + ...(approvesSetup ? { approvesSetup } : {}) }) this.store.dispatch({ type: 'jsonClaude/approvalRequested', payload }) log( diff --git a/src/main/build-initial-state.test.ts b/src/main/build-initial-state.test.ts index 95e87d527..e17e17208 100644 --- a/src/main/build-initial-state.test.ts +++ b/src/main/build-initial-state.test.ts @@ -8,7 +8,7 @@ vi.mock('electron', () => ({ } })) -import { buildInitialAppState } from './build-initial-state' +import { buildInitialAppState, sanitizeApprovedSetupCommands } from './build-initial-state' import { runMigrations } from './persistence-migrations' import type { Config } from './persistence' import { initialPRs } from '../shared/state/prs' @@ -176,3 +176,18 @@ describe('buildInitialAppState', () => { expect(wt.requests?.map((r) => r.id)).toEqual(['r1']) }) }) + +describe('sanitizeApprovedSetupCommands', () => { + it('keeps absolute repo roots with non-empty string commands only', () => { + expect( + sanitizeApprovedSetupCommands({ + '/repo': 'npm install', + relative: 'npm install', + '/blank': ' ', + '/num': 3 + }) + ).toEqual({ '/repo': 'npm install' }) + expect(sanitizeApprovedSetupCommands(undefined)).toEqual({}) + expect(sanitizeApprovedSetupCommands(['/repo'])).toEqual({}) + }) +}) diff --git a/src/main/build-initial-state.ts b/src/main/build-initial-state.ts index 98a67e4af..42c671e0a 100644 --- a/src/main/build-initial-state.ts +++ b/src/main/build-initial-state.ts @@ -261,9 +261,12 @@ export function buildInitialAppState( aliases: config.aliases ? { byPath: { ...config.aliases } } : initialAliases, - permissions: config.permissionRules - ? { rules: sanitizePermissionRules(config.permissionRules) } - : initialPermissions, + permissions: { + rules: config.permissionRules + ? sanitizePermissionRules(config.permissionRules) + : initialPermissions.rules, + approvedSetupCommands: sanitizeApprovedSetupCommands(config.approvedSetupCommands) + }, reviews: config.reviews ? { byPath: sanitizeReviews(config.reviews) } : initialReviews, subscriptions: Array.isArray(config.worktreeSubscriptions) ? { list: config.worktreeSubscriptions.filter(isStoredSubscription) } @@ -443,3 +446,14 @@ function sanitizeBottomIconOrder(input: unknown): BottomIconKey[] { } return out } + +/** Drops anything that isn't a non-empty string command keyed by an + * absolute repo path, so a hand-edited config can't widen the gate. */ +export function sanitizeApprovedSetupCommands(raw: unknown): Record { + const out: Record = {} + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out + for (const [root, cmd] of Object.entries(raw as Record)) { + if (root.startsWith('/') && typeof cmd === 'string' && cmd.trim()) out[root] = cmd + } + return out +} diff --git a/src/main/index.ts b/src/main/index.ts index 135b1737b..84400a612 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -496,12 +496,18 @@ const approvalBridge = new ApprovalBridge(store, { store.getSnapshot().state.settings.autoApprovePermissions === true, getAutoApproveSteerInstructions: () => store.getSnapshot().state.settings.autoApproveSteerInstructions || '', - repoSetupCommandFor: (sessionId, repoRoot) => { + repoSetupFor: (sessionId, repoRoot) => { const state = store.getSnapshot().state const sessionPath = state.jsonClaude.sessions[sessionId]?.worktreePath const root = - repoRoot ?? state.worktrees.list.find((w) => w.path === sessionPath)?.repoRoot - return root ? loadRepoConfig(root).setupCommand?.trim() || '' : null + repoRoot?.replace(/\/+$/, '') ?? + state.worktrees.list.find((w) => w.path === sessionPath)?.repoRoot + if (!root) return null + return { repoRoot: root, command: loadRepoConfig(root).setupCommand?.trim() || '' } + }, + onSetupCommandApproved: (repoRoot, command) => { + store.dispatch({ type: 'permissions/setupCommandApproved', payload: { repoRoot, command } }) + persistPermissionRules() }, isOpenRepo: (repoRoot) => { const want = repoRoot.replace(/\/+$/, '') @@ -1598,7 +1604,9 @@ function grantPermissionRules(rules: PermissionRule[], grantedFrom?: string): nu } function persistPermissionRules(): void { - config.permissionRules = store.getSnapshot().state.permissions.rules + const { rules, approvedSetupCommands } = store.getSnapshot().state.permissions + config.permissionRules = rules + config.approvedSetupCommands = approvedSetupCommands saveConfig(config) } @@ -3365,6 +3373,13 @@ function registerIpcHandlers(): void { return true }) + transport.onRequest('permissions:forgetSetupCommand', (_ctx, repoRoot: string): boolean => { + if (typeof repoRoot !== 'string' || !repoRoot) return false + store.dispatch({ type: 'permissions/setupCommandForgotten', payload: { repoRoot } }) + persistPermissionRules() + return true + }) + transport.onRequest('mcp:prepareForTerminal', (_ctx, terminalId: string): string | null => { if (config.harnessMcpEnabled === false) return null if (!terminalId) return null diff --git a/src/main/persistence.ts b/src/main/persistence.ts index 5c5064687..144be1a00 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -333,6 +333,8 @@ export interface Config { // shared/permission-match.ts. Only json-mode consults it; terminal // tabs prompt in Claude's own TUI and persist separately. permissionRules?: unknown[] + // repoRoot → approved .ness.json setupCommand (permissions slice). + approvedSetupCommands?: Record // Diagnostic toggle (no UI): when true, json-mode tabs spawn the user's // PATH `claude` instead of the bundled one. Default off. useSystemClaudeForJsonMode?: boolean diff --git a/src/renderer/build-backend.ts b/src/renderer/build-backend.ts index 61dd19d33..612637ab0 100644 --- a/src/renderer/build-backend.ts +++ b/src/renderer/build-backend.ts @@ -374,6 +374,7 @@ export function buildBackend( req('permissions:grant', rule, grantedFrom), revokePermission: (id: string) => req('permissions:revoke', id), clearPermissions: () => req('permissions:clear'), + forgetSetupCommand: (repoRoot: string) => req('permissions:forgetSetupCommand', repoRoot), setNewWorktreeAdvancedOpen: (open: boolean) => reqConfig('config:setNewWorktreeAdvancedOpen', open), setStarterTasksDismissed: (dismissed: boolean) => diff --git a/src/renderer/types.ts b/src/renderer/types.ts index 55bb09208..9495f71a3 100644 --- a/src/renderer/types.ts +++ b/src/renderer/types.ts @@ -466,6 +466,7 @@ export interface ElectronAPI { grantPermission(rule: { toolName: string; ruleContent?: string }, grantedFrom?: string): Promise revokePermission(id: string): Promise clearPermissions(): Promise + forgetSetupCommand(repoRoot: string): Promise setNewWorktreeAdvancedOpen(open: boolean): Promise setStarterTasksDismissed(dismissed: boolean): Promise setHarnessSystemPromptEnabled(enabled: boolean): Promise diff --git a/src/shared/ness-tool-policy.test.ts b/src/shared/ness-tool-policy.test.ts index 9e9e128f9..fd1615875 100644 --- a/src/shared/ness-tool-policy.test.ts +++ b/src/shared/ness-tool-policy.test.ts @@ -103,6 +103,18 @@ describe('ness tool policy', () => { expect(nessAllowedToolsFlagValue()).not.toContain('create_worktree') }) + it('auto-allows create_worktree when the repo setup command is the approved one', () => { + const cw = 'mcp__ness-control__create_worktree' + const ctx = (approved: string) => ({ + repoSetupCommandFor: () => 'npm install', + isSetupCommandApproved: (_root: string | undefined, cmd: string) => cmd === approved + }) + expect(isAutoAllowedNessCall(cw, { branchName: 'b' }, ctx('npm install'))).toBe(true) + expect(isAutoAllowedNessCall(cw, { branchName: 'b' }, ctx('npm ci'))).toBe(false) + // Approval never overrides the PR-checkout gate. + expect(isAutoAllowedNessCall(cw, { prNumber: 1 }, ctx('npm install'))).toBe(false) + }) + it('asks for create_worktree on a PR checkout', () => { const ctx = { repoSetupCommandFor: () => '', isOpenRepo: () => true } const cw = 'mcp__ness-control__create_worktree' diff --git a/src/shared/ness-tool-policy.ts b/src/shared/ness-tool-policy.ts index d4fabb94e..fab890445 100644 --- a/src/shared/ness-tool-policy.ts +++ b/src/shared/ness-tool-policy.ts @@ -33,8 +33,10 @@ // .claude/settings.json hooks and .mcp.json load in the new session), // and an explicit repoRoot that isn't open in Ness (the same as add_repo, // which asks). It is auto-allowed only with no prNumber, a repoRoot that -// is omitted or already open, and no repo setupCommand; otherwise it asks. -// The global setup command from Settings isn't gated: the user typed it, +// is omitted or already open, and no repo setupCommand (or the one the +// user last allowed for that repo, see isSetupCommandApproved); otherwise +// it asks. Allowing one of those prompts remembers that repo's command, +// so only a changed command asks again. The global setup command from Settings isn't gated: the user typed it, // and gating it would prompt on every worktree for anyone who set one. // - create_worktree and send_message start or message other agents with // text the calling agent wrote. They are auto-allowed because @@ -128,6 +130,9 @@ export interface NessCallContext { * means the caller's own repo): '' when none, null when it can't be * determined. Absent means unknown, so create_worktree asks. */ repoSetupCommandFor?: (repoRoot: string | undefined) => string | null + /** True when the user already allowed `command` to run for `repoRoot` + * (undefined = the caller's own repo). Absent means nothing is approved. */ + isSetupCommandApproved?: (repoRoot: string | undefined, command: string) => boolean /** True when `repoRoot` is a repo already open in Ness. Absent means * unknown, so a create_worktree naming a repoRoot asks. */ isOpenRepo?: (repoRoot: string) => boolean @@ -155,7 +160,9 @@ export function isAutoAllowedNessCall( if (rawRoot !== undefined && typeof rawRoot !== 'string') return false const repoRoot = rawRoot === undefined || rawRoot === '' ? undefined : rawRoot if (repoRoot !== undefined && ctx.isOpenRepo?.(repoRoot) !== true) return false - return ctx.repoSetupCommandFor?.(repoRoot) === '' + const command = ctx.repoSetupCommandFor?.(repoRoot) + if (command === '') return true + return typeof command === 'string' && ctx.isSetupCommandApproved?.(repoRoot, command) === true } if (!URL_GATED_TOOLS.has(bare)) return true const url = input['url'] diff --git a/src/shared/state/permissions.test.ts b/src/shared/state/permissions.test.ts index f3fef6828..274a8e68a 100644 --- a/src/shared/state/permissions.test.ts +++ b/src/shared/state/permissions.test.ts @@ -147,4 +147,48 @@ describe('permissionsReducer', () => { permissionsReducer(initialPermissions, { type: 'permissions/cleared' }) ).toBe(initialPermissions) }) + + it('setupCommandApproved records the command per repo and replaces it', () => { + const a = apply(initialPermissions, { + type: 'permissions/setupCommandApproved', + payload: { repoRoot: '/r', command: 'npm install' } + }) + expect(a.approvedSetupCommands).toEqual({ '/r': 'npm install' }) + const b = apply(a, { + type: 'permissions/setupCommandApproved', + payload: { repoRoot: '/r', command: 'npm ci' } + }) + expect(b.approvedSetupCommands).toEqual({ '/r': 'npm ci' }) + expect( + permissionsReducer(b, { + type: 'permissions/setupCommandApproved', + payload: { repoRoot: '/r', command: 'npm ci' } + }) + ).toBe(b) + }) + + it('cleared also forgets approved setup commands', () => { + const seeded = apply(initialPermissions, { + type: 'permissions/setupCommandApproved', + payload: { repoRoot: '/r', command: 'npm install' } + }) + expect(apply(seeded, { type: 'permissions/cleared' })).toEqual(initialPermissions) + }) + + it('setupCommandForgotten drops one repo and ignores unknown ones', () => { + const seeded = apply(initialPermissions, { + type: 'permissions/setupCommandApproved', + payload: { repoRoot: '/r', command: 'npm install' } + }) + expect( + apply(seeded, { type: 'permissions/setupCommandForgotten', payload: { repoRoot: '/r' } }) + .approvedSetupCommands + ).toEqual({}) + expect( + permissionsReducer(seeded, { + type: 'permissions/setupCommandForgotten', + payload: { repoRoot: '/other' } + }) + ).toBe(seeded) + }) }) diff --git a/src/shared/state/permissions.ts b/src/shared/state/permissions.ts index 433248c5d..0bb37755a 100644 --- a/src/shared/state/permissions.ts +++ b/src/shared/state/permissions.ts @@ -24,10 +24,16 @@ export interface PermissionsState { /** Insertion-ordered. The matcher short-circuits on the first hit, so * order is observable only in which rule gets attributed in the log. */ rules: StoredPermissionRule[] + /** repoRoot → the .ness.json setupCommand the user last allowed an + * agent's create_worktree to run there. While the repo's command still + * equals this, create_worktree runs without asking; once it changes, the + * next one asks again. See shared/ness-tool-policy.ts. */ + approvedSetupCommands: Record } export const initialPermissions: PermissionsState = { - rules: [] + rules: [], + approvedSetupCommands: {} } export type PermissionsEvent = @@ -35,6 +41,8 @@ export type PermissionsEvent = | { type: 'permissions/granted'; payload: { rule: StoredPermissionRule } } | { type: 'permissions/revoked'; payload: { id: string } } | { type: 'permissions/cleared' } + | { type: 'permissions/setupCommandApproved'; payload: { repoRoot: string; command: string } } + | { type: 'permissions/setupCommandForgotten'; payload: { repoRoot: string } } export function permissionsReducer( state: PermissionsState, @@ -62,8 +70,26 @@ export function permissionsReducer( } } case 'permissions/cleared': - if (state.rules.length === 0) return state - return { ...state, rules: [] } + // Clearing every grant also forgets approved setup commands: both are + // "run this without asking me". + if (state.rules.length === 0 && Object.keys(state.approvedSetupCommands).length === 0) { + return state + } + return { rules: [], approvedSetupCommands: {} } + case 'permissions/setupCommandApproved': { + const { repoRoot, command } = event.payload + if (state.approvedSetupCommands[repoRoot] === command) return state + return { + ...state, + approvedSetupCommands: { ...state.approvedSetupCommands, [repoRoot]: command } + } + } + case 'permissions/setupCommandForgotten': { + if (!(event.payload.repoRoot in state.approvedSetupCommands)) return state + const { [event.payload.repoRoot]: _dropped, ...rest } = state.approvedSetupCommands + void _dropped + return { ...state, approvedSetupCommands: rest } + } default: { const _exhaustive: never = event void _exhaustive From f2ae80e9190ef887b56c0718115ff0fe31ae9f8f Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Wed, 25 Nov 2026 19:05:56 -0500 Subject: [PATCH 2/6] Permissions: keep approved setup commands on 'Remove all' The Settings button that sends permissions/cleared is labelled with the grant count, so wiping approved setup commands too was a side effect it didn't promise. Commands are forgotten per repo instead. Co-Authored-By: Claude Opus 5.5 --- src/shared/state/permissions.test.ts | 18 ++++++++++++------ src/shared/state/permissions.ts | 11 +++++------ 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/src/shared/state/permissions.test.ts b/src/shared/state/permissions.test.ts index 274a8e68a..4cdd6350e 100644 --- a/src/shared/state/permissions.test.ts +++ b/src/shared/state/permissions.test.ts @@ -167,12 +167,18 @@ describe('permissionsReducer', () => { ).toBe(b) }) - it('cleared also forgets approved setup commands', () => { - const seeded = apply(initialPermissions, { - type: 'permissions/setupCommandApproved', - payload: { repoRoot: '/r', command: 'npm install' } - }) - expect(apply(seeded, { type: 'permissions/cleared' })).toEqual(initialPermissions) + it('cleared removes grants but keeps approved setup commands', () => { + const seeded = apply( + initialPermissions, + { type: 'permissions/granted', payload: { rule: rule('Read') } }, + { + type: 'permissions/setupCommandApproved', + payload: { repoRoot: '/r', command: 'npm install' } + } + ) + const cleared = apply(seeded, { type: 'permissions/cleared' }) + expect(cleared.rules).toEqual([]) + expect(cleared.approvedSetupCommands).toEqual({ '/r': 'npm install' }) }) it('setupCommandForgotten drops one repo and ignores unknown ones', () => { diff --git a/src/shared/state/permissions.ts b/src/shared/state/permissions.ts index 0bb37755a..09825cd0d 100644 --- a/src/shared/state/permissions.ts +++ b/src/shared/state/permissions.ts @@ -70,12 +70,11 @@ export function permissionsReducer( } } case 'permissions/cleared': - // Clearing every grant also forgets approved setup commands: both are - // "run this without asking me". - if (state.rules.length === 0 && Object.keys(state.approvedSetupCommands).length === 0) { - return state - } - return { rules: [], approvedSetupCommands: {} } + // Grants only: the Settings button that sends this is labelled with + // the grant count. Approved setup commands are forgotten one repo at + // a time (setupCommandForgotten). + if (state.rules.length === 0) return state + return { ...state, rules: [] } case 'permissions/setupCommandApproved': { const { repoRoot, command } = event.payload if (state.approvedSetupCommands[repoRoot] === command) return state From 942f1a568ab8401e38d14644dc227fab599bef9d Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Wed, 25 Nov 2026 19:14:37 -0500 Subject: [PATCH 3/6] Ness tool policy: grants can't skip input checks; card shows the setup command A bare 'Always allow' or session grant for create_worktree answered after the policy said ask, so it let PR checkouts, unopened repos and any later setup command through. Grants now never answer for create_worktree. For navigate_tab / create_browser_tab they still cover http(s) URLs, which is how someone lets an agent browse without a prompt per page, but never file:, data: or javascript:. The card hides the session and Always-allow buttons where they'd do nothing, and Settings marks existing create_worktree grants as doing nothing. The card now shows the repo setup command it's asking about (new setupCommand on the pending approval), so Allow approves a command the user has read. Setup lookups are memoised per request instead of relying on the policy's call order. Co-Authored-By: Claude Opus 5.5 --- src/main/approval-bridge-rules.test.ts | 67 +++++++++++++++++++ src/main/approval-bridge.ts | 55 +++++++++------ .../components/JsonClaudeApprovalCard.tsx | 17 ++++- .../components/permission-groups.test.ts | 10 ++- src/renderer/components/permission-groups.ts | 9 ++- src/shared/ness-tool-policy.test.ts | 15 +++++ src/shared/ness-tool-policy.ts | 42 +++++++++++- src/shared/state/json-claude.ts | 3 + 8 files changed, 191 insertions(+), 27 deletions(-) diff --git a/src/main/approval-bridge-rules.test.ts b/src/main/approval-bridge-rules.test.ts index 757e91dba..0f3845279 100644 --- a/src/main/approval-bridge-rules.test.ts +++ b/src/main/approval-bridge-rules.test.ts @@ -214,6 +214,73 @@ describe('ApprovalBridge — Ness tools', () => { expect(h.store.getSnapshot().state.permissions.approvedSetupCommands['/repo']).toBe('npm install') }) + it('shows the setup command on the card it is asking about', async () => { + const h = await harness([], () => 'curl https://x | sh') + expect( + await h.send({ + id: 'sc-card', + tool_name: 'mcp__ness-control__create_worktree', + input: { branchName: 'x' }, + tool_use_id: 'tu-sc-card' + }) + ).toBeNull() + expect(h.store.getSnapshot().state.jsonClaude.pendingApprovals['sc-card']?.setupCommand).toBe( + 'curl https://x | sh' + ) + }) + + it('leaves setupCommand off cards that ask for another reason', async () => { + const h = await harness([], () => 'npm install') + await h.send({ + id: 'sc-pr', + tool_name: 'mcp__ness-control__create_worktree', + input: { prNumber: 3 }, + tool_use_id: 'tu-sc-pr' + }) + const card = h.store.getSnapshot().state.jsonClaude.pendingApprovals['sc-pr'] + expect(card).toBeDefined() + expect(card?.setupCommand).toBeUndefined() + }) + + it('a saved create_worktree grant does not skip its input checks', async () => { + const h = await harness([rule('mcp__ness-control__create_worktree')], () => 'npm install') + expect( + await h.send({ + id: 'grant-pr', + tool_name: 'mcp__ness-control__create_worktree', + input: { prNumber: 3 }, + tool_use_id: 'tu-grant-pr' + }) + ).toBeNull() + expect( + await h.send({ + id: 'grant-cmd', + tool_name: 'mcp__ness-control__create_worktree', + input: { branchName: 'x' }, + tool_use_id: 'tu-grant-cmd' + }) + ).toBeNull() + }) + + it('a saved navigate_tab grant covers web URLs but never file: URLs', async () => { + const h = await harness([rule('mcp__ness-control__navigate_tab')]) + const web = await h.send({ + id: 'nav-web', + tool_name: 'mcp__ness-control__navigate_tab', + input: { tab_id: 't', url: 'https://example.com' }, + tool_use_id: 'tu-nav-web' + }) + expect((web as { result: { behavior: string } }).result.behavior).toBe('allow') + expect( + await h.send({ + id: 'nav-file', + tool_name: 'mcp__ness-control__navigate_tab', + input: { tab_id: 't', url: 'file:///Users/me/.ssh/id_rsa' }, + tool_use_id: 'tu-nav-file' + }) + ).toBeNull() + }) + it('does not remember a setup command the user denied', async () => { const h = await harness([], () => 'npm install') expect( diff --git a/src/main/approval-bridge.ts b/src/main/approval-bridge.ts index 5f381b0eb..24774933f 100644 --- a/src/main/approval-bridge.ts +++ b/src/main/approval-bridge.ts @@ -35,7 +35,7 @@ import { log } from './debug' import { autoReview, checkDenyList } from './auto-approver' import type { AutoReviewStatus } from '../shared/state/json-claude' import { findMatchingRule, ruleKey } from '../shared/permission-match' -import { isAutoAllowedNessCall } from '../shared/ness-tool-policy' +import { isAutoAllowedNessCall, nessGrantsMayAnswer } from '../shared/ness-tool-policy' export interface ApprovalResult { behavior: 'allow' | 'deny' @@ -420,24 +420,29 @@ export class ApprovalBridge { // a human; see shared/ness-tool-policy.ts for what's excluded and why. // No approvalSessionAllowed dispatch either: these calls fire every // turn, and an "auto-allowed" chip on each would be noise. + // Resolve each repoRoot's setup command once per request, so the + // policy check, the remembered-command check and the card all see the + // same snapshot. const repoSetupFor = this.deps?.repoSetupFor - let setup: { repoRoot: string; command: string } | null = null + const setups = new Map() + const setupFor = (repoRoot: string | undefined): { repoRoot: string; command: string } | null => { + const key = repoRoot ?? '' + if (!setups.has(key)) setups.set(key, repoSetupFor?.(basePayload.sessionId, repoRoot) ?? null) + return setups.get(key) ?? null + } + const approved = this.store.getSnapshot().state.permissions.approvedSetupCommands const nessCtx = { repoSetupCommandFor: repoSetupFor - ? (repoRoot: string | undefined): string | null => { - setup = repoSetupFor(basePayload.sessionId, repoRoot) - return setup?.command ?? null - } + ? (repoRoot: string | undefined): string | null => setupFor(repoRoot)?.command ?? null : undefined, isOpenRepo: this.deps?.isOpenRepo } - const approved = this.store.getSnapshot().state.permissions.approvedSetupCommands if ( isAutoAllowedNessCall(basePayload.toolName, basePayload.input, { ...nessCtx, - isSetupCommandApproved: () => { - const s = setup as { repoRoot: string; command: string } | null - return s !== null && approved[s.repoRoot] === s.command + isSetupCommandApproved: (repoRoot, command) => { + const resolved = setupFor(repoRoot) + return resolved !== null && approved[resolved.repoRoot] === command } }) ) { @@ -448,6 +453,10 @@ export class ApprovalBridge { ) return } + // The policy said ask. For an input-gated Ness tool, a bare saved or + // session-wide grant mustn't overrule that wholesale; see + // nessGrantsMayAnswer for what it may still cover. + const grantsApply = !isQuestion && nessGrantsMayAnswer(basePayload.toolName, basePayload.input) // Two explicit-user-grant paths, both checked before the LLM // auto-reviewer because a grant the user made by hand is cheaper and @@ -459,7 +468,7 @@ export class ApprovalBridge { // is what this replaced. // 2. The session-scoped set ("Allow {tool} this session"). const rootState = this.store.getSnapshot().state - if (!isQuestion) { + if (grantsApply) { const matched = findMatchingRule( rootState.permissions.rules, basePayload.toolName, @@ -478,7 +487,7 @@ export class ApprovalBridge { const slice = rootState.jsonClaude const session = slice.sessions[basePayload.sessionId] - if (!isQuestion && session?.sessionToolApprovals.includes(basePayload.toolName)) { + if (grantsApply && session?.sessionToolApprovals.includes(basePayload.toolName)) { this.resolveAllowed(respond, basePayload) log( 'approval-bridge', @@ -502,19 +511,25 @@ export class ApprovalBridge { : { state: 'pending' } } - const payload: JsonClaudePendingApproval = { ...basePayload, autoReview } // Would this call have gone through with its setup command approved? - // Then the command is the only thing the user is being asked about. - const pendingSetup = setup as { repoRoot: string; command: string } | null - const approvesSetup = - pendingSetup && - pendingSetup.command !== '' && + // Then the command is the only thing the user is being asked about, + // so the card shows it and allowing remembers it. + let approvesSetup: { repoRoot: string; command: string } | undefined + if ( isAutoAllowedNessCall(basePayload.toolName, basePayload.input, { ...nessCtx, isSetupCommandApproved: () => true }) - ? pendingSetup - : undefined + ) { + const rawRoot = basePayload.input['repoRoot'] + const resolved = setupFor(typeof rawRoot === 'string' && rawRoot ? rawRoot : undefined) + if (resolved && resolved.command) approvesSetup = resolved + } + const payload: JsonClaudePendingApproval = { + ...basePayload, + autoReview, + ...(approvesSetup ? { setupCommand: approvesSetup.command } : {}) + } this.pendingResponses.set(payload.requestId, { respond, socket, diff --git a/src/renderer/components/JsonClaudeApprovalCard.tsx b/src/renderer/components/JsonClaudeApprovalCard.tsx index ac7d2f5c9..8e6f2eca2 100644 --- a/src/renderer/components/JsonClaudeApprovalCard.tsx +++ b/src/renderer/components/JsonClaudeApprovalCard.tsx @@ -14,6 +14,7 @@ import { useJsonClaudeSession, useSettings } from '../store' import { useBackend } from '../backend' import { useViewport } from '../hooks/useViewport' import { getChatCapabilities } from '../../shared/agent-registry' +import { nessGrantsMayAnswer } from '../../shared/ness-tool-policy' import { suggestPermissionPatterns, type PermissionPatternSuggestion @@ -112,6 +113,10 @@ export function JsonClaudeApprovalCard({ const display = useMemo(() => getToolDisplay(approval.toolName), [approval.toolName]) const parsedArgs = useMemo(() => extractArgs(approval.input), [approval.input]) + // Ness ignores saved and session grants for some of its own tools' + // calls (see nessGrantsMayAnswer), so those buttons would promise nothing. + const inputGated = !nessGrantsMayAnswer(approval.toolName, approval.input) + const session = useJsonClaudeSession(approval.sessionId) const cwd = session?.worktreePath const chatCaps = getChatCapabilities(session?.agentKind) @@ -329,6 +334,14 @@ export function JsonClaudeApprovalCard({ {mode === 'summary' && (
+ {approval.setupCommand && ( +
+
Runs this repo's setup command:
+
+                {approval.setupCommand}
+              
+
+ )} {approval.toolName === 'Bash' && typeof approval.input?.command === 'string' ? (
@@ -357,7 +370,7 @@ export function JsonClaudeApprovalCard({ Allow once {approveHotkeyLabel} - {!alreadyGranted && ( + {!alreadyGranted && !inputGated && ( )} + {!inputGated && ( + )} +
+ ))} +
+ + ) +} diff --git a/src/renderer/components/Settings.tsx b/src/renderer/components/Settings.tsx index 7c105254b..067ea842b 100644 --- a/src/renderer/components/Settings.tsx +++ b/src/renderer/components/Settings.tsx @@ -8,7 +8,8 @@ import { useRepoConfigs, useRepoConfigFilename, useHooks, - usePermissionRules + usePermissionRules, + useApprovedSetupCommands } from '../store' import { useBackend } from '../backend' import type { ReviewAgentChoice } from '../../shared/state/settings' @@ -20,7 +21,7 @@ import { Tooltip } from './Tooltip' import { HotkeyBadge } from './HotkeyBadge' import { AGENT_REGISTRY, agentDisplayName, CLAUDE_MODELS, CODEX_MODELS, CURSOR_MODELS } from '../../shared/agent-registry' import { AgentIcon } from './AgentIcon' -import { PermissionRulesList } from './PermissionRulesList' +import { ApprovedSetupCommandsList, PermissionRulesList } from './PermissionRulesList' import { LochRecordingRepos } from './LochRecordingRepos' import { InterfaceToggle } from './InterfaceToggle' import { BUILT_IN_THEMES_BY_MODE, type ThemeOption } from '../themes' @@ -360,6 +361,7 @@ export function Settings({ onClose, onOpenGuide, onOpenMyWeek, initialSection }: // re-renders Settings whenever any client updates any of them. const settings = useSettings() const permissionRules = usePermissionRules() + const approvedSetupCommands = useApprovedSetupCommands() const { themeMode, themeLight, @@ -2726,6 +2728,10 @@ export function Settings({ onClose, onOpenGuide, onOpenMyWeek, initialSection }: onRevokeMany={(ids) => { void backend.revokePermissions(ids) }} onClear={() => { void backend.clearPermissions() }} /> + { void backend.forgetSetupCommand(repoRoot) }} + /> diff --git a/src/renderer/store.ts b/src/renderer/store.ts index 0f7df932e..136f5f931 100644 --- a/src/renderer/store.ts +++ b/src/renderer/store.ts @@ -1439,6 +1439,11 @@ export function usePermissionRules() { return useAppState((s) => s.permissions.rules) } +/** repoRoot → approved .ness.json setup command; Settings only. */ +export function useApprovedSetupCommands() { + return useAppState((s) => s.permissions.approvedSetupCommands) +} + export function useBrowser() { return useAppState((s) => s.browser) } From e2d838d429f55d541c32c0285db01818f106e067 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Wed, 25 Nov 2026 19:20:23 -0500 Subject: [PATCH 5/6] Approval card: show the setup command whenever create_worktree would run one PR-checkout and unopened-repo cards also run the repo's .ness.json setup command on Allow, but only showed it when the command was the sole reason to ask. Show it on every create_worktree card; remembering it is still limited to the sole-reason case. Documents the edit-while-open race in the policy header. Co-Authored-By: Claude Opus 5.5 --- src/main/approval-bridge-rules.test.ts | 38 ++++++++++++++++++++------ src/main/approval-bridge.ts | 28 +++++++++++++------ src/shared/ness-tool-policy.ts | 6 +++- src/shared/state/json-claude.ts | 2 +- 4 files changed, 54 insertions(+), 20 deletions(-) diff --git a/src/main/approval-bridge-rules.test.ts b/src/main/approval-bridge-rules.test.ts index 0f3845279..9e67db5b8 100644 --- a/src/main/approval-bridge-rules.test.ts +++ b/src/main/approval-bridge-rules.test.ts @@ -229,17 +229,37 @@ describe('ApprovalBridge — Ness tools', () => { ) }) - it('leaves setupCommand off cards that ask for another reason', async () => { + it('shows the setup command on a PR-checkout card but does not remember it', async () => { const h = await harness([], () => 'npm install') - await h.send({ - id: 'sc-pr', - tool_name: 'mcp__ness-control__create_worktree', - input: { prNumber: 3 }, - tool_use_id: 'tu-sc-pr' - }) + expect( + await h.send({ + id: 'sc-pr', + tool_name: 'mcp__ness-control__create_worktree', + input: { prNumber: 3 }, + tool_use_id: 'tu-sc-pr' + }) + ).toBeNull() const card = h.store.getSnapshot().state.jsonClaude.pendingApprovals['sc-pr'] - expect(card).toBeDefined() - expect(card?.setupCommand).toBeUndefined() + expect(card?.setupCommand).toBe('npm install') + h.bridge.resolveApproval('sc-pr', { behavior: 'allow' }) + expect(h.store.getSnapshot().state.permissions.approvedSetupCommands).toEqual({}) + }) + + it('shows the setup command for a repo that is not open in Ness', async () => { + const h = await harness([], () => 'make bootstrap') + expect( + await h.send({ + id: 'sc-clone', + tool_name: 'mcp__ness-control__create_worktree', + input: { branchName: 'x', repoRoot: '/Users/me/Downloads/clone' }, + tool_use_id: 'tu-sc-clone' + }) + ).toBeNull() + expect( + h.store.getSnapshot().state.jsonClaude.pendingApprovals['sc-clone']?.setupCommand + ).toBe('make bootstrap') + h.bridge.resolveApproval('sc-clone', { behavior: 'allow' }) + expect(h.store.getSnapshot().state.permissions.approvedSetupCommands).toEqual({}) }) it('a saved create_worktree grant does not skip its input checks', async () => { diff --git a/src/main/approval-bridge.ts b/src/main/approval-bridge.ts index 24774933f..36bf13617 100644 --- a/src/main/approval-bridge.ts +++ b/src/main/approval-bridge.ts @@ -35,7 +35,11 @@ import { log } from './debug' import { autoReview, checkDenyList } from './auto-approver' import type { AutoReviewStatus } from '../shared/state/json-claude' import { findMatchingRule, ruleKey } from '../shared/permission-match' -import { isAutoAllowedNessCall, nessGrantsMayAnswer } from '../shared/ness-tool-policy' +import { + isAutoAllowedNessCall, + nessControlToolName, + nessGrantsMayAnswer +} from '../shared/ness-tool-policy' export interface ApprovalResult { behavior: 'allow' | 'deny' @@ -514,21 +518,27 @@ export class ApprovalBridge { // Would this call have gone through with its setup command approved? // Then the command is the only thing the user is being asked about, // so the card shows it and allowing remembers it. - let approvesSetup: { repoRoot: string; command: string } | undefined - if ( + // Any create_worktree card shows the repo setup command that Allow + // would run, whatever else it's asking about (a PR checkout or an + // unopened clone runs it too). Remembering it is narrower: only when + // the command was the sole reason to ask. + let shownSetup: { repoRoot: string; command: string } | null = null + if (nessControlToolName(basePayload.toolName) === 'create_worktree') { + const rawRoot = basePayload.input['repoRoot'] + shownSetup = setupFor(typeof rawRoot === 'string' && rawRoot ? rawRoot : undefined) + } + const approvesSetup = + shownSetup?.command && isAutoAllowedNessCall(basePayload.toolName, basePayload.input, { ...nessCtx, isSetupCommandApproved: () => true }) - ) { - const rawRoot = basePayload.input['repoRoot'] - const resolved = setupFor(typeof rawRoot === 'string' && rawRoot ? rawRoot : undefined) - if (resolved && resolved.command) approvesSetup = resolved - } + ? shownSetup + : undefined const payload: JsonClaudePendingApproval = { ...basePayload, autoReview, - ...(approvesSetup ? { setupCommand: approvesSetup.command } : {}) + ...(shownSetup?.command ? { setupCommand: shownSetup.command } : {}) } this.pendingResponses.set(payload.requestId, { respond, diff --git a/src/shared/ness-tool-policy.ts b/src/shared/ness-tool-policy.ts index 0500a60cc..9057d2be1 100644 --- a/src/shared/ness-tool-policy.ts +++ b/src/shared/ness-tool-policy.ts @@ -36,7 +36,11 @@ // is omitted or already open, and no repo setupCommand (or the one the // user last allowed for that repo, see isSetupCommandApproved); otherwise // it asks. Allowing one of those prompts remembers that repo's command, -// so only a changed command asks again. The global setup command from Settings isn't gated: the user typed it, +// so only a changed command asks again. Known gap: the card shows the +// command as it was when the card opened, but worktree creation re-reads +// .ness.json after Allow, so an edit made while the card is open runs +// once unseen (the next call then asks, since it differs from the +// remembered one). The global setup command from Settings isn't gated: the user typed it, // and gating it would prompt on every worktree for anyone who set one. // - create_worktree and send_message start or message other agents with // text the calling agent wrote. They are auto-allowed because diff --git a/src/shared/state/json-claude.ts b/src/shared/state/json-claude.ts index 497b3c742..9a7796a97 100644 --- a/src/shared/state/json-claude.ts +++ b/src/shared/state/json-claude.ts @@ -580,7 +580,7 @@ export interface JsonClaudePendingApproval { timestamp: number autoReview?: AutoReviewStatus /** create_worktree only: the repo's .ness.json setupCommand this call - * would run, set when that command is the only reason it asks. */ + * would run, whatever the card is asking about. */ setupCommand?: string } From 221ef48c61c5e464513ea560124588cee9b9f9b2 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Wed, 25 Nov 2026 19:27:41 -0500 Subject: [PATCH 6/6] Approval bridge: drop a stale comment line Co-Authored-By: Claude Opus 5.5 --- src/main/approval-bridge.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/approval-bridge.ts b/src/main/approval-bridge.ts index 36bf13617..75bcd15a2 100644 --- a/src/main/approval-bridge.ts +++ b/src/main/approval-bridge.ts @@ -515,9 +515,6 @@ export class ApprovalBridge { : { state: 'pending' } } - // Would this call have gone through with its setup command approved? - // Then the command is the only thing the user is being asked about, - // so the card shows it and allowing remembers it. // Any create_worktree card shows the repo setup command that Allow // would run, whatever else it's asking about (a PR checkout or an // unopened clone runs it too). Remembering it is narrower: only when