diff --git a/src/main/approval-bridge-rules.test.ts b/src/main/approval-bridge-rules.test.ts index f20c2865..9e67db5b 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,134 @@ 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('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('shows the setup command on a PR-checkout card but does not remember it', async () => { + const h = await harness([], () => 'npm install') + 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?.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 () => { + 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( + 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 ea9b8b0f..75bcd15a 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 } from '../shared/ness-tool-policy' +import { + isAutoAllowedNessCall, + nessControlToolName, + nessGrantsMayAnswer +} from '../shared/ness-tool-policy' export interface ApprovalResult { behavior: 'allow' | 'deny' @@ -66,6 +70,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 +94,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 +259,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 +424,30 @@ 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 + // 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 + 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 => setupFor(repoRoot)?.command ?? null + : undefined, + isOpenRepo: this.deps?.isOpenRepo + } if ( isAutoAllowedNessCall(basePayload.toolName, basePayload.input, { - repoSetupCommandFor: repoSetupCommandFor - ? (repoRoot) => repoSetupCommandFor(basePayload.sessionId, repoRoot) - : undefined, - isOpenRepo: this.deps?.isOpenRepo + ...nessCtx, + isSetupCommandApproved: (repoRoot, command) => { + const resolved = setupFor(repoRoot) + return resolved !== null && approved[resolved.repoRoot] === command + } }) ) { respond({ behavior: 'allow', updatedInput: basePayload.input }) @@ -421,6 +457,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 @@ -432,7 +472,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, @@ -451,7 +491,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', @@ -475,12 +515,34 @@ export class ApprovalBridge { : { state: 'pending' } } - const payload: JsonClaudePendingApproval = { ...basePayload, autoReview } + // 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 + }) + ? shownSetup + : undefined + const payload: JsonClaudePendingApproval = { + ...basePayload, + autoReview, + ...(shownSetup?.command ? { setupCommand: shownSetup.command } : {}) + } 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 95e87d52..e17e1720 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 98a67e4a..42c671e0 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 67e45372..43a91bf3 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -498,12 +498,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(/\/+$/, '') @@ -1603,7 +1609,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) } @@ -3379,6 +3387,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 5c506468..144be1a0 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 f4fd3ca4..34f1bf2a 100644 --- a/src/renderer/build-backend.ts +++ b/src/renderer/build-backend.ts @@ -375,6 +375,7 @@ export function buildBackend( revokePermission: (id: string) => req('permissions:revoke', id), revokePermissions: (ids: string[]) => req('permissions:revokeMany', ids), 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/components/JsonClaudeApprovalCard.tsx b/src/renderer/components/JsonClaudeApprovalCard.tsx index ac7d2f5c..8e6f2eca 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 7c105254..067ea842 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/components/permission-groups.test.ts b/src/renderer/components/permission-groups.test.ts index 1b261b81..71eee39f 100644 --- a/src/renderer/components/permission-groups.test.ts +++ b/src/renderer/components/permission-groups.test.ts @@ -196,15 +196,19 @@ describe('redundantRules', () => { // Without the grant, a non-loopback URL prompts; with it, it doesn't. expect(redundancy(rule('mcp__ness-control__navigate_tab'))).toBeNull() expect(redundancy(rule('mcp__ness-control__create_browser_tab'))).toBeNull() - // Same for create_worktree (a grant skips the setup-script check) and - // add_repo (always asks without one). - expect(redundancy(rule('mcp__ness-control__create_worktree'))).toBeNull() + // add_repo always asks without one. expect(redundancy(rule('mcp__ness-control__add_repo'))).toBeNull() // Under the old server name they can't match any call, so they're dead. expect(redundancy(rule('mcp__harness-control__navigate_tab'))).toBe('old-name') }) }) +describe('redundancy for create_worktree', () => { + it('flags create_worktree grants, which Ness ignores', () => { + expect(redundancy(rule('mcp__ness-control__create_worktree'))).toBe('input-checked') + }) +}) + describe('filterGroups', () => { const groups = groupPermissionRules(REALISTIC) const label = (r: StoredPermissionRule): string => r.toolName diff --git a/src/renderer/components/permission-groups.ts b/src/renderer/components/permission-groups.ts index d9ff92ba..446190d8 100644 --- a/src/renderer/components/permission-groups.ts +++ b/src/renderer/components/permission-groups.ts @@ -11,7 +11,7 @@ // filter state. import { ruleKey, type StoredPermissionRule } from '../../shared/permission-match' -import { isAlwaysAutoAllowedNessTool } from '../../shared/ness-tool-policy' +import { isAlwaysAutoAllowedNessTool, isGrantIgnoredNessTool } from '../../shared/ness-tool-policy' import { getMcpServerDisplay, parseMcpToolName } from './json-mode-cards/tool-display' /** At or below this many grants the list renders flat, as before. */ @@ -184,9 +184,14 @@ const LEGACY_NESS_PREFIX = 'mcp__harness-control__' * registers `harness-control` any more, so those can never match, even * for the input-gated tools (browser navigation, create_worktree) that a * `ness-control` grant would still widen. */ -export function redundancy(rule: StoredPermissionRule): 'built-in' | 'old-name' | null { +export function redundancy( + rule: StoredPermissionRule +): 'built-in' | 'old-name' | 'input-checked' | null { if (rule.toolName.startsWith(LEGACY_NESS_PREFIX)) return 'old-name' if (isAlwaysAutoAllowedNessTool(rule.toolName)) return 'built-in' + // Ness decides these from their input and ignores saved grants for them + // (create_worktree). The URL-gated tools still honour grants for http(s). + if (isGrantIgnoredNessTool(rule.toolName)) return 'input-checked' return null } diff --git a/src/renderer/store.ts b/src/renderer/store.ts index 0f7df932..136f5f93 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) } diff --git a/src/renderer/types.ts b/src/renderer/types.ts index c10c8759..b4935123 100644 --- a/src/renderer/types.ts +++ b/src/renderer/types.ts @@ -467,6 +467,7 @@ export interface ElectronAPI { revokePermission(id: string): Promise revokePermissions(ids: 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 5e589cdf..3b67dcd3 100644 --- a/src/shared/ness-tool-policy.test.ts +++ b/src/shared/ness-tool-policy.test.ts @@ -7,6 +7,7 @@ import { isAlwaysAutoAllowedNessTool, isAutoAllowedNessCall, isSafeAgentUrl, + nessGrantsMayAnswer, nessAllowedToolsFlagValue, nessControlToolName } from './ness-tool-policy' @@ -118,6 +119,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' @@ -132,4 +145,18 @@ describe('ness tool policy', () => { // Without an isOpenRepo answer, a named repoRoot can't be vetted. expect(isAutoAllowedNessCall(cw, { branchName: 'b', repoRoot: '/r' }, { repoSetupCommandFor: () => '' })).toBe(false) }) + + it('lets grants answer only where an input check would not be skipped', () => { + const cw = 'mcp__ness-control__create_worktree' + const nav = 'mcp__ness-control__navigate_tab' + expect(nessGrantsMayAnswer(cw, { branchName: 'b' })).toBe(false) + expect(nessGrantsMayAnswer(nav, { url: 'https://example.com' })).toBe(true) + expect(nessGrantsMayAnswer(nav, { url: 'github.com' })).toBe(true) + expect(nessGrantsMayAnswer(nav, { url: 'file:///etc/passwd' })).toBe(false) + expect(nessGrantsMayAnswer(nav, { url: 'javascript:alert(1)' })).toBe(false) + expect(nessGrantsMayAnswer(nav, {})).toBe(false) + expect(nessGrantsMayAnswer('mcp__ness-control__create_browser_tab', {})).toBe(true) + expect(nessGrantsMayAnswer('Bash', { command: 'ls' })).toBe(true) + expect(nessGrantsMayAnswer('mcp__ness-control__eval_tab', {})).toBe(true) + }) }) diff --git a/src/shared/ness-tool-policy.ts b/src/shared/ness-tool-policy.ts index e435129a..9057d2be 100644 --- a/src/shared/ness-tool-policy.ts +++ b/src/shared/ness-tool-policy.ts @@ -33,8 +33,14 @@ // .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. 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 @@ -128,6 +134,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 +164,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'] @@ -170,7 +181,47 @@ export function isAutoAllowedNessCall( * agent load arbitrary URLs or create a worktree that runs a setup script. */ export function isAlwaysAutoAllowedNessTool(toolName: string): boolean { const bare = nessControlToolName(toolName) - return bare !== null && AUTO_ALLOWED.has(bare) && !URL_GATED_TOOLS.has(bare) && bare !== 'create_worktree' + return bare !== null && AUTO_ALLOWED.has(bare) && !isInputGatedNessTool(toolName) +} + +/** Ness tools whose approval depends on their input (the URL-gated tools + * and create_worktree). */ +export function isInputGatedNessTool(toolName: string): boolean { + const bare = nessControlToolName(toolName) + return bare !== null && (URL_GATED_TOOLS.has(bare) || bare === 'create_worktree') +} + +/** A Ness tool no saved or session grant ever answers for, whatever the + * call's input. */ +export function isGrantIgnoredNessTool(toolName: string): boolean { + return nessControlToolName(toolName) === 'create_worktree' +} + +/** Whether a saved ("Always allow") or session-wide grant may answer a + * call that isAutoAllowedNessCall said to ask about. A bare grant has no + * input of its own, so for input-gated tools it would otherwise skip every + * input check from then on: + * - create_worktree: never. A grant would let prNumber checkouts, unopened + * repos and any later setup command through. + * - navigate_tab / create_browser_tab: only for http(s) URLs. A grant is + * how someone lets an agent browse real sites without a prompt per page, + * but it must never open file:, data: or javascript: URLs. + * Everything else: yes. */ +export function nessGrantsMayAnswer(toolName: string, input: Record): boolean { + const bare = nessControlToolName(toolName) + if (bare === null || !isInputGatedNessTool(toolName)) return true + if (isGrantIgnoredNessTool(toolName)) return false + const url = input['url'] + if (url === undefined && bare === 'create_browser_tab') return true + if (typeof url !== 'string') return false + const normalized = normalizeBrowserUrl(url) + if (normalized === null) return false + try { + const { protocol } = new URL(normalized) + return protocol === 'http:' || protocol === 'https:' + } catch { + return false + } } /** Value for Claude's `--allowedTools`, for terminal tabs where Claude diff --git a/src/shared/state/json-claude.ts b/src/shared/state/json-claude.ts index f047697e..9a7796a9 100644 --- a/src/shared/state/json-claude.ts +++ b/src/shared/state/json-claude.ts @@ -579,6 +579,9 @@ export interface JsonClaudePendingApproval { toolUseId?: string timestamp: number autoReview?: AutoReviewStatus + /** create_worktree only: the repo's .ness.json setupCommand this call + * would run, whatever the card is asking about. */ + setupCommand?: string } export interface JsonClaudeState { diff --git a/src/shared/state/permissions.test.ts b/src/shared/state/permissions.test.ts index 2e7b87c8..0e0b96fb 100644 --- a/src/shared/state/permissions.test.ts +++ b/src/shared/state/permissions.test.ts @@ -173,4 +173,54 @@ 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 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', () => { + 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 9d5b42df..3527e308 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 = @@ -38,6 +44,8 @@ export type PermissionsEvent = * Ness-tool cleanup — so one click is one dispatch and one config write. */ | { type: 'permissions/revokedMany'; payload: { ids: string[] } } | { type: 'permissions/cleared' } + | { type: 'permissions/setupCommandApproved'; payload: { repoRoot: string; command: string } } + | { type: 'permissions/setupCommandForgotten'; payload: { repoRoot: string } } export function permissionsReducer( state: PermissionsState, @@ -71,8 +79,25 @@ export function permissionsReducer( return { ...state, rules } } case 'permissions/cleared': + // 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 + 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