Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(open-knowledge): auto-approve OK tools in the built-in terminal (#2541)
tim-inkeep9420217d6110
diff --git a/.changeset/ok-terminal-auto-approve-ok-tools.md b/.changeset/ok-terminal-auto-approve-ok-tools.mdnew file mode 100644index 000000000..277b449a0--- /dev/null+++ b/.changeset/ok-terminal-auto-approve-ok-tools.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": minor+---++Built-in terminal now auto-approves OpenKnowledge's own tools for agents it launches, so the read/write loop runs without a per-call approval wall. Claude gets an allow-list (OK's MCP tools + the `ok open` command) with a deny-list that keeps `delete`/`move`/`share_link`/`install` prompting; Codex gets its per-server `approve` mode. Other shell commands, non-OK file edits, and other MCP servers stay gated as before. Applied per launch (nothing written to your CLI config files). Toggle in Settings → Terminal ("Let agents use OpenKnowledge without asking", `agents.autoApproveOkTools`), on by default, per machine. When Codex is installed but OpenKnowledge isn't configured for it, the toggle says so instead of letting Codex quietly keep asking.diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdxindex 606bbe185..6d4989455 100644--- a/docs/content/features/editor.mdx+++ b/docs/content/features/editor.mdx@@ -167,6 +167,12 @@ The menu is organized into two sections. **Terminal** (desktop app only) leads:The empty-state create composer on a fresh project carries the same Desktop / Terminal split: its Desktop rows pick the default agent the **Create** button uses, while its Terminal rows (desktop only, disabled until the workspace resolves) launch any of the four CLIs with the brief you typed.+When Claude or Codex launches from the docked terminal, OpenKnowledge auto-approves its own MCP tools, so the agent searches, reads, and edits the knowledge base without a per-call approval prompt. Claude additionally auto-approves the `ok open` command. OpenCode, Cursor, and Pi launch unchanged.++Four tools stay gated: `delete` and `move` (knowledge-base-wide blast radius), `share_link` (publishes content), and `install` (writes executable skill scripts into the agent's own config directory). For Claude, everything outside OpenKnowledge still prompts too, including shell commands and non-OK file edits. The guarantee is best-effort per agent: Claude uses an explicit allow/deny list, while Codex uses its own **approve** mode (auto-approve except potentially-unsafe actions) and only gets it once its OpenKnowledge entry is already configured, so run `ok init` for Codex if it keeps asking.++Turn it off in **Settings → Terminal → “Let agents use OpenKnowledge without asking”** ([`agents.autoApproveOkTools`](/docs/reference/configuration)). It applies to every project on this machine and defaults on.+## Command palette`Cmd+K` opens the command palette in both the desktop app and the browser. Type to jump to any file or folder, run create commands, open the graph or settings, or dispatch to an agent; recently opened entries surface first. In the desktop app it also switches projects and worktrees.diff --git a/docs/content/reference/configuration.mdx b/docs/content/reference/configuration.mdxindex 1456bb45c..0103e050c 100644--- a/docs/content/reference/configuration.mdx+++ b/docs/content/reference/configuration.mdx@@ -40,6 +40,7 @@ A key set in a file more specific than its scope (a user-scope key in `.ok/confi| `editor.wordWrap` | boolean | `true` | user | Soft-wrap long lines in the source-mode CodeMirror editor. A personal preference, not project-shared. Toggle from the Settings pane. || `appearance.preview.autoOpen` | boolean | `true` | user | Whether the agent should open or refresh the OpenKnowledge preview when it edits a doc through the MCP. Default `true` lets the agent route the preview by host capability: the host's in-app browser (Cursor preview pane, Codex's built-in browser, Claude Code Desktop) when one exists, the system browser otherwise. Set `false` to keep the agent's hands off your preview window. This is useful when you're already viewing the doc in OK Desktop, a browser tab on a second display, a non-default browser, or any flow where your extensions / accessibility tooling only work in your own browser. The agent then surfaces the URL on request but does not navigate. The change takes effect on the next preview-related tool call. Toggle from **Settings → Preferences → "Open preview when agent edits"**. || `terminal.enabled` | `boolean \| null` | `null` | project-local | Opt-out for the in-app terminal (a real OS shell at full user privilege). On by default; set `false` to disable it for this project on this machine. |+| `agents.autoApproveOkTools` | boolean | `true` | user | Auto-approve OpenKnowledge's own MCP tools (and the `ok open` command on Claude) for agents launched from the built-in [docked terminal](/docs/features/editor#terminal), so reading and writing the knowledge base runs without a per-call approval prompt. Destructive tools (`delete`, `move`, `share_link`, `install`) still prompt; other shell commands and non-OpenKnowledge file edits are untouched. Per-machine preference; toggle from **Settings → Terminal**. Best-effort per agent — Claude uses an allow/deny list, Codex uses its per-server `approve` mode (and only when its OpenKnowledge entry is already configured). || `telemetry.localSink.enabled` | boolean | `true` | project | Write local diagnostic spans + logs under `.ok/local/` for `ok diagnose bundle` to collect. Local-only: nothing leaves the machine until you run `bundle`. Set `false` for sensitive workspaces. || `telemetry.localSink.spans.maxBytes` | number | `52428800` (~50 MB) | project | Max size of the local diagnostic spans file before it rotates. || `telemetry.localSink.logs.maxBytes` | number | `26214400` (~25 MB) | project | Max size of the local diagnostic logs file before it rotates. |diff --git a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx b/packages/app/src/components/TerminalPanel.launch.dom.test.tsxindex 3482c8bd9..3db3c8d49 100644--- a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx+++ b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx@@ -17,6 +17,8 @@import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';import type { TerminalCli } from '@inkeep/open-knowledge-core';import { act, cleanup, render, screen, waitFor } from '@testing-library/react';+import type { ReactElement } from 'react';+import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';import type {ClaudeReadiness,CliReadiness,@@ -88,6 +90,9 @@ const WIRED_FOREIGN_PROJECT: ClaudeReadiness = {mcpPreApprovable: false,};const ON_PATH: CliReadiness = { onPath: 'present' };+/** Codex on PATH AND OK's `open-knowledge` server already in the codex config —+ * the gate that lets the launch add the `-c` tool-auto-approve override. */+const CODEX_OK_CONFIGURED: CliReadiness = { onPath: 'present', okServerConfigured: true };function makeBridge(preflight: ClaudeReadiness = WIRED, cliReadiness: CliReadiness = ON_PATH) {const dataSubs: Array<(m: OkPtyData) => void> = [];@@ -147,13 +152,47 @@ function launchInputWrites(inputMock: ReturnType<typeof mock>): string[] {}/**- * Claude's MCP pre-approval prefix (built from MCP_SERVER_NAME in core's- * terminal-launch.ts): the in-app launch carries `--settings` ahead of the- * prompt to pre-trust OK's project `.mcp.json` server — but ONLY when the- * preflight reports `mcpPreApprovable` (the project entry is verified as OK's- * own). Codex/Cursor never carry it, so this prefix is claude-only.+ * Claude's inline `--settings` prefix (built from MCP_SERVER_NAME in core's+ * terminal-launch.ts): a WIRED launch carries it ahead of the prompt — but ONLY+ * when the preflight reports `mcpPreApprovable` (the project entry is verified as+ * OK's own). It bundles server trust (`enabledMcpjsonServers`) AND — since the+ * `agents.autoApproveOkTools` preference defaults on and most tests below render+ * without a ConfigProvider — the OK-tool auto-approve allow-list plus the+ * gated-tool deny-list. Both ride the same `mcpPreApprovable` gate, so a+ * foreign/unverified entry bakes neither (the "bare" tests below). Codex/Cursor+ * never carry it, so this prefix is claude-only.*/-const CLAUDE_PRE = `--settings '{"enabledMcpjsonServers":["open-knowledge"]}'`;+const CLAUDE_PRE = `--settings '{"enabledMcpjsonServers":["open-knowledge"],"permissions":{"allow":["mcp__open-knowledge","Bash(ok open:*)"],"deny":["mcp__open-knowledge__delete","mcp__open-knowledge__move","mcp__open-knowledge__share_link","mcp__open-knowledge__install"]}}'`;++/** What a WIRED Claude launch bakes once the user turns the auto-approve toggle+ * OFF: server trust survives (it is a separate opt-in), the permissions block+ * does not. The contrast against {@link CLAUDE_PRE} is what makes the default-on+ * assertions above meaningful. */+const CLAUDE_TRUST_ONLY = `--settings '{"enabledMcpjsonServers":["open-knowledge"]}'`;++/**+ * Render under a ConfigContext whose user scope has `agents.autoApproveOkTools`+ * explicitly false — the OFF path of the feature's primary safety control. The+ * panel reads the context nullably (`use(ConfigContext)`), so every other test in+ * this file exercises the `?? true` default-on fallback instead.+ */+function renderWithAutoApproveOff(ui: ReactElement) {+ const value = {+ userConfig: { agents: { autoApproveOkTools: false } },+ userBinding: null,+ userSynced: true,+ projectBinding: null,+ projectConfig: null,+ projectSynced: false,+ projectLocalBinding: null,+ projectLocalConfig: null,+ projectLocalSynced: false,+ okignoreBinding: null,+ okignoreSynced: false,+ merged: null,+ } as unknown as ConfigContextValue;+ return render(<ConfigContext.Provider value={value}>{ui}</ConfigContext.Provider>);+}describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', () => {beforeEach(() => {@@ -272,6 +311,51 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (expect(launchInputWrites(terminal.input)).toEqual([]);});+ test("codex auto-approves OK tools (-c approve) when OK's server is configured in codex", async () => {+ // No ConfigProvider in this harness → the user preference defaults on, so the+ // launch bakes the per-server `-c` override once codex reports the OK entry.+ const { bridge, terminal } = makeBridge(WIRED, CODEX_OK_CONFIGURED);+ render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'codex', nonce: 1 }} />);++ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));+ expect(bakedLaunch(terminal.create)).toBe(+ `codex -c 'mcp_servers.open-knowledge.default_tools_approval_mode="approve"' 'hi'`,+ );+ });++ test('codex stays BARE (no -c) when OK is not configured in codex — the launch never breaks', async () => {+ const { bridge, terminal } = makeBridge(WIRED, {+ onPath: 'present',+ okServerConfigured: false,+ });+ render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'codex', nonce: 1 }} />);++ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));+ expect(bakedLaunch(terminal.create)).toBe("codex 'hi'");+ expect(bakedLaunch(terminal.create)).not.toContain('-c');+ });++ test('toggle OFF: a WIRED claude launch keeps server trust but bakes no permissions block', async () => {+ const { bridge, terminal } = makeBridge(WIRED);+ renderWithAutoApproveOff(+ <TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'claude', nonce: 1 }} />,+ );++ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));+ expect(bakedLaunch(terminal.create)).toBe(`claude ${CLAUDE_TRUST_ONLY} 'hi'`);+ expect(bakedLaunch(terminal.create)).not.toContain('permissions');+ });++ test("toggle OFF: codex stays BARE (no -c) even when OK's server is configured", async () => {+ const { bridge, terminal } = makeBridge(WIRED, CODEX_OK_CONFIGURED);+ renderWithAutoApproveOff(+ <TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'codex', nonce: 1 }} />,+ );++ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));+ expect(bakedLaunch(terminal.create)).toBe("codex 'hi'");+ });+test('cursor launch bakes the cursor-agent command (the agent CLI, not the editor)', async () => {const { bridge, terminal } = makeBridge(WIRED, ON_PATH);render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'cursor', nonce: 1 }} />);diff --git a/packages/app/src/components/TerminalPanel.tsx b/packages/app/src/components/TerminalPanel.tsxindex 98c0b2fda..71a6f093e 100644--- a/packages/app/src/components/TerminalPanel.tsx+++ b/packages/app/src/components/TerminalPanel.tsx@@ -12,7 +12,8 @@ import { WebLinksAddon } from '@xterm/addon-web-links';import { WebglAddon } from '@xterm/addon-webgl';import { Terminal } from '@xterm/xterm';import { useTheme } from 'next-themes';-import { useEffect, useRef, useState } from 'react';+import { use, useEffect, useRef, useState } from 'react';+import { ConfigContext } from '@/lib/config-context';import type { ClaudeReadiness, OkDesktopBridge } from '@/lib/desktop-bridge-types';import { cn } from '@/lib/utils';import { ClaudeReadinessBanner } from './ClaudeReadinessBanner';@@ -190,12 +191,21 @@ function TerminalSession({// the missing-CLI banner. Claude uses its own readiness banner instead.const [missingCli, setMissingCli] = useState<TerminalCli | null>(null);+ // Auto-approve OK's own tools for the baked launch (user-scope preference,+ // default on). Read the config context nullably (`use`, not `useConfigContext`)+ // so a TerminalPanel mounted without a ConfigProvider degrades to the default+ // rather than throwing. Held in a ref so a config change never re-runs the mount+ // effect (which would respawn the PTY) — the launch reads it once.+ const configCtx = use(ConfigContext);+ const autoApproveOkToolsRef = useRef(configCtx?.userConfig?.agents?.autoApproveOkTools ?? true);+// Keep the callbacks fresh without re-running the mount effect — a new// callback identity must NOT tear down and respawn the PTY.useEffect(() => {onExitRef.current = onExit;onTitleChangeRef.current = onTitleChange;onPtyIdRef.current = onPtyId;+ autoApproveOkToolsRef.current = configCtx?.userConfig?.agents?.autoApproveOkTools ?? true;});useEffect(() => {@@ -549,6 +559,11 @@ function TerminalSession({if (!cancelled) setReadiness(fresh);return buildCliLaunchArgString('claude', intent.prompt, {mcpPreApprove: fresh.mcpPreApprovable === true,+ // Auto-approve OK's tools only when the project's `.mcp.json` entry is+ // verified OK's own (same gate as server-trust): auto-approving an+ // unverified/foreign same-named server's tools is the RCE risk+ // `isOwnManagedEntry` exists to prevent.+ autoApproveOkTools: autoApproveOkToolsRef.current && fresh.mcpPreApprovable === true,});}// Not confirmed present (not-found OR unknown) — suppress the bake and@@ -581,7 +596,18 @@ function TerminalSession({if (cancelled) return undefined;res = await bridge.terminal.cliPreflight(intent.cli);}- if (res.onPath === 'present') return buildCliLaunchArgString(intent.cli, intent.prompt);+ if (res.onPath === 'present') {+ // Codex auto-approve rides three gates: the user preference, codex on+ // PATH (this branch), AND OK's server already configured in codex —+ // else the `-c` override would break codex's config load. Other CLIs+ // (cursor/opencode/pi) never receive it.+ return buildCliLaunchArgString(intent.cli, intent.prompt, {+ autoApproveOkTools:+ intent.cli === 'codex' &&+ res.okServerConfigured === true &&+ autoApproveOkToolsRef.current,+ });+ }} catch (err) {console.warn('[terminal] cliPreflight failed', { cli: intent.cli, err });}diff --git a/packages/app/src/components/settings/TerminalSection.dom.test.tsx b/packages/app/src/components/settings/TerminalSection.dom.test.tsxindex 8e32cd2b9..1ac31b4f7 100644--- a/packages/app/src/components/settings/TerminalSection.dom.test.tsx+++ b/packages/app/src/components/settings/TerminalSection.dom.test.tsx@@ -1,14 +1,13 @@/**- * Behavioral tests for the Settings → Terminal opt-out toggle.+ * Behavioral tests for the Settings → Terminal section: the per-project shell+ * opt-out toggle and the per-machine "auto-approve OpenKnowledge tools" toggle.*- * The system boundary (the CRDT-backed consent hook) is mocked; the real shadcn- * Switch is rendered. Assertions pin the default-on opt-out: the default- * (never-chosen) and granted states read as on; only an explicit `false` reads- * as off; on → off writes `false`; off → on writes `true` directly (no consent- * dialog); the control is disabled until the binding is ready.+ * The system boundaries (the CRDT-backed consent hook, the user ConfigBinding)+ * are mocked; the real shadcn Switch is rendered. Two switches now exist, so+ * every query is scoped by test id.*/import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';-import { cleanup, render, screen } from '@testing-library/react';+import { cleanup, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';import type { ReactNode } from 'react';@@ -19,6 +18,15 @@ let consentState: ConsentState = { enabled: false, synced: true };let writerImpl: Writer = null;const writerCalls: boolean[] = [];+let userConfig: { agents?: { autoApproveOkTools?: boolean } } | null = {+ agents: { autoApproveOkTools: true },+};+let userSynced = true;+let userBinding: { patch: (p: unknown) => { ok: true } | { ok: false; error: unknown } } | null = {+ patch: () => ({ ok: true }),+};+const userPatchCalls: unknown[] = [];+mock.module('@lingui/react/macro', () => ({Trans: ({ children }: { children: ReactNode }) => <>{children}</>,useLingui: () => ({@@ -36,10 +44,17 @@ mock.module('@/hooks/use-terminal-enabled', () => ({useTerminalEnabledWriter: () => writerImpl,}));+mock.module('@/lib/config-provider', () => ({+ useConfigContext: () => ({ userConfig, userSynced, userBinding }),+}));+const { TerminalSection } = await import('./TerminalSection');-function switchChecked(): string | null {- return (screen.getByRole('switch') as HTMLButtonElement).getAttribute('aria-checked');+function shellSwitch(): HTMLButtonElement {+ return screen.getByTestId('settings-terminal-toggle') as HTMLButtonElement;+}+function autoApproveSwitch(): HTMLButtonElement {+ return screen.getByTestId('settings-terminal-autoapprove-toggle') as HTMLButtonElement;}describe('TerminalSection (Settings opt-out toggle)', () => {@@ -50,38 +65,47 @@ describe('TerminalSection (Settings opt-out toggle)', () => {return { ok: true };};writerCalls.length = 0;+ userConfig = { agents: { autoApproveOkTools: true } };+ userSynced = true;+ userBinding = {+ patch: (p) => {+ userPatchCalls.push(p);+ return { ok: true };+ },+ };+ userPatchCalls.length = 0;});afterEach(() => cleanup());test('the default (never-chosen) state reads as on', () => {consentState = { enabled: null, synced: true };render(<TerminalSection />);- expect(switchChecked()).toBe('true');+ expect(shellSwitch().getAttribute('aria-checked')).toBe('true');});test('the granted state reads as on', () => {consentState = { enabled: true, synced: true };render(<TerminalSection />);- expect(switchChecked()).toBe('true');+ expect(shellSwitch().getAttribute('aria-checked')).toBe('true');});test('an explicit opt-out reads as off', () => {consentState = { enabled: false, synced: true };render(<TerminalSection />);- expect(switchChecked()).toBe('false');+ expect(shellSwitch().getAttribute('aria-checked')).toBe('false');});test('on → off opts out immediately via writer(false)', async () => {consentState = { enabled: true, synced: true };render(<TerminalSection />);- await userEvent.click(screen.getByRole('switch'));+ await userEvent.click(shellSwitch());expect(writerCalls).toEqual([false]);});test('off → on re-enables directly via writer(true), no dialog', async () => {consentState = { enabled: false, synced: true };render(<TerminalSection />);- await userEvent.click(screen.getByRole('switch'));+ await userEvent.click(shellSwitch());expect(writerCalls).toEqual([true]);});@@ -89,6 +113,124 @@ describe('TerminalSection (Settings opt-out toggle)', () => {consentState = { enabled: null, synced: false };writerImpl = null;render(<TerminalSection />);- expect((screen.getByRole('switch') as HTMLButtonElement).disabled).toBe(true);+ expect(shellSwitch().disabled).toBe(true);+ });+});++describe('TerminalSection (auto-approve OpenKnowledge tools toggle)', () => {+ beforeEach(() => {+ consentState = { enabled: true, synced: true };+ writerImpl = () => ({ ok: true });+ userConfig = { agents: { autoApproveOkTools: true } };+ userSynced = true;+ userBinding = {+ patch: (p) => {+ userPatchCalls.push(p);+ return { ok: true };+ },+ };+ userPatchCalls.length = 0;+ });+ afterEach(() => cleanup());++ test('default (unset) reads as on', () => {+ userConfig = { agents: {} };+ render(<TerminalSection />);+ expect(autoApproveSwitch().getAttribute('aria-checked')).toBe('true');+ });++ test('an explicit false reads as off', () => {+ userConfig = { agents: { autoApproveOkTools: false } };+ render(<TerminalSection />);+ expect(autoApproveSwitch().getAttribute('aria-checked')).toBe('false');+ });++ test('toggling writes the user-scope leaf via the user binding', async () => {+ userConfig = { agents: { autoApproveOkTools: true } };+ render(<TerminalSection />);+ await userEvent.click(autoApproveSwitch());+ expect(userPatchCalls).toEqual([{ agents: { autoApproveOkTools: false } }]);+ });++ test('is disabled until the user binding is ready', () => {+ userSynced = false;+ userBinding = null;+ render(<TerminalSection />);+ expect(autoApproveSwitch().disabled).toBe(true);+ });+});++/**+ * The codex-can't-honor signal. Codex only receives the `-c` auto-approve+ * override once OK's server entry exists in its config; without the note, a user+ * who turns the toggle on watches codex prompt anyway with no explanation.+ */+type CodexReadiness = { onPath: string; okServerConfigured?: boolean };++function stubDesktopBridge(readiness: CodexReadiness | Error): void {+ (globalThis as unknown as { window: { okDesktop?: unknown } }).window.okDesktop = {+ terminal: {+ cliPreflight: async () =>+ readiness instanceof Error ? Promise.reject(readiness) : readiness,+ },+ };+}++function codexNote(): HTMLElement | null {+ return screen.queryByTestId('settings-terminal-autoapprove-codex-note');+}++describe("TerminalSection (codex-can't-honor note)", () => {+ beforeEach(() => {+ consentState = { enabled: true, synced: true };+ writerImpl = () => ({ ok: true });+ userConfig = { agents: { autoApproveOkTools: true } };+ userSynced = true;+ userBinding = { patch: () => ({ ok: true }) };+ });+ afterEach(() => {+ cleanup();+ (globalThis as unknown as { window: { okDesktop?: unknown } }).window.okDesktop = undefined;+ });++ test('shows the note when codex is installed but OK is not configured for it', async () => {+ stubDesktopBridge({ onPath: 'present', okServerConfigured: false });+ render(<TerminalSection />);+ await waitFor(() => expect(codexNote()).not.toBeNull());+ });++ test('stays silent when codex already has OK configured', async () => {+ stubDesktopBridge({ onPath: 'present', okServerConfigured: true });+ render(<TerminalSection />);+ await waitFor(() => expect(autoApproveSwitch()).not.toBeNull());+ expect(codexNote()).toBeNull();+ });++ test('stays silent when codex is not installed', async () => {+ stubDesktopBridge({ onPath: 'not-found' });+ render(<TerminalSection />);+ await waitFor(() => expect(autoApproveSwitch()).not.toBeNull());+ expect(codexNote()).toBeNull();+ });++ test('stays silent when the auto-approve toggle is off (nothing to explain)', async () => {+ userConfig = { agents: { autoApproveOkTools: false } };+ stubDesktopBridge({ onPath: 'present', okServerConfigured: false });+ render(<TerminalSection />);+ await waitFor(() => expect(autoApproveSwitch()).not.toBeNull());+ expect(codexNote()).toBeNull();+ });++ test('a failed preflight probe stays silent rather than warning about a CLI the user may not have', async () => {+ stubDesktopBridge(new Error('ipc down'));+ render(<TerminalSection />);+ await waitFor(() => expect(autoApproveSwitch()).not.toBeNull());+ expect(codexNote()).toBeNull();+ });++ test('the web build (no desktop bridge) never probes', async () => {+ render(<TerminalSection />);+ await waitFor(() => expect(autoApproveSwitch()).not.toBeNull());+ expect(codexNote()).toBeNull();});});diff --git a/packages/app/src/components/settings/TerminalSection.tsx b/packages/app/src/components/settings/TerminalSection.tsxindex 3c0d6826f..f72aa5745 100644--- a/packages/app/src/components/settings/TerminalSection.tsx+++ b/packages/app/src/components/settings/TerminalSection.tsx@@ -1,18 +1,21 @@/**- * Settings → Terminal: the per-project opt-out toggle for the in-app real OS- * shell.- *- * The terminal is available by default; this toggle is the silent opt-out. Reads- * + writes the project-local `terminal.enabled` leaf (human-only —- * `agentSettable:false`). On → off writes `false` (opt out, tearing down any- * running shell via the gate); off → on writes `true` (re-enable). Only an- * explicit `false` reads as off, so the toggle shows on for the default- * (never-chosen) state.+ * Settings → Terminal: two desktop-only toggles.+ * 1. The per-project opt-out for the in-app real OS shell (`terminal.enabled`,+ * project-local — reads/writes via `use-terminal-enabled`).+ * 2. A per-machine (user-scope) toggle to auto-approve OpenKnowledge's OWN tools+ * for agents launched from the docked terminal (`agents.autoApproveOkTools`).+ * Default on; only an explicit `false` reads as off. Written through the+ * user ConfigBinding (`~/.ok/global.yml`), so it spans every project on this+ * machine — distinct from the per-project shell toggle above. Carries an+ * inline note when codex is installed but cannot honor the toggle.*/+import { humanFormat } from '@inkeep/open-knowledge-core';import { useLingui } from '@lingui/react/macro';+import { useEffect, useState } from 'react';import { toast } from 'sonner';import { Switch } from '@/components/ui/switch';import { useTerminalConsentState, useTerminalEnabledWriter } from '@/hooks/use-terminal-enabled';+import { useConfigContext } from '@/lib/config-provider';export function TerminalSection() {const { t } = useLingui();@@ -20,9 +23,40 @@ export function TerminalSection() {const writer = useTerminalEnabledWriter();const isOn = enabled !== false;+ const { userConfig, userBinding, userSynced } = useConfigContext();+ // Default on: only an explicit `false` reads as off (mirrors the launch-site+ // `?? true` fallback in TerminalPanel).+ const autoApproveOn = userConfig?.agents?.autoApproveOkTools !== false;++ // Codex can only honor the toggle when OK's server entry already exists in its+ // config — the launch site withholds the `-c` override otherwise (a `-c` under+ // an undefined server id breaks codex's config load). Surface that rather than+ // let the user watch codex prompt anyway with no explanation. Same preflight+ // the launch runs; the section is desktop-only, so no bridge means no note.+ const [codexNeedsInit, setCodexNeedsInit] = useState(false);+ useEffect(() => {+ const bridge = window.okDesktop;+ if (!bridge) return;+ let cancelled = false;+ bridge.terminal+ .cliPreflight('codex')+ .then((res) => {+ if (!cancelled) {+ setCodexNeedsInit(res.onPath === 'present' && res.okServerConfigured !== true);+ }+ })+ .catch(() => {+ // A failed probe is indistinguishable from "not installed" here — stay quiet+ // rather than warn about a CLI the user may not have.+ });+ return () => {+ cancelled = true;+ };+ }, []);+function applyEnabled(next: boolean): void {if (writer === null) {- toast.error(t`Terminal settings not loaded yet — try again in a moment.`);+ toast.error(t`Terminal settings not yet loaded — try again in a moment`);return;}const result = writer(next);@@ -35,6 +69,18 @@ export function TerminalSection() {}}+ function applyAutoApprove(next: boolean): void {+ if (userBinding === null) {+ toast.error(t`Auto-approve settings not yet loaded — try again in a moment`);+ return;+ }+ const result = userBinding.patch({ agents: { autoApproveOkTools: next } });+ if (!result.ok) {+ const detail = humanFormat(result.error);+ toast.error(t`Failed to update the auto-approve setting — ${detail}`);+ }+ }+return (<section aria-labelledby="settings-terminal-title" className="space-y-3"><div className="space-y-1">@@ -66,6 +112,36 @@ export function TerminalSection() {data-testid="settings-terminal-toggle"/></div>++ <div className="flex items-center justify-between gap-3 rounded-md border p-3">+ <div className="space-y-0.5">+ <label htmlFor="settings-terminal-autoapprove-toggle" className="text-sm font-medium">+ {t`Let agents use OpenKnowledge without asking`}+ </label>+ <p+ className="text-1sm text-muted-foreground"+ data-testid="settings-terminal-autoapprove-body"+ >+ {t`Applies to all projects on this machine. Claude and Codex, started from the built-in terminal, auto-approve OpenKnowledge's read and write tools (Claude also auto-runs "ok open"). Deleting, moving, sharing, installing skills, other commands, and non-OpenKnowledge file edits still ask. Cursor, OpenCode, and Pi are unaffected. Best-effort per agent.`}+ </p>+ {autoApproveOn && codexNeedsInit ? (+ <p+ className="text-1sm text-muted-foreground"+ data-testid="settings-terminal-autoapprove-codex-note"+ >+ {t`Codex will still ask until you run "ok init" in a terminal for this project.`}+ </p>+ ) : null}+ </div>+ <Switch+ id="settings-terminal-autoapprove-toggle"+ checked={autoApproveOn}+ onCheckedChange={applyAutoApprove}+ disabled={!userSynced || userBinding === null}+ aria-label={t`Let agents use OpenKnowledge without asking`}+ data-testid="settings-terminal-autoapprove-toggle"+ />+ </div></section>);}diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.tsindex 3448f63b2..e69d54a8b 100644--- a/packages/app/src/lib/desktop-bridge-types.ts+++ b/packages/app/src/lib/desktop-bridge-types.ts@@ -815,6 +815,25 @@ export interface ClaudeReadiness {* mirrored verbatim here (drift-tested). */export interface CliReadiness {readonly onPath: 'present' | 'not-found' | 'unknown';+ /** Codex-only: whether OK's `open-knowledge` MCP server is already configured+ * in the user's codex config. Gates the per-launch `-c` tool-auto-approve+ * override — codex fails to load its config if `-c` targets a server that is+ * not defined, so the launch site adds the override only when this is true.+ * Absent for CLIs where it does not apply.+ *+ * DELIBERATELY WEAKER THAN CLAUDE'S GATE, and not its security equivalent.+ * This is existence-by-name (any object under `mcp_servers.open-knowledge`),+ * whereas claude's `mcpPreApprovable` runs `isOwnManagedEntry` to verify the+ * entry is byte-exactly OK's own. The asymmetry is sound because the two read+ * different files: claude's is a PROJECT-scoped `.mcp.json` that travels in a+ * clone, so a same-named foreign entry is a real RCE vector; codex's target is+ * `scope: 'global'` (`~/.codex/config.toml`, resolved from `home`, never from+ * cwd), so anyone able to plant a foreign entry there can already register+ * arbitrary MCP servers and has won regardless. Tightening this to an exact+ * ownership match would also fail closed on a legitimate entry carrying any+ * extra codex key, silently disabling auto-approve for real users. This gate's+ * job is availability (don't break codex's config load), not authorization. */+ readonly okServerConfigured?: boolean;}export interface OkDesktopBridge {diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 935d65f43..ffe024b16 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -863,6 +863,7 @@"KkEAud": ["Create a file from the current document or folder context."],"KmydK6": ["Bold"],"KnoB--": ["Will be saved as <0>", ["sanitized"], "</0>."],+ "Kr3VPS": ["Codex will still ask until you run \"ok init\" in a terminal for this project."],"KsAPaB": ["This branch is checked out in:"],"KszKI_": ["Skill level"],"KujtjC": ["Find"],@@ -1674,6 +1675,7 @@"fcgvCA": ["Claude"],"fiMNLl": ["Sync settings not yet loaded — try again in a moment"],"fj5YiP": ["Downloads a fresh copy from GitHub."],+ "fnlBN4": ["Auto-approve settings not yet loaded — try again in a moment"],"fo0VXg": ["Uninstall"],"fqSfXY": ["Replace"],"fuJZKk": ["Search branches"],@@ -1761,6 +1763,7 @@"hYgDIe": ["Create"],"hZoBHK": ["Empty starting content"],"haHgQj": ["Copied relative path"],+ "habOU_": ["Failed to update the auto-approve setting — ", ["detail"]],"he3ygx": ["Copy"],"hjO0Mq": ["Add tab"],"hmYd9H": [@@ -1812,6 +1815,7 @@"ig5vUe": ["Failed to load file"],"iilQXA": ["Folder duplicated"],"ijLc3m": ["Bullet list"],+ "ilodsp": ["Let agents use OpenKnowledge without asking"],"ipn17C": ["The <0>type</0> every document created from this template gets (e.g. <1>research-note</1>). Keeps new docs Open Knowledge Format–conformant."],@@ -2002,6 +2006,9 @@],"nNYV3Y": ["and ", ["remaining"], " more"],"nP-KFo": ["New ", ["0"], " chat"],+ "nP76lk": [+ "Applies to all projects on this machine. Claude and Codex, started from the built-in terminal, auto-approve OpenKnowledge's read and write tools (Claude also auto-runs \"ok open\"). Deleting, moving, sharing, installing skills, other commands, and non-OpenKnowledge file edits still ask. Cursor, OpenCode, and Pi are unaffected. Best-effort per agent."+ ],"nTwL53": ["Open a doc to share its URL."],"nUNZL4": ["Ask ", ["0"]],"nWv1ja": ["Manage hidden files in Settings → Ignore patterns."],@@ -2328,6 +2335,7 @@"w4hMYl": ["Could not read branch state for this project. Close this dialog and open the share link again."],+ "w6sBjd": ["Terminal settings not yet loaded — try again in a moment"],"w7SsvI": ["That folder isn't an OpenKnowledge project yet. Initialize it and open?"],"w7nm4K": ["Indented blockquote for citations."],"wDgmsr": ["\"", ["0"], "\" install refreshed (", ["1"], ")"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 3c673c919..b9b344f12 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -846,6 +846,10 @@ msgstr "API key set"msgid "Append-only log of what changed."msgstr "Append-only log of what changed."+#: src/components/settings/TerminalSection.tsx+msgid "Applies to all projects on this machine. Claude and Codex, started from the built-in terminal, auto-approve OpenKnowledge's read and write tools (Claude also auto-runs \"ok open\"). Deleting, moving, sharing, installing skills, other commands, and non-OpenKnowledge file edits still ask. Cursor, OpenCode, and Pi are unaffected. Best-effort per agent."+msgstr "Applies to all projects on this machine. Claude and Codex, started from the built-in terminal, auto-approve OpenKnowledge's read and write tools (Claude also auto-runs \"ok open\"). Deleting, moving, sharing, installing skills, other commands, and non-OpenKnowledge file edits still ask. Cursor, OpenCode, and Pi are unaffected. Best-effort per agent."+#: src/editor/bubble-menu/LinkEditPopover.tsxmsgid "Apply link"msgstr "Apply link"@@ -921,6 +925,10 @@ msgstr "Authoritative content; mirrored verbatim everywhere it's referenced."msgid "Authorize in browser"msgstr "Authorize in browser"+#: src/components/settings/TerminalSection.tsx+msgid "Auto-approve settings not yet loaded — try again in a moment"+msgstr "Auto-approve settings not yet loaded — try again in a moment"+#: src/components/FolderTimelineCard.tsx#: src/components/TimelinePanel.tsxmsgid "Auto-save"@@ -1423,6 +1431,10 @@ msgstr "Code copied to clipboard"msgid "Code expired — please try again"msgstr "Code expired — please try again"+#: src/components/settings/TerminalSection.tsx+msgid "Codex will still ask until you run \"ok init\" in a terminal for this project."+msgstr "Codex will still ask until you run \"ok init\" in a terminal for this project."+#: src/components/AutoSyncEnableWarning.tsxmsgid "Collaborators see your in-progress edits as soon as they sync."msgstr "Collaborators see your in-progress edits as soon as they sync."@@ -3057,6 +3069,10 @@ msgstr "Failed to update attachment location — {detail}"msgid "Failed to update property"msgstr "Failed to update property"+#: src/components/settings/TerminalSection.tsx+msgid "Failed to update the auto-approve setting — {detail}"+msgstr "Failed to update the auto-approve setting — {detail}"+#: src/components/settings/SettingsDialogBody.tsxmsgid "Failed to update the project sync default — {detail}"msgstr "Failed to update the project sync default — {detail}"@@ -3874,6 +3890,10 @@ msgstr "Layout"msgid "Layout options"msgstr "Layout options"+#: src/components/settings/TerminalSection.tsx+msgid "Let agents use OpenKnowledge without asking"+msgstr "Let agents use OpenKnowledge without asking"+#: src/lib/keyboard-shortcuts.tsmsgid "Let Tab leave the source editor instead of indenting."msgstr "Let Tab leave the source editor instead of indenting."@@ -6908,11 +6928,14 @@ msgstr "Terminal failed to load"msgid "Terminal sessions"msgstr "Terminal sessions"-#: src/components/settings/TerminalSection.tsx#: src/components/TerminalGate.tsxmsgid "Terminal settings not loaded yet — try again in a moment."msgstr "Terminal settings not loaded yet — try again in a moment."+#: src/components/settings/TerminalSection.tsx+msgid "Terminal settings not yet loaded — try again in a moment"+msgstr "Terminal settings not yet loaded — try again in a moment"+#: src/components/PropertyWidgets.tsxmsgid "Text"msgstr "Text"diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 7d861fdee..0e29e4904 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -863,6 +863,7 @@"KkEAud": ["Ćŕēàţē à ƒĩĺē ƒŕōḿ ţĥē ćũŕŕēńţ ďōćũḿēńţ ōŕ ƒōĺďēŕ ćōńţēxţ."],"KmydK6": ["ßōĺď"],"KnoB--": ["Ŵĩĺĺ ƀē śàvēď àś <0>", ["sanitized"], "</0>."],+ "Kr3VPS": ["Ćōďēx ŵĩĺĺ śţĩĺĺ àśķ ũńţĩĺ ŷōũ ŕũń \"ōķ ĩńĩţ\" ĩń à ţēŕḿĩńàĺ ƒōŕ ţĥĩś ƥŕōĴēćţ."],"KsAPaB": ["Ţĥĩś ƀŕàńćĥ ĩś ćĥēćķēď ōũţ ĩń:"],"KszKI_": ["Śķĩĺĺ ĺēvēĺ"],"KujtjC": ["Ƒĩńď"],@@ -1674,6 +1675,7 @@"fcgvCA": ["Ćĺàũďē"],"fiMNLl": ["Śŷńć śēţţĩńĝś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],"fj5YiP": ["Ďōŵńĺōàďś à ƒŕēśĥ ćōƥŷ ƒŕōḿ ĜĩţĤũƀ."],+ "fnlBN4": ["Àũţō-àƥƥŕōvē śēţţĩńĝś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],"fo0VXg": ["Ũńĩńśţàĺĺ"],"fqSfXY": ["Ŕēƥĺàćē"],"fuJZKk": ["Śēàŕćĥ ƀŕàńćĥēś"],@@ -1761,6 +1763,7 @@"hYgDIe": ["Ćŕēàţē"],"hZoBHK": ["Ēḿƥţŷ śţàŕţĩńĝ ćōńţēńţ"],"haHgQj": ["Ćōƥĩēď ŕēĺàţĩvē ƥàţĥ"],+ "habOU_": ["Ƒàĩĺēď ţō ũƥďàţē ţĥē àũţō-àƥƥŕōvē śēţţĩńĝ — ", ["detail"]],"he3ygx": ["Ćōƥŷ"],"hjO0Mq": ["Àďď ţàƀ"],"hmYd9H": [@@ -1812,6 +1815,7 @@"ig5vUe": ["Ƒàĩĺēď ţō ĺōàď ƒĩĺē"],"iilQXA": ["Ƒōĺďēŕ ďũƥĺĩćàţēď"],"ijLc3m": ["ßũĺĺēţ ĺĩśţ"],+ "ilodsp": ["Ĺēţ àĝēńţś ũśē ŌƥēńĶńōŵĺēďĝē ŵĩţĥōũţ àśķĩńĝ"],"ipn17C": ["Ţĥē <0>ţŷƥē</0> ēvēŕŷ ďōćũḿēńţ ćŕēàţēď ƒŕōḿ ţĥĩś ţēḿƥĺàţē ĝēţś (ē.ĝ. <1>ŕēśēàŕćĥ-ńōţē</1>). Ķēēƥś ńēŵ ďōćś Ōƥēń Ķńōŵĺēďĝē Ƒōŕḿàţ–ćōńƒōŕḿàńţ."],@@ -2002,6 +2006,9 @@],"nNYV3Y": ["àńď ", ["remaining"], " ḿōŕē"],"nP-KFo": ["Ńēŵ ", ["0"], " ćĥàţ"],+ "nP76lk": [+ "Àƥƥĺĩēś ţō àĺĺ ƥŕōĴēćţś ōń ţĥĩś ḿàćĥĩńē. Ćĺàũďē àńď Ćōďēx, śţàŕţēď ƒŕōḿ ţĥē ƀũĩĺţ-ĩń ţēŕḿĩńàĺ, àũţō-àƥƥŕōvē ŌƥēńĶńōŵĺēďĝē'ś ŕēàď àńď ŵŕĩţē ţōōĺś (Ćĺàũďē àĺśō àũţō-ŕũńś \"ōķ ōƥēń\"). Ďēĺēţĩńĝ, ḿōvĩńĝ, śĥàŕĩńĝ, ĩńśţàĺĺĩńĝ śķĩĺĺś, ōţĥēŕ ćōḿḿàńďś, àńď ńōń-ŌƥēńĶńōŵĺēďĝē ƒĩĺē ēďĩţś śţĩĺĺ àśķ. Ćũŕśōŕ, ŌƥēńĆōďē, àńď Ƥĩ àŕē ũńàƒƒēćţēď. ßēśţ-ēƒƒōŕţ ƥēŕ àĝēńţ."+ ],"nTwL53": ["Ōƥēń à ďōć ţō śĥàŕē ĩţś ŨŔĹ."],"nUNZL4": ["Àśķ ", ["0"]],"nWv1ja": ["Ḿàńàĝē ĥĩďďēń ƒĩĺēś ĩń Śēţţĩńĝś → Ĩĝńōŕē ƥàţţēŕńś."],@@ -2328,6 +2335,7 @@"w4hMYl": ["Ćōũĺď ńōţ ŕēàď ƀŕàńćĥ śţàţē ƒōŕ ţĥĩś ƥŕōĴēćţ. Ćĺōśē ţĥĩś ďĩàĺōĝ àńď ōƥēń ţĥē śĥàŕē ĺĩńķ àĝàĩń."],+ "w6sBjd": ["Ţēŕḿĩńàĺ śēţţĩńĝś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],"w7SsvI": ["Ţĥàţ ƒōĺďēŕ ĩśń'ţ àń ŌƥēńĶńōŵĺēďĝē ƥŕōĴēćţ ŷēţ. Ĩńĩţĩàĺĩźē ĩţ àńď ōƥēń?"],"w7nm4K": ["Ĩńďēńţēď ƀĺōćķǫũōţē ƒōŕ ćĩţàţĩōńś."],"wDgmsr": ["\"", ["0"], "\" ĩńśţàĺĺ ŕēƒŕēśĥēď (", ["1"], ")"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 14fd423b0..bda56d974 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -841,6 +841,10 @@ msgstr ""msgid "Append-only log of what changed."msgstr ""+#: src/components/settings/TerminalSection.tsx+msgid "Applies to all projects on this machine. Claude and Codex, started from the built-in terminal, auto-approve OpenKnowledge's read and write tools (Claude also auto-runs \"ok open\"). Deleting, moving, sharing, installing skills, other commands, and non-OpenKnowledge file edits still ask. Cursor, OpenCode, and Pi are unaffected. Best-effort per agent."+msgstr ""+#: src/editor/bubble-menu/LinkEditPopover.tsxmsgid "Apply link"msgstr ""@@ -916,6 +920,10 @@ msgstr ""msgid "Authorize in browser"msgstr ""+#: src/components/settings/TerminalSection.tsx+msgid "Auto-approve settings not yet loaded — try again in a moment"+msgstr ""+#: src/components/FolderTimelineCard.tsx#: src/components/TimelinePanel.tsxmsgid "Auto-save"@@ -1418,6 +1426,10 @@ msgstr ""msgid "Code expired — please try again"msgstr ""+#: src/components/settings/TerminalSection.tsx+msgid "Codex will still ask until you run \"ok init\" in a terminal for this project."+msgstr ""+#: src/components/AutoSyncEnableWarning.tsxmsgid "Collaborators see your in-progress edits as soon as they sync."msgstr ""@@ -3052,6 +3064,10 @@ msgstr ""msgid "Failed to update property"msgstr ""+#: src/components/settings/TerminalSection.tsx+msgid "Failed to update the auto-approve setting — {detail}"+msgstr ""+#: src/components/settings/SettingsDialogBody.tsxmsgid "Failed to update the project sync default — {detail}"msgstr ""@@ -3869,6 +3885,10 @@ msgstr ""msgid "Layout options"msgstr ""+#: src/components/settings/TerminalSection.tsx+msgid "Let agents use OpenKnowledge without asking"+msgstr ""+#: src/lib/keyboard-shortcuts.tsmsgid "Let Tab leave the source editor instead of indenting."msgstr ""@@ -6903,11 +6923,14 @@ msgstr ""msgid "Terminal sessions"msgstr ""-#: src/components/settings/TerminalSection.tsx#: src/components/TerminalGate.tsxmsgid "Terminal settings not loaded yet — try again in a moment."msgstr ""+#: src/components/settings/TerminalSection.tsx+msgid "Terminal settings not yet loaded — try again in a moment"+msgstr ""+#: src/components/PropertyWidgets.tsxmsgid "Text"msgstr ""diff --git a/packages/core/src/config/field-registry.test.ts b/packages/core/src/config/field-registry.test.tsindex 1a40842d7..ca4b32e73 100644--- a/packages/core/src/config/field-registry.test.ts+++ b/packages/core/src/config/field-registry.test.ts@@ -143,7 +143,7 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'expect(allowlisted).toEqual([]);});- test('user-strict fields cover appearance.preview.autoOpen + appearance.theme + editor.wordWrap', () => {+ test('user-strict fields cover agents.autoApproveOkTools + appearance.preview.autoOpen + appearance.theme + editor.wordWrap', () => {const leaves: { path: string[]; schema: unknown }[] = [];walkLeaves(ConfigSchema, [], leaves);const userStrict = leaves@@ -151,6 +151,7 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'.map((l) => l.path.join('.')).sort();expect(userStrict).toEqual([+ 'agents.autoApproveOkTools','appearance.preview.autoOpen','appearance.theme','editor.wordWrap',diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.tsindex 2e528d8ea..6ceb87e55 100644--- a/packages/core/src/config/schema.ts+++ b/packages/core/src/config/schema.ts@@ -205,6 +205,32 @@ export const ConfigSchema = z.looseObject({.default(true),}).default({ wordWrap: true }),+ // USER-scope: auto-approve OpenKnowledge's OWN MCP tools (and, on Claude, the+ // `ok open` verb) for agents launched from the docked terminal, so the KB+ // read/write loop runs without a per-call approval wall. Destructive/exfil OK+ // tools stay gated (Claude deny-list); other shell + non-OK edits are+ // untouched. A per-machine personal preference (user scope); default on.+ //+ // Deliberate namespace: every sibling here names a feature area, `agents` names+ // the execution domain instead. Agent-facing policy is not the terminal's — the+ // deep-link GUI handoff dispatches the same agents to the same tools and will+ // reuse this leaf, so `terminal.*` would have been the wrong home the moment+ // that lands. Keys under `agents.*` are the user's cross-surface agent policy;+ // config paths are a user-facing `~/.ok/global.yml` contract and hard to rename.+ agents: z+ .looseObject({+ autoApproveOkTools: z+ .boolean()+ .register(fieldRegistry, {+ scope: 'user',+ agentSettable: false,+ defaultScope: 'user',+ description:+ "Auto-approve OpenKnowledge's own tools (and `ok open` on Claude) for agents launched from the built-in terminal. Destructive tools (delete/move/share/install) still prompt. Per-machine personal preference (user scope).",+ })+ .default(true),+ })+ .default({ autoApproveOkTools: true }),// `autoSync.enabled` is a per-machine, per-project preference: each// teammate decides independently whether their machine should auto-pull /// auto-push commits for *this* project. Project scope would bleed acrossdiff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.tsindex 4eab3218d..6225d5c8c 100644--- a/packages/core/src/desktop-bridge.ts+++ b/packages/core/src/desktop-bridge.ts@@ -912,6 +912,25 @@ export interface ClaudeReadiness {* contract + the app renderer copy (drift-tested). */export interface CliReadiness {readonly onPath: 'present' | 'not-found' | 'unknown';+ /** Codex-only: whether OK's `open-knowledge` MCP server is already configured+ * in the user's codex config. Gates the per-launch `-c` tool-auto-approve+ * override — codex fails to load its config if `-c` targets a server that is+ * not defined, so the launch site adds the override only when this is true.+ * Absent for CLIs where it does not apply.+ *+ * DELIBERATELY WEAKER THAN CLAUDE'S GATE, and not its security equivalent.+ * This is existence-by-name (any object under `mcp_servers.open-knowledge`),+ * whereas claude's `mcpPreApprovable` runs `isOwnManagedEntry` to verify the+ * entry is byte-exactly OK's own. The asymmetry is sound because the two read+ * different files: claude's is a PROJECT-scoped `.mcp.json` that travels in a+ * clone, so a same-named foreign entry is a real RCE vector; codex's target is+ * `scope: 'global'` (`~/.codex/config.toml`, resolved from `home`, never from+ * cwd), so anyone able to plant a foreign entry there can already register+ * arbitrary MCP servers and has won regardless. Tightening this to an exact+ * ownership match would also fail closed on a legitimate entry carrying any+ * extra codex key, silently disabling auto-approve for real users. This gate's+ * job is availability (don't break codex's config load), not authorization. */+ readonly okServerConfigured?: boolean;}export interface OkDesktopBridge {diff --git a/packages/core/src/handoff/index.ts b/packages/core/src/handoff/index.tsindex 05b467132..883482b7b 100644--- a/packages/core/src/handoff/index.ts+++ b/packages/core/src/handoff/index.ts@@ -31,6 +31,7 @@ export {buildClaudeLaunchCommand,buildCliLaunchArgString,buildCliLaunchCommand,+ OK_GATED_TOOL_NAMES,shellSingleQuote,TERMINAL_CLI_IDS,TERMINAL_CLIS,diff --git a/packages/core/src/handoff/terminal-launch.test.ts b/packages/core/src/handoff/terminal-launch.test.tsindex 1099f5533..4a1b8a3a6 100644--- a/packages/core/src/handoff/terminal-launch.test.ts+++ b/packages/core/src/handoff/terminal-launch.test.ts@@ -4,6 +4,7 @@ import {buildClaudeLaunchCommand,buildCliLaunchArgString,buildCliLaunchCommand,+ OK_GATED_TOOL_NAMES,shellSingleQuote,TERMINAL_CLI_IDS,TERMINAL_CLIS,@@ -13,6 +14,8 @@ import {// `.mcp.json` server, mirrored here so the expectation breaks loudly if the// shape (or the canonical server name) ever changes.const CLAUDE_PREAPPROVE = `--settings '{"enabledMcpjsonServers":["${MCP_SERVER_NAME}"]}'`;+const OK_ALLOW = `["mcp__${MCP_SERVER_NAME}","Bash(ok open:*)"]`;+const OK_DENY = `["mcp__${MCP_SERVER_NAME}__delete","mcp__${MCP_SERVER_NAME}__move","mcp__${MCP_SERVER_NAME}__share_link","mcp__${MCP_SERVER_NAME}__install"]`;describe('TERMINAL_CLI_IDS', () => {it('lists the CLIs in auto-pick priority order (claude > codex > opencode > cursor > pi)', () => {@@ -179,6 +182,26 @@ describe('buildCliLaunchArgString promptless (New chat)', () => {expect(arg.endsWith(' ')).toBe(false);});+ it('still applies Claude OK auto-approve on a promptless launch, alone and merged with pre-approval', () => {+ // The cross-product of the two independent branches: with no prompt to trail+ // it, `trimEnd()` must strip the separator space WITHOUT eating the settings+ // arg. A regression here would silently drop auto-approve from "New chat".+ const autoOnly = buildCliLaunchArgString('claude', null, { autoApproveOkTools: true });+ expect(autoOnly).toBe(+ `claude --settings '{"permissions":{"allow":${OK_ALLOW},"deny":${OK_DENY}}}'`,+ );+ expect(autoOnly.endsWith(' ')).toBe(false);++ const both = buildCliLaunchArgString('claude', null, {+ mcpPreApprove: true,+ autoApproveOkTools: true,+ });+ expect(both).toBe(+ `claude --settings '{"enabledMcpjsonServers":["${MCP_SERVER_NAME}"],"permissions":{"allow":${OK_ALLOW},"deny":${OK_DENY}}}'`,+ );+ expect(both.endsWith(' ')).toBe(false);+ });+it('never adds --prompt or a positional to a promptless opencode launch, even opted in', () => {expect(buildCliLaunchArgString('opencode', '', { mcpPreApprove: true })).toBe('opencode');});@@ -218,3 +241,55 @@ describe('claude MCP pre-approval', () => {);});});++describe('OK auto-approve (autoApproveOkTools)', () => {+ it('adds the OK allow-list + destructive deny-list to Claude --settings when on', () => {+ expect(buildCliLaunchArgString('claude', 'hi', { autoApproveOkTools: true })).toBe(+ `claude --settings '{"permissions":{"allow":${OK_ALLOW},"deny":${OK_DENY}}}' 'hi'`,+ );+ });++ it('merges server-trust + auto-approve into one --settings object when both on', () => {+ expect(+ buildCliLaunchArgString('claude', 'hi', { mcpPreApprove: true, autoApproveOkTools: true }),+ ).toBe(+ `claude --settings '{"enabledMcpjsonServers":["${MCP_SERVER_NAME}"],"permissions":{"allow":${OK_ALLOW},"deny":${OK_DENY}}}' 'hi'`,+ );+ });++ it('keeps every gated tool in the deny list (never silently auto-approved)', () => {+ const arg = buildCliLaunchArgString('claude', 'hi', { autoApproveOkTools: true });+ expect(OK_GATED_TOOL_NAMES).toEqual(['delete', 'move', 'share_link', 'install']);+ for (const denied of OK_GATED_TOOL_NAMES) {+ expect(arg).toContain(`"mcp__${MCP_SERVER_NAME}__${denied}"`);+ }+ });++ it('adds the codex per-server `-c approve` override only when on', () => {+ expect(buildCliLaunchArgString('codex', 'hi', { autoApproveOkTools: true })).toBe(+ `codex -c 'mcp_servers.${MCP_SERVER_NAME}.default_tools_approval_mode="approve"' 'hi'`,+ );+ expect(buildCliLaunchArgString('codex', 'hi')).toBe("codex 'hi'");+ });++ it('is claude/codex only — cursor/opencode/pi never get an auto-approve arg', () => {+ expect(buildCliLaunchArgString('cursor', 'hi', { autoApproveOkTools: true })).toBe(+ "cursor-agent 'hi'",+ );+ expect(buildCliLaunchArgString('opencode', 'hi', { autoApproveOkTools: true })).toBe(+ "opencode --prompt 'hi'",+ );+ expect(buildCliLaunchArgString('pi', 'hi', { autoApproveOkTools: true })).toBe("pi 'hi'");+ });++ it('keeps the prompt the final escaped arg with auto-approve on (injection inert)', () => {+ const arg = buildCliLaunchArgString('claude', "'; rm -rf / #", { autoApproveOkTools: true });+ expect(arg.endsWith("''\\''; rm -rf / #'")).toBe(true);+ });++ it('emits a bare `<bin>` for a promptless auto-approve launch with the fixed args', () => {+ expect(buildCliLaunchArgString('codex', null, { autoApproveOkTools: true })).toBe(+ `codex -c 'mcp_servers.${MCP_SERVER_NAME}.default_tools_approval_mode="approve"'`,+ );+ });+});diff --git a/packages/core/src/handoff/terminal-launch.ts b/packages/core/src/handoff/terminal-launch.tsindex 0f8e5b7ac..e8ba1a312 100644--- a/packages/core/src/handoff/terminal-launch.ts+++ b/packages/core/src/handoff/terminal-launch.ts@@ -48,16 +48,16 @@ export type TerminalCli = 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi';export interface TerminalCliInfo {/** PATH binary launched in the PTY. Interpolated (alongside any opted-in- * {@link mcpPreApproveArg}) into the fixed `<bin> [<fixed-args>…] '<prompt>'`- * shape — fixed registry values, never user input. */+ * {@link TerminalCliInfo.autoApproveArg}) into the fixed+ * `<bin> [<fixed-args>…] '<prompt>'` shape — fixed registry values, never+ * user input. */readonly bin: string;- /** Claude's MCP pre-approval fragment, inserted verbatim between `<bin>` and- * the prompt ONLY when the caller passes `mcpPreApprove: true` (see- * {@link buildCliLaunchArgString}) — i.e. after the launch site has verified the- * project's `open-knowledge` `.mcp.json` entry is OK's own. An already-shell-- * safe fragment (NOT re-quoted); registry-fixed, never user input. Claude-only;- * omit for CLIs with no pre-approval. */- readonly mcpPreApproveArg?: string;+ /** Fixed launch arg that auto-approves OK's OWN tools for this CLI, inserted+ * ONLY when the caller passes `autoApproveOkTools: true`. Codex-only today (a+ * `-c` per-server approval-mode override); already shell-safe, registry-fixed,+ * never user input. Claude's equivalent (an allow/deny list) is computed inline+ * by {@link buildClaudeSettingsArg}, not from the registry. */+ readonly autoApproveArg?: string;/** User-facing brand name ("Claude" / "Codex" / "Cursor"). */readonly displayName: string;/** Install / setup docs, opened from the "not installed" terminal banner. */@@ -75,30 +75,81 @@ export interface TerminalCliInfo {}/**- * Claude Code launch arg that pre-approves OK's project-scoped `.mcp.json`- * server (`mcpServers["open-knowledge"]`) so the docked-terminal launch skips- * the one-time "New MCP server found in this project" trust prompt. Applied- * ONLY when the caller opts in via `mcpPreApprove: true`, which the launch site- * sets only after verifying the project's `open-knowledge` entry is OK's OWN- * managed server (`isOwnManagedEntry`) — never blindly by name. That gate is- * load-bearing: `.mcp.json` is committed and travels with shared/cloned- * projects, so a foreign or tampered same-named entry must keep Claude's trust- * prompt rather than be silently approved (RCE / tool-poisoning otherwise).- * `--settings` takes a JSON string the CLI layers on top of the user's- * settings, so passing it per-invocation writes nothing to the user's machine.- * Built from {@link MCP_SERVER_NAME} so the pre-approval names exactly what OK's- * editor wiring registers in `.mcp.json`.+ * Claude allow-rules that let OK's OWN MCP tools + the `ok open` CLI verb run+ * without a per-call approval prompt: `mcp__<server>` matches every tool of OK's+ * MCP server; `Bash(ok open:*)` matches only the `ok open` verb. Registry-fixed,+ * never user input.+ */+const OK_AUTO_APPROVE_ALLOW_RULES: readonly string[] = [+ `mcp__${MCP_SERVER_NAME}`,+ 'Bash(ok open:*)',+];++/**+ * OK MCP tools kept GATED even when auto-approve is on: `deny` out-ranks `allow`+ * in Claude's precedence (deny then ask then allow), so these keep prompting.+ * The goal is a frictionless read/write loop, never a silent `delete` / `move`+ * (KB-wide blast radius), `share_link` (data exfiltration), or `install` (writes+ * executable skill scripts into the agent's own config dir — a persistence+ * vector, unlike a version-recoverable doc write).*- * This pins an external Claude Code contract (`--settings` accepting inline JSON- * + the `enabledMcpjsonServers` key). If a future `claude` drops the key the- * trust prompt simply returns — safe degradation. The bare-launch path- * (`mcpPreApprove` false/omitted) is the default and stays reachable, so if the- * flag ever broke launches it could be disabled without restructuring.+ * The allow-rule is open-ended (`mcp__<server>` matches EVERY OK tool) while this+ * deny-list is closed, so a new destructive tool would silently inherit+ * auto-approval. `registry.test.ts` in the server package pins every registered+ * tool name against this list plus its auto-approved complement — adding a tool+ * fails that test until it is consciously classified. Keep the two in lockstep.+ */+export const OK_GATED_TOOL_NAMES: readonly string[] = ['delete', 'move', 'share_link', 'install'];++const OK_AUTO_APPROVE_DENY_RULES: readonly string[] = OK_GATED_TOOL_NAMES.map(+ (tool) => `mcp__${MCP_SERVER_NAME}__${tool}`,+);++/**+ * Codex per-launch config override (via `-c`, so it writes nothing to the user's+ * `~/.codex/config.toml`) that sets OK's MCP server tool-approval to `approve`+ * ("auto-approve except potentially-unsafe actions", per codex's own permission+ * vocabulary). Registry-fixed. LOAD-BEARING PRECONDITION: only add this when OK's+ * server entry ALREADY exists in the user's codex config — a `-c` key under a+ * non-existent server id creates a partial (command-less) entry that makes codex+ * fail to load its config and breaks the launch. The launch site owns that gate.*/-const CLAUDE_MCP_PREAPPROVE_ARG = `--settings ${shellSingleQuote(- JSON.stringify({ enabledMcpjsonServers: [MCP_SERVER_NAME] }),+const CODEX_OK_AUTO_APPROVE_ARG = `-c ${shellSingleQuote(+ `mcp_servers.${MCP_SERVER_NAME}.default_tools_approval_mode="approve"`,)}`;+/**+ * Build Claude's inline `--settings` arg from two INDEPENDENT opt-ins that share+ * one settings object. `mcpPreApprove` adds server trust (`enabledMcpjsonServers`)+ * so the launch skips the one-time "New MCP server found" prompt — set by the+ * launch site only after `isOwnManagedEntry` verifies the project's+ * `open-knowledge` `.mcp.json` entry is OK's OWN (a committed, cloned `.mcp.json`+ * could carry a foreign same-named server; RCE otherwise). `autoApproveOkTools`+ * adds the OK-tool + `ok open` allow-list and the destructive-tool deny-list.+ * `--settings` takes an inline JSON string the CLI layers on the user's settings,+ * so nothing is written to disk. Returns '' when neither opt-in is set. Content is+ * registry-fixed and single-quoted — never user input.+ */+function buildClaudeSettingsArg(opts: BuildCliLaunchOptions): string {+ const settings: {+ enabledMcpjsonServers?: string[];+ permissions?: { allow: string[]; deny: string[] };+ } = {};+ if (opts.mcpPreApprove === true) {+ settings.enabledMcpjsonServers = [MCP_SERVER_NAME];+ }+ if (opts.autoApproveOkTools === true) {+ settings.permissions = {+ allow: [...OK_AUTO_APPROVE_ALLOW_RULES],+ deny: [...OK_AUTO_APPROVE_DENY_RULES],+ };+ }+ if (settings.enabledMcpjsonServers === undefined && settings.permissions === undefined) {+ return '';+ }+ return `--settings ${shellSingleQuote(JSON.stringify(settings))}`;+}+/*** Static registry for each launchable CLI. Cursor's agent CLI binary is* `cursor-agent` (the `cursor` command opens the GUI editor, not the agent).@@ -109,13 +160,13 @@ export const TERMINAL_CLIS = {displayName: 'Claude',docsUrl: 'https://docs.claude.com/en/docs/claude-code',handoffTarget: 'claude-code',- mcpPreApproveArg: CLAUDE_MCP_PREAPPROVE_ARG,},codex: {bin: 'codex',displayName: 'Codex',docsUrl: 'https://developers.openai.com/codex/cli',handoffTarget: 'codex',+ autoApproveArg: CODEX_OK_AUTO_APPROVE_ARG,},cursor: {bin: 'cursor-agent',@@ -162,22 +213,32 @@ export const TERMINAL_CLI_IDS = [export interface BuildCliLaunchOptions {/**- * Include Claude's MCP pre-approval flag ({@link TerminalCliInfo.mcpPreApproveArg}).+ * Include Claude's MCP server-trust pre-approval (`enabledMcpjsonServers`).* Honored only for `claude`. Defaults to false — the SAFE default. The launch* site sets it true only after confirming the project's `open-knowledge`* `.mcp.json` entry is OK's own (desktop preflight `mcpPreApprovable` ←* `isOwnManagedEntry`); a bare launch lets Claude show its trust prompt.*/readonly mcpPreApprove?: boolean;+ /**+ * Auto-approve OK's OWN tools so the KB read/write loop runs without a per-call+ * prompt. Claude: an allow-list (OK tools + `ok open`) with a destructive-tool+ * deny-list, via {@link buildClaudeSettingsArg}. Codex: the registry+ * {@link TerminalCliInfo.autoApproveArg} `-c` override — the launch site MUST+ * only pass true for codex once it has confirmed OK's server entry exists in the+ * codex config (see that field's precondition). Other CLIs: no effect. Defaults+ * to false.+ */+ readonly autoApproveOkTools?: boolean;}/**- * Build the fixed `<bin> [<mcp-pre-approve>] '<prompt>'` launch shape WITHOUT a- * trailing newline — the CLI's registry binary, then Claude's registry-fixed- * {@link TerminalCliInfo.mcpPreApproveArg} inserted verbatim ONLY when- * `opts.mcpPreApprove` is true, then the prompt POSIX-single-quoted via- * {@link shellSingleQuote}. This is the canonical command string; the two- * transports add what each needs:+ * Build the fixed `<bin> [<fixed-args>…] '<prompt>'` launch shape WITHOUT a+ * trailing newline — the CLI's registry binary, then the opted-in fixed args+ * (Claude's inline `--settings` from {@link buildClaudeSettingsArg}; every other+ * CLI's registry {@link TerminalCliInfo.autoApproveArg}), then the prompt+ * POSIX-single-quoted via {@link shellSingleQuote}. This is the canonical command+ * string; the two transports add what each needs:* - typed into an interactive shell → {@link buildCliLaunchCommand} appends `\r`;* - baked into the launch PTY's `$SHELL -l -i -c '<this>; exec …'` argv → used* as-is (no `\r`: it's an argv element, not bytes fed to the line editor, so@@ -198,17 +259,27 @@ export function buildCliLaunchArgString(opts: BuildCliLaunchOptions = {},): string {const info: TerminalCliInfo = TERMINAL_CLIS[cli];- const preApprove =- opts.mcpPreApprove === true && info.mcpPreApproveArg ? `${info.mcpPreApproveArg} ` : '';- // Promptless: emit a bare `<bin>` (plus any opted-in pre-approval). `preApprove`+ // Registry-fixed fixed args between `<bin>` and the prompt (never user input):+ // Claude's inline `--settings` (server trust + OK auto-approve allow/deny),+ // computed inline because two independent opt-ins share one settings object;+ // every other CLI uses its registry `autoApproveArg` when `autoApproveOkTools`+ // is on (codex's `-c` override today).+ const fixedArgs =+ cli === 'claude'+ ? buildClaudeSettingsArg(opts)+ : opts.autoApproveOkTools === true && info.autoApproveArg+ ? info.autoApproveArg+ : '';+ const fixedPrefix = fixedArgs ? `${fixedArgs} ` : '';+ // Promptless: emit a bare `<bin>` (plus any opted-in fixed args). `fixedPrefix`// carries its own trailing separator space, redundant with nothing after it.if (prompt == null || prompt.length === 0) {- return `${info.bin} ${preApprove}`.trimEnd();+ return `${info.bin} ${fixedPrefix}`.trimEnd();}// CLIs whose positional arg isn't the prompt (e.g. OpenCode, whose positional// is the project dir) carry it via a flag instead.const promptFlag = info.promptFlag ? `${info.promptFlag} ` : '';- return `${info.bin} ${preApprove}${promptFlag}${shellSingleQuote(prompt)}`;+ return `${info.bin} ${fixedPrefix}${promptFlag}${shellSingleQuote(prompt)}`;}/**diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex a14122f75..39557170b 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -363,6 +363,7 @@ export {type IpcChannelReason,type IpcChannelWithUrn,lookupUrnInRegistry,+ OK_GATED_TOOL_NAMES,OK_PROJECT_SKILL_POINTER,OK_TERMINAL_SURFACE_PREAMBLE,shellSingleQuote,diff --git a/packages/desktop/src/main/claude-readiness.ts b/packages/desktop/src/main/claude-readiness.tsindex c4468bf04..d7f2c2ec1 100644--- a/packages/desktop/src/main/claude-readiness.ts+++ b/packages/desktop/src/main/claude-readiness.ts@@ -182,6 +182,12 @@ export interface ResolveCliOnPathDeps {/** Runs the login-shell PATH probe for the CLI's binary; resolves the exit* code or `null` (probe failed → UNKNOWN). */probe(): Promise<number | null>;+ /** Codex-only: whether OK's MCP server is already configured in the user's+ * codex config (gates the per-launch `-c` auto-approve override). Synchronous;+ * a throw here degrades to `false` (treated as not configured) rather than+ * failing the whole readiness probe. Omit for CLIs where it does not apply —+ * the result then carries no `okServerConfigured`. */+ okServerConfigured?(): boolean;}/**@@ -200,7 +206,18 @@ export async function resolveCliOnPath(deps: ResolveCliOnPathDeps): Promise<CliR);return null;});- return { onPath: interpretClaudeProbe(code) };+ const onPath = interpretClaudeProbe(code);+ if (deps.okServerConfigured === undefined) return { onPath };+ let okServerConfigured = false;+ try {+ okServerConfigured = deps.okServerConfigured();+ } catch (err) {+ getLogger('cli-readiness').warn(+ { err },+ 'okServerConfigured probe threw; treating the OK server as not configured',+ );+ }+ return { onPath, okServerConfigured };}export interface ResolveCliInstalledMapDeps {diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex df72ce221..806f414e7 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -2868,6 +2868,17 @@ function resolveTerminalClaudeReadiness(projectRoot: string | undefined): Promisfunction resolveTerminalCliOnPath(cli: TerminalCli): Promise<CliReadiness> {return resolveCliOnPath({probe: () => probeLoginShellOnPath(cliProbeArgs(TERMINAL_CLIS[cli].bin)),+ // Codex-only: report whether OK's `open-knowledge` server is already in the+ // user's codex config, so the launch site adds the `-c` tool-auto-approve+ // override only when it won't break config load (a `-c` under an undefined+ // server id makes codex fail to load its config). `classifyExistingMcpEntry`+ // never throws; `resolveCliOnPath` guards it anyway.+ ...(cli === 'codex'+ ? {+ okServerConfigured: () =>+ classifyExistingMcpEntry(EDITOR_TARGETS.codex, '', osHomedir()).kind === 'present',+ }+ : {}),});}diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.tsindex 06b24d42a..ba47ceb74 100644--- a/packages/desktop/src/shared/bridge-contract.ts+++ b/packages/desktop/src/shared/bridge-contract.ts@@ -965,6 +965,25 @@ export interface ClaudeReadiness {*/export interface CliReadiness {readonly onPath: 'present' | 'not-found' | 'unknown';+ /** Codex-only: whether OK's `open-knowledge` MCP server is already configured+ * in the user's codex config. Gates the per-launch `-c` tool-auto-approve+ * override — codex fails to load its config if `-c` targets a server that is+ * not defined, so the launch site adds the override only when this is true.+ * Absent for CLIs where it does not apply.+ *+ * DELIBERATELY WEAKER THAN CLAUDE'S GATE, and not its security equivalent.+ * This is existence-by-name (any object under `mcp_servers.open-knowledge`),+ * whereas claude's `mcpPreApprovable` runs `isOwnManagedEntry` to verify the+ * entry is byte-exactly OK's own. The asymmetry is sound because the two read+ * different files: claude's is a PROJECT-scoped `.mcp.json` that travels in a+ * clone, so a same-named foreign entry is a real RCE vector; codex's target is+ * `scope: 'global'` (`~/.codex/config.toml`, resolved from `home`, never from+ * cwd), so anyone able to plant a foreign entry there can already register+ * arbitrary MCP servers and has won regardless. Tightening this to an exact+ * ownership match would also fail closed on a legitimate entry carrying any+ * extra codex key, silently disabling auto-approve for real users. This gate's+ * job is availability (don't break codex's config load), not authorization. */+ readonly okServerConfigured?: boolean;}/** Renderer-facing Electron bridge. Populated on `window.okDesktop` by the desktop preload script. */diff --git a/packages/desktop/tests/main/claude-readiness.test.ts b/packages/desktop/tests/main/claude-readiness.test.tsindex 6c6a874ce..ca1b53ccf 100644--- a/packages/desktop/tests/main/claude-readiness.test.ts+++ b/packages/desktop/tests/main/claude-readiness.test.ts@@ -279,6 +279,26 @@ describe('resolveCliOnPath', () => {onPath: 'unknown',});});++ test('folds okServerConfigured when the codex-only dep is supplied', async () => {+ expect(+ await resolveCliOnPath({ probe: () => Promise.resolve(0), okServerConfigured: () => true }),+ ).toEqual({ onPath: 'present', okServerConfigured: true });+ expect(+ await resolveCliOnPath({ probe: () => Promise.resolve(0), okServerConfigured: () => false }),+ ).toEqual({ onPath: 'present', okServerConfigured: false });+ });++ test('a throwing okServerConfigured dep degrades to false (never fails the probe)', async () => {+ expect(+ await resolveCliOnPath({+ probe: () => Promise.resolve(0),+ okServerConfigured: () => {+ throw new Error('codex config read blew up');+ },+ }),+ ).toEqual({ onPath: 'present', okServerConfigured: false });+ });});describe('resolveCliInstalledMap', () => {diff --git a/packages/server/src/mcp/tools/registry.test.ts b/packages/server/src/mcp/tools/registry.test.tsindex f9487de0f..b25ffa170 100644--- a/packages/server/src/mcp/tools/registry.test.ts+++ b/packages/server/src/mcp/tools/registry.test.ts@@ -19,10 +19,12 @@* This test guards both ends: the 17 retained tools are present; none of the* names in RETIRED_TOOL_NAMES are.*/+import { describe, expect, test } from 'bun:test';import { mkdtempSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';+import { OK_GATED_TOOL_NAMES } from '@inkeep/open-knowledge-core';import { type Config, ConfigSchema } from '../../config/schema.ts';import { registerAllTools } from './index.ts';import type { ServerInstance } from './shared.ts';@@ -151,3 +153,58 @@ describe('registerAllTools — 19-tool surface (SPEC.md §9.1 / AC8 + PRD-6935 iexpect(names.length).toBe(new Set(names).size);});});++/**+ * Guards the docked terminal's auto-approve policy (core `terminal-launch.ts`)+ * against this registry. Claude's allow-rule is the open-ended `mcp__<server>`+ * (every OK tool); safety is subtracted back by the CLOSED `OK_GATED_TOOL_NAMES`+ * deny-list. Left uncoupled, a newly registered destructive tool would inherit+ * auto-approval the moment it shipped.+ *+ * Every registered tool must therefore appear in exactly one of the two lists —+ * adding a tool fails here until it is consciously classified as gated or+ * auto-approved.+ *+ * On the auto-approved side: `write` / `edit` / `checkpoint` / `restore_version`+ * / `resolve_conflict` all mutate KB content, but the shadow repo versions every+ * write, so `history` + `restore_version` recover them. `exec` is a read-only+ * allowlisted sandbox. `install` is NOT here — it projects executable skill+ * scripts into the agent's own config dir, which no KB version history undoes.+ */+const OK_AUTO_APPROVED_TOOLS = [+ 'exec',+ 'search',+ 'history',+ 'links',+ 'skills',+ 'config',+ 'palette',+ 'preview_url',+ 'write',+ 'edit',+ 'checkpoint',+ 'restore_version',+ 'conflicts',+ 'resolve_conflict',+ 'workflow',+] as const;++describe('docked-terminal auto-approve classification', () => {+ test('every registered tool is classified as gated or auto-approved', () => {+ expect(new Set([...OK_AUTO_APPROVED_TOOLS, ...OK_GATED_TOOL_NAMES])).toEqual(+ new Set(captureRegistered()),+ );+ });++ test('no tool is both gated and auto-approved', () => {+ const gated = new Set<string>(OK_GATED_TOOL_NAMES);+ expect(OK_AUTO_APPROVED_TOOLS.filter((name) => gated.has(name))).toEqual([]);+ });++ test('the deny-list only names tools that actually exist', () => {+ const registered = new Set(captureRegistered());+ for (const gated of OK_GATED_TOOL_NAMES) {+ expect(registered).toContain(gated);+ }+ });+});