As agentic developer tools transition from localized IDE assistance to fully autonomous CLI execution, managing the friction of human-in-the-loop permission approvals becomes a foundational architectural concern. Anthropic’s Claude Code CLI uses interactive authorization prompts for file edits, system command execution, and network access. To achieve high developer velocity and unlock headless automation in CI/CD pipelines, engineers rely on persistent permission states—commonly managed via the "Don't Ask Again" pattern and persistent project configuration rules.
Deploying this capability safely at scale requires balancing developer productivity against critical security risks, including prompt injection, arbitrary command execution, and untrusted file mutation. This guide covers the internal mechanics of Claude Code permission persistence, architectural blueprints for headless sandboxing, distributed policy engines, and production strategies for enterprise-grade deployment.
The Architectural Challenge: Autonomous Execution vs. Security Scoping
Claude Code acts as a tool-calling loop over standard input/output channels. Every operation—whether running git diff, executing npm test, or overwriting src/server.ts—maps to a discrete tool invocation (Bash, FileEdit, FileRead, GlobTool).
┌─────────────────┐ ┌──────────────────────┐ ┌────────────────────────┐
│ │ │ Permission Engine │ │ Execution Subsystem │
│ Claude Code │──────>│ (Policy Evaluation) │──────>│ (OS Shell / Storage) │
│ Agent Engine │ └──────────────────────┘ └────────────────────────┘
└─────────────────┘ │
▼
┌────────────────────────┐
│ Persistent Policy Store│
│ (.claude.json / DB) │
└────────────────────────┘
In standard interactive mode, Claude Code halts execution and prompts the user for confirmation when a tool poses side effects (e.g., executing arbitrary bash scripts). Selecting "Don't Ask Again" serializes that authorization grant into a local, project-scoped memory state or configuration manifest.
When scaling this behavior across engineering organizations, three architectural failure modes emerge:
- Over-Granting Wildcards: Developer approval of a broad command pattern (e.g.,
bash: *) exposes the environment to prompt injection vectors embedded in dynamic third-party code or git pull requests. - State Drift and Privilege Creep: Stale local permission files (
.claude.json) accumulate unmonitored execution rights over time, bypassing compliance auditing. - Headless Execution Failures: Running agents inside non-interactive CI/CD containers without pre-configured, granular permission state causes deadlocks, hung builds, or abrupt runtime terminations.
Anatomy of the Permission & State Persistence Engine
Claude Code evaluates permissions deterministically across four distinct scope layers:
- Global Deny List: Hardware/OS-level blocks, explicit administrative prohibitions, and restricted file paths (e.g.,
/etc/passwd,.env). - Session Grants ("Don't Ask Again"): Ephemeral runtime permissions stored in-memory during an active CLI process.
- Project Scoped Grants (
.claude.json): Persisted JSON objects mapping tools and allowed arguments/patterns within a given root repository. - Interactive Prompt Fallback: Default blocking state triggered when no matching rule is resolved.
Deterministic Rule Evaluation Hierarchy
When an agent requests execution of tool $T$ with parameter payload $P$, the permission evaluation engine follows this resolution flow:
$$\text{Decision}(T, P) = \begin{cases} \text{DENY} & \text{if } (T, P) \in \text{DenyRules} \ \text{ALLOW} & \text{if } (T, P) \in \text{ExplicitAllowRules} \ \text{ALLOW} & \text{if } (T, P) \in \text{SessionCache ("Don't Ask Again")} \ \text{PROMPT} & \text{otherwise} \end{cases}$$
Configuration Anatomy
Local project persistence structures use exact pattern matching and path globbing to authorize execution. A canonical .claude.json policy manifest looks like this:
{
"allowedTools": [
"FileRead",
"GlobTool",
"GrepTool"
],
"allowedCommands": [
"git status",
"git log *",
"npm test",
"tsc --noEmit"
],
"deniedCommands": [
"rm -rf *",
"curl * | bash",
"sudo *"
],
"trustedPaths": [
"src/**",
"tests/**"
]
}
Implementing a Production-Grade Policy Interceptor Engine
To run Claude Code scalably in multi-tenant or enterprise environments, local JSON files are insufficient. We must enforce dynamic policy evaluation via a centralized, cryptographically verified proxy server before permitting "Don't Ask Again" auto-approvals.
The TypeScript implementation below provides a zero-trust, pattern-matching policy engine that intercepts Claude Code tool calls, validates token lifetimes, checks path boundaries, and logs audit events.
import { createHash, timingSafeEqual } from "crypto";
import * as path from "path";
export interface ToolInvocation {
toolName: string;
command?: string;
filePath?: string;
sessionId: string;
signature: string;
}
export interface PolicyRule {
id: string;
toolPattern: string;
argumentRegex: RegExp;
maxScopePath?: string;
ttlSeconds: number;
createdAt: number;
}
export class PolicyEngine {
private allowedPolicies: Map<string, PolicyRule> = new Map();
private secretKey: string;
constructor(secretKey: string) {
this.secretKey = secretKey;
}
/**
* Register a dynamic "Don't Ask Again" approval rule with strict TTL and scope bounds.
*/
public registerAutoApproval(rule: Omit<PolicyRule, "createdAt">): void {
const fullRule: PolicyRule = {
...rule,
createdAt: Math.floor(Date.now() / 1000),
};
this.allowedPolicies.set(rule.id, fullRule);
}
/**
* Evaluates whether an incoming Claude Code tool execution is auto-approved.
*/
public evaluatePermission(invocation: ToolInvocation): {
approved: boolean;
reason: string;
} {
// 1. Verify Cryptographic Session Signature
if (!this.verifySignature(invocation)) {
return { approved: false, reason: "INVALID_SESSION_SIGNATURE" };
}
// 2. Iterate through policies matching the tool
for (const [id, rule] of this.allowedPolicies.entries()) {
// Check TTL Expiration
const currentTime = Math.floor(Date.now() / 1000);
if (currentTime - rule.createdAt > rule.ttlSeconds) {
this.allowedPolicies.delete(id);
continue;
}
if (rule.toolPattern === invocation.toolName || rule.toolPattern === "*") {
const payloadToTest = invocation.command || invocation.filePath || "";
if (rule.argumentRegex.test(payloadToTest)) {
// Verify Path Traversal Boundary if filePath is present
if (invocation.filePath && rule.maxScopePath) {
const normalizedTarget = path.resolve(invocation.filePath);
const normalizedBoundary = path.resolve(rule.maxScopePath);
if (!normalizedTarget.startsWith(normalizedBoundary)) {
return {
approved: false,
reason: `PATH_OUT_OF_BOUNDS: ${invocation.filePath} violates boundary ${rule.maxScopePath}`,
};
}
}
return {
approved: true,
reason: `AUTO_APPROVED_BY_POLICY: ${rule.id}`,
};
}
}
}
return {
approved: false,
reason: "NO_MATCHING_POLICY_REQUIRES_INTERACTIVE_PROMPT",
};
}
private verifySignature(invocation: ToolInvocation): boolean {
const payload = `${invocation.sessionId}:${invocation.toolName}:${invocation.command || invocation.filePath}`;
const expectedHmac = createHash("sha256")
.update(payload + this.secretKey)
.digest("hex");
const tokenBuffer = Buffer.from(invocation.signature, "hex");
const expectedBuffer = Buffer.from(expectedHmac, "hex");
if (tokenBuffer.length !== expectedBuffer.length) {
return false;
}
return timingSafeEqual(tokenBuffer, expectedBuffer);
}
}
Hardening Headless Executions in CI/CD and Remote Environments
Running Claude Code unattended inside CI/CD runners (GitHub Actions, GitLab CI) or remote containers requires explicitly injecting policy contexts while locking down system isolation boundaries. You must never run --dangerously-skip-permissions directly on host machines or shared virtual nodes without sandboxing.
Secure Containerization Strategy
To safely scale unattended executions with pre-granted "Don't Ask Again" permissions:
- Mount Read-Only Source Code: Ensure working directories isolate critical secrets from agent access.
- Enforce Non-Root Execution: Map runtime processes to low-privilege system users.
- Container-Level Seccomp and Linux Namespaces: Limit execution capabilities at the kernel level using Docker security profiles.
Here is a hardened Dockerfile designed for automated, non-interactive Claude Code execution with embedded policy seeding:
# Multi-stage secure build for Headless Claude Code Agent
FROM node:20-alpine AS builder
WORKDIR /app
RUN npm install -g @anthropic-ai/claude-code
FROM alpine:3.19
# Install minimal execution dependencies (git, nodejs)
RUN apk add --no-dependencies --no-cache \
nodejs \
git \
bash \
shadow \
&& useradd -u 10001 -m agentrunner
# Copy installed Claude Code binary from builder
COPY --from=builder /usr/local/lib/node_modules /usr/local/lib/node_modules
COPY --from=builder /usr/local/bin/claude /usr/local/bin/claude
# Create isolated app directory and policy store
WORKDIR /workspace
RUN chown -R agentrunner:agentrunner /workspace
# Switch to non-privileged user context
USER agentrunner
# Inject pre-approved granular permissions manifest
COPY --chown=agentrunner:agentrunner config/.claude.json /home/agentrunner/.claude.json
# Environment flag for non-interactive execution mode
ENV CLAUDE_CODE_NON_INTERACTIVE=true
ENV NODE_ENV=production
ENTRYPOINT ["/usr/local/bin/claude"]
CMD ["--print", "Executing pre-configured headless task..."]
Architectural Comparison of Approval Modes
Choosing the appropriate execution and authorization architecture requires weighing developer ergonomics against security isolation and operational complexity.
| Dimension | Interactive Manual Mode | Global Skip (--dangerously-skip-permissions) |
Local Stateful (.claude.json / "Don't Ask Again") |
Enterprise Proxy & Container Sandbox |
|---|---|---|---|---|
| Security Risk Profile | Low (Human in the loop) | Critical (Arbitrary code execution risk) | Moderate (Path/Command drift risk) | Low-Zero (Kernel isolation & TTL rules) |
| Developer Velocity | Low (Frequent context switches) | High (Zero friction) | High (Persistent velocity) | High (Automated friction-free execution) |
| CI/CD Pipeline Compatibility | Incompatible (Hangs on tty prompt) | Compatible (High security risk) | Compatible (Requires static seed files) | Native (Fully automated & audited) |
| Auditability | Manual terminal history | Poor (No explicit boundary logs) | Local JSON tracking | Real-time structured telemetry & SIEM |
| Blast Radius | User workstation context | System root / Container environment | Workspace sub-tree bounds | Isolated micro-sandbox / Ephemeral container |
| Maintenance Overhead | Zero | Low | Medium (Rule file maintenance) | Medium-High (Infrastructure required) |
Production Security Practices
When building systems that automate or persist agent authorization states, apply these four operational controls:
1. Ephemeral Policy Tokens with Short TTLs
Do not allow "Don't Ask Again" authorizations to persist indefinitely. Inject policies with defined expirations tied to specific task IDs, git branches, or deployment pipelines.
2. Static Command Hashing Over Regex Matchers
Regular expressions like npm test* can be bypassed using shell tricks like npm test; rm -rf /. Instead, register precise cryptographic hashes of allowed command strings in your policy backend.
3. Real-Time Telemetry and Anomaly Detection
Stream stdout/stderr and tool execution calls to an external log aggregator (e.g., Datadog, Splunk). If an auto-approved agent triggers an abnormal volume of file modifications or unexpected outbound network calls, revoke session privileges automatically via API.
How BrickTry Helps You Build and Scale This
Integrating agentic workflows like Claude Code into web platforms, custom SaaS architectures, and internal developer platforms requires specialized system engineering. BrickTry simplifies this integration through a combined AI-human platform designed to build, secure, and deploy agent pipelines reliably.
┌────────────────────────────────────────────────────────────────────────┐
│ BRICKTRY PLATFORM ENGINE │
├───────────────────────────────┬────────────────────────────────────────┤
│ In-Browser Lab Sandbox (/lab) │ Real-time Agent AST & Policy Previews │
├───────────────────────────────┼────────────────────────────────────────┤
│ Autonomous AI Dev Pairing │ Automated Schema & Boilerplate Generation│
├───────────────────────────────┼────────────────────────────────────────┤
│ Dedicated Senior Engineers │ Security Audits & Architecture Reviews │
├───────────────────────────────┼────────────────────────────────────────┤
│ 100% IP Ownership │ Clean Git Delivery (Zero Lock-In) │
└───────────────────────────────┴────────────────────────────────────────┘
- Interactive Lab Sandbox (
/lab): Prototype and test Claude Code policy interceptors, permission scopes, and multi-agent orchestrations directly inside a zero-setup, web-based container environment before pushing to production. - AI-Human Dev Pairing: Accelerate development by combining AI agents—which generate policy engine boilerplate, unit tests, and security configurations—with senior engineering oversight to verify sandboxing safety and system stability.
- Enterprise Security Audits: BrickTry platform engineers review tool-calling architectures, set up eBPF/Seccomp container boundaries, and implement production-ready SIEM telemetry.
- Complete Code Ownership: All platform architectures, custom proxy microservices, container manifests, and deployment scripts are committed directly to your private GitHub repositories with zero vendor lock-in.
Frequently Asked Questions
How do you mitigate prompt injection risks when "Don't Ask Again" permissions are active?
Prompt injection happens when untrusted input (e.g., a pulled pull request or external API response) tricks the agent into issuing malicious tool commands. When auto-approvals are enabled, mitigation requires enforcing strict command boundaries (e.g., disabling subshell execution like ; or &&), restricting file mutations to a isolated git directory using path globs, and running the agent inside an ephemeral container stripped of ambient environment secrets.
Where does Claude Code persist "Don't Ask Again" permissions, and can they be committed to version control?
By default, interactive auto-approval choices reside in local session states and the project's root .claude.json configuration file. While .claude.json can be committed to Git to standardize developer tool access across teams, you should never commit global wildcard rules or authorization states that grant unrestricted shell (bash: *) access.
How can we dynamically revoke "Don't Ask Again" permissions across headless agents in real time?
For headless CI/CD runners or distributed dev containers, use an external proxy architecture (such as the TypeScript Policy Engine above). Rather than reading standard local JSON files, the agent queries a centralized policy store prior to executing tools. If an anomaly is detected, an operator or automated security monitor revokes the active session token in the centralized store, causing all subsequent tool calls to fail closed immediately.
Build, Test, and Scale This on BrickTry
BrickTry pairs you with autonomous AI scaffolding supervised by dedicated senior full-stack software engineers in an interactive in-browser development sandbox (/lab). Test, build, and deploy production-grade software with 100% source code ownership and zero vendor lock-in.