Part IV · Safety, Policy, and Extensibility
Chapter 11
The Permission Engine: Modes, Rules, Classifiers, and Persistence
Layer: Layer 4 (Safety, Policy, Sandbox & Lifecycle Hooks)
Prerequisites: Chapter 01, Chapter 02, Chapter 06, Chapter 08, Chapter 10
Primary Source Files:
types/permissions.ts— mode unions, 8PermissionRuleSources,PermissionUpdate,PermissionResult, andYoloClassifierResultcontracts (441 lines; present in this snapshot)utils/permissions/PermissionMode.ts— Zod mode schemas, UI metadata,toExternalPermissionMode, andpermissionModeFromString(141 lines)utils/permissions/permissions.ts— two-layer evaluator (hasPermissionsToUseToolInner,hasPermissionsToUseTool),checkRuleBasedPermissions, headless hooks, andsyncPermissionRulesFromDisk(1,486 lines)utils/permissions/permissionSetup.ts— dangerous-permission stripping/restoration,transitionPermissionMode, plan/auto coordination, CLI init, and killswitches (1,532 lines)utils/permissions/permissionsLoader.ts&utils/permissions/PermissionUpdate.ts— disk loader (allowManagedPermissionRulesOnly, lenient edit-only JSON), reducer, and 3-source persistence (296 & 389 lines)utils/permissions/filesystem.ts&utils/permissions/pathValidation.ts— symlink containment, gitignore prefix lattice, protected paths, internal carve-outs, and shell TOCTOU guards (1,777 & 485 lines)utils/permissions/shellRuleMatching.ts—ShellPermissionRuleparser (prefix/wildcard/exact) and regexmatchWildcardPattern(228 lines)utils/permissions/yoloClassifier.ts&utils/permissions/classifierDecision.ts— sanitized transcript builder, two-stage XML /classify_resultclassifier, andisAutoModeAllowlistedTool(1,495 & 98 lines)utils/permissions/denialTracking.ts— immutableDENIAL_LIMITS(maxConsecutive: 3,maxTotal: 20) circuit breaker andshouldFallbackToPrompting(45 lines)hooks/useCanUseTool.tsx,hooks/toolPermission/PermissionContext.ts&hooks/toolPermission/handlers/interactiveHandler.ts— compiledCanUseToolFnwaterfall, two-phaseclaim()lock, and 5-racer modal (204, 388 & 536 lines)
Why This Layer Exists
Layers 1–3 wired every caller into permissions: Tool.checkPermissions() (Chapter 02), runToolUse() via resolveHookPermissionDecision() (services/tools/toolExecution.ts:921-929, Chapter 06), and QueryEngine.ts:244-271 tracking SDK permissionDenials (Chapter 08).
Memory agents (Chapter 10) supply scoped CanUseToolFn wrappers (createMemoryFileCanUseTool at services/SessionMemory/sessionMemory.ts:460-482, createAutoMemCanUseTool at services/extractMemories/extractMemories.ts:171-222) while stashing CLAUDE.md in bootstrap/state.ts (context.ts:176).
Giving an LLM shell and filesystem write access demands three guarantees before any tool executes:
- Non-bypassable precedence: Enterprise policy, CLI flags, settings, hooks, modes, and config guards must compose without letting a hook, a broad allow rule, or
bypassPermissionsdefeat a deny rule or.claude/settings.jsonedit. - Adversarial path & shell defenses: Symlink chains, dangling links, case-insensitive filesystems, Windows NTFS short names, UNC paths, and shell expansions (
$VAR,~root) all open parser-vs-OS TOCTOU gaps. - Autonomous safety under untrusted context: An
auto-mode classifier must judge risk without prompt injection fromtool_resultoutputs or assistant prose, fail closed on outages, and fall back to human prompts before spinning forever.
1. Permission Contracts, Modes, and the Eight Rule Sources
The Problem
Permissions sit in a high-fan-in import diamond spanning Tool.ts, utils/claudemd.ts, hooks, and UI. Rules come from eight origins, while modes must span external SDKs, a feature-gated classifier (auto), and an internal subagent mode (bubble) users must never pass on the CLI.
The Mechanism: Leaf Contracts, Mode Projections, and the Source Lattice
Unlike absent types/message.ts, types/permissions.ts is present (441 lines) to break circular imports (types/permissions.ts:1-7). Watch one divergence: types/permissions.ts:427-441 omits isAutoModeAvailable?: boolean, whereas runtime evaluators (utils/permissions/permissions.ts:8) import the authoritative DeepImmutable<ToolPermissionContext> from Tool.ts:123-138 (isAutoModeAvailable at Tool.ts:130).
types/permissions.ts:16-38 defines three concentric mode sets—5 external modes, 6 user-addressable runtime modes (feature('TRANSCRIPT_CLASSIFIER')), and 7 type literals including internal 'bubble':
// types/permissions.ts:16-38
export const EXTERNAL_PERMISSION_MODES = [
'acceptEdits',
'bypassPermissions',
'default',
'dontAsk',
'plan',
] as const
export type ExternalPermissionMode = (typeof EXTERNAL_PERMISSION_MODES)[number]
// Exhaustive mode union for typechecking. The user-addressable runtime set
// is INTERNAL_PERMISSION_MODES below.
export type InternalPermissionMode = ExternalPermissionMode | 'auto' | 'bubble'
export type PermissionMode = InternalPermissionMode
// Runtime validation set: modes that are user-addressable (settings.json
// defaultMode, --permission-mode CLI flag, conversation recovery).
export const INTERNAL_PERMISSION_MODES = [
...EXTERNAL_PERMISSION_MODES,
...(feature('TRANSCRIPT_CLASSIFIER') ? (['auto'] as const) : ([] as const)),
] as const satisfies readonly PermissionMode[]
export const PERMISSION_MODES = INTERNAL_PERMISSION_MODES
- Internal
'bubble'mode: Excluded fromINTERNAL_PERMISSION_MODESand assigned only toFORK_AGENT(tools/AgentTool/forkSubagent.ts:67). When explicitcanShowPermissionPromptsis undefined (tools/AgentTool/runAgent.ts:440-463),'bubble'keeps localshouldAvoidPromptsfalseso async fork children skip settingshouldAvoidPermissionPrompts: true(without overwriting an inheritedtrue), bubbling prompts to the parent while settingawaitAutomatedChecksBeforeDialog = truewhen async. - Parent-mode floor: Agent definitions cannot override parent
bypassPermissions,acceptEdits, orfeature('TRANSCRIPT_CLASSIFIER')auto(tools/AgentTool/runAgent.ts:421-434). - Mode projections (
utils/permissions/PermissionMode.ts:42-121):PERMISSION_MODE_CONFIGmaps modes to UI metadata and anexternalfallback (autogated onfeature('TRANSCRIPT_CLASSIFIER')).toExternalPermissionModeprojects'auto'and'bubble'to'default'at SDK edges;permissionModeFromStringdefaults unknown strings to'default'. - Shift+Tab carousel (
utils/permissions/getNextPermissionMode.ts:17-101): Cyclesdefault -> acceptEdits -> plan -> [bypassPermissions] -> [auto] -> default(USER_TYPE === 'ant'skipsacceptEdits/planfromdefault;dontAsk/autoreturn to'default'). Underfeature('TRANSCRIPT_CLASSIFIER'),canCycleToAutochecks both cachedisAutoModeAvailableand liveisAutoModeGateEnabled()socyclePermissionModenever throws mid-session.
All rules in alwaysAllowRules, alwaysDenyRules, and alwaysAskRules are keyed by PermissionRuleSource (types/permissions.ts:54-62), ordered by PERMISSION_RULE_SOURCES (utils/permissions/permissions.ts:109-114):
| # | PermissionRuleSource |
Origin | Editable? | Update Dest? | Shared? |
|---|---|---|---|---|---|
| 1 | userSettings |
~/.claude/settings.json |
Yes | Yes | Personal |
| 2 | projectSettings |
<repo>/.claude/settings.json |
Yes | Yes | Shared |
| 3 | localSettings |
<repo>/.claude/settings.local.json |
Yes | Yes | Personal |
| 4 | flagSettings |
--settings CLI path/JSON |
No | No | Personal |
| 5 | policySettings |
Enterprise managed policy | No | No | Shared |
| 6 | cliArg |
--allowed-tools / --disallowed-tools / --tools |
No | Yes | Personal |
| 7 | command |
Skill / command frontmatter allowed-tools |
No | No | Shared |
| 8 | session |
Ephemeral in-session approvals | No | Yes | Personal |
Three utilities parse, load, and audit rules across these sources:
- Parser & aliases (
utils/permissions/permissionRuleParser.ts:10-198):permissionRuleValueFromStringsplitsTool(ruleContent)via backslash-parity paren scanning, collapsesBash()/Bash(*)to blanket{ toolName: 'Bash' }, and normalizesLEGACY_TOOL_NAME_ALIASES(Task -> Agent,KillShell -> TaskStop,AgentOutputTool/BashOutputTool -> TaskOutput, plusBriefunderfeature('KAIROS') || feature('KAIROS_BRIEF')). - Managed lockdown (
utils/permissions/permissionsLoader.ts:31-242): WhenpolicySettings.allowManagedPermissionRulesOnly === true,loadAllPermissionRulesFromDisk()ignores all other sources,shouldShowAlwaysAllowOptions()hides permanent allow prompts, andaddPermissionRulesToSettings()refuses writes. - Shadowed-rule audit:
detectUnreachableRules(utils/permissions/shadowedRuleDetection.ts:193-234) flags content-specificallowrules masked by tool-widedeny/askrules;isAllowRuleShadowedByAskRule(utils/permissions/shadowedRuleDetection.ts:111-147) exempts sandboxedBashonly for personalasksources (!isSharedSettingSource,utils/permissions/shadowedRuleDetection.ts:61-67), since teammates sharingprojectSettings/policySettingsmay run unsandboxed.
Hidden Invariants & Production Scars
- Lenient edit-only JSON fallback (
utils/permissions/permissionsLoader.ts:61-83,utils/permissions/permissionsLoader.ts:253-256): Ifsettings.jsonfails strict Zod validation (e.g., malformedhooks), writing{ permissions: {} }would wipe existing settings.getSettingsForSourceLenient_FOR_EDITING_ONLY_NOT_FOR_READINGparses raw JSON without Zod so edits preserve untouched keys. - Legacy ant-only drift (
utils/permissions/PermissionMode.ts:97-105):isExternalPermissionModereturnstrueunconditionally whenprocess.env.USER_TYPE !== 'ant', thoughtypes/permissions.ts:35gates'auto'onfeature('TRANSCRIPT_CLASSIFIER')in external builds. SDK edges rely ontoExternalPermissionMode. - Within-bucket vs. cross-bucket order (
utils/permissions/permissions.ts:275-302,utils/permissions/permissions.ts:362-390): Cross-behavior precedence (deny > ask > allow) is fixed by pipeline order. Inside one bucket, tool-wide matchers use.find()(earliest source wins), whilegetRuleByContentsForToolNamefills aMap1 -> 8(later source overwrites identicalruleContent).
2. Two-Layer Evaluation Precedence, Stripping, Transitions, and Persistence
The Problem
A flat evaluator with scattered early returns lets one new 'ask' branch silently bypass dontAsk, auto-mode classification, or headless hooks. Likewise, letting a PreToolUse hook skip deny/ask rules—or leaving Bash(python:*) active inside auto mode—breaks defense in depth.
The Mechanism: Inner Precedence, Outer Transforms, and Reversible Stripping
utils/permissions/permissions.ts splits evaluation into an inner evaluator, a hook mirror, and an outer mode wrapper:
- Inner evaluator —
hasPermissionsToUseToolInner(utils/permissions/permissions.ts:1158-1319):- Steps 0–1b (
utils/permissions/permissions.ts:1163-1206): ThrowsAbortErrorif aborted; checks blanketdeny(canonicalgetToolNameForPermissionCheckblockingCLAUDE_AGENT_SDK_MCP_NO_PREFIXcollisions plusmcp__serverwildcards,utils/permissions/permissions.ts:238-269); checks blanketask(except sandboxed auto-allowBash, which falls through to1c). - Steps 1c–1g (
utils/permissions/permissions.ts:1210-1260): Parses input and awaitstool.checkPermissions(re-throwing aborts; falling through aspassthroughon other errors); returns immediately on tool'deny'(1d),requiresUserInteraction?.()'ask'(1e), content-specificaskrules (1f), andsafetyCheckasks (1g). - Steps 2a–3 (
utils/permissions/permissions.ts:1264-1318): Re-reads freshcontext.getAppState()forbypassPermissions(orplanwithisBypassPermissionsModeAvailable), checks blanketallow(toolAlwaysAllowedRule,2b), then promotespassthroughto'ask'viacreatePermissionRequestMessage.
- Steps 0–1b (
Steps 1a–1g are bypass-immune—even bypassPermissions cannot cross the 1g -> 2a wall:
// utils/permissions/permissions.ts:1252-1281
// 1g. Safety checks (e.g. .git/, .claude/, .vscode/, shell configs) are
// bypass-immune — they must prompt even in bypassPermissions mode.
// checkPathSafetyForAutoEdit returns {type:'safetyCheck'} for these paths.
if (
toolPermissionResult?.behavior === 'ask' &&
toolPermissionResult.decisionReason?.type === 'safetyCheck'
) {
return toolPermissionResult
}
// 2a. Check if mode allows the tool to run
// IMPORTANT: Call getAppState() to get the latest value
appState = context.getAppState()
// Check if permissions should be bypassed:
// - Direct bypassPermissions mode
// - Plan mode when the user originally started with bypass mode (isBypassPermissionsModeAvailable)
const shouldBypassPermissions =
appState.toolPermissionContext.mode === 'bypassPermissions' ||
(appState.toolPermissionContext.mode === 'plan' &&
appState.toolPermissionContext.isBypassPermissionsModeAvailable)
if (shouldBypassPermissions) {
return {
behavior: 'allow',
updatedInput: getUpdatedInputOrFallback(toolPermissionResult, input),
decisionReason: {
type: 'mode',
mode: appState.toolPermissionContext.mode,
},
}
}
- Hook parity mirror —
checkRuleBasedPermissions(utils/permissions/permissions.ts:1071-1156): Mirrors only steps1a,1b,1c,1d,1f, and1g. Called solely byresolveHookPermissionDecision(services/tools/toolHooks.ts:373-377), it enforces theinc-4788 analoginvariant (services/tools/toolHooks.ts:324-325): aPreToolUsehook's'allow'never overrides deny/ask rules orsafetyChecks. - Outer wrapper —
hasPermissionsToUseTool(utils/permissions/permissions.ts:473-956): Ensures inner early returns cannot escape mode transforms (utils/permissions/permissions.ts:504). On inner'allow'inautomode, it resets consecutive denials (utils/permissions/permissions.ts:486-501). On inner'ask':dontAsk(utils/permissions/permissions.ts:508-517): Converts'ask'to'deny'.auto/plan-with-auto (utils/permissions/permissions.ts:520-927,feature('TRANSCRIPT_CLASSIFIER')): Runs beforeshouldAvoidPermissionPromptsfor headless coverage: non-classifierApprovablesafetyCheck,requiresUserInteraction(), PowerShell guard unlessfeature('POWERSHELL_AUTO_MODE'), andacceptEditsfast-path (excludingAgent/REPL,utils/permissions/permissions.ts:596-603).- Remaining actions check
isAutoModeAllowlistedTool, then callclassifyYoloAction, honoringtengu_iron_gate_closedand denial tracking.
- Remaining actions check
- Headless / async (
shouldAvoidPermissionPrompts,utils/permissions/permissions.ts:932-952): RunsrunPermissionRequestHooksForHeadlessAgent(utils/permissions/permissions.ts:400-471) before auto-denying as{ type: 'asyncAgent' }.
Because inner steps 1c and 2b return 'allow' before the outer classifier executes, utils/permissions/permissionSetup.ts strips dangerous allow rules on auto-mode entry and restores them on exit:
- Stripping & restoration (
utils/permissions/permissionSetup.ts:94-579):isDangerousClassifierPermission(utils/permissions/permissionSetup.ts:272-285) matches broadBash(DANGEROUS_BASH_PATTERNS, 5 shapes: exact,:*,*,*,-*),PowerShell(CROSS_PLATFORM_CODE_EXEC+ cmdlets, bare/.exe), allAgent/Taskallows, and ant-onlyTmux.stripDangerousPermissionsForAutoMode(utils/permissions/permissionSetup.ts:510-553) stashes them instrippedDangerousRules({}sentinel if empty);restoreDangerousPermissionsreplays them on exit.
- Ant broad-shell strip (startup vs. reload):
- Startup: Under
USER_TYPE === 'ant'outsideCLAUDE_CODE_REMOTEandCLAUDE_CODE_ENTRYPOINT === 'local-agent',utils/permissions/permissionSetup.ts:953-965detects overly broadBashandPowerShellallows in all modes, which callermain.tsx:1763-1768strips viaremoveDangerousPermissions. - Live settings reload:
utils/settings/applySettingsChange.ts:51-59re-strips overly broadBashallows only, gated onUSER_TYPE === 'ant'andCLAUDE_CODE_ENTRYPOINT !== 'local-agent'(with noCLAUDE_CODE_REMOTEcheck).
- Startup: Under
- Centralized transitions (
utils/permissions/permissionSetup.ts:597-646,utils/permissions/permissionSetup.ts:1446-1532):transitionPermissionModedelegates plan entry toprepareContextForPlanModeand usesautoModeStateModule.isAutoModeActive()as the authoritative classifier signal:
// utils/permissions/permissionSetup.ts:617-637
// Plan with auto active counts as using the classifier (for the leaving side).
// isAutoModeActive() is the authoritative signal — prePlanMode/strippedDangerousRules
// are unreliable proxies because auto can be deactivated mid-plan (non-opt-in
// entry, transitionPlanAutoMode) while those fields remain set/unset.
const fromUsesClassifier =
fromMode === 'auto' ||
(fromMode === 'plan' &&
(autoModeStateModule?.isAutoModeActive() ?? false))
const toUsesClassifier = toMode === 'auto' // plan entry handled above
if (toUsesClassifier && !fromUsesClassifier) {
if (!isAutoModeGateEnabled()) {
throw new Error('Cannot transition to auto mode: gate is not enabled')
}
autoModeStateModule?.setAutoModeActive(true)
context = stripDangerousPermissionsForAutoMode(context)
} else if (fromUsesClassifier && !toUsesClassifier) {
autoModeStateModule?.setAutoModeActive(false)
setNeedsAutoModeExitAttachment(true)
context = restoreDangerousPermissions(context)
}
- CLI init:
initialPermissionModeFromCLI(utils/permissions/permissionSetup.ts:689-811) orders--dangerously-skip-permissions>--permission-mode>defaultMode(capped inCLAUDE_CODE_REMOTE) >'default', usingNO_CACHED_AUTO_MODE_CONFIG(Symbol('no-cached-auto-mode-config')atutils/permissions/permissionSetup.ts:1335-1352).initializeToolPermissionContext(utils/permissions/permissionSetup.ts:872-1033) turns--toolsexclusions intocliArgdenies, adds symlinkedPWDas'session', and validates--add-dirin parallel.
- Bypass killswitch: GrowthBook
'tengu_disable_bypass_permissions_mode'downgrades interactive sessions (utils/permissions/bypassPermissionsKillswitch.ts:19-70) but callsgracefulShutdown(1)headlessly (utils/permissions/permissionSetup.ts:1411-1431). - Update persistence & deletion:
PermissionUpdate(types/permissions.ts:88-131,utils/permissions/PermissionUpdateSchema.ts:27-78) persists viapersistPermissionUpdate(utils/permissions/PermissionUpdate.ts:208-342) only to editable sources;deletePermissionRule(utils/permissions/permissions.ts:1329-1370) throws on read-only sources (utils/permissions/permissions.ts:1334-1340).
Hidden Invariants & Production Scars
- Closure-returning async killswitch (
utils/permissions/permissionSetup.ts:1078-1260,utils/permissions/bypassPermissionsKillswitch.ts:74-155): Underfeature('TRANSCRIPT_CLASSIFIER')(utils/permissions/bypassPermissionsKillswitch.ts:79),checkAndDisableAutoModeIfNeededawaitsverifyAutoModeGateAccess(tengu_auto_mode_config,modelSupportsAutoModeatutils/betas.ts:160-195,disableFastMode).- Applying its returned
updateContextclosure insidesetAppState(prev => ...)prevents stale awaits from clobbering a Shift+Tab while still evicting auto and defusingprePlanMode(utils/permissions/permissionSetup.ts:1223).
- Applying its returned
- Untrusted
projectSettingsexclusion (utils/permissions/permissionSetup.ts:1446-1455,utils/settings/settings.ts:896-928):hasAutoModeOptIn()andgetUseAutoModeDuringPlan()ignoreprojectSettingsso cloned repos cannot opt themselves into auto mode. - Stale-rule clearing & plan-mode reload re-strip:
syncPermissionRulesFromDisk(utils/permissions/permissions.ts:1448-1470) pre-clears all 3 behaviors across the 3 editable disk sources (userSettings,projectSettings,localSettingsatutils/permissions/permissions.ts:1453-1457—notflagSettings/policySettings—pluscliArg/sessionunderallowManagedPermissionRulesOnly,utils/permissions/permissions.ts:1426-1446) beforereplaceRulesso deleting a last deny rule never lingers.- Next,
transitionPlanAutoMode(utils/settings/applySettingsChange.ts:68,utils/permissions/permissionSetup.ts:1502-1532) re-strips dangerous allows duringplanmode when plan-auto was already active (utils/permissions/permissionSetup.ts:1516-1521); guarded byif (context.mode !== 'plan') return context(utils/permissions/permissionSetup.ts:1506), it is a no-op outsideplanmode (including directmode === 'auto').
- Next,
3. Filesystem Path Validation, Symlinks, Working Directories, and Protected Paths
The Problem
Path strings hide traps: ./data may symlink to /etc/cron.d/, ./evil.txt may be a dangling link targeting ~/.ssh/authorized_keys2, Windows NTFS 8.3 short names (GIT~1) or trailing dots (.git.) evade naive checks, and acceptEdits must never let the model modify .claude/settings.json or .git/hooks/*.
The Mechanism: Multi-Representation Containment and the Write-Safety Lattice
getPathsForPermissionCheck(inputPath) (utils/fsOperations.ts:288-382) expands each path into all security-relevant forms. safeResolvePath (utils/fsOperations.ts:138-178) short-circuits ///\\ pre-syscall (stopping Windows NTLM leaks) and checks lstatSync so FIFOs/sockets/devices never hang realpathSync.
The walk follows symlinks up to maxDepth = 40 (visited guard), appends canonical realpathSync (/etc/passwd -> /private/etc/passwd), and calls resolveDeepestExistingAncestorSync (utils/fsOperations.ts:215-270, utils/fsOperations.ts:325-340) so new files under live parent symlinks (./data -> /etc/cron.d/) and dangling links (./evil.txt -> ~/.ssh/authorized_keys2) expose their true target.
Negative checks (deny, ask, checkPathSafetyForAutoEdit) fail closed if any representation matches (some), whereas working-directory containment requires every representation to stay inside some symmetrically resolved root (utils/permissions/filesystem.ts:683-707):
// utils/permissions/filesystem.ts:683-707
export function pathInAllowedWorkingPath(
path: string,
toolPermissionContext: ToolPermissionContext,
precomputedPathsToCheck?: readonly string[],
): boolean {
// Check both the original path and the resolved symlink path
const pathsToCheck =
precomputedPathsToCheck ?? getPathsForPermissionCheck(path)
// Resolve working directories the same way we resolve input paths so
// comparisons are symmetric. Without this, a resolved input path
// (e.g. /System/Volumes/Data/home/... on macOS) would not match an
// unresolved working directory (/home/...), causing false denials.
const workingPaths = Array.from(
allWorkingDirectories(toolPermissionContext),
).flatMap(wp => getResolvedWorkingDirPaths(wp))
// All paths must be within allowed working paths
// If any resolved path is outside, deny access
return pathsToCheck.every(pathToCheck =>
workingPaths.some(workingPath =>
pathInWorkingPath(pathToCheck, workingPath),
),
)
}
getOriginalCwd()anchor & normalization:allWorkingDirectories(utils/permissions/filesystem.ts:667-674),isClaudeConfigFilePath(utils/permissions/filesystem.ts:225-242),getClaudeSkillScope, androotPathForSourceanchor on startupgetOriginalCwd().pathInWorkingPath(utils/permissions/filesystem.ts:709-744) expands viaexpandPath, normalizes/private/var/and/private/tmp, lowercases vianormalizeCaseForComparison, and rejects..;getResolvedWorkingDirPaths+precomputedPathsToCheckavoid ~30 syscalls.
- Gitignore prefix lattice (
utils/permissions/filesystem.ts:853-1025):patternWithRootandmatchingRuleForInputuseignorewith tool collapse (Editgoverns all writes;Readgoverns all reads) and/**stripping/back-mapping. Single/is not filesystem root:
| Rule Prefix | Anchored Root (patternWithRoot) |
Meaning |
|---|---|---|
//path |
/ (or ${drive}:\\ for Windows //c/...) |
Absolute filesystem path (createReadRuleSuggestion emits //path/**, utils/permissions/PermissionUpdate.ts:361-389) |
~/path |
homedir().normalize('NFC') |
Relative to user home directory |
/path |
rootPathForSource(source) (utils/permissions/filesystem.ts:746-759, delegating disk sources to getSettingsRootPathForSource at utils/settings/settings.ts:239-253) |
Relative to settings root (getOriginalCwd(), ~/.claude, or dirname(--settings)) |
path or ./path |
null (matched against getCwd()) |
Relative to current working directory (leading ./ stripped) |
- Protected paths & auto-edit safety:
DANGEROUS_FILES(utils/permissions/filesystem.ts:57-68, 10 dotfiles:.gitconfig,.gitmodules, shell rc/profiles,.ripgreprc,.mcp.json,.claude.json) andDANGEROUS_DIRECTORIES(utils/permissions/filesystem.ts:74-79:.git,.vscode,.idea,.claude—carving out.claude/worktrees/atutils/permissions/filesystem.ts:456-468).isClaudeSettingsPath(utils/permissions/filesystem.ts:200-222) matches.claude/settings.jsonand.claude/settings.local.jsonin any repo (plus activegetSettingsPaths());isClaudeConfigFilePathguards.claude/{commands,agents,skills}.
checkPathSafetyForAutoEdit(utils/permissions/filesystem.ts:620-665) step 1 runshasSuspiciousWindowsPathPattern(utils/permissions/filesystem.ts:537-602, favoring pattern detection over TOCTOU-proneGetLongPathNameW): NTFS ADS (windows/wsl), 8.3 names (~\d),\\?\///?/prefixes, trailing dots/spaces, DOS device suffixes,...segments (keeping[...slug]), and UNC detection, returning{ safe: false, classifierApprovable: false }.- Its
containsVulnerableUncPathcheck (utils/shell/readOnlyCommandValidation.ts:1562-1638) is Windows-only (if (getPlatform() !== 'windows') return falseatutils/shell/readOnlyCommandValidation.ts:1564-1566).
- Its
- Steps 2–3 run
isClaudeConfigFilePath(utils/permissions/filesystem.ts:642-650) andisDangerousFilePathToAutoEdit(utils/permissions/filesystem.ts:653-661), which also carries the explicit non-Windows write-side///\\check (utils/permissions/filesystem.ts:442-444), returning{ safe: false, classifierApprovable: true }(bypass-immune tobypassPermissions/acceptEdits, reviewable byauto).- Pre-syscall and read-side non-Windows
///\\guards sit insafeResolvePath(utils/fsOperations.ts:144-146),getPathsForPermissionCheck(utils/fsOperations.ts:306-308), andcheckReadPermissionForTool(utils/permissions/filesystem.ts:1053-1064).
- Pre-syscall and read-side non-Windows
- Read/Write precedence & internal carve-outs:
checkReadPermissionForTool(utils/permissions/filesystem.ts:1030-1194): UNC -> suspicious Windows -> Readdeny-> Readask-> Edit implies Read ->pathInAllowedWorkingPath->checkReadableInternalPath-> Readallow->ask(getFileReadIgnorePatternshides Read-denied paths fromGlobTool/GrepTool).checkWritePermissionForTool(utils/permissions/filesystem.ts:1205-1412): Editdeny-> 1.5checkEditableInternalPath(ahead of safety checks since plans/memory live in.claude/) -> 1.6 session-only.claude/**/~/.claude/**allow rules (utils/permissions/filesystem.ts:1252-1300, rejecting.., paired withgetClaudeSkillScope) -> 1.7checkPathSafetyForAutoEdit(beatsacceptEditsand permanentEditallows) -> Editask->acceptEdits-> Editallow->ask.- Editable (
utils/permissions/filesystem.ts:1479-1605, 6 paths): plans,tengu_scratchscratchpad,feature('TEMPLATES')CLAUDE_JOB_DIR(hijack/symlink guards;utils/permissions/filesystem.ts:1511-1513notes absentjobs/state), agent memory (CLAUDE_CODE_REMOTE_MEMORY_DIR), auto-memory (!hasAutoMemPathOverride() && isAutoMemPath, disabled byCLAUDE_COWORK_MEMORY_PATH_OVERRIDE;memdir/paths.ts:172-186excludesprojectSettings), and<origCwd>/.claude/launch.json. - Readable (
utils/permissions/filesystem.ts:1611-1777, 11 paths): session memory, tool results,CLAUDE_CODE_TMPDIRtemp dirs, tasks/teams, andgetBundledSkillsRoot()(utils/permissions/filesystem.ts:350-370:{claudeTempDir}/bundled-skills/{MACRO.VERSION}/{128-bit nonce}stopping/tmpsquatting).
- Shell TOCTOU & sandbox allowlist (
utils/permissions/pathValidation.ts:101-485):validatePathexpands only~/~//~\, rejects UNC, unexpanded~root/~+, shell expansions ($,%, leading=), and write globs (GLOB_PATTERN_REGEX), delegates read globs tovalidateGlobPattern, and passesisCanonical ? [resolvedPath] : undefinedintoisPathAllowed(no Step 1.6.claude/**).- Step 3.7 (
utils/permissions/pathValidation.ts:233-245) honorsisPathInSandboxWriteAllowlist(utils/permissions/pathValidation.ts:101-123, symmetrically resolvingallowOnlyanddenyWithinAllow) strictly when!isInWorkingDir—otherwisesandbox-adapter.tsseeding'.'intoallowOnlywould bypassacceptEditsinside cwd. isDangerousRemovalPath(utils/permissions/pathValidation.ts:331-367) blocks*,/*,/, drive roots,homedir(), and direct children of/or a drive root.
- Step 3.7 (
Hidden Invariants & Production Scars
- Auto-mode downgrade guard (
utils/permissions/filesystem.ts:1439-1446):generateSuggestionsemits{ type: 'setMode', mode: 'acceptEdits' }only in'default'or'plan'—never'auto'or'bypassPermissions'—so SDK hosts cannot silently downgrade'auto'. - Lexical allow vs. expanded deny/ask (
utils/permissions/filesystem.ts:1161,utils/permissions/filesystem.ts:1378,utils/permissions/filesystem.ts:1428-1463): Deny, ask, and safety checks iterate allpathsToCheck, whereasallowlookups match lexicalpath. HencegenerateSuggestionsemits rules/directories covering both the symlink and resolved target.
4. Shell Wildcard Rule Matching and Dangerous Command Patterns
The Problem
Users need both legacy prefix rules (Bash(git:*)) and modern wildcards (Bash(git *), Bash(* --version)), across multiline heredocs and case-insensitive PowerShell. Meanwhile, auto mode needs an exact list of interpreter and runner prefixes to strip without touching safe commands.
The Mechanism: Three-Kind Rule Parsing, Sentinel Escaping, and Dangerous Prefixes
parsePermissionRule (utils/permissions/shellRuleMatching.ts:159-184) classifies every shell rule into ShellPermissionRule (utils/permissions/shellRuleMatching.ts:25-37): prefix via permissionRuleExtractPrefix (/^(.+):\*$/), wildcard via hasWildcards (unescaped * by backslash parity), or fallback exact.
matchWildcardPattern(pattern, command, caseInsensitive = false) (utils/permissions/shellRuleMatching.ts:90-154) swaps \*/\\ for null-byte placeholders, escapes regex metacharacters, converts * to .*, restores placeholders, aligns single trailing * with :*, and compiles with 's' (dotAll):
// utils/permissions/shellRuleMatching.ts:142-153
const unescapedStarCount = (processed.match(/\*/g) || []).length
if (regexPattern.endsWith(' .*') && unescapedStarCount === 1) {
regexPattern = regexPattern.slice(0, -3) + '( .*)?'
}
// Create regex that matches the entire string.
// The 's' (dotAll) flag makes '.' match newlines, so wildcards match
// commands containing embedded newlines (e.g. heredoc content after splitCommand_DEPRECATED).
const flags = 's' + (caseInsensitive ? 'i' : '')
const regex = new RegExp(`^${regexPattern}$`, flags)
return regex.test(command)
- Word boundaries & shell case sensitivity:
'git *'compiles to^git( .*)?$(rejecting'gitconfig'), whereas'git*'compiles to^git.*$.BashToolusescaseInsensitive = false(tools/BashTool/bashPermissions.ts:353-358);PowerShellToolusestrue(tools/PowerShellTool/powershellPermissions.ts:243). - Workspace tool reuse: Five workspace tools reuse
matchWildcardPatternforpreparePermissionMatcher:FileReadTool(tools/FileReadTool/FileReadTool.ts:395-397),FileEditTool(tools/FileEditTool/FileEditTool.ts:122-124),FileWriteTool(tools/FileWriteTool/FileWriteTool.ts:132-134),GlobTool(tools/GlobTool/GlobTool.ts:91-93), andGrepTool(tools/GrepTool/GrepTool.ts:198-200). - Dangerous prefixes (
utils/permissions/dangerousPatterns.ts:18-80): ExportsCROSS_PLATFORM_CODE_EXEC(19 interpreters/runners/shells/ssh) andDANGEROUS_BASH_PATTERNS(26 external plus 11USER_TYPE === 'ant'entries includinggh,gh api,curl,wget,git,kubectl,aws,gcloud,gsutil). Distinct multi-word entries ('gh'and'gh api') are needed becauseutils/permissions/permissionSetup.ts:117-146tests fixed 5-shape forms.
Hidden Invariants & Production Scars
- The
\*-only dead-rule scar (tools/PowerShellTool/powershellPermissions.ts:143-155): Escaping a literal*to\*with no other wildcard makeshasWildcards()returnfalse, routing it to{ type: 'exact' }with the backslash intact—a dead rule that never matches. PowerShell skips exact suggestions containing*or\n.
5. The Auto-Mode Security Classifier and Denial Circuit Breaker
The Problem
In auto mode (and auto-backed plan), unallowlisted mutations outside acceptEdits go to an LLM classifier. Three hazards dominate: prompt injection via tool_result data or assistant prose, latency/false-positive tradeoffs, and runaway denial loops during outages or repeated blocks.
The Mechanism: Sanitized Transcripts, Two-Stage XML, and Bounded Denials
utils/permissions/yoloClassifier.ts (1,495 lines) runs auto-mode classification under feature('TRANSCRIPT_CLASSIFIER'):
- Absent
.txttemplates &<user_*_to_replace>(utils/permissions/yoloClassifier.ts:54-142): Module load requiresauto_mode_system_prompt.txt,permissions_external.txt, and ant-onlypermissions_anthropic.txt(utils/permissions/yoloClassifier.ts:55,utils/permissions/yoloClassifier.ts:62,utils/permissions/yoloClassifier.ts:67)—all three are absent from this snapshot.EXTERNAL_PERMISSIONS_TEMPLATEloads in allfeature('TRANSCRIPT_CLASSIFIER')builds—even in ant builds (utils/permissions/yoloClassifier.ts:58-63, consumed bycli/handlers/autoMode.ts:25), andisUsingExternalPermissions()honorstengu_auto_mode_config.forceExternalPermissions.- Regexes and comments in
buildYoloSystemPromptshowsettings.autoMode(allow,soft_deny,environment) fills<user_allow_rules_to_replace>,<user_deny_rules_to_replace>, and<user_environment_to_replace>: external defaults sit inside those tags (user rules replace them), while Anthropic defaults sit outside empty tags (user rules are additive,utils/permissions/yoloClassifier.ts:511-540). - Ant builds prepend
feature('BASH_CLASSIFIER')descriptions (stubbed to[]in externalutils/permissions/bashClassifier.ts:28-38) andfeature('POWERSHELL_AUTO_MODE')POWERSHELL_DENY_GUIDANCE(utils/permissions/yoloClassifier.ts:1402-1411, guardingiex,Remove-Item -Recurse -Force,$PROFILEpersistence, and AMSI bypasses).
- Prompt-injection-hardened transcript (
utils/permissions/yoloClassifier.ts:302-477,utils/permissions/yoloClassifier.ts:1019-1106):buildClaudeMdMessage()(utils/permissions/yoloClassifier.ts:460-477) readsgetCachedClaudeMdContent()(bootstrap/state.ts:1211-1213) into a cached<user_claude_md>prefix, breaking the 4-hopclaudemd -> filesystem -> permissions -> yoloClassifiercycle (Chapter 04, Chapter 10).buildTranscriptEntries(utils/permissions/yoloClassifier.ts:302-360) keeps queued commands, usertext, and assistanttool_useblocks—stripping alltool_resultoutputs and assistant prose/thinking.buildTranscriptForClassifier(utils/permissions/yoloClassifier.ts:434-442) also serves subagent handoffs (tools/AgentTool/agentToolUtils.ts:407).toCompactBlockprojectstool_useviatool.toAutoClassifierInput(input)insidetry/catch; empty''returns{ shouldBlock: false }immediately (utils/permissions/yoloClassifier.ts:1023-1029) to prevent API 400s on empty cached blocks. Ant-onlyCLAUDE_CODE_JSONL_TRANSCRIPTortengu_auto_mode_config.jsonlTranscriptenables JSONL framing ({"user":"..."}\n) against newline turn spoofing.- No local truncation & 3-breakpoint cache (
utils/permissions/yoloClassifier.ts:1068-1106,utils/permissions/yoloClassifier.ts:1463-1471): Relies on projection shrinkage and Chapter 09 auto-compact (detectPromptTooLongcatches 400s). Breakpoints on system, optionalCLAUDE.md, and the action block stay within 3 breakpoints so Stage 2 hits warm cache.
- Two-stage XML vs.
classify_result(utils/permissions/yoloClassifier.ts:550-996,utils/permissions/classifierShared.ts:15-39): Controlled by ant-onlyCLAUDE_CODE_TWO_STAGE_CLASSIFIERortengu_auto_mode_config.twoStageClassifier. Off forcesclassify_resulttool_use; on runsclassifyYoloActionXml('both'default), escalating'yes'or unparseable Stage 1 verdicts (XML_S1_SUFFIX,max_tokens: 64 + thinkingPadding,stop_sequences: ['</block>']) to Stage 2.- Stage 2 runs CoT with
XML_S2_SUFFIXandmax_tokens: 4096 + thinkingPadding(utils/permissions/yoloClassifier.ts:868);twoStageClassifieralso supports single-stage'fast'(256 + thinkingPadding, nostop_sequences,utils/permissions/yoloClassifier.ts:781-792) and'thinking'(utils/permissions/yoloClassifier.ts:703-706,utils/permissions/yoloClassifier.ts:1316).stripThinkingstrips<thinking>before matching<block>/<reason>:
- Stage 2 runs CoT with
// utils/permissions/yoloClassifier.ts:567-584
function stripThinking(text: string): string {
return text
.replace(/<thinking>[\s\S]*?<\/thinking>/g, '')
.replace(/<thinking>[\s\S]*$/, '')
}
/**
* Parse XML block response: <block>yes/no</block>
* Strips thinking content first to avoid matching tags inside reasoning.
* Returns true for "yes" (should block), false for "no", null if unparseable.
*/
function parseXmlBlock(text: string): boolean | null {
const matches = [
...stripThinking(text).matchAll(/<block>(yes|no)\b(<\/block>)?/gi),
]
if (matches.length === 0) return null
return matches[0]![1]!.toLowerCase() === 'yes'
}
- Allowlist, DCE state & fail-closed denial circuit breaker:
SAFE_YOLO_ALLOWLISTED_TOOLS(utils/permissions/classifierDecision.ts:56-98) allowlists 22 unconditional tools (7 read/search, 7 task, 3 plan/UI, 3 swarm,SLEEP_TOOL_NAME, andYOLO_CLASSIFIER_TOOL_NAME) plus 4 gated snapshot-absent constants (= 26total);utils/permissions/autoModeState.ts:1-39isolatesautoModeActive,autoModeFlagCli, andautoModeCircuitBrokenbehindfeature('TRANSCRIPT_CLASSIFIER').- Gated snapshot-absent allowlist constants (
utils/permissions/classifierDecision.ts:27-47):TerminalCaptureTool(feature('TERMINAL_PANEL'),utils/permissions/classifierDecision.ts:27-31),OverflowTestTool(feature('OVERFLOW_TEST_TOOL'),utils/permissions/classifierDecision.ts:32-36),VerifyPlanExecutionTool(process.env.USER_TYPE === 'ant',utils/permissions/classifierDecision.ts:37-42), andWorkflowTool(feature('WORKFLOW_SCRIPTS'),utils/permissions/classifierDecision.ts:43-47). - Fail-closed outcomes (
utils/permissions/permissions.ts:818-1058): Parse errors always block; Stage-2 throws after Stage-1 escalation keepunavailable: false(utils/permissions/yoloClassifier.ts:977-983).transcriptTooLongaborts headless and asks interactively;unavailablecheckstengu_iron_gate_closed(defaulttrue, 30 min TTL atutils/permissions/permissions.ts:107) to fail closed ('deny') without tripping denial counters. - Denial circuit breaker (
utils/permissions/denialTracking.ts:12-45): Caps blocks atDENIAL_LIMITS(maxConsecutive: 3,maxTotal: 20).recordSuccesspreserves object identity at0so React skips redundant renders (utils/permissions/permissions.ts:974):
- Gated snapshot-absent allowlist constants (
// utils/permissions/denialTracking.ts:32-45
export function recordSuccess(state: DenialTrackingState): DenialTrackingState {
if (state.consecutiveDenials === 0) return state // No change needed
return {
...state,
consecutiveDenials: 0,
}
}
export function shouldFallbackToPrompting(state: DenialTrackingState): boolean {
return (
state.consecutiveDenials >= DENIAL_LIMITS.maxConsecutive ||
state.totalDenials >= DENIAL_LIMITS.maxTotal
)
}
When shouldFallbackToPrompting trips (utils/permissions/permissions.ts:984-1058), headless agents throw AbortError, whereas interactive sessions reset counts on hitTotalLimit (utils/permissions/permissions.ts:1034-1040) and return 'ask' to open the human dialog.
Hidden Invariants & Production Scars
alwaysOnThinkingtuple scar (utils/permissions/yoloClassifier.ts:666-693,utils/model/antModels.ts:51-64): Models flaggedalwaysOnThinkingintengu_ant_model_overriderejectthinking: falsewith HTTP 400.getClassifierThinkingConfigreturns tuple[undefined, 2048](avoiding leaked property names), keeping thinking enabled and paddingmax_tokensby 2,048 above Stage 1's 64-token cap.- In-place
localDenialTracking(utils/forkedAgent.ts:418-422,utils/permissions/permissions.ts:963-1004): Forked agents have a no-opsetAppState;persistDenialStatemutateslocalDenialTrackingviaObject.assign, sohandleDenialLimitExceededsnapshots counts before resetting. - Model selection,
sideQuery& dumps:getClassifierModel(utils/permissions/yoloClassifier.ts:1334-1347) resolves ant-onlyCLAUDE_CODE_AUTO_MODE_MODEL>tengu_auto_mode_config.model>getMainLoopModel().sideQueryretries 429/5xx without mutating session cost (utils/permissions/permissions.ts:765-766); errors dump to<claudeTempDir>/auto-mode-classifier-errors/<sessionId>.txt, and antCLAUDE_CODE_DUMP_AUTO_MODEdumps.req.json/.res.json.
6. Interactive, Coordinator, and Swarm Permission Handlers
The Problem
Once hasPermissionsToUseTool emits 'ask', up to five concurrent sources can answer: the local terminal user, a remote web bridge, an MCP channel, a PermissionRequest hook, or a background bash classifier. Because onAllow awaits disk persistence and recheckPermission awaits re-evaluation, a single resolved boolean permits double-resolution races.
The Mechanism: Four-Tier Waterfall and Two-Phase claim() Locking
hooks/useCanUseTool.tsx (204 lines; React-Compiler-compiled .tsx with _c(3) slots and inline source map on line 204) wraps hasPermissionsToUseTool with createPermissionContext (hooks/toolPermission/PermissionContext.ts:96-348), guarding async boundaries via ctx.resolveIfAborted(resolve) (hooks/useCanUseTool.tsx:34, hooks/useCanUseTool.tsx:110) and clearing clearClassifierChecking in .finally.
- On
'allow'(hooks/useCanUseTool.tsx:39-54): recordssetYoloClassifierApproval(hooks/useCanUseTool.tsx:43-45,utils/classifierApprovals.ts:41-49) only underfeature('TRANSCRIPT_CLASSIFIER')forauto-modeclassifier allows, logsaccept/config, and resolves. - On
'deny'(hooks/useCanUseTool.tsx:65-92): logsreject/config, and—only underfeature('TRANSCRIPT_CLASSIFIER')forauto-modeclassifier denies (hooks/useCanUseTool.tsx:77-89)—appends to the 20-entryrecordAutoModeDenialring buffer (utils/autoModeDenials.ts:19-22) and posts an error toast. - On
'ask'(hooks/useCanUseTool.tsx:93-169), executes a four-tier waterfall:- Coordinator worker (
hooks/toolPermission/handlers/coordinatorHandler.ts:26-62): WhenawaitAutomatedChecksBeforeDialogis true, awaitsctx.runHooksthenfeature('BASH_CLASSIFIER') ? ctx.tryClassifier : nullbefore interrupting the user. - Swarm worker (
hooks/toolPermission/handlers/swarmWorkerHandler.ts:40-156): Active underisAgentSwarmsEnabled()(utils/agentSwarmsEnabled.ts:24-44:USER_TYPE === 'ant', or--agent-teams/CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS+tengu_amber_flint) andisSwarmWorker().- Tries
feature('BASH_CLASSIFIER')ctx.tryClassifier(hooks/toolPermission/handlers/swarmWorkerHandler.ts:52-57) before registeringregisterPermissionCallbackahead ofsendPermissionRequestViaMailbox(hooks/toolPermission/handlers/swarmWorkerHandler.ts:81-123) to prevent leader-reply races. (Forward seam to Chapter 19.)
- Tries
- 2-second speculative bash grace period (
hooks/useCanUseTool.tsx:126-159,feature('BASH_CLASSIFIER')): PeekspeekSpeculativeClassifierCheck(command)(tools/BashTool/bashPermissions.ts:1491-1495) against a 2,000 ms timeout; a high-confidence hit skips the modal. (Externalutils/permissions/bashClassifier.ts:1-61is a stub, though plumbing stays wired.) - Five-racer modal (
hooks/toolPermission/handlers/interactiveHandler.ts:57-531): Races local UI (200 msGRACE_PERIOD_MS,onAllowcallingpersistPermissionUpdates,recheckPermission), CCR bridge (feature('BRIDGE_MODE'),hooks/useCanUseTool.tsx:165), KAIROS MCP relay (feature('KAIROS') || feature('KAIROS_CHANNELS')), backgroundPermissionRequesthooks, and backgroundBASH_CLASSIFIER.checkmarkAbortHandler(hooks/toolPermission/handlers/interactiveHandler.ts:498-520) reconciles Chapter 06'ssiblingAbortControllerwhen a sibling aborts while the modal is open.
- Coordinator worker (
All five racers coordinate through createResolveOnce (hooks/toolPermission/PermissionContext.ts:75-94), separating synchronous ownership acquisition (claim()) from promise delivery (resolve()):
// hooks/toolPermission/PermissionContext.ts:75-94
function createResolveOnce<T>(resolve: (value: T) => void): ResolveOnce<T> {
let claimed = false
let delivered = false
return {
resolve(value: T) {
if (delivered) return
delivered = true
claimed = true
resolve(value)
},
isResolved() {
return claimed
},
claim() {
if (claimed) return false
claimed = true
return true
},
}
}
Hidden Invariants & Production Scars
- Telemetry dedup:
hooks/toolPermission/permissionLogging.ts:181-235populatestoolUseContext.toolDecisionssoservices/tools/toolExecution.ts:952-966(Chapter 06) skips duplicate OTel logging. permissionDenialsownership (interactive vs. headless/SDK):hooks/useCanUseTool.tsxis mounted exclusively in interactivescreens/REPL.tsx:2382and does not track SDKpermissionDenials; on headless/SDK paths (cli/print.ts:91,QueryEngine.ts:1249),QueryEngine.ts:244-271wrapscanUseToolinwrappedCanUseTooland pushes everyresult.behavior !== 'allow'ontothis.permissionDenials(QueryEngine.ts:631,QueryEngine.ts:863,QueryEngine.ts:1148).
Snapshot Absences & Build Gates in Chapter 11:
types/permissions.ts(441 lines) andutils/model/antModels.ts(64 lines) are present. Five type-only imports reference absenttypes/message.ts(hooks/useCanUseTool.tsx:13,hooks/toolPermission/PermissionContext.ts:16,utils/permissions/permissions.ts:14,utils/permissions/yoloClassifier.ts:20,utils/permissions/permissionExplainer.ts:4).Eight other targets are absent from this snapshot (call-site/comment evidence only): the 3
.txtprompts inutils/permissions/yolo-classifier-prompts/(utils/permissions/yoloClassifier.ts:55,utils/permissions/yoloClassifier.ts:62,utils/permissions/yoloClassifier.ts:67), comment-referencedjobs/state(utils/permissions/filesystem.ts:1511-1513), and 4 gated allowlist constants (utils/permissions/classifierDecision.ts:27-47):
TerminalCaptureTool(feature('TERMINAL_PANEL'),utils/permissions/classifierDecision.ts:27-31),OverflowTestTool(feature('OVERFLOW_TEST_TOOL'),utils/permissions/classifierDecision.ts:32-36),VerifyPlanExecutionTool(process.env.USER_TYPE === 'ant',utils/permissions/classifierDecision.ts:37-42), andWorkflowTool(feature('WORKFLOW_SCRIPTS'),utils/permissions/classifierDecision.ts:43-47).
Putting the Layer Together
runToolUse (Ch 06) -> resolveHookPermissionDecision -> canUseTool
| [PreToolUse hook allow -> checkRuleBasedPermissions (1a-1d, 1f-1g)]
v
hasPermissionsToUseToolInner (utils/permissions/permissions.ts:1158-1319)
1a Blanket deny | 1b Blanket ask (Bash sandbox bypass) | 1c checkPermissions
1d Tool deny | 1e requiresUserInteraction | 1f Content ask | 1g safetyCheck
------------------ BYPASS-IMMUNE BOUNDARY (1a..1g) --------------------------
2a Fresh getAppState(): bypassPermissions / plan+bypass -> ALLOW
2b Blanket allow (stripped on auto entry!) -> ALLOW | 3 passthrough -> ASK
|
v
hasPermissionsToUseTool outer wrapper (utils/permissions/permissions.ts:473)
- dontAsk -> DENY | auto / plan+auto -> safetyCheck | PS guard | acceptEdits
fast-path (no Agent/REPL) | allowlist | yoloClassifier (S1->S2 XML/tool)
-> tengu_iron_gate_closed (fail-closed) | denialTracking (3 consec / 20)
- shouldAvoidPermissionPrompts -> headless PermissionRequest hooks -> DENY
| (if ASK)
v
useCanUseTool.tsx 4-tier waterfall -> interactiveHandler (5 racers + claim())
-> persistPermissionUpdates (user/project/localSettings) + apply to AppState
flowchart TD
EXEC["Ch 06: runToolUse() & toolHooks.ts"]
QE["Ch 08: QueryEngine wrappedCanUseTool (permissionDenials)"]
INNER["permissions.ts: hasPermissionsToUseToolInner (1a-3)"]
TOOLS["Tool.checkPermissions(): filesystem.ts / pathValidation.ts / shellRuleMatching.ts"]
OUTER["permissions.ts: hasPermissionsToUseTool (dontAsk / auto / headless)"]
SETUP["permissionSetup.ts: strip & restore dangerous rules + transitions"]
YOLO["yoloClassifier.ts: S1->S2 XML + cachedClaudeMdContent (Ch 10)"]
DENIAL["denialTracking.ts: maxConsecutive 3 / maxTotal 20"]
HOOK["useCanUseTool.tsx: coordinator / swarm / 2s bash / interactiveHandler (claim)"]
PERSIST["PermissionUpdate.ts & permissionsLoader.ts (3 disk sources + sync)"]
EXEC -->|"checkRuleBasedPermissions() on hook allow"| INNER
EXEC -->|"interactive REPL"| HOOK
EXEC -->|"headless / SDK"| QE
HOOK --> OUTER
QE --> OUTER
OUTER --> INNER
INNER --> TOOLS
OUTER -->|"auto / plan+auto"| YOLO
YOLO --> DENIAL
DENIAL -->|"limit exceeded (interactive)"| HOOK
SETUP <-->|"strippedDangerousRules"| PERSIST
HOOK -->|"onAllow + persistPermissionUpdates()"| PERSIST
How This Snaps Into the Next Layer
Chapter 11 built the generic policy engine; Chapter 12: Shell Execution, Sandboxing, and Core Workspace Tools plugs concrete tools and OS-level isolation directly into these primitives:
- Shell permission evaluators:
tools/BashTool/bashPermissions.ts(called fromtools/BashTool/BashTool.tsx:540) consumesgetRuleByContentsForTool,createPermissionRequestMessage,parsePermissionRule, andmatchWildcardPattern.- It also owns
speculativeChecks(tools/BashTool/bashPermissions.ts:1483-1545) consumed back byhooks/useCanUseTool.tsx, and pairs withtools/BashTool/pathValidation.ts(allWorkingDirectories,validatePath,isDangerousRemovalPath).
- It also owns
- PowerShell evaluator:
tools/PowerShellTool/powershellPermissions.ts(called fromtools/PowerShellTool/PowerShellTool.tsx:376) mirrors Bash with case-insensitivematchWildcardPattern,tools/PowerShellTool/pathValidation.ts, andutils/powershell/dangerousCmdlets.ts(CROSS_PLATFORM_CODE_EXEC). - Workspace file tools (both
checkPermissions()&preparePermissionMatcher()):tools/FileReadTool/FileReadTool.ts(tools/FileReadTool/FileReadTool.ts:395-405),tools/FileEditTool/FileEditTool.ts(tools/FileEditTool/FileEditTool.ts:122-132), andtools/FileWriteTool/FileWriteTool.ts(tools/FileWriteTool/FileWriteTool.ts:132-142), plusGlobToolandGrepTool.- These five delegate
checkPermissions()tocheckReadPermissionForTool/checkWritePermissionForToolandpreparePermissionMatcher()tomatchWildcardPattern; by contrast,LSPTool(tools/LSPTool/LSPTool.ts:210-217) andNotebookEditTool(tools/NotebookEditTool/NotebookEditTool.ts:125-132) delegatecheckPermissions()only (neither implementspreparePermissionMatcher()).
- These five delegate
- OS sandbox boundary & cycle breaker (
utils/sandbox/sandbox-adapter.ts):SandboxManagerimportsgetClaudeTempDir(utils/sandbox/sandbox-adapter.ts:57) and translates Ch 11Edit/Readrules viaresolvePathPatternForSandbox(utils/sandbox/sandbox-adapter.ts:99-119, invoked across the rule-conversion loop atutils/sandbox/sandbox-adapter.ts:304-349).- It locally duplicates
permissionRuleValueFromStringandpermissionRuleExtractPrefix(utils/sandbox/sandbox-adapter.ts:61-81) to break thepermissions.ts -> SandboxManager -> bashPermissions.ts -> permissions.tscycle.
- It locally duplicates
Reading Exercises & Code Checkpoints
- Trace mode unions, all 8 rule sources, and auto-mode rule stripping:
Run
rg -n "EXTERNAL_PERMISSION_MODES|PERMISSION_RULE_SOURCES|stripDangerousPermissionsForAutoMode" types/permissions.ts utils/permissions/permissions.ts utils/permissions/permissionSetup.tsand verify whystripDangerousPermissionsForAutoModemirrorsisPermissionUpdateDestinationwhen populatingstrippedDangerousRules. - Inspect protected dotfiles, auto-edit safety, and shell wildcard compilation:
Run
rg -n "DANGEROUS_FILES|DANGEROUS_DIRECTORIES|checkPathSafetyForAutoEdit|matchWildcardPattern" utils/permissions/filesystem.ts utils/permissions/pathValidation.ts utils/permissions/shellRuleMatching.tsand trace whycheckPathSafetyForAutoEditreturnsclassifierApprovable: falseonly forhasSuspiciousWindowsPathPattern. - Verify two-stage XML prompts, fail-closed
tengu_iron_gate_closed, and denial limits: Runrg -n "DENIAL_LIMITS|shouldFallbackToPrompting|tengu_iron_gate_closed|user_allow_rules_to_replace|XML_S1_SUFFIX|XML_S2_SUFFIX" utils/permissions/yoloClassifier.ts utils/permissions/denialTracking.ts utils/permissions/permissions.tsand confirm whytranscriptTooLongbypassestengu_iron_gate_closedwhileunavailablehonors it. - Check the two-phase
claim()racer lock and the Ch 11 -> Ch 12 sandbox cycle breaker: Runrg -n 'createResolveOnce|if \(!claim\(\)\)|Local copies to avoid circular dependency' hooks/toolPermission/ utils/sandbox/sandbox-adapter.tsand trace what breaks ifonAllowchecksisResolved()without first callingclaim()synchronously beforeawait.
Manuscript chapters/11-the-permission-engine.md from AtlantisPleb/cc at 5aa286a, synced Nov 24, 2026.