Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
137 changes: 136 additions & 1 deletion src/main/approval-bridge-rules.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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<string, unknown> = { 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({
Expand Down
88 changes: 75 additions & 13 deletions src/main/approval-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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 {
Expand All @@ -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
}
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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<string, { repoRoot: string; command: string } | null>()
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 })
Expand All @@ -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
Expand All @@ -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,
Expand All @@ -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',
Expand All @@ -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(
Expand Down
17 changes: 16 additions & 1 deletion src/main/build-initial-state.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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({})
})
})
20 changes: 17 additions & 3 deletions src/main/build-initial-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
Expand Down Expand Up @@ -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<string, string> {
const out: Record<string, string> = {}
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out
for (const [root, cmd] of Object.entries(raw as Record<string, unknown>)) {
if (root.startsWith('/') && typeof cmd === 'string' && cmd.trim()) out[root] = cmd
}
return out
}
Loading
Loading