(await d.dispatch('grep', { pattern: 'key' }));
+ expect(grep.matches.map((m) => path.relative(project, m.file))).toEqual([path.join('src', 'ok.txt')]);
+ expect(grep.filtered).toBe(2);
+ });
+
+ it('puts additionalDirectories in the snapshot', async () => {
+ const extra = path.join(base, 'extra');
+ mkdirSync(extra);
+ const { policy } = await claude({ permissions: { additionalDirectories: [extra] } });
+ expect(policy.additionalRoots).toEqual([extra]);
+ });
+
+ it.runIf(posix)('matches deny rules against the path as written, not only the real path', async () => {
+ const { d, project } = await claude({ permissions: { deny: ['Read(./secrets/**)'] } }, { 'data/key.txt': 'k\n' });
+ symlinkSync(path.join(project, 'data'), path.join(project, 'secrets'));
+ const viaLink = await d.dispatch('read', { path: 'secrets/key.txt' });
+ expect(viaLink.ok).toBe(false);
+ expect(viaLink.ok ? undefined : viaLink.error.code).toBe('denied');
+ value(await d.dispatch('read', { path: 'data/key.txt' }));
+ });
+});
diff --git a/src/core/dispatcher.ts b/src/core/dispatcher.ts
index 30a1ecc..30819c0 100644
--- a/src/core/dispatcher.ts
+++ b/src/core/dispatcher.ts
@@ -1,3 +1,4 @@
+import { realpathSync } from 'node:fs';
import path from 'node:path';
import { ToolError, errorMessage } from './errors.js';
import { frozenCopy } from './freeze.js';
@@ -130,10 +131,15 @@ export class Dispatcher {
readonly #warnings: string[] = [];
#deniedCount = 0;
#bashCommits = 0;
+ /** The session cwd and roots as real paths, the form prepared paths take. */
+ readonly #canonicalCwd: string;
+ readonly #canonicalRoots: readonly string[];
constructor(opts: DispatcherOptions
) {
this.#opts = opts;
this.#now = opts.now ?? (() => performance.now());
+ this.#canonicalCwd = canonicalPath(opts.ctx.cwd);
+ this.#canonicalRoots = [...new Set([...opts.ctx.roots, ...(isPolicyError(opts.policy) ? [] : (opts.policy.additionalRoots ?? []))])].map(canonicalPath);
}
/** Signal aborted when the dispatcher stops. */
@@ -333,7 +339,7 @@ export class Dispatcher
{
if (returned === ABORTED) return this.#stoppedFailure();
// A dispatcher-owned deep-frozen copy: what is authorized and then
// committed cannot be changed by the runtime or anyone holding its object.
- prepared = frozenCopy(returned);
+ prepared = frozenCopy(withRequestedPath(returned, call));
} catch (err) {
return this.#toolFailure(err);
}
@@ -341,7 +347,7 @@ export class Dispatcher
{
return { kind: 'error', error: new ToolError('tool-error', 'tool runtime returned a prepared call for another call') };
}
if (prepared.tool === 'write' || prepared.tool === 'edit') {
- const hit = findMatchingPattern(prepared.effect.absPath, policy.protectedPaths);
+ const hit = findMatchingPattern(prepared.effect.absPath, this.#protectedPatterns(policy));
if (hit !== undefined) {
return { kind: 'error', error: new ToolError('protected-path', `${prepared.effect.absPath} is a protected host policy path`) };
}
@@ -487,8 +493,39 @@ export class Dispatcher
{
return { ok: false, error };
}
+ /**
+ * Protected patterns as written by the adapter plus the same patterns with
+ * a cwd or root prefix rewritten to its real path: prepared paths are real
+ * paths, so a cwd reached through a symlink must not let a write slip past
+ * a pattern spelled with the symlinked cwd.
+ */
+ #protectedPatterns(policy: PolicySnapshot
): readonly string[] {
+ if (this.#protectedCache?.policy === policy) return this.#protectedCache.patterns;
+ const pairs: [string, string][] = [];
+ const add = (spelled: string, real: string): void => {
+ if (spelled !== real && path.isAbsolute(spelled)) pairs.push([spelled, real]);
+ };
+ add(this.#opts.ctx.cwd, this.#canonicalCwd);
+ const spelledRoots = [...new Set([...this.#opts.ctx.roots, ...(policy.additionalRoots ?? [])])];
+ spelledRoots.forEach((root, i) => add(root, this.#canonicalRoots[i] ?? root));
+ const out = new Set(policy.protectedPaths);
+ for (const pattern of policy.protectedPaths) {
+ for (const [spelled, real] of pairs) {
+ const rel = path.relative(spelled, pattern);
+ if (rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))) out.add(rel === '' ? real : path.join(real, rel));
+ }
+ // Patterns under some other symlinked directory (e.g. home): resolve their literal prefix.
+ out.add(canonicalPattern(pattern));
+ }
+ const patterns = [...out];
+ this.#protectedCache = { policy, patterns };
+ return patterns;
+ }
+
+ #protectedCache: { readonly policy: PolicySnapshot
; readonly patterns: readonly string[] } | undefined;
+
#addChanged(absPath: string): void {
- const shown = displayPath(absPath, this.#opts.ctx.cwd);
+ const shown = displayPath(absPath, this.#canonicalCwd);
if (!this.#changed.includes(shown)) this.#changed.push(shown);
}
@@ -497,6 +534,42 @@ export class Dispatcher
{
}
}
+/** Real path of `p`, or `p` resolved lexically when it does not exist. */
+function canonicalPath(p: string): string {
+ try {
+ return realpathSync.native(p);
+ } catch {
+ return path.resolve(p);
+ }
+}
+
+/** A path pattern whose literal (wildcard-free) directory prefix is replaced by its real path when it exists. */
+function canonicalPattern(pattern: string): string {
+ if (!path.isAbsolute(pattern)) return pattern;
+ const parts = pattern.split(/[\\/]/);
+ const firstWild = parts.findIndex((part) => /[*?[]/.test(part));
+ const literalCount = firstWild === -1 ? parts.length - 1 : firstWild;
+ for (let n = literalCount; n > 1; n--) {
+ const prefix = parts.slice(0, n).join(path.sep) || path.sep;
+ let real: string;
+ try {
+ real = realpathSync.native(prefix);
+ } catch {
+ continue;
+ }
+ return path.join(real, ...parts.slice(n));
+ }
+ return pattern;
+}
+
+/** The prepared call with `requestedPath` set from the call the script made (never from the runtime). */
+function withRequestedPath(prepared: PreparedCall, call: ToolCall): PreparedCall {
+ const { requestedPath: _ignored, ...rest } = prepared;
+ const requested = call.tool === 'bash' ? undefined : call.args.path;
+ // The spread keeps the tool/args/effect pairing of `prepared`; only the optional field changes.
+ return requested === undefined ? rest : { ...rest, requestedPath: requested };
+}
+
/** Path relative to `cwd` when inside it, else the absolute path. */
export function displayPath(absPath: string, cwd: string): string {
const rel = path.relative(cwd, absPath);
diff --git a/src/core/types.ts b/src/core/types.ts
index 34193eb..0eb823f 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -157,10 +157,14 @@ export interface WriteResult {
}
/**
- * How `edit` located `oldString`. `exact` is a byte-for-byte match; the other
- * strategies are tolerant fallbacks the tool runtime may implement.
+ * How `edit` located `oldString`: the rung of the tolerant-match ladder that
+ * found it, tried in this order. `exact` is a byte-for-byte match;
+ * `line-endings` ignores CRLF/LF differences; `line-numbers` strips line
+ * numbers copied from `read` output; `trailing-whitespace` ignores spaces at
+ * line ends; `indentation` ignores a uniform indentation shift; `punctuation`
+ * folds typographic quotes and dashes to ASCII.
*/
-export type MatchStrategy = 'exact' | 'line-trimmed' | 'whitespace-normalized' | 'indentation-flexible';
+export type MatchStrategy = 'exact' | 'line-endings' | 'line-numbers' | 'trailing-whitespace' | 'indentation' | 'punctuation';
/** Result of `edit`. */
export interface EditResult {
@@ -188,6 +192,8 @@ export interface GrepResult {
readonly matches: readonly GrepMatch[];
/** True when more matches existed than were returned. */
readonly truncated: boolean;
+ /** Files left out of the search because the host's Read rules deny them (`PolicySnapshot.readFilter`). */
+ readonly filtered: number;
}
/** Result of `glob`. */
@@ -196,6 +202,8 @@ export interface GlobResult {
readonly files: readonly string[];
/** True when more files existed than were returned. */
readonly truncated: boolean;
+ /** Entries left out because the host's Read rules deny them (`PolicySnapshot.readFilter`). */
+ readonly filtered: number;
}
/** Maps each tool to its result type. */
@@ -320,6 +328,15 @@ export type PreparedCall = {
readonly tool: K;
readonly args: ToolArgsMap[K];
readonly effect: ToolEffectMap[K];
+ /**
+ * The `path` argument exactly as the script wrote it (before `~`
+ * expansion, cwd resolution and symlink resolution), for host rules that
+ * must also match the path as written. Absent for `bash` and when grep or
+ * glob got no path. Set by the dispatcher from the very call it prepared
+ * (any value the tool runtime returns is replaced), so it always names the
+ * path that resolved to `effect.absPath` / `effect.absRoot`.
+ */
+ readonly requestedPath?: string;
};
}[ToolName];
@@ -407,6 +424,19 @@ export interface PolicySnapshot
{
* tool runtime refuses writes and edits there with `ToolError('protected-path')`.
*/
readonly protectedPaths: readonly string[];
+ /**
+ * The host's additional working directories (e.g. Claude
+ * `permissions.additionalDirectories`, `--add-dir`): absolute directories
+ * the tools may touch besides the session cwd and roots.
+ */
+ readonly additionalRoots?: readonly string[];
+ /**
+ * Whether a real absolute path is readable under the host's Read rules.
+ * The tool runtime applies it to every grep match and glob entry and drops
+ * the ones it returns false for, counting them in `filtered`. Absent: every
+ * path inside the workspace is readable.
+ */
+ readonly readFilter?: (realAbsPath: string) => boolean;
readonly payload: P;
}
diff --git a/src/hosts/claude/adapter.test.ts b/src/hosts/claude/adapter.test.ts
new file mode 100644
index 0000000..2d03783
--- /dev/null
+++ b/src/hosts/claude/adapter.test.ts
@@ -0,0 +1,612 @@
+import { mkdir, mkdtemp, readFile, realpath, symlink, writeFile } from 'node:fs/promises';
+import { createServer, type Server } from 'node:http';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { afterAll, describe, expect, it } from 'vitest';
+import { Dispatcher } from '../../core/dispatcher.js';
+import type { Decision, PolicySnapshot, PreparedCall, SessionContext } from '../../core/types.js';
+import { MemoryToolRuntime, makeContext } from '../../testing/index.js';
+import { ClaudeHostAdapter, type ClaudePolicy } from './adapter.js';
+
+const posix = process.platform !== 'win32';
+const FIXTURES = path.join(path.dirname(fileURLToPath(import.meta.url)), 'fixtures');
+const HOOK = path.join(FIXTURES, 'example-hook.mjs');
+
+/** A command hook handler running the example hook in `mode`. */
+function exampleHook(mode: string, arg?: string, extra: Record = {}): Record {
+ return { type: 'command', command: process.execPath, args: [HOOK, mode, ...(arg === undefined ? [] : [arg])], ...extra };
+}
+
+function preHooks(matcher: string, ...hooks: Record[]): Record {
+ return { hooks: { PreToolUse: [{ matcher, hooks }] } };
+}
+
+interface Setup {
+ readonly adapter: ClaudeHostAdapter;
+ readonly ctx: SessionContext;
+ readonly policy: PolicySnapshot;
+ readonly project: string;
+ readonly home: string;
+ readonly base: string;
+}
+
+interface SetupOptions {
+ readonly project?: Record;
+ readonly local?: Record;
+ readonly user?: Record;
+ /** Extra Claude CLI args seen on the parent process. */
+ readonly argv?: readonly string[];
+ readonly trusted?: boolean;
+ /** Live permission mode from the companion hook. */
+ readonly mode?: string;
+ readonly env?: Record;
+ readonly files?: Record;
+}
+
+async function setup(o: SetupOptions = {}): Promise {
+ const base = await realpath(await mkdtemp(path.join(os.tmpdir(), 'acm-claude-')));
+ const home = path.join(base, 'home');
+ const project = path.join(base, 'project');
+ await mkdir(path.join(home, '.claude'), { recursive: true });
+ await mkdir(path.join(project, '.claude'), { recursive: true });
+ if (o.project) await writeFile(path.join(project, '.claude', 'settings.json'), JSON.stringify(o.project));
+ if (o.local) await writeFile(path.join(project, '.claude', 'settings.local.json'), JSON.stringify(o.local));
+ if (o.user) await writeFile(path.join(home, '.claude', 'settings.json'), JSON.stringify(o.user));
+ if (o.trusted !== false) await writeFile(path.join(home, '.claude.json'), JSON.stringify({ projects: { [project]: { hasTrustDialogAccepted: true } } }));
+ for (const [rel, content] of Object.entries(o.files ?? {})) {
+ await mkdir(path.dirname(path.join(project, rel)), { recursive: true });
+ await writeFile(path.join(project, rel), content);
+ }
+ const adapter = new ClaudeHostAdapter({
+ env: o.env ?? {},
+ home,
+ managedDir: null,
+ stateDir: path.join(base, 'state'),
+ readParent: async () => (o.argv ? { argv: ['claude', ...o.argv], cwd: project } : undefined),
+ });
+ const ctx = makeContext(project, {
+ host: 'claude',
+ sessionId: 'session-1',
+ toolUseId: 'toolu_1',
+ transcriptPath: path.join(base, 't.jsonl'),
+ permissionMode: o.mode ?? 'default',
+ sources: o.mode === undefined ? { cwd: 'roots' } : { cwd: 'roots', permissionMode: 'ctx-file' },
+ });
+ const policy = await adapter.loadPolicy(ctx);
+ if ('error' in policy) throw new Error(policy.error);
+ return { adapter, ctx, policy, project, home, base };
+}
+
+const containment = { mode: 'none' } as const;
+
+function bash(command: string, cwd: string): PreparedCall {
+ return { id: 'c1', tool: 'bash', args: { command, cwd, timeoutMs: 120_000 }, effect: { command, cwd, timeoutMs: 120_000, containment } };
+}
+function read(p: string, real = p): PreparedCall {
+ return { id: 'c1', tool: 'read', args: { path: p, offset: 1, limit: 2000 }, effect: { absPath: real, offset: 1, limit: 2000 } };
+}
+function write(p: string, content = 'x'): PreparedCall {
+ return { id: 'c1', tool: 'write', args: { path: p, content }, effect: { absPath: p, beforeHash: null, afterContent: content, diff: '' } };
+}
+function edit(p: string, matched: string, newString: string): PreparedCall {
+ return {
+ id: 'c1',
+ tool: 'edit',
+ args: { path: p, oldString: matched.trim(), newString },
+ effect: { absPath: p, beforeHash: 'h', afterContent: newString, diff: '', matchedOldString: matched, matchStrategy: 'trailing-whitespace', replacements: 1 },
+ };
+}
+function grep(root: string): PreparedCall {
+ return { id: 'c1', tool: 'grep', args: { pattern: 'x', path: root }, effect: { absRoot: root, pattern: 'x', glob: '*.ts', ignoreCase: true, maxResults: 50 } };
+}
+function glob(root: string): PreparedCall {
+ return { id: 'c1', tool: 'glob', args: { pattern: '**/*.ts', path: root }, effect: { absRoot: root, pattern: '**/*.ts', maxResults: 50 } };
+}
+
+function check(s: Setup, prepared: PreparedCall): Decision['kind'] {
+ return s.adapter.checkStatic(prepared, s.ctx, s.policy).kind;
+}
+
+function authorize(s: Setup, prepared: PreparedCall, signal = new AbortController().signal): Promise {
+ return s.adapter.authorize(prepared, s.ctx, s.policy, signal);
+}
+
+describe('Bash rules', () => {
+ it.each([
+ ['echo ok && rm -rf x', 'deny'],
+ ['echo $(rm -rf x)', 'deny'],
+ ['echo `rm x`', 'deny'],
+ ['FOO=1 rm x', 'deny'],
+ ['timeout 5 rm x', 'deny'],
+ ['sudo rm x', 'deny'],
+ ['sudo -u root rm x', 'deny'],
+ ["bash -c 'rm x'", 'deny'],
+ ['sh -ec "echo a; rm x"', 'deny'],
+ ['nice -n 5 nohup rm x', 'deny'],
+ ['env A=1 rm x', 'deny'],
+ ['/bin/rm -rf build', 'deny'],
+ ['ls | xargs rm', 'deny'],
+ ['ls | xargs -n1 rm', 'deny'],
+ ['find . -name a -exec rm {} \\;', 'deny'],
+ ['cat <(rm z)', 'deny'],
+ ['(cd sub && rm x)', 'deny'],
+ ['for f in a b; do rm "$f"; done', 'deny'],
+ ['rm', 'deny'],
+ ['rm $TARGET', 'deny'],
+ ['echo ok', 'allow'],
+ ['rmdir x', 'allow'],
+ ['echo rm', 'allow'],
+ ['echo "unbalanced', 'ask'],
+ ['eval "$X"', 'ask'],
+ ['cat < {
+ const s = await setup({ user: { permissions: { deny: ['Bash(rm:*)'] } }, mode: 'bypassPermissions' });
+ expect(check(s, bash(command, s.project))).toBe(expected);
+ });
+
+ it('applies ask rules after deny rules, in every mode', async () => {
+ const s = await setup({ user: { permissions: { deny: ['Bash(git push --force *)'], ask: ['Bash(git push *)'] } }, mode: 'bypassPermissions' });
+ expect(check(s, bash('git push --force origin', s.project))).toBe('deny');
+ expect(check(s, bash('git push origin main', s.project))).toBe('ask');
+ expect(check(s, bash('cd x && echo "$(git push)"', s.project))).toBe('ask');
+ expect(check(s, bash('git status', s.project))).toBe('allow');
+ });
+
+ it('matches a parameter rule and the ambiguous timeout command', async () => {
+ const s = await setup({ user: { permissions: { deny: ['Bash(timeout:*)'] } }, mode: 'bypassPermissions' });
+ // `timeout:*` is both a parameter rule (any timeout) and a `timeout` prefix rule: strict reading denies.
+ expect(check(s, bash('echo hi', s.project))).toBe('deny');
+ });
+
+ it('allow rules approve only when every subcommand is approved', async () => {
+ const s = await setup({ user: { permissions: { allow: ['Bash(npm run *)', 'Bash(git status)'] } } });
+ expect(check(s, bash('npm run build', s.project))).toBe('allow');
+ expect(check(s, bash('npm run build && git status', s.project))).toBe('allow');
+ expect(check(s, bash('timeout 30 npm run test', s.project))).toBe('allow');
+ expect(check(s, bash('npm run build && rm -rf x', s.project))).toBe('ask');
+ expect(check(s, bash('NODE_ENV=x npm run build', s.project))).toBe('ask');
+ expect(check(s, bash('sudo npm run build', s.project))).toBe('ask');
+ expect(check(s, bash('npm install', s.project))).toBe('ask');
+ expect(check(s, bash('npm run build > /tmp/out.log', s.project))).toBe('ask');
+ expect(check(s, bash('npm run build > out.log', s.project))).toBe('allow');
+ });
+
+ it('checks redirect and file-reader targets against Read/Edit rules', async () => {
+ const s = await setup({ user: { permissions: { deny: ['Read(./.env)', 'Edit(./locked/**)'] } }, mode: 'bypassPermissions' });
+ expect(check(s, bash('cat .env', s.project))).toBe('deny');
+ expect(check(s, bash('wc -l < .env', s.project))).toBe('deny');
+ expect(check(s, bash('echo x > .env', s.project))).toBe('deny'); // a Read deny also blocks writes
+ expect(check(s, bash('echo x > locked/a.txt', s.project))).toBe('deny');
+ expect(check(s, bash('echo x | tee locked/a.txt', s.project))).toBe('deny');
+ expect(check(s, bash('echo x > "$OUT"', s.project))).toBe('ask');
+ expect(check(s, bash('cd sub && cat .env', s.project))).toBe('ask');
+ expect(check(s, bash('echo x > notes.txt', s.project))).toBe('allow');
+ expect(check(s, bash('cat README.md 2>/dev/null', s.project))).toBe('allow');
+ });
+});
+
+describe('path rules', () => {
+ it('anchors //, ~/, /, ./ and bare patterns like gitignore', async () => {
+ const s = await setup({
+ project: { permissions: { deny: ['Read(./.env)', 'Edit(/src/generated/**)', 'Read(secrets/**)', 'Read(*.pem)'] } },
+ user: { permissions: { deny: ['Read(~/notes/secret.txt)', 'Read(//etc/example-shadow)', 'Read(/private/**)'] } },
+ mode: 'bypassPermissions',
+ });
+ const p = (rel: string): string => path.join(s.project, rel);
+ expect(check(s, read(p('.env')))).toBe('deny');
+ expect(check(s, read(p('sub/.env')))).toBe('allow'); // ./ is anchored
+ expect(check(s, read(path.join(s.home, 'notes', 'secret.txt')))).toBe('deny');
+ expect(check(s, read('/etc/example-shadow'))).toBe('deny');
+ expect(check(s, write(p('src/generated/a.ts')))).toBe('deny');
+ expect(check(s, edit(p('src/generated/deep/b.ts'), 'a', 'b'))).toBe('deny');
+ expect(check(s, write(p('src/a.ts')))).toBe('allow');
+ expect(check(s, write(p('vendor/src/generated/a.ts')))).toBe('allow');
+ expect(check(s, read(p('a/b/secrets/key')))).toBe('deny'); // single-dir deny matches at any depth
+ expect(check(s, read(p('certs/x.pem')))).toBe('deny'); // bare name: any depth
+ expect(check(s, read(path.join(s.home, '.claude', 'private', 'x')))).toBe('deny'); // `/` in user settings → config dir
+ expect(check(s, read(p('private/x')))).toBe('allow');
+ expect(check(s, write(p('.env')))).toBe('deny'); // Read deny blocks Write
+ expect(check(s, grep(p('a/secrets')))).toBe('deny'); // Read rules govern Grep
+ expect(check(s, glob(p('secrets')))).toBe('deny'); // and Glob
+ expect(check(s, grep(p('src')))).toBe('allow');
+ });
+
+ it.skipIf(!posix)('checks the real path, so a symlink cannot dodge a deny', async () => {
+ const s = await setup({ project: { permissions: { deny: ['Read(./.env)'] } }, mode: 'bypassPermissions', files: { '.env': 'SECRET=1' } });
+ await symlink(path.join(s.project, '.env'), path.join(s.project, 'innocent.txt'));
+ const real = await realpath(path.join(s.project, 'innocent.txt'));
+ expect(check(s, read(path.join(s.project, 'innocent.txt'), real))).toBe('deny');
+ });
+
+ it.skipIf(!posix)('applies a rule written through a symlinked directory to the real location', async () => {
+ const s0 = await setup();
+ const realDir = path.join(s0.base, 'real-secrets');
+ await mkdir(realDir);
+ await symlink(realDir, path.join(s0.base, 'alias'));
+ const s = await setup({ user: { permissions: { deny: [`Read(/${path.join(s0.base, 'alias')}/**)`] } }, mode: 'bypassPermissions' });
+ expect(check(s, read(path.join(realDir, 'k')))).toBe('deny');
+ });
+
+ it('allow rules need both the requested and the real path to match', async () => {
+ const s = await setup({ user: { permissions: { allow: ['Read(//opt/shared/**)'] } } });
+ expect(check(s, read('/opt/shared/a'))).toBe('allow');
+ expect(check(s, read('/opt/shared/link', '/etc/passwd'))).toBe('ask');
+ });
+});
+
+describe('permission modes (no rule matches)', () => {
+ const cases: Record> = {
+ default: { readIn: 'allow', readOut: 'ask', writeIn: 'ask', writeOut: 'ask', editIn: 'ask', bash: 'ask', grepIn: 'allow', globIn: 'allow' },
+ acceptEdits: { readIn: 'allow', readOut: 'ask', writeIn: 'allow', writeOut: 'ask', editIn: 'allow', bash: 'ask', grepIn: 'allow', globIn: 'allow' },
+ plan: { readIn: 'allow', readOut: 'ask', writeIn: 'deny', writeOut: 'deny', editIn: 'deny', bash: 'deny', grepIn: 'allow', globIn: 'allow' },
+ dontAsk: { readIn: 'allow', readOut: 'deny', writeIn: 'deny', writeOut: 'deny', editIn: 'deny', bash: 'deny', grepIn: 'allow', globIn: 'allow' },
+ auto: { readIn: 'allow', readOut: 'allow', writeIn: 'allow', writeOut: 'allow', editIn: 'allow', bash: 'allow', grepIn: 'allow', globIn: 'allow' },
+ bypassPermissions: { readIn: 'allow', readOut: 'allow', writeIn: 'allow', writeOut: 'allow', editIn: 'allow', bash: 'allow', grepIn: 'allow', globIn: 'allow' },
+ 'not-a-mode': { readIn: 'allow', readOut: 'ask', writeIn: 'ask', writeOut: 'ask', editIn: 'ask', bash: 'ask', grepIn: 'allow', globIn: 'allow' },
+ };
+ for (const [mode, expected] of Object.entries(cases)) {
+ it(`${mode}`, async () => {
+ const s = await setup({ mode });
+ const inside = path.join(s.project, 'a.ts');
+ const outside = path.join(s.base, 'elsewhere', 'b.ts');
+ const got = {
+ readIn: check(s, read(inside)),
+ readOut: check(s, read(outside)),
+ writeIn: check(s, write(inside)),
+ writeOut: check(s, write(outside)),
+ editIn: check(s, edit(inside, 'a', 'b')),
+ bash: check(s, bash('ls', s.project)),
+ grepIn: check(s, grep(s.project)),
+ globIn: check(s, glob(s.project)),
+ };
+ expect(got).toEqual(expected);
+ });
+ }
+
+ it('ask rules still ask in bypassPermissions and deny in dontAsk', async () => {
+ const ask = { user: { permissions: { ask: ['Read(./a.ts)'] } } };
+ const bypass = await setup({ ...ask, mode: 'bypassPermissions' });
+ expect(check(bypass, read(path.join(bypass.project, 'a.ts')))).toBe('ask');
+ const dontAsk = await setup({ ...ask, mode: 'dontAsk' });
+ expect(check(dontAsk, read(path.join(dontAsk.project, 'a.ts')))).toBe('deny');
+ });
+
+ it('takes the mode from the companion hook, else the CLI flag, else settings defaultMode', async () => {
+ const fromFlag = await setup({ argv: ['--permission-mode', 'acceptEdits'], user: { permissions: { defaultMode: 'plan' } } });
+ expect(check(fromFlag, write(path.join(fromFlag.project, 'a.ts')))).toBe('allow');
+ const fromSettings = await setup({ user: { permissions: { defaultMode: 'plan' } } });
+ expect(check(fromSettings, write(path.join(fromSettings.project, 'a.ts')))).toBe('deny');
+ const fromCtx = await setup({ mode: 'bypassPermissions', argv: ['--permission-mode', 'plan'] });
+ expect(check(fromCtx, bash('ls', fromCtx.project))).toBe('allow');
+ const locked = await setup({ mode: 'bypassPermissions', user: { permissions: { disableBypassPermissionsMode: 'disable' } } });
+ expect(check(locked, bash('ls', locked.project))).toBe('ask');
+ });
+
+ it('additionalDirectories count as working directories', async () => {
+ const s = await setup({ user: { permissions: { additionalDirectories: ['~/shared'] } } });
+ expect(check(s, read(path.join(s.home, 'shared', 'x')))).toBe('allow');
+ });
+});
+
+describe.skipIf(!posix)('PreToolUse hooks', () => {
+ const anyBash = (s: Setup): PreparedCall => bash('ls -la', s.project);
+
+ it('exit 2 denies with stderr as the reason', async () => {
+ const s = await setup({ user: preHooks('Bash', exampleHook('exit2')) });
+ expect(await authorize(s, anyBash(s))).toEqual({ kind: 'deny', source: 'hook', reason: 'blocked by example hook' });
+ });
+
+ it('a shell-form hook script denies', async () => {
+ const s = await setup({ user: preHooks('Bash', { type: 'command', command: `"${path.join(FIXTURES, 'deny-rm.sh')}"` }) });
+ expect(await authorize(s, bash('rm -rf build', s.project))).toMatchObject({ kind: 'deny', source: 'hook', reason: 'rm is not allowed' });
+ expect(await authorize(s, bash('ls', s.project))).toEqual({ kind: 'allow' });
+ });
+
+ it.each([
+ ['deny', { kind: 'deny', source: 'hook' }],
+ ['legacy-block', { kind: 'deny', source: 'hook', reason: 'legacy block' }],
+ ['stop', { kind: 'deny', source: 'hook', reason: 'stop requested' }],
+ ['ask', { kind: 'ask' }],
+ ['defer', { kind: 'ask' }],
+ ['allow', { kind: 'allow' }],
+ ['empty', { kind: 'allow' }],
+ ['exit1', { kind: 'deny', source: 'hook-error' }],
+ ['crash', { kind: 'deny', source: 'hook-error' }],
+ ['invalid', { kind: 'deny', source: 'hook-error' }],
+ ['bad-decision', { kind: 'deny', source: 'hook-error' }],
+ ])('JSON/exit behavior %s', async (mode, expected) => {
+ const s = await setup({ user: preHooks('Bash', exampleHook(mode)) });
+ expect(await authorize(s, anyBash(s))).toMatchObject(expected);
+ });
+
+ it('a hook that cannot start denies', async () => {
+ const s = await setup({ user: preHooks('Bash', { type: 'command', command: path.join(s0Dir(), 'missing-hook.sh') }) });
+ expect(await authorize(s, anyBash(s))).toMatchObject({ kind: 'deny', source: 'hook-error' });
+ });
+
+ it('honors onFailure: continue', async () => {
+ const s = await setup({ user: preHooks('Bash', exampleHook('crash', undefined, { onFailure: 'continue' })) });
+ expect(await authorize(s, anyBash(s))).toEqual({ kind: 'allow' });
+ });
+
+ it('times out, kills the hook and denies with hook-timeout', async () => {
+ const pidFile = path.join(os.tmpdir(), `acm-hook-pid-${process.pid}-${Date.now()}`);
+ const s = await setup({ user: preHooks('Bash', { type: 'command', command: `echo $$ > "${pidFile}"; exec sleep 30`, timeout: 0.5 }) });
+ const started = Date.now();
+ const decision = await authorize(s, anyBash(s));
+ expect(decision).toMatchObject({ kind: 'deny', source: 'hook-timeout' });
+ expect(Date.now() - started).toBeLessThan(5_000);
+ const pid = Number((await readFile(pidFile, 'utf8')).trim());
+ await new Promise((r) => setTimeout(r, 100));
+ expect(() => process.kill(pid, 0)).toThrow();
+ });
+
+ it('rewrites the call with updatedInput (mapped back to binding args)', async () => {
+ const s = await setup({ user: preHooks('Bash', exampleHook('update', JSON.stringify({ command: 'echo safe', timeout: 5000 }))) });
+ expect(await authorize(s, anyBash(s))).toEqual({
+ kind: 'allow',
+ reason: 'example allow',
+ updatedArgs: { command: 'echo safe', cwd: s.project, timeoutMs: 5000 },
+ });
+ const w = await setup({ user: preHooks('Write', exampleHook('update-only', JSON.stringify({ file_path: '/x/y', content: 'clean' }))) });
+ expect(await authorize(w, write(path.join(w.project, 'a')))).toMatchObject({ kind: 'allow', updatedArgs: { path: '/x/y', content: 'clean' } });
+ const bad = await setup({ user: preHooks('Bash', exampleHook('update', JSON.stringify({ command: 'ls', run_in_background: true }))) });
+ expect(await authorize(bad, anyBash(bad))).toMatchObject({ kind: 'deny', source: 'hook' });
+ });
+
+ it('matches tool names exactly or by regex', async () => {
+ const exact = await setup({ user: preHooks('Edit|Write', exampleHook('deny')) });
+ expect((await authorize(exact, write(path.join(exact.project, 'a')))).kind).toBe('deny');
+ expect((await authorize(exact, read(path.join(exact.project, 'a')))).kind).toBe('allow');
+ const partial = await setup({ user: preHooks('Bas', exampleHook('deny')) });
+ expect((await authorize(partial, anyBash(partial))).kind).toBe('allow');
+ const regex = await setup({ user: preHooks('^(Bash|Read)$', exampleHook('deny')) });
+ expect((await authorize(regex, read(path.join(regex.project, 'a')))).kind).toBe('deny');
+ expect((await authorize(regex, glob(regex.project))).kind).toBe('allow');
+ const all = await setup({ user: preHooks('*', exampleHook('deny')) });
+ expect((await authorize(all, grep(all.project))).kind).toBe('deny');
+ });
+
+ it('combines parallel hooks: deny > ask > allow; two updatedInputs are refused', async () => {
+ const denyWins = await setup({ user: preHooks('Bash', exampleHook('allow'), exampleHook('deny'), exampleHook('ask')) });
+ expect((await authorize(denyWins, anyBash(denyWins))).kind).toBe('deny');
+ const askWins = await setup({ user: preHooks('Bash', exampleHook('allow'), exampleHook('ask')) });
+ expect((await authorize(askWins, anyBash(askWins))).kind).toBe('ask');
+ const twoUpdates = await setup({
+ user: preHooks('Bash', exampleHook('update', JSON.stringify({ command: 'a' })), exampleHook('update', JSON.stringify({ command: 'b' }))),
+ });
+ expect(await authorize(twoUpdates, anyBash(twoUpdates))).toMatchObject({ kind: 'deny', source: 'unsupported-config' });
+ const started = Date.now();
+ const slow = await setup({ user: preHooks('Bash', exampleHook('sleep', '600'), exampleHook('sleep', '600'), exampleHook('sleep', '600')) });
+ expect((await authorize(slow, anyBash(slow))).kind).toBe('allow');
+ expect(Date.now() - started).toBeLessThan(1_700); // ran in parallel, not 1.8 s in sequence
+ });
+
+ it('merges hooks from every source and runs a duplicate once', async () => {
+ const record = path.join(os.tmpdir(), `acm-dup-${process.pid}-${Date.now()}`);
+ const hook = { type: 'command', command: `echo run >> "${record}"` };
+ const s = await setup({ user: preHooks('Bash', hook), project: preHooks('Bash', hook) });
+ await authorize(s, anyBash(s));
+ expect((await readFile(record, 'utf8')).trim().split('\n')).toEqual(['run']);
+ });
+
+ it('disableAllHooks turns hooks off', async () => {
+ const s = await setup({ user: preHooks('Bash', exampleHook('deny')), project: { disableAllHooks: true } });
+ expect((await authorize(s, anyBash(s))).kind).toBe('allow');
+ });
+
+ it('a hook type it cannot evaluate denies matching calls with unsupported-config', async () => {
+ const s = await setup({ user: preHooks('Bash', { type: 'prompt', prompt: 'Is this safe? $ARGUMENTS' }) });
+ expect(await authorize(s, anyBash(s))).toMatchObject({ kind: 'deny', source: 'unsupported-config' });
+ expect((await authorize(s, read(path.join(s.project, 'a')))).kind).toBe('allow'); // matcher does not match
+ const weird = await setup({ user: preHooks('Bash', { type: 'teleport' }) });
+ expect(await authorize(weird, anyBash(weird))).toMatchObject({ kind: 'deny', source: 'unsupported-config' });
+ });
+
+ it('honors the `if` filter', async () => {
+ const s = await setup({ user: preHooks('Bash', exampleHook('deny', undefined, { if: 'Bash(git push *)' })) });
+ expect((await authorize(s, bash('git status', s.project))).kind).toBe('allow');
+ expect((await authorize(s, bash('npm test && git push origin', s.project))).kind).toBe('deny');
+ expect((await authorize(s, bash('echo $(date)', s.project))).kind).toBe('deny'); // dynamic: runs anyway
+ });
+
+ it('exec form substitutes ${CLAUDE_PROJECT_DIR} and exports it', async () => {
+ const s = await setup({ files: { '.claude/hooks/check.mjs': "process.stderr.write(process.env.CLAUDE_PROJECT_DIR + '|' + process.argv[2]); process.exit(2);" } });
+ const s2 = await setup({ user: preHooks('Bash', { type: 'command', command: process.execPath, args: [`${s.project}/.claude/hooks/check.mjs`, '${CLAUDE_PROJECT_DIR}'] }) });
+ const d = await authorize(s2, anyBash(s2));
+ expect(d).toEqual({ kind: 'deny', source: 'hook', reason: `${s2.project}|${s2.project}` });
+ });
+
+ it('runs hooks of enabled plugins', async () => {
+ const s0 = await setup();
+ const pluginRoot = path.join(s0.base, 'plugin');
+ await mkdir(path.join(pluginRoot, 'hooks'), { recursive: true });
+ await writeFile(path.join(pluginRoot, 'hooks', 'hooks.json'), JSON.stringify(preHooks('Bash', exampleHook('deny'))));
+ const configDir = path.join(s0.base, 'config');
+ await mkdir(path.join(configDir, 'plugins'), { recursive: true });
+ await writeFile(path.join(configDir, 'plugins', 'installed_plugins.json'), JSON.stringify({ plugins: { 'guard@example': [{ installPath: pluginRoot }] } }));
+ await writeFile(path.join(configDir, 'settings.json'), JSON.stringify({ enabledPlugins: { 'guard@example': true } }));
+ const s = await setup({ env: { CLAUDE_CONFIG_DIR: configDir } });
+ expect(await authorize(s, anyBash(s))).toMatchObject({ kind: 'deny', source: 'hook' });
+ });
+
+ it('sends the exact native payload (byte-identical command)', async () => {
+ const out = path.join(os.tmpdir(), `acm-payload-${process.pid}-${Date.now()}.json`);
+ const s = await setup({ user: preHooks('*', exampleHook('record', out)) });
+ const command = 'printf "%s" \'héllo "wörld"\' && echo ✓\nline two\t$HOME \\n';
+ expect((await authorize(s, bash(command, path.join(s.project, 'sub')))).kind).toBe('allow');
+ const payload: unknown = JSON.parse(await readFile(out, 'utf8'));
+ expect(payload).toEqual({
+ session_id: 'session-1',
+ transcript_path: path.join(s.base, 't.jsonl'),
+ cwd: path.join(s.project, 'sub'),
+ permission_mode: 'default',
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Bash',
+ tool_input: { command, timeout: 120_000, description: 'agent-code-mode script call c1', run_in_background: false },
+ tool_use_id: 'toolu_1/c1',
+ });
+
+ await authorize(s, edit(path.join(s.project, 'a.ts'), ' const a = 1;', 'const a = 2;'));
+ expect(JSON.parse(await readFile(out, 'utf8'))).toMatchObject({
+ tool_name: 'Edit',
+ tool_input: { file_path: path.join(s.project, 'a.ts'), old_string: ' const a = 1;', new_string: 'const a = 2;', replace_all: false },
+ });
+ await authorize(s, grep(s.project));
+ expect(JSON.parse(await readFile(out, 'utf8'))).toMatchObject({
+ tool_name: 'Grep',
+ tool_input: { pattern: 'x', path: s.project, glob: '*.ts', '-i': true, output_mode: 'content', '-n': true, head_limit: 50 },
+ });
+ });
+
+ it('kills running hooks when the signal aborts', async () => {
+ const s = await setup({ user: preHooks('Bash', exampleHook('sleep', '30000')) });
+ const controller = new AbortController();
+ const started = Date.now();
+ const pending = authorize(s, anyBash(s), controller.signal);
+ setTimeout(() => controller.abort(), 200);
+ expect((await pending).kind).toBe('deny');
+ expect(Date.now() - started).toBeLessThan(5_000);
+ });
+});
+
+function s0Dir(): string {
+ return os.tmpdir();
+}
+
+describe('HTTP hooks', () => {
+ let server: Server | undefined;
+ let url = '';
+ let reply: { status: number; body: string } = { status: 200, body: '' };
+ let lastBody = '';
+ let lastAuth: string | undefined;
+
+ async function start(): Promise {
+ if (server) return;
+ server = createServer((req, res) => {
+ const chunks: Buffer[] = [];
+ req.on('data', (c: Buffer) => chunks.push(c));
+ req.on('end', () => {
+ lastBody = Buffer.concat(chunks).toString('utf8');
+ lastAuth = req.headers['authorization'];
+ res.writeHead(reply.status, { 'content-type': 'application/json' });
+ res.end(reply.body);
+ });
+ });
+ await new Promise((resolve) => server?.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ if (address === null || typeof address === 'string') throw new Error('no address');
+ url = `http://127.0.0.1:${address.port}/hook`;
+ }
+
+ afterAll(async () => {
+ await new Promise((r) => server?.close(r));
+ });
+
+ it('POSTs the input and applies the JSON decision', async () => {
+ await start();
+ reply = { status: 200, body: JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: 'http says no' } }) };
+ const s = await setup({
+ user: preHooks('Bash', { type: 'http', url, headers: { Authorization: 'Bearer $HOOK_TOKEN', 'X-Other': '$NOT_ALLOWED' }, allowedEnvVars: ['HOOK_TOKEN'] }),
+ });
+ process.env['HOOK_TOKEN'] = 'tok';
+ try {
+ expect(await authorize(s, bash('ls', s.project))).toEqual({ kind: 'deny', source: 'hook', reason: 'http says no' });
+ } finally {
+ delete process.env['HOOK_TOKEN'];
+ }
+ expect(JSON.parse(lastBody)).toMatchObject({ tool_name: 'Bash', tool_input: { command: 'ls' } });
+ expect(lastAuth).toBe('Bearer tok');
+ });
+
+ it('treats a non-2xx status or a non-JSON body as a failure (deny) unless onFailure is continue', async () => {
+ await start();
+ reply = { status: 500, body: 'oops' };
+ const s = await setup({ user: preHooks('Bash', { type: 'http', url }) });
+ expect(await authorize(s, bash('ls', s.project))).toMatchObject({ kind: 'deny', source: 'hook-error' });
+ reply = { status: 200, body: 'plain text' };
+ expect(await authorize(s, bash('ls', s.project))).toMatchObject({ kind: 'deny', source: 'hook-error' });
+ reply = { status: 200, body: '' };
+ expect(await authorize(s, bash('ls', s.project))).toEqual({ kind: 'allow' });
+ reply = { status: 503, body: '' };
+ const lenient = await setup({ user: preHooks('Bash', { type: 'http', url, onFailure: 'continue' }) });
+ expect(await authorize(lenient, bash('ls', lenient.project))).toEqual({ kind: 'allow' });
+ });
+
+ it('times out', async () => {
+ const hang = createServer(() => undefined);
+ await new Promise((resolve) => hang.listen(0, '127.0.0.1', resolve));
+ const address = hang.address();
+ if (address === null || typeof address === 'string') throw new Error('no address');
+ const s = await setup({ user: preHooks('Bash', { type: 'http', url: `http://127.0.0.1:${address.port}/`, timeout: 0.3 }) });
+ expect(await authorize(s, bash('ls', s.project))).toMatchObject({ kind: 'deny', source: 'hook-timeout' });
+ hang.closeAllConnections();
+ await new Promise((r) => hang.close(r));
+ });
+});
+
+describe.skipIf(!posix)('PostToolUse hooks', () => {
+ it('reports a block as an error the dispatcher turns into a warning', async () => {
+ const s = await setup({ user: { hooks: { PostToolUse: [{ matcher: 'Bash', hooks: [exampleHook('exit2')] }] } } });
+ const result = { exitCode: 0, signal: null, stdout: 'ok', stderr: '', truncated: false, timedOut: false };
+ await expect(s.adapter.postToolUse(bash('ls', s.project), result, s.ctx, s.policy)).rejects.toThrow(/blocked after the call ran.*blocked by example hook/);
+ const quiet = await setup({ user: { hooks: { PostToolUse: [{ matcher: 'Bash', hooks: [exampleHook('empty')] }] } } });
+ await expect(quiet.adapter.postToolUse(bash('ls', quiet.project), result, quiet.ctx, quiet.policy)).resolves.toBeUndefined();
+ });
+});
+
+describe('policy snapshot', () => {
+ it('lists protected paths and no containment without the sandbox', async () => {
+ const s = await setup();
+ expect(s.policy.bashContainment).toEqual({ mode: 'none' });
+ expect(s.policy.protectedPaths).toEqual(
+ expect.arrayContaining([
+ path.join(s.project, '.claude', 'settings*.json'),
+ path.join(s.project, '.claude', 'hooks', '**'),
+ path.join(s.project, '.claude', 'agents', '**'),
+ path.join(s.project, '.mcp.json'),
+ path.join(s.home, '.claude', '**'),
+ path.join(s.base, 'state', '**'),
+ ]),
+ );
+ });
+
+ it('returns a sandbox containment when Claude sandboxing is enabled', async () => {
+ const s = await setup({ user: { sandbox: { enabled: true, filesystem: { allowWrite: ['~/.cache/tool', '/opt/build'] } }, permissions: { additionalDirectories: ['/opt/extra'] } } });
+ expect(s.policy.bashContainment).toEqual({
+ mode: 'sandbox',
+ readOnly: false,
+ writableRoots: [s.project, path.resolve(s.project, '/opt/extra'), path.join(s.home, '.cache', 'tool'), path.resolve(s.project, '/opt/build')],
+ network: false,
+ });
+ });
+});
+
+describe.skipIf(!posix)('with the dispatcher', () => {
+ it('re-prepares and re-checks a hook rewrite; a rewrite into a denied command is refused', async () => {
+ const s = await setup({
+ user: {
+ permissions: { deny: ['Bash(rm:*)'] },
+ hooks: {
+ PreToolUse: [
+ { matcher: 'Write', hooks: [exampleHook('update', JSON.stringify({ file_path: '/workspace/a.txt', content: 'sanitized' }))] },
+ { matcher: 'Bash', hooks: [exampleHook('update', JSON.stringify({ command: 'rm -rf /workspace' }))] },
+ ],
+ },
+ },
+ mode: 'bypassPermissions',
+ });
+ const tools = new MemoryToolRuntime({ root: '/workspace' });
+ const ctx: SessionContext = { ...s.ctx, cwd: '/workspace', roots: ['/workspace'] };
+ const dispatcher = new Dispatcher({ adapter: s.adapter, tools, ctx, policy: s.policy });
+ const wrote = await dispatcher.dispatch('write', { path: 'a.txt', content: 'secret' });
+ expect(wrote.ok).toBe(true);
+ expect(tools.read('a.txt')).toBe('sanitized');
+ const ran = await dispatcher.dispatch('bash', { command: 'echo hi' });
+ expect(ran).toMatchObject({ ok: false, error: { name: 'PermissionDenied', source: 'rule' } });
+ });
+});
diff --git a/src/hosts/claude/adapter.ts b/src/hosts/claude/adapter.ts
new file mode 100644
index 0000000..36c1dfd
--- /dev/null
+++ b/src/hosts/claude/adapter.ts
@@ -0,0 +1,733 @@
+import { realpath } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { errorMessage } from '../../core/errors.js';
+import { stateDirPath } from '../../core/state-dir.js';
+import type {
+ BashContainment,
+ Decision,
+ HostAdapter,
+ PolicyLoadError,
+ PolicySnapshot,
+ PreparedCall,
+ SessionContext,
+ ToolResult,
+} from '../../core/types.js';
+import { BashAnalyzer, type BashAnalysis } from './bash.js';
+import {
+ NATIVE_TOOL,
+ combineOutcomes,
+ mapUpdatedInput,
+ matcherMatches,
+ nativeCall,
+ nativeResponse,
+ runHook,
+ unsupportedReason,
+ type CompiledHook,
+ type HookOutcome,
+ type NativeCall,
+} from './hooks.js';
+import { parseClaudeFlags, readParentClaudeProcess, type ClaudeCliFlags, type ParentArgsReader } from './parent-args.js';
+import {
+ bashSpecMayMatchDynamic,
+ isInsidePath,
+ isValidRuleSyntax,
+ matchesBashSpec,
+ matchesParamValue,
+ matchesPath,
+ matchesToolName,
+ parseRule,
+ resolveCommandPath,
+ toPosixPath,
+ type NativeToolName,
+ type PathPattern,
+ type Rule,
+ type RuleKind,
+} from './rules.js';
+import { claudeConfigDir, firstSetting, loadSettings, managedSettingsDir, type LoadedSettings, type SettingsDoc } from './settings.js';
+import type { HookMatcherEntry } from './settings.js';
+
+/**
+ * Claude Code host adapter.
+ *
+ * Static check (`checkStatic`, no I/O): permission rules from every settings
+ * source, deny → ask → allow, first match wins, then the permission mode for
+ * calls no rule decides. Hooks (`authorize`): the PreToolUse hooks that match
+ * the native tool name, run in parallel with the JSON Claude Code would send.
+ */
+
+/** Claude permission modes. Unknown values are treated as `default`. */
+export type PermissionMode = 'default' | 'acceptEdits' | 'plan' | 'dontAsk' | 'auto' | 'bypassPermissions';
+
+const MODES: readonly PermissionMode[] = ['default', 'acceptEdits', 'plan', 'dontAsk', 'auto', 'bypassPermissions'];
+
+function toMode(value: string | undefined): PermissionMode | undefined {
+ if (value === 'manual') return 'default';
+ return MODES.find((m) => m === value);
+}
+
+export interface ClaudePolicy {
+ readonly projectRoot: string;
+ readonly cwd: string;
+ readonly home: string;
+ readonly configDir: string;
+ readonly mode: PermissionMode;
+ readonly rules: { readonly deny: readonly Rule[]; readonly ask: readonly Rule[]; readonly allow: readonly Rule[] };
+ /** Project root, MCP roots and additional directories: reads there need no approval. */
+ readonly workingDirs: readonly string[];
+ readonly preHooks: readonly CompiledHook[];
+ readonly postHooks: readonly CompiledHook[];
+ /** Env added for every hook. */
+ readonly hookEnv: Readonly>;
+ /**
+ * True when an allow rule approves this server's `run` tool. Claude Code
+ * resolves such a call from the rule, so in auto mode the classifier never
+ * reviewed the script (https://code.claude.com/docs/en/permission-modes,
+ * "How the classifier evaluates actions").
+ */
+ readonly runApprovedByAllowRule: boolean;
+ /**
+ * Whether a Read deny or ask rule covers a real absolute path. Exposed to
+ * the tool runtime as `PolicySnapshot.readFilter`, which drops such files
+ * from grep and glob results: a recursive search otherwise returns what
+ * `read` would refuse.
+ */
+ readonly isReadDenied: (absPath: string) => boolean;
+}
+
+export interface ClaudeHostAdapterOptions {
+ readonly env?: Readonly>;
+ readonly home?: string;
+ /** Managed settings directory; `null` disables managed settings (tests). Defaults to the platform path. */
+ readonly managedDir?: string | null;
+ /** Server state directory (protected). Defaults to `stateDirPath()`. */
+ readonly stateDir?: string;
+ /** Reads the parent Claude process argv. Defaults to the platform reader. */
+ readonly readParent?: ParentArgsReader;
+ readonly platform?: NodeJS.Platform;
+ /** MCP server name this server is registered under (`mcp____run`). Defaults to `agent-code-mode`. */
+ readonly serverName?: string;
+}
+
+const NO_FLAGS: ClaudeCliFlags = { settings: [], allowedTools: [], disallowedTools: [], addDirs: [] };
+
+/** Which native tools a rule's tool name governs. */
+function governs(rule: Rule, tool: NativeToolName): boolean {
+ if (matchesToolName(rule.tool, tool)) return true;
+ if (rule.tool === 'Read') return tool === 'Grep' || tool === 'Glob' || (rule.kind === 'deny' && (tool === 'Write' || tool === 'Edit'));
+ if (rule.tool === 'Edit') return tool === 'Write';
+ return false;
+}
+
+/**
+ * Paths a file call touches: the path as the script wrote it (resolved
+ * lexically against the cwd, `~` expanded, symlinks not followed), the
+ * normalized path in args, and the real path of the effect.
+ */
+function callPaths(prepared: PreparedCall, cwd: string, home: string): string[] {
+ const written = prepared.requestedPath === undefined ? [] : [resolveWritten(prepared.requestedPath, cwd, home)];
+ switch (prepared.tool) {
+ case 'read':
+ case 'write':
+ case 'edit':
+ return [...new Set([...written, prepared.args.path, prepared.effect.absPath])];
+ case 'grep':
+ case 'glob':
+ return [...new Set([...written, ...(prepared.args.path === undefined ? [] : [prepared.args.path]), prepared.effect.absRoot])];
+ case 'bash':
+ return [];
+ }
+}
+
+function resolveWritten(p: string, cwd: string, home: string): string {
+ if (p === '~') return home;
+ if (p.startsWith('~/') || p.startsWith('~\\')) return path.join(home, p.slice(2));
+ return path.resolve(cwd, p);
+}
+
+type Verdict = 'match' | 'maybe' | 'no';
+
+interface CallView {
+ readonly prepared: PreparedCall;
+ readonly native: NativeCall;
+ /** `callPaths` of the call. */
+ readonly paths: readonly string[];
+ readonly analysis: BashAnalysis | undefined;
+ /** Resolved file targets of a bash command; undefined path = only known at run time. */
+ readonly bashFiles: readonly { readonly access: 'read' | 'write'; readonly path: string | undefined }[];
+}
+
+function pathRuleVerdict(patterns: readonly PathPattern[], paths: readonly string[], kind: RuleKind): Verdict {
+ if (paths.length === 0) return 'no';
+ const hits = paths.map((p) => matchesPath(p, patterns));
+ // Deny/ask: either the requested or the real path. Allow: both.
+ return (kind === 'allow' ? hits.every(Boolean) : hits.some(Boolean)) ? 'match' : 'no';
+}
+
+/** Evaluates one deny/ask rule against a call. */
+function restrictVerdict(rule: Rule, view: CallView): Verdict {
+ const { prepared, native } = view;
+ const m = rule.matcher;
+ if (m.type === 'never') return 'no';
+ if (prepared.tool === 'bash' && view.analysis) {
+ // File targets of the command (redirects, tee, cat ...) against Read/Edit rules.
+ let fileVerdict: Verdict = 'no';
+ const targetTool = (access: 'read' | 'write'): NativeToolName => (access === 'read' ? 'Read' : 'Edit');
+ for (const target of view.bashFiles) {
+ const asTool = targetTool(target.access);
+ if (!(matchesToolName(rule.tool, asTool) || (rule.tool === 'Read' && rule.kind === 'deny' && asTool === 'Edit'))) continue;
+ if (m.type === 'all') return 'match';
+ if (m.type !== 'path') continue;
+ if (target.path === undefined) fileVerdict = 'maybe';
+ else if (matchesPath(target.path, m.patterns)) return 'match';
+ }
+ if (!governs(rule, 'Bash')) return fileVerdict;
+ if (m.type === 'all') return 'match';
+ if (m.type === 'param') {
+ if (matchesParamValue(m.value, native.toolInput[m.name])) return 'match';
+ if (m.bashSpec === undefined) return fileVerdict;
+ }
+ const spec = m.type === 'bash' ? m.spec : m.type === 'param' ? m.bashSpec : undefined;
+ if (spec === undefined) return fileVerdict;
+ let verdict: Verdict = fileVerdict;
+ for (const cmd of view.analysis.commands) {
+ if (cmd.denyForms.some((form) => matchesBashSpec(spec, form))) return 'match';
+ if (cmd.dynamic && cmd.staticPrefixes.some((prefix) => bashSpecMayMatchDynamic(spec, prefix))) verdict = 'maybe';
+ }
+ return verdict;
+ }
+ if (!governs(rule, native.toolName)) return 'no';
+ switch (m.type) {
+ case 'all':
+ return 'match';
+ case 'param':
+ return matchesParamValue(m.value, native.toolInput[m.name]) ? 'match' : 'no';
+ case 'path':
+ return pathRuleVerdict(m.patterns, view.paths, rule.kind);
+ case 'bash':
+ return 'no';
+ }
+}
+
+function insideWorkingDirs(paths: readonly string[], dirs: readonly string[]): boolean {
+ return paths.length > 0 && paths.every((p) => dirs.some((d) => isInsidePath(p, d)));
+}
+
+/** Whether allow rules approve the call. */
+function allowedByRule(view: CallView, rules: readonly Rule[], policy: ClaudePolicy): boolean {
+ const { prepared, native } = view;
+ const applicable = rules.filter((r) => r.matcher.type !== 'never');
+ if (prepared.tool === 'bash') {
+ const analysis = view.analysis;
+ if (!analysis || analysis.uncertain.length > 0 || analysis.commands.length === 0) {
+ return applicable.some((r) => governs(r, 'Bash') && r.matcher.type === 'all');
+ }
+ if (applicable.some((r) => governs(r, 'Bash') && r.matcher.type === 'all') && view.bashFiles.length === 0) return true;
+ // Every subcommand must be approved; files it names must be inside the working directories.
+ const everyCommand = analysis.commands.every((cmd) => {
+ const form = cmd.allowForm;
+ if (form === undefined) return false;
+ return applicable.some((r) => governs(r, 'Bash') && (r.matcher.type === 'all' || (r.matcher.type === 'bash' && matchesBashSpec(r.matcher.spec, form))));
+ });
+ const filesInside = view.bashFiles.every((f) => f.path !== undefined && policy.workingDirs.some((d) => isInsidePath(f.path ?? '', d)));
+ return everyCommand && filesInside;
+ }
+ const paths = view.paths;
+ return applicable.some((r) => {
+ if (!governs(r, native.toolName) || r.kind !== 'allow') return false;
+ if (r.matcher.type === 'all') return true;
+ if (r.matcher.type === 'path') return pathRuleVerdict(r.matcher.patterns, paths, 'allow') === 'match';
+ return false;
+ });
+}
+
+/** What the permission mode does with a call that no rule decided. */
+function modeDecision(view: CallView, policy: ClaudePolicy): Decision {
+ const { prepared } = view;
+ const mode = policy.mode;
+ const tool = NATIVE_TOOL[prepared.tool];
+ const isRead = prepared.tool === 'read' || prepared.tool === 'grep' || prepared.tool === 'glob';
+ const isEdit = prepared.tool === 'write' || prepared.tool === 'edit';
+ const inside = isRead || isEdit ? insideWorkingDirs(view.paths, policy.workingDirs) : false;
+ if (mode === 'bypassPermissions') return { kind: 'allow' };
+ if (mode === 'auto') {
+ // The classifier reviewed the whole script once, unless an allow rule approved `run` before it.
+ if (!policy.runApprovedByAllowRule) return { kind: 'allow' };
+ // Then only auto mode's own step 2 applies: reads and edits inside the working directories.
+ if ((isRead || isEdit) && inside) return { kind: 'allow' };
+ return {
+ kind: 'ask',
+ reason: `auto mode: an allow rule approves the run tool, so its script skipped the classifier; ${tool}${isRead || isEdit ? ' outside the working directories' : ''} needs approval`,
+ };
+ }
+ if (isRead) {
+ if (inside) return { kind: 'allow' };
+ if (mode === 'dontAsk') return { kind: 'deny', source: 'rule', reason: `dontAsk mode: ${tool} outside the working directories is not pre-approved by an allow rule` };
+ return { kind: 'ask', reason: `${tool} outside the working directories needs approval in ${mode} mode` };
+ }
+ if (mode === 'plan') return { kind: 'deny', source: 'rule', reason: `plan mode does not allow ${tool}` };
+ if (mode === 'dontAsk') return { kind: 'deny', source: 'rule', reason: `dontAsk mode: ${tool} is not pre-approved by an allow rule` };
+ if (isEdit && mode === 'acceptEdits' && inside) return { kind: 'allow' };
+ return { kind: 'ask', reason: `${tool} needs approval in ${mode} mode` };
+}
+
+const TOP_LEVEL = /^\/[^/]+$/;
+
+/**
+ * A recognized `rm`/`rmdir` removal of a critical path (filesystem root, a
+ * top-level directory, home, the working directory or a parent of it, a bare
+ * `*` glob under a working directory, a recursive removal of a target only
+ * known at run time). No allow rule, mode or hook approves one
+ * (https://code.claude.com/docs/en/permission-modes, "Critical paths").
+ */
+function criticalRemoval(view: CallView, policy: ClaudePolicy): string | undefined {
+ const analysis = view.analysis;
+ if (!analysis || view.prepared.tool !== 'bash') return undefined;
+ const cwd = view.prepared.effect.cwd;
+ const anchors = [cwd, policy.projectRoot];
+ const isCritical = (p: string, glob: boolean): boolean => {
+ const posix = toPosixPath(p);
+ if (posix === '/' || TOP_LEVEL.test(posix)) return true;
+ if (isInsidePath(toPosixPath(policy.home), posix) && isInsidePath(posix, toPosixPath(policy.home))) return true;
+ if (anchors.some((a) => isInsidePath(a, posix))) return true; // the working directory or one of its parents
+ return glob && policy.workingDirs.some((d) => isInsidePath(d, posix));
+ };
+ for (const removal of analysis.removals) {
+ for (const target of removal.targets) {
+ if (target.value === undefined) {
+ if (removal.recursive || target.glob) return `\`rm ${target.raw}\` removes a target only known at run time`;
+ continue;
+ }
+ let value = target.value;
+ let glob = false;
+ if (target.glob) {
+ const segments = value.split('/');
+ const stars = segments.filter((seg) => /[*?[]/.test(seg));
+ if (stars.length > 1) return `\`rm ${target.raw}\` reaches directories that cannot be known before it runs`;
+ const at = segments.findIndex((seg) => seg === '*');
+ if (at === -1) continue;
+ value = segments.slice(0, at).join('/') || (value.startsWith('/') ? '/' : '.');
+ glob = true;
+ }
+ const relative = !(value.startsWith('/') || value.startsWith('~') || path.isAbsolute(value));
+ if (relative && analysis.changesDirectory) {
+ if (glob || value === '.' || value === '..' || value.startsWith('../')) return `\`rm ${target.raw}\` after \`cd\` may remove a working directory`;
+ continue;
+ }
+ if (isCritical(resolveCommandPath(value, cwd, policy.home), glob)) return `\`rm ${target.raw}\` removes a critical path`;
+ }
+ }
+ return undefined;
+}
+
+/** Resolves symlinks of a command's file target; for a missing file, of its directory. */
+async function realTarget(p: string): Promise {
+ if (process.platform === 'win32') return p;
+ try {
+ return toPosixPath(await realpath(p));
+ } catch {
+ try {
+ return path.posix.join(toPosixPath(await realpath(path.posix.dirname(p))), path.posix.basename(p));
+ } catch {
+ return p;
+ }
+ }
+}
+
+function describe(rule: Rule): string {
+ return `${rule.kind} rule ${JSON.stringify(rule.raw)} from ${rule.source} settings`;
+}
+
+function compileHooks(entries: readonly HookMatcherEntry[] | undefined, origin: string, env: Readonly>, platform: NodeJS.Platform, seen: Set): CompiledHook[] {
+ const out: CompiledHook[] = [];
+ for (const entry of entries ?? []) {
+ for (const handler of entry.hooks) {
+ // The same handler defined in several settings files runs once.
+ const key = JSON.stringify([entry.matcher ?? '', handler, env]);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push({ handler, matcher: entry.matcher, origin, env, unsupported: unsupportedReason(handler, platform) });
+ }
+ }
+ return out;
+}
+
+/** Literal leading directory of a glob pattern (before the first segment with a glob character). */
+function literalHead(pattern: string): { head: string; rest: string } {
+ const segments = pattern.split('/');
+ const i = segments.findIndex((s) => /[*?[]/.test(s));
+ const cut = i === -1 ? Math.max(0, segments.length - 1) : i;
+ return { head: segments.slice(0, cut).join('/'), rest: segments.slice(cut).join('/') };
+}
+
+/** Adds the real location of rules written through a symlinked directory (`//etc/**` → `/private/etc/**`). */
+async function withRealAnchors(rule: Rule): Promise {
+ if (rule.matcher.type !== 'path' || rule.kind === 'allow') return rule;
+ const extra: PathPattern[] = [];
+ for (const p of rule.matcher.patterns) {
+ if (p.pattern.startsWith('**')) continue;
+ const { head, rest } = literalHead(p.pattern);
+ const dir = path.posix.join(p.anchor, head);
+ try {
+ const real = toPosixPath(await realpath(dir));
+ if (real !== dir && rest !== '') extra.push({ anchor: real, pattern: rest });
+ else if (real !== dir) extra.push({ anchor: path.posix.dirname(real), pattern: path.posix.basename(real) });
+ } catch {
+ // Missing directory: nothing to alias.
+ }
+ }
+ return extra.length === 0 ? rule : { ...rule, matcher: { type: 'path', patterns: [...rule.matcher.patterns, ...extra] } };
+}
+
+function resolveDir(p: string, base: string, home: string): string {
+ if (p === '~') return home;
+ if (p.startsWith('~/')) return path.join(home, p.slice(2));
+ return path.resolve(base, p);
+}
+
+export class ClaudeHostAdapter implements HostAdapter {
+ readonly host = 'claude' as const;
+ readonly #opts: ClaudeHostAdapterOptions;
+
+ constructor(opts: ClaudeHostAdapterOptions = {}) {
+ this.#opts = opts;
+ }
+
+ async loadPolicy(ctx: SessionContext): Promise | PolicyLoadError> {
+ try {
+ return await this.#load(ctx);
+ } catch (err) {
+ return { error: errorMessage(err) };
+ }
+ }
+
+ async #load(ctx: SessionContext): Promise> {
+ const env = this.#opts.env ?? process.env;
+ const home = this.#opts.home ?? os.homedir();
+ const platform = this.#opts.platform ?? process.platform;
+ const configDir = claudeConfigDir(env, home);
+ const projectRoot = ctx.roots[0] ?? ctx.cwd;
+ const stateDir = this.#opts.stateDir ?? stateDirPath(env, home);
+ const managedDir = this.#opts.managedDir === null ? undefined : (this.#opts.managedDir ?? managedSettingsDir(platform));
+ const parent = await (this.#opts.readParent ?? readParentClaudeProcess)();
+ const flags = parent ? parseClaudeFlags(parent.argv) : NO_FLAGS;
+ const settings: LoadedSettings = await loadSettings({ projectRoot, home, configDir, managedDir, env, flags, parentCwd: parent?.cwd });
+ const docs = settings.docs;
+
+ // Permission rules.
+ const managedOnly = firstSetting(docs.filter((d) => d.source === 'managed'), (s) => s.allowManagedPermissionRulesOnly) === true;
+ const ruleDocs = managedOnly ? docs.filter((d) => d.source === 'managed') : docs;
+ const holdsCapability = (doc: SettingsDoc): boolean => (doc.source === 'project' || doc.source === 'local') && !settings.projectTrusted;
+ const rules: { deny: Rule[]; ask: Rule[]; allow: Rule[] } = { deny: [], ask: [], allow: [] };
+ // A malformed rule would match nothing; refuse the whole policy instead of failing open.
+ for (const doc of docs) {
+ for (const kind of ['deny', 'ask', 'allow'] as const) {
+ for (const raw of doc.data.permissions?.[kind] ?? []) {
+ if (!isValidRuleSyntax(raw)) {
+ throw new Error(`${kind} rule ${JSON.stringify(raw)} in ${doc.file ?? `${doc.source} settings`} is not a valid \`Tool\` or \`Tool(specifier)\` rule`);
+ }
+ }
+ }
+ }
+ for (const doc of ruleDocs) {
+ const anchors = { cwd: ctx.cwd, sourceDir: doc.anchorDir, home };
+ for (const kind of ['deny', 'ask', 'allow'] as const) {
+ if (kind === 'allow' && holdsCapability(doc)) continue;
+ for (const raw of doc.data.permissions?.[kind] ?? []) {
+ const rule = parseRule(raw, kind, doc.source, anchors);
+ if (!rule) throw new Error(`${kind} rule ${JSON.stringify(raw)} in ${doc.file ?? doc.source} cannot be parsed`);
+ rules[kind].push(await withRealAnchors(rule));
+ }
+ }
+ }
+
+ // Working directories.
+ const workingDirs = new Set([projectRoot, ctx.cwd, ...ctx.roots]);
+ const additionalRoots = new Set();
+ for (const doc of docs) {
+ if (holdsCapability(doc)) continue;
+ for (const dir of doc.data.permissions?.additionalDirectories ?? []) {
+ const resolved = resolveDir(dir, projectRoot, home);
+ workingDirs.add(resolved);
+ additionalRoots.add(resolved);
+ }
+ }
+
+ // Permission mode: the live mode from the companion hook, else the CLI flag, else settings, else default.
+ const fromCtx = ctx.sources['permissionMode'] !== undefined && ctx.sources['permissionMode'] !== 'default' ? toMode(ctx.permissionMode) : undefined;
+ let mode: PermissionMode = fromCtx ?? toMode(flags.permissionMode) ?? toMode(firstSetting(docs, (s) => s.permissions?.defaultMode)) ?? 'default';
+ if (mode === 'bypassPermissions' && firstSetting(docs, (s) => s.permissions?.disableBypassPermissionsMode) === 'disable') mode = 'default';
+
+ // Hooks.
+ const managedDocs = docs.filter((d) => d.source === 'managed');
+ const managedDisable = firstSetting(managedDocs, (s) => s.disableAllHooks) === true;
+ const otherDisable = firstSetting(docs.filter((d) => d.source !== 'managed'), (s) => s.disableAllHooks) === true;
+ const managedOnlyHooks = firstSetting(managedDocs, (s) => s.allowManagedHooksOnly) === true;
+ // A handler defined in several sources runs once per event, never across events.
+ const seenPre = new Set();
+ const seenPost = new Set();
+ const pre: CompiledHook[] = [];
+ const post: CompiledHook[] = [];
+ for (const doc of docs) {
+ const isManaged = doc.source === 'managed';
+ if (managedDisable) break;
+ if (!isManaged && (otherDisable || managedOnlyHooks)) continue;
+ const origin = `${doc.source} settings`;
+ pre.push(...compileHooks(doc.data.hooks?.PreToolUse, origin, {}, platform, seenPre));
+ post.push(...compileHooks(doc.data.hooks?.PostToolUse, origin, {}, platform, seenPost));
+ }
+ if (!managedDisable && !otherDisable && !managedOnlyHooks) {
+ for (const plugin of settings.plugins) {
+ const env = { CLAUDE_PLUGIN_ROOT: plugin.root };
+ pre.push(...compileHooks(plugin.hooks.PreToolUse, `plugin ${plugin.plugin}`, env, platform, seenPre));
+ post.push(...compileHooks(plugin.hooks.PostToolUse, `plugin ${plugin.plugin}`, env, platform, seenPost));
+ }
+ }
+
+ // Bash containment: Claude's sandbox when enabled.
+ let bashContainment: BashContainment = { mode: 'none' };
+ if (firstSetting(docs, (s) => s.sandbox?.enabled) === true) {
+ const roots = new Set([projectRoot, ...workingDirs]);
+ const fsDisabled = firstSetting(
+ docs.filter((d) => d.source === 'managed' || d.source === 'user' || d.source === 'flag-settings'),
+ (s) => s.sandbox?.filesystem?.disabled,
+ );
+ for (const doc of docs) {
+ for (const entry of doc.data.sandbox?.filesystem?.allowWrite ?? []) roots.add(resolveDir(entry, projectRoot, home));
+ }
+ bashContainment = {
+ mode: 'sandbox',
+ readOnly: false,
+ writableRoots: fsDisabled === true ? [path.parse(projectRoot).root] : [...roots],
+ // Claude's sandbox filters network by domain through a proxy; a boolean
+ // cannot express an allowlist, so network stays off (strict).
+ network: false,
+ };
+ }
+
+ const serverName = this.#opts.serverName ?? 'agent-code-mode';
+ const serverRule = `mcp__${serverName}`;
+ const runTool = `mcp__${serverName}__run`;
+
+ const protectedPaths = [
+ ...new Set([
+ ...[projectRoot, ctx.cwd].flatMap((root) => [
+ path.join(root, '.claude', 'settings*.json'),
+ path.join(root, '.claude', 'hooks', '**'),
+ path.join(root, '.claude', 'agents', '**'),
+ path.join(root, '.mcp.json'),
+ ]),
+ path.join(configDir, '**'),
+ path.join(home, '.claude', '**'),
+ path.join(home, '.claude.json'),
+ ...(managedDir === undefined ? [] : [path.join(managedDir, '**')]),
+ path.join(stateDir, '**'),
+ ...docs.flatMap((d) => (d.source === 'flag-settings' && d.file !== undefined ? [d.file] : [])),
+ ]),
+ ];
+
+ // Read rules that refuse a path: deny, and ask (an ask is a deny here).
+ const readRestrictions = [...rules.deny, ...rules.ask].filter((r) => governs(r, 'Read'));
+ const isReadDenied = (absPath: string): boolean =>
+ readRestrictions.some((r) => r.matcher.type === 'all' || (r.matcher.type === 'path' && matchesPath(absPath, r.matcher.patterns)));
+
+ return {
+ host: 'claude',
+ bashContainment,
+ protectedPaths,
+ additionalRoots: [...additionalRoots],
+ readFilter: (realAbsPath: string): boolean => !isReadDenied(realAbsPath),
+ payload: {
+ projectRoot,
+ cwd: ctx.cwd,
+ home,
+ configDir,
+ mode,
+ rules,
+ workingDirs: [...workingDirs],
+ preHooks: pre,
+ postHooks: post,
+ hookEnv: { CLAUDE_PROJECT_DIR: projectRoot },
+ runApprovedByAllowRule: rules.allow.some((r) => r.matcher.type !== 'never' && (r.tool === serverRule || matchesToolName(r.tool, runTool))),
+ isReadDenied,
+ },
+ };
+ }
+
+ #view(prepared: PreparedCall, policy: ClaudePolicy): CallView {
+ const native = nativeCall(prepared);
+ const paths = callPaths(prepared, policy.cwd, policy.home);
+ if (prepared.tool !== 'bash') return { prepared, native, paths, analysis: undefined, bashFiles: [] };
+ const analysis = BashAnalyzer.analyze(prepared.effect.command);
+ const bashFiles = analysis.files.map((f) => {
+ if (f.path === undefined) return { access: f.access, path: undefined };
+ const relative = !(f.path.startsWith('/') || f.path.startsWith('~') || path.isAbsolute(f.path));
+ // After a `cd`, a relative target cannot be resolved statically.
+ if (relative && analysis.changesDirectory) return { access: f.access, path: undefined };
+ return { access: f.access, path: resolveCommandPath(f.path, prepared.effect.cwd, policy.home) };
+ });
+ return { prepared, native, paths, analysis, bashFiles };
+ }
+
+ /** Deny and ask rules. Undefined when none decides. */
+ #restrictions(view: CallView, policy: ClaudePolicy): Decision | undefined {
+ const askOrDeny = (reason: string): Decision =>
+ policy.mode === 'dontAsk' ? { kind: 'deny', source: 'rule', reason: `dontAsk mode denies what would ask: ${reason}` } : { kind: 'ask', reason };
+ for (const rule of policy.rules.deny) {
+ const v = restrictVerdict(rule, view);
+ if (v === 'match') return { kind: 'deny', source: 'rule', reason: `denied by ${describe(rule)}` };
+ }
+ // A deny rule that may match once run-time values are known: cannot be settled statically.
+ for (const rule of policy.rules.deny) {
+ if (restrictVerdict(rule, view) === 'maybe') return askOrDeny(`${describe(rule)} may match parts of the command that are only known at run time`);
+ }
+ for (const rule of policy.rules.ask) {
+ const v = restrictVerdict(rule, view);
+ if (v !== 'no') return askOrDeny(`${describe(rule)} matches`);
+ }
+ return undefined;
+ }
+
+ checkStatic(prepared: PreparedCall, _ctx: SessionContext, snapshot: PolicySnapshot): Decision {
+ const policy = snapshot.payload;
+ const view = this.#view(prepared, policy);
+ const askOrDeny = (reason: string): Decision =>
+ policy.mode === 'dontAsk' ? { kind: 'deny', source: 'rule', reason: `dontAsk mode denies what would ask: ${reason}` } : { kind: 'ask', reason };
+ const restricted = this.#restrictions(view, policy);
+ if (restricted) return restricted;
+ if (view.analysis && view.analysis.uncertain.length > 0) {
+ return askOrDeny(`the command cannot be checked statically (${view.analysis.uncertain.join('; ')})`);
+ }
+ const critical = criticalRemoval(view, policy);
+ if (critical !== undefined) return askOrDeny(`${critical}; no rule or mode approves it`);
+ if (allowedByRule(view, policy.rules.allow, policy)) return { kind: 'allow' };
+ return modeDecision(view, policy);
+ }
+
+ /**
+ * Re-checks a bash command's file targets after resolving symlinks (I/O,
+ * so not in `checkStatic`): `cat link` where `link -> .env` is denied.
+ */
+ async #realFiles(prepared: PreparedCall, policy: ClaudePolicy): Promise {
+ if (prepared.tool !== 'bash') return undefined;
+ const view = this.#view(prepared, policy);
+ const real = await Promise.all(view.bashFiles.map(async (f) => ({ access: f.access, path: f.path === undefined ? undefined : await realTarget(f.path) })));
+ if (real.every((f, i) => f.path === view.bashFiles[i]?.path)) return undefined;
+ return this.#restrictions({ ...view, bashFiles: real }, policy);
+ }
+
+ #select(hooks: readonly CompiledHook[], view: CallView, policy: ClaudePolicy): CompiledHook[] {
+ return hooks.filter((hook) => matcherMatches(hook.matcher, view.native.toolName) && this.#ifMatches(hook, view, policy));
+ }
+
+ /** The `if` filter: a hook is skipped only when the call certainly does not match its rule. */
+ #ifMatches(hook: CompiledHook, view: CallView, policy: ClaudePolicy): boolean {
+ const condition = hook.handler.if;
+ if (condition === undefined) return true;
+ const rule = parseRule(condition, 'allow', 'project', { cwd: policy.cwd, sourceDir: policy.projectRoot, home: policy.home });
+ if (!rule || rule.matcher.type === 'never') return true;
+ if (!matchesToolName(rule.tool, view.native.toolName) && !governs(rule, view.native.toolName)) return false;
+ const m = rule.matcher;
+ if (m.type === 'all') return true;
+ if (m.type === 'bash') {
+ const a = view.analysis;
+ if (!a || a.uncertain.length > 0) return true;
+ // Documented: a pattern naming more than the command (`Bash(git push *)`) runs the hook on any `$()`, backticks or `$VAR`.
+ const specific = (m.spec.split('*')[0] ?? '').trim().split(/\s+/).length > 1;
+ return a.commands.some(
+ (cmd) => cmd.denyForms.some((f) => matchesBashSpec(m.spec, f)) || (cmd.dynamic && (specific || cmd.staticPrefixes.some((prefix) => bashSpecMayMatchDynamic(m.spec, prefix)))),
+ );
+ }
+ if (m.type === 'path') return pathRuleVerdict(m.patterns, view.paths, 'deny') === 'match';
+ if (m.type === 'param') return matchesParamValue(m.value, view.native.toolInput[m.name]);
+ return true;
+ }
+
+ #input(view: CallView, ctx: SessionContext, policy: ClaudePolicy, event: 'PreToolUse' | 'PostToolUse'): Record {
+ const { prepared, native } = view;
+ return {
+ session_id: ctx.sessionId ?? null,
+ transcript_path: ctx.transcriptPath ?? null,
+ // For bash the command runs in the effect's cwd, so that is what the hook is told.
+ cwd: prepared.tool === 'bash' ? prepared.effect.cwd : ctx.cwd,
+ permission_mode: policy.mode,
+ hook_event_name: event,
+ tool_name: native.toolName,
+ tool_input: native.toolInput,
+ tool_use_id: `${ctx.toolUseId ?? 'unknown'}/${prepared.id}`,
+ ...(ctx.agentId === undefined ? {} : { agent_id: ctx.agentId }),
+ ...(ctx.agentType === undefined ? {} : { agent_type: ctx.agentType }),
+ };
+ }
+
+ async authorize(prepared: PreparedCall, ctx: SessionContext, snapshot: PolicySnapshot, signal: AbortSignal): Promise {
+ const policy = snapshot.payload;
+ const realFiles = await this.#realFiles(prepared, policy);
+ if (realFiles) return realFiles;
+ const view = this.#view(prepared, policy);
+ const hooks = this.#select(policy.preHooks, view, policy);
+ const unsupported = hooks.find((h) => h.unsupported !== undefined);
+ if (unsupported) {
+ return { kind: 'deny', source: 'unsupported-config', reason: `${unsupported.origin}: ${unsupported.unsupported ?? 'unsupported hook'}` };
+ }
+ if (hooks.length === 0) return { kind: 'allow' };
+ const input = this.#input(view, ctx, policy, 'PreToolUse');
+ const opts = { event: 'PreToolUse' as const, input, cwd: policy.projectRoot, env: policy.hookEnv, signal };
+ const blocking: Promise[] = [];
+ for (const hook of hooks) {
+ if (hook.handler.async === true || hook.handler.asyncRewake === true) {
+ // Background hooks cannot block natively either; run them and ignore the result.
+ void runHook(hook, opts);
+ continue;
+ }
+ blocking.push(runHook(hook, opts));
+ }
+ const combined = combineOutcomes(await Promise.all(blocking));
+ switch (combined.kind) {
+ case 'deny':
+ return combined;
+ case 'ask':
+ return { kind: 'ask', reason: combined.reason };
+ case 'none':
+ case 'allow': {
+ if (combined.updatedInput === undefined) return { kind: 'allow', ...(combined.reason === undefined ? {} : { reason: combined.reason }) };
+ const mapped = mapUpdatedInput(prepared, combined.updatedInput);
+ if ('error' in mapped) return { kind: 'deny', source: 'hook', reason: mapped.error };
+ if (prepared.tool === 'bash' && 'command' in mapped.args) {
+ // The dispatcher re-checks the rewrite statically; the symlink check needs I/O, so it runs here.
+ const command = mapped.args.command;
+ const rewritten: PreparedCall = { ...prepared, args: { ...prepared.args, command }, effect: { ...prepared.effect, command } };
+ const again = await this.#realFiles(rewritten, policy);
+ if (again) return again.kind === 'deny' ? again : { kind: 'ask', reason: `hook rewrite: ${again.reason}` };
+ }
+ return { kind: 'allow', updatedArgs: mapped.args, ...(combined.reason === undefined ? {} : { reason: combined.reason }) };
+ }
+ }
+ }
+
+ async postToolUse(prepared: PreparedCall, result: ToolResult, ctx: SessionContext, snapshot: PolicySnapshot): Promise {
+ const policy = snapshot.payload;
+ const view = this.#view(prepared, policy);
+ const hooks = this.#select(policy.postHooks, view, policy);
+ if (hooks.length === 0) return;
+ const input = { ...this.#input(view, ctx, policy, 'PostToolUse'), tool_response: nativeResponse(prepared, result) };
+ const controller = new AbortController();
+ const opts = { event: 'PostToolUse' as const, input, cwd: policy.projectRoot, env: policy.hookEnv, signal: controller.signal };
+ const notes: string[] = [];
+ const outcomes = await Promise.all(
+ hooks.map(async (hook) => {
+ if (hook.unsupported !== undefined) return { hook, outcome: { kind: 'failure', source: 'hook-error', reason: hook.unsupported } satisfies HookOutcome };
+ if (hook.handler.async === true || hook.handler.asyncRewake === true) {
+ void runHook(hook, opts);
+ return { hook, outcome: { kind: 'none' } satisfies HookOutcome };
+ }
+ return { hook, outcome: await runHook(hook, opts) };
+ }),
+ );
+ for (const { hook, outcome } of outcomes) {
+ if (outcome.kind === 'deny') notes.push(`${hook.origin} PostToolUse hook blocked after the call ran (it was not undone): ${outcome.reason}`);
+ else if (outcome.kind === 'failure') notes.push(`${hook.origin} PostToolUse hook failed: ${outcome.reason}`);
+ }
+ if (notes.length > 0) throw new Error(notes.join('; '));
+ }
+}
diff --git a/src/hosts/claude/bash.ts b/src/hosts/claude/bash.ts
new file mode 100644
index 0000000..41686ff
--- /dev/null
+++ b/src/hosts/claude/bash.ts
@@ -0,0 +1,598 @@
+import { parse, walk } from 'sh-syntax/sync';
+import type { CallExpr, DeclClause, File, Node, Redirect, Word, WordPart } from 'sh-syntax/sync';
+
+/**
+ * Splits a Bash command line into the simple commands it would run, the way
+ * Claude Code does before it matches Bash permission rules, but stricter.
+ *
+ * Parser: `sh-syntax` (mvdan/sh, the parser behind shfmt, compiled to WASM
+ * with a synchronous Node entry). It understands the full bash grammar, so
+ * commands nested in `&&`, `||`, `;`, `|`, `&`, subshells, blocks, control
+ * flow, `$(...)`, backticks, process substitution and here-documents are all
+ * found. On top of the parse tree this module:
+ * - strips leading `VAR=value` assignments and process wrappers (`timeout`,
+ * `time`, `nice`, `nohup`, `stdbuf`, `command`, `builtin`, `noglob`, `exec`,
+ * `env`, `sudo`, `xargs`, `find -exec`) and offers every stripped form to
+ * deny/ask matching;
+ * - parses the inner string of `bash -c`/`sh -c` (and other shells) and adds
+ * its commands;
+ * - collects redirection targets (`> f`, `< f`, `tee f`) so file rules can
+ * check them;
+ * - reports constructs it cannot evaluate statically (`eval`, `source`, a
+ * dynamic command name, a shell reading commands from stdin, a here-document
+ * with substitutions, a parse error) as `uncertain`, which callers treat as
+ * `ask`.
+ */
+
+/** One simple command, as matching sees it. */
+export interface SimpleCommand {
+ /** Source text of the command as written (assignments included). */
+ readonly raw: string;
+ /** Every text deny/ask rules are matched against: normalized forms with and without wrappers. */
+ readonly denyForms: readonly string[];
+ /**
+ * Text allow rules are matched against: the command after stripping only
+ * the wrappers Claude Code documents (`timeout`, `time`, `nice`, `nohup`,
+ * `stdbuf`, `command`, `builtin`, `noglob`, bare `xargs`). Undefined when the
+ * command cannot be approved by an allow rule (dynamic words, leading
+ * assignments, unknown command name).
+ */
+ readonly allowForm: string | undefined;
+ /**
+ * For each form (as written, each stripped wrapper level, each basename
+ * variant): the words before the first word only known at run time.
+ */
+ readonly staticPrefixes: readonly string[];
+ /** True when some word's value is only known at run time. */
+ readonly dynamic: boolean;
+}
+
+/** A file a command reads or writes by name (redirection or `tee`). */
+export interface FileTarget {
+ readonly access: 'read' | 'write';
+ /** The path as written, or undefined when it is only known at run time. */
+ readonly path: string | undefined;
+}
+
+export interface BashAnalysis {
+ readonly commands: readonly SimpleCommand[];
+ readonly files: readonly FileTarget[];
+ /** Reasons the command cannot be evaluated statically. Non-empty means `ask`. */
+ readonly uncertain: readonly string[];
+ /** True when a `cd` appears, so relative file targets may not resolve against the call's cwd. */
+ readonly changesDirectory: boolean;
+ /** Every `rm`/`rmdir` invocation, for the critical-path check. */
+ readonly removals: readonly Removal[];
+}
+
+/** An operand of a command: its value when static, else undefined. */
+export interface Operand {
+ readonly value: string | undefined;
+ readonly raw: string;
+ /** Unquoted glob characters appear. */
+ readonly glob: boolean;
+}
+
+/** One `rm` or `rmdir` call. */
+export interface Removal {
+ readonly recursive: boolean;
+ readonly targets: readonly Operand[];
+}
+
+/** Commands longer than this are not analyzed (treated as uncertain). */
+export const MAX_ANALYZED_COMMAND_CHARS = 100_000;
+
+/** How deep `bash -c '...'` strings are followed. */
+const MAX_SHELL_NESTING = 4;
+
+const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'mksh', 'ash', 'fish', 'busybox']);
+
+/** Shell options followed by a separate operand (`bash -O extglob -c ...`). */
+const SHELL_OPTIONS_WITH_OPERAND = new Set(['-o', '+o', '-O', '+O', '--rcfile', '--init-file', '--debugger-file']);
+
+/** Builtins whose arguments become shell code: always uncertain. */
+const CODE_EVALUATORS = new Set(['eval', 'source', '.', 'trap', 'fc']);
+
+/**
+ * Commands whose operands may be files they read, for Read rules. Every
+ * non-option operand is treated as a possible file (a `sed` script or a `grep`
+ * pattern too): matching a pattern text against path rules is harmless, and
+ * missing a file is not.
+ */
+const FILE_READERS = new Set([
+ 'cat', 'head', 'tail', 'less', 'more', 'most', 'nl', 'tac', 'rev', 'strings', 'xxd', 'od', 'hexdump', 'base64', 'base32',
+ 'sed', 'awk', 'gawk', 'mawk', 'nawk', 'grep', 'egrep', 'fgrep', 'rg', 'ag', 'ack', 'zcat', 'zgrep', 'zless', 'bzcat', 'xzcat',
+ 'cut', 'sort', 'uniq', 'wc', 'diff', 'cmp', 'comm', 'join', 'paste', 'column', 'fold', 'fmt', 'pr', 'expand', 'unexpand',
+ 'jq', 'yq', 'xmllint', 'file', 'md5sum', 'sha1sum', 'sha256sum', 'sha512sum', 'cksum', 'b2sum', 'iconv', 'dos2unix',
+ 'vi', 'vim', 'nano', 'view', 'emacs', 'openssl', 'gpg', 'tar', 'zip', 'unzip', 'gzip', 'gunzip', 'bzip2', 'xz', 'curl', 'wget', 'scp',
+]);
+
+/** Commands that write (or delete) the files they name, for Edit rules. */
+const FILE_WRITERS = new Set(['tee', 'touch', 'truncate', 'rm', 'rmdir', 'unlink', 'shred', 'mkdir', 'chmod', 'chown', 'chgrp', 'ln']);
+
+/** Commands that read some operands and write others: every operand is both. */
+const FILE_COPIERS = new Set(['cp', 'mv', 'rsync', 'install', 'scp', 'dd']);
+
+/** Wrapper levels stripped before the command is reported as uncertain. */
+const MAX_WRAPPER_LEVELS = 64;
+
+/** Builtins that rebind a command name: the commands after them cannot be matched by name. */
+const NAME_REBINDERS = new Set(['alias', 'hash', 'enable']);
+
+// Redirect operators (sh-syntax RedirOperator values).
+const REDIR_OUT = new Set([63, 64, 69, 70, 74, 75, 76, 77]); // > >> >| >>| &> &>| &>> &>>|
+const REDIR_IN = new Set([65]); // <
+const REDIR_INOUT = new Set([66]); // <>
+const REDIR_HDOC = new Set([71, 72]); // << <<-
+const REDIR_DUP = new Set([67, 68]); // <& >&
+
+type WordValue = Operand;
+
+function decodeUnquoted(lit: string): string {
+ let out = '';
+ for (let i = 0; i < lit.length; i++) {
+ const ch = lit[i];
+ if (ch === '\\' && i + 1 < lit.length) {
+ const next = lit[i + 1];
+ i++;
+ if (next !== '\n') out += next;
+ } else {
+ out += ch;
+ }
+ }
+ return out;
+}
+
+function decodeDoubleQuoted(lit: string): string {
+ let out = '';
+ for (let i = 0; i < lit.length; i++) {
+ const ch = lit[i];
+ const next = lit[i + 1];
+ if (ch === '\\' && next !== undefined && '$`"\\\n'.includes(next)) {
+ i++;
+ if (next !== '\n') out += next;
+ } else {
+ out += ch;
+ }
+ }
+ return out;
+}
+
+const ANSI_ESCAPES: Record = { n: '\n', t: '\t', r: '\r', '\\': '\\', "'": "'", '"': '"', a: '\x07', b: '\b', e: '\x1b', E: '\x1b', f: '\f', v: '\v' };
+
+/** Decodes `$'...'`; undefined when an escape is not a simple one. */
+function decodeAnsi(lit: string): string | undefined {
+ let out = '';
+ for (let i = 0; i < lit.length; i++) {
+ const ch = lit[i];
+ if (ch !== '\\') {
+ out += ch;
+ continue;
+ }
+ const next = lit[i + 1];
+ const mapped = next === undefined ? undefined : ANSI_ESCAPES[next];
+ if (mapped === undefined) return undefined;
+ out += mapped;
+ i++;
+ }
+ return out;
+}
+
+const UNQUOTED_GLOB = /(^|[^\\])[*?[]/;
+
+function partsValue(parts: readonly WordPart[], quoted: boolean): { value: string | undefined; glob: boolean } {
+ let value: string | undefined = '';
+ let glob = false;
+ for (const part of parts) {
+ let piece: string | undefined;
+ switch (part.type) {
+ case 'Lit':
+ if (!quoted && UNQUOTED_GLOB.test(part.value)) glob = true;
+ piece = quoted ? decodeDoubleQuoted(part.value) : decodeUnquoted(part.value);
+ break;
+ case 'SglQuoted':
+ piece = part.dollar ? decodeAnsi(part.value) : part.value;
+ break;
+ case 'DblQuoted': {
+ if (part.dollar) {
+ piece = undefined; // $"..." is locale translation
+ break;
+ }
+ const inner = partsValue(part.parts, true);
+ piece = inner.value;
+ break;
+ }
+ default:
+ piece = undefined;
+ }
+ if (piece === undefined || value === undefined) value = undefined;
+ else value += piece;
+ }
+ return { value, glob };
+}
+
+export class BashAnalyzer {
+ readonly #commands: SimpleCommand[] = [];
+ readonly #files: FileTarget[] = [];
+ readonly #uncertain: string[] = [];
+ #changesDirectory = false;
+ readonly #removals: Removal[] = [];
+
+ static analyze(command: string): BashAnalysis {
+ const analyzer = new BashAnalyzer();
+ analyzer.#analyzeSource(command, 0);
+ return {
+ commands: analyzer.#commands,
+ files: analyzer.#files,
+ uncertain: [...new Set(analyzer.#uncertain)],
+ changesDirectory: analyzer.#changesDirectory,
+ removals: analyzer.#removals,
+ };
+ }
+
+ #analyzeSource(source: string, depth: number): void {
+ if (source.includes('\0')) {
+ this.#uncertain.push('command contains a NUL byte');
+ return;
+ }
+ if (source.length > MAX_ANALYZED_COMMAND_CHARS) {
+ this.#uncertain.push(`command is longer than ${MAX_ANALYZED_COMMAND_CHARS} characters`);
+ return;
+ }
+ let file: File;
+ try {
+ file = parse(source);
+ } catch (err) {
+ this.#uncertain.push(`command could not be parsed: ${err instanceof Error ? err.message : String(err)}`);
+ return;
+ }
+ const ctx = { source, depth };
+ walk(file, (node) => {
+ switch (node.type) {
+ case 'CallExpr':
+ this.#callExpr(node, ctx);
+ break;
+ case 'DeclClause':
+ this.#declClause(node, ctx);
+ break;
+ case 'Redirect':
+ this.#redirect(node, ctx);
+ break;
+ case 'Stmt':
+ if (node.coprocess) this.#uncertain.push('coprocesses are not analyzed');
+ break;
+ case 'CoprocClause':
+ this.#uncertain.push('coprocesses are not analyzed');
+ break;
+ default:
+ break;
+ }
+ });
+ }
+
+ #text(node: Node, ctx: { source: string }): string {
+ return ctx.source.slice(node.start, node.end);
+ }
+
+ #word(word: Word, ctx: { source: string }): WordValue {
+ const { value, glob } = partsValue(word.parts, false);
+ return { value, raw: this.#text(word, ctx), glob };
+ }
+
+ #declClause(decl: DeclClause, ctx: { source: string; depth: number }): void {
+ // `export`, `declare`, `local`, `readonly`, `typeset`, `nameref`: their own
+ // words are assignments; nested substitutions are walked generically.
+ const name = decl.variant?.value ?? 'declare';
+ const raw = this.#text(decl, ctx);
+ this.#commands.push({ raw, denyForms: [raw, name], allowForm: undefined, staticPrefixes: [name], dynamic: true });
+ }
+
+ #redirect(redir: Redirect, ctx: { source: string; depth: number }): void {
+ if (REDIR_HDOC.has(redir.op)) {
+ const body = redir.hdoc;
+ if (body && body.parts.some((p) => p.type !== 'Lit')) {
+ this.#uncertain.push('here-document with substitutions');
+ }
+ return;
+ }
+ if (REDIR_DUP.has(redir.op) || redir.word === null) return;
+ const target = this.#word(redir.word, ctx);
+ const path = target.value !== undefined && !target.glob ? target.value : undefined;
+ if (path === '/dev/null' || path === '/dev/stdout' || path === '/dev/stderr') return;
+ if (REDIR_OUT.has(redir.op)) this.#files.push({ access: 'write', path });
+ else if (REDIR_IN.has(redir.op)) this.#files.push({ access: 'read', path });
+ else if (REDIR_INOUT.has(redir.op)) {
+ this.#files.push({ access: 'read', path });
+ this.#files.push({ access: 'write', path });
+ }
+ // Here-strings (`<<<`) carry no file.
+ }
+
+ #callExpr(call: CallExpr, ctx: { source: string; depth: number }): void {
+ const raw = this.#text(call, ctx);
+ const words = call.args.map((w) => this.#word(w, ctx));
+ if (words.length === 0) return; // pure assignment, e.g. `A=$(rm x)`: nested commands are walked
+ this.#addCommand(raw, words, call.assigns.length > 0, ctx);
+ }
+
+ #fileOperands(base: string, operands: readonly WordValue[]): void {
+ const reads = FILE_READERS.has(base) || FILE_COPIERS.has(base);
+ let writes = FILE_WRITERS.has(base) || FILE_COPIERS.has(base);
+ if (base === 'sed' && operands.some((o) => o.value !== undefined && (o.value === '-i' || o.value.startsWith('--in-place') || /^-[a-zA-Z]*i/.test(o.value)))) writes = true;
+ if (!reads && !writes) return;
+ for (let k = 0; k < operands.length; k++) {
+ const operand = operands[k];
+ if (!operand) continue;
+ if (operand.raw.startsWith('<(') || operand.raw.startsWith('>(')) continue;
+ let value = operand.value;
+ if (value !== undefined && value.startsWith('-')) {
+ // `-n 5`: skip a numeric option value; `--file=x`, `-fX`: the value may be a file.
+ const next = operands[k + 1]?.value;
+ if (next !== undefined && /^\d+$/.test(next)) k++;
+ const eq = value.indexOf('=');
+ if (eq === -1) continue;
+ value = value.slice(eq + 1);
+ }
+ if (base === 'dd' && value !== undefined) {
+ const m = /^(if|of)=(.*)$/s.exec(value);
+ if (!m) continue;
+ value = m[2];
+ }
+ const path = value !== undefined && !operand.glob ? value : undefined;
+ if (reads) this.#files.push({ access: 'read', path });
+ if (writes) this.#files.push({ access: 'write', path });
+ }
+ }
+
+ #addCommand(raw: string, words: readonly WordValue[], hasAssigns: boolean, ctx: { source: string; depth: number }): void {
+ const denyForms = new Set([raw]);
+ const staticPrefixes = new Set