Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix(security): record engine folder trust only for folders the daemon made empty (OH-14) (#351)

0xken15bbb3a1f5be53
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index b56f5423e..e8cbf6465 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -15,6 +15,7 @@ import * as mediaPreview from './lib/mediaPreview.js'
import * as gitProject from './lib/gitProject.js'
import * as machineResources from './lib/machineResources.js'
import * as projectFolder from './lib/projectFolder.js'
+import * as claudeTrust from './lib/claudeTrust.js'
import * as projectPreview from './lib/projectPreview.js'
import * as storeCatalog from './dsh/catalog.js'
import { randomUUID } from 'node:crypto'
@@ -212,6 +213,12 @@ const wsMock = vi.hoisted(() => {
})
vi.mock('ws', () => ({ WebSocket: wsMock.MockWebSocket }))
+// Never the person's real ~/.claude.json or ~/.codex/config.toml: creating an agent records folder trust,
+// and an unmocked run of these specs used to write test paths into the developer's own config.
+vi.mock('./lib/claudeTrust.js', () => ({
+ claudeTrusts: vi.fn(() => false), codexTrusts: vi.fn(() => false),
+ preTrustClaudeProject: vi.fn(() => 'trusted'), preTrustCodexProject: vi.fn(() => 'trusted'),
+}))
function parseSent(ws: InstanceType<typeof wsMock.MockWebSocket>): Array<Record<string, unknown>> {
return ws.sent.map((s) => JSON.parse(s) as Record<string, unknown>)
@@ -1177,6 +1184,33 @@ describe('BackendSocket outbound queue', () => {
}
})
+ it.each([
+ { name: 'a new empty folder', project: { projectSource: 'new' }, sourceTrusted: false, trusts: true },
+ { name: 'a clone', project: { projectSource: 'remote', repositoryUrl: 'owner/repo' }, sourceTrusted: false, trusts: false },
+ { name: 'the person\'s own repo (branch)', project: { projectSource: 'branch', gitSource: '/work/repo', branchRef: 'refs/heads/feature' }, sourceTrusted: true, trusts: false },
+ { name: 'a worktree of an untrusted repo', project: { projectSource: 'worktree', gitSource: '/work/repo', branchRef: 'refs/heads/main' }, sourceTrusted: false, trusts: false },
+ { name: 'a worktree of a repo Claude already trusts', project: { projectSource: 'worktree', gitSource: '/work/repo', branchRef: 'refs/heads/main' }, sourceTrusted: true, trusts: true },
+ ])('records Claude trust for $name: $trusts', async ({ project, sourceTrusted, trusts }) => {
+ // Only a folder the daemon made empty, or a worktree of a repo already trusted, is trusted for the person.
+ const socket = new BackendSocket('token')
+ const frames: Array<Record<string, unknown>> = []
+ socket.registerLocalClient('local:trust', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })
+ vi.spyOn(projectFolder, 'prepareProjectFolder').mockResolvedValue('/work/prepared')
+ vi.mocked(claudeTrust.claudeTrusts).mockReturnValue(sourceTrusted)
+ vi.mocked(claudeTrust.preTrustClaudeProject).mockClear()
+ socket.onCreateAgent = vi.fn(async () => ({ ok: false as const, error: 'TMUX_UNAVAILABLE' }))
+ try {
+ socket.handleLocalFrame('local:trust', { type: 'agent_create', payload: { requestId: 'r', creationId: randomUUID(), engine: 'claude', ...project } })
+ await vi.waitFor(() => expect(socket.onCreateAgent).toHaveBeenCalled())
+ if (trusts) expect(claudeTrust.preTrustClaudeProject).toHaveBeenCalledExactlyOnceWith('/work/prepared')
+ else expect(claudeTrust.preTrustClaudeProject).not.toHaveBeenCalled()
+ if (project.projectSource === 'worktree') expect(claudeTrust.claudeTrusts).toHaveBeenCalledWith('/work/repo')
+ } finally {
+ await socket.unregisterLocalClient('local:trust')
+ await socket.stop()
+ }
+ })
+
it('checks an unknown creation without spawning and rejects malformed creation ids before launch', async () => {
const socket = new BackendSocket('token')
const frames: Array<Record<string, unknown>> = []
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 9c8d9637e..f28285bc5 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -50,7 +50,7 @@ import { readMachineResources } from './lib/machineResources.js'
import { AgentCreationReceipts, AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationStatus } from './lib/agentCreationReceipt.js'
import { engineInstallRecipe } from './lib/engineInstall.js'
import { parseProjectFolder, prepareProjectFolder, ProjectFolderError } from './lib/projectFolder.js'
-import { preTrustClaudeProject, preTrustCodexProject } from './lib/claudeTrust.js'
+import { claudeTrusts, codexTrusts, preTrustClaudeProject, preTrustCodexProject } from './lib/claudeTrust.js'
import { projectPreview } from './lib/projectPreview.js'
import { readGitProject } from './lib/gitProject.js'
import { agentFrame, lastActivityAt, type AgentDshContext, type AgentFrame } from './lib/agentFrame.js'
@@ -2359,10 +2359,16 @@ export class BackendSocket {
return { state: 'failed', error: error instanceof ProjectFolderError ? error.code : 'PROJECT_PREPARATION_FAILED',
detail: error instanceof ProjectFolderError ? error.message : 'Could not prepare the project folder.' }
}
- // A folder this daemon just made is one Claude Code need not ask about.
+ // Only a folder this daemon just made EMPTY is one the engine need not ask about. A clone or
+ // the person's own repo is theirs to answer for (lib/claudeTrust.ts); a worktree gets only
+ // the answer its source repo already has. `branch` IS the source folder: nothing to record.
try {
- if (input.engine === 'claude') preTrustClaudeProject(preparedFolder)
- if (input.engine === 'codex') preTrustCodexProject(preparedFolder)
+ const engineTrust = input.engine === 'claude' ? { trusts: claudeTrusts, record: preTrustClaudeProject }
+ : input.engine === 'codex' ? { trusts: codexTrusts, record: preTrustCodexProject } : null
+ if (engineTrust && (projectFolder.source === 'new'
+ || (projectFolder.source === 'worktree' && engineTrust.trusts(projectFolder.gitSource)))) {
+ engineTrust.record(preparedFolder)
+ }
} catch (error) { console.warn(`[agent] pre-trust ${preparedFolder} · ${error instanceof Error ? error.message : error}`) }
}
const result = await create(preparedFolder ? { ...input, cwd: preparedFolder } : input)
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index fa90a4913..fa0b6479d 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -188,7 +188,7 @@ import {
} from './lib/selfUpdate.js'
import { managedNodePath } from './lib/nodeRuntime.js'
import { ensureLauncher, ensureManagedGrid, ensureManagedRuntime, startGridPinRecheck } from './lib/runtimeInstall.js'
-import { stat } from 'fs/promises'
+import { readdir, stat } from 'fs/promises'
import { CodexNormalizer, codexTaskError, lastCodexTurnText } from './engines/codex/normalizer.js'
import { codexSubagentResolverFor } from './engines/codex/subagent.js'
import { CursorNormalizer, lastCursorTurnText } from './engines/cursor/normalizer.js'
@@ -4939,11 +4939,17 @@ async function runForeground(session: AuthSession | null): Promise<void> {
}
try {
dshAccount = { privateGrid: await backend.privateGridName().catch(() => null) }
+ // Asked BEFORE the template goes in: afterwards every folder has content.
+ // Not there yet is empty; unreadable is not — trust is only ever granted on evidence.
+ const emptyBefore = await readdir(cwd).then((names) => names.length === 0,
+ (error: NodeJS.ErrnoException) => error.code === 'ENOENT')
const materialized = await materializeWorkspace(installed, cwd, dshAccount, engine)
for (const warning of materialized.warnings) console.warn(`[dsh] ${dsh} materialize · ${warning}`)
console.log(`[dsh] ${dsh} materialized ${cwd} · created ${materialized.created.length} · kept ${materialized.kept.length}`)
- // The template just went in: the folder is the harness's, and Claude Code need not ask.
- if (materialized.created.some((item) => item.startsWith('template'))) {
+ // The template just went into an EMPTY folder: everything in it is the harness's, and Claude Code
+ // need not ask. Laid into a folder that already held something — a clone, the person's own repo —
+ // it proves nothing about the rest, so trust stays the person's call (lib/claudeTrust.ts).
+ if (emptyBefore && materialized.created.some((item) => item.startsWith('template'))) {
try {
if (engine === 'claude') preTrustClaudeProject(cwd)
if (engine === 'codex') preTrustCodexProject(cwd)
diff --git a/cli/src/lib/claudeTrust.spec.ts b/cli/src/lib/claudeTrust.spec.ts
index 801ef4da0..255ba29c2 100644
--- a/cli/src/lib/claudeTrust.spec.ts
+++ b/cli/src/lib/claudeTrust.spec.ts
@@ -2,7 +2,7 @@ import { lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, symlinkSy
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
-import { preTrustClaudeProject, preTrustCodexProject } from './claudeTrust.js'
+import { claudeTrusts, codexTrusts, preTrustClaudeProject, preTrustCodexProject } from './claudeTrust.js'
describe('preTrustClaudeProject', () => {
it('records trust for a new folder the way Claude Code does, keeping everything else', () => {
@@ -146,3 +146,33 @@ describe('preTrustCodexProject', () => {
expect(readFileSync(join(home, 'dotfiles', 'codex.toml'), 'utf8')).toContain('[projects."/Users/example/w"]')
})
})
+
+describe('whether a source repo is already trusted (a worktree inherits only that)', () => {
+ it('reads Claude trust from the folder or a folder above it, as Claude Code does', () => {
+ const home = mkdtempSync(join(tmpdir(), 'trust-'))
+ expect(claudeTrusts('/work/repo', home)).toBe(false)
+ writeFileSync(join(home, '.claude.json'), JSON.stringify({ projects: {
+ '/work/repo': { hasTrustDialogAccepted: true },
+ '/work/other': { hasTrustDialogAccepted: false },
+ '/code/': { hasTrustDialogAccepted: true },
+ } }))
+ expect(claudeTrusts('/work/repo', home)).toBe(true)
+ expect(claudeTrusts('/work/repo/sub', home)).toBe(true)
+ expect(claudeTrusts('/code/anything', home)).toBe(true)
+ expect(claudeTrusts('/work/other', home)).toBe(false)
+ expect(claudeTrusts('/work/repo-evil', home)).toBe(false) // a prefix of the name is not a parent
+ writeFileSync(join(home, '.claude.json'), '{not json')
+ expect(claudeTrusts('/work/repo', home)).toBe(false)
+ })
+
+ it('reads Codex trust from exactly that folder\'s table', () => {
+ const home = mkdtempSync(join(tmpdir(), 'trust-'))
+ expect(codexTrusts('/work/repo', home)).toBe(false)
+ mkdirSync(join(home, '.codex'))
+ writeFileSync(join(home, '.codex', 'config.toml'),
+ '[projects."/work/repo"]\ntrust_level = "trusted"\n\n[projects."/work/other"]\ntrust_level = "untrusted"\n')
+ expect(codexTrusts('/work/repo', home)).toBe(true)
+ expect(codexTrusts('/work/other', home)).toBe(false)
+ expect(codexTrusts('/work', home)).toBe(false)
+ })
+})
diff --git a/cli/src/lib/claudeTrust.ts b/cli/src/lib/claudeTrust.ts
index 9bc5c9a90..f598b5e5d 100644
--- a/cli/src/lib/claudeTrust.ts
+++ b/cli/src/lib/claudeTrust.ts
@@ -1,12 +1,16 @@
/**
* Claude Code asks "do you trust this folder?" the first time it opens a project. For a workspace
- * Harness itself just made — a fresh `~/harnesses/codex-2026-09-17-15-26`, or a harness template it laid out —
- * the answer is the one the person already gave by clicking Create, so the daemon records it the
- * way Claude Code does: `projects[<path>].hasTrustDialogAccepted` in `~/.claude.json`.
+ * Harness itself just made EMPTY — a fresh `~/harnesses/codex-2026-09-17-15-26`, or one a harness
+ * template was laid into — there is nothing in it to review, so the daemon records the answer the way
+ * Claude Code does: `projects[<path>].hasTrustDialogAccepted` in `~/.claude.json`.
*
- * Only ever ADDS trust for a folder the daemon created; never touches a folder the person chose
- * themselves, never removes anything, and does nothing when Claude Code has never run here (no
- * `~/.claude.json`), when the file does not parse, or when the entry already says yes.
+ * ⚠️ Never for a folder with content the person has not been asked about — a clone, their own repo,
+ * a worktree of one: that answer is theirs. The callers decide; see `backendSocket.ts` (project
+ * folders) and `cli.ts` (harness templates). A worktree only inherits the answer its source repo
+ * already has.
+ *
+ * Only ever ADDS trust, never removes anything, and does nothing when Claude Code has never run here
+ * (no `~/.claude.json`), when the file does not parse, or when the entry already says yes.
*/
import { existsSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs'
import { homedir } from 'node:os'
@@ -51,6 +55,22 @@ export function preTrustClaudeProject(cwd: string, home = homedir()): 'trusted'
return 'trusted'
}
+/** Whether Claude Code already trusts `path`: its own entry, or a folder above it, says yes — the
+ * same inheritance Claude Code applies. Unreadable or absent config reads as no. */
+export function claudeTrusts(path: string, home = homedir()): boolean {
+ const file = join(home, '.claude.json')
+ if (!existsSync(file)) return false
+ let config: unknown
+ try { config = JSON.parse(readFileSync(file, 'utf8')) } catch { return false }
+ if (!isPlainObject(config) || !isPlainObject(config.projects)) return false
+ for (const [key, entry] of Object.entries(config.projects)) {
+ if (!isPlainObject(entry) || entry.hasTrustDialogAccepted !== true) continue
+ const base = key.replace(/\/+$/, '')
+ if (path === base || path.startsWith(`${base}/`)) return true
+ }
+ return false
+}
+
/** A `[projects.<key>]` header, however it is spaced or quoted. */
const CODEX_PROJECT_HEADER_RE = /^[ \t]*\[[ \t]*projects[ \t]*\.[ \t]*("(?:[^"\\\r\n]|\\.)*"|'[^'\r\n]*')[ \t]*\]/gm
/** `projects` defined any other way: an inline table, dotted keys, or a bare `[projects]` table. */
@@ -62,10 +82,26 @@ function tomlKey(quoted: string): string | null {
try { return JSON.parse(quoted) as string } catch { return null }
}
+/** Whether Codex already trusts exactly `path` (a `[projects."<path>"]` table saying `trusted`). */
+export function codexTrusts(path: string, home = homedir()): boolean {
+ const file = join(home, '.codex', 'config.toml')
+ if (!existsSync(file)) return false
+ const text = readFileSync(file, 'utf8')
+ for (const match of text.matchAll(CODEX_PROJECT_HEADER_RE)) {
+ if (tomlKey(match[1]) !== path) continue
+ // The table's body runs to the next header; its trust_level is the answer.
+ const rest = text.slice((match.index ?? 0) + match[0].length)
+ const body = rest.split(/^[ \t]*\[/m)[0]
+ return /^[ \t]*trust_level[ \t]*=[ \t]*["']trusted["']/m.test(body)
+ }
+ return false
+}
+
/**
* Codex keeps the same answer in `~/.codex/config.toml` as a `[projects."<path>"]` table with
- * `trust_level = "trusted"`. Same rules: only a folder the daemon made, only when Codex has a
- * config here, never rewriting what is there — the table is appended at the end.
+ * `trust_level = "trusted"`. Same rules: only a folder the daemon made empty (or a worktree of one Codex
+ * already trusts), only when Codex has a config here, never rewriting what is there — the table is
+ * appended at the end.
*
* Appending is only safe when nothing else defines that table. The same folder under another quoting,
* or `projects` written as an inline table or dotted keys, would make the appended table a duplicate