AI Coding Agent Security Architecture: Containment-First vs. Analyze-First

    This article examines two dominant approaches to securing AI coding agents: containment-first architectures, which use operating-system and runtime-level isolation to prevent dangerous actions, and analyze-first architectures, which evaluate intent and risk before allowing tool execution. It covers the cascading design decisions created by each boundary choice, their attack surfaces and trade-offs, a structured comparison, recommended layered defenses for production, a selection checklist, and common mistakes.

    1. Start with where the boundary sits, not with which approach is “stronger”

    Current mainstream AI coding agents generally fall into two opposing engineering camps. Reducing the difference to “one vendor does this better than another” is an ineffective discussion, because the two routes rest on different assumptions. They are simply two different answers to the same question:

    When the model is about to execute commands, modify files, or access the network, what prevents it from crossing the boundary?

    • Containment first: Assumes the model will make mistakes and may even be deliberately misled. Instead of trying to judge whether a given command is good or bad, this approach turns the execution environment into a physical cage where harmful actions cannot be performed. It controls capabilities.
    • Analyze first: Assumes the model is not fully trustworthy, but that mistakes can be identified. It inserts a judgment step before an action takes effect, assessing intent and risk level. If the risk is high, the system stops and asks a human.

    One is a deterministic system. The other is a probabilistic system. This is not an implementation detail. It is the dividing line of the entire architecture.

    2. Why this one boundary choice triggers a chain reaction

    Once the boundary position is chosen, the next seven or eight “independent-looking” design decisions are almost automatically derived. Teams have very little freedom to choose arbitrarily.

    Decision derived from the boundary Inevitable result under containment first Inevitable result under analyze first
    Interception point At the system-call or process-start stage, in the kernel/runtime layer Before a tool call, in a pre-execution inspection layer
    Failure semantics The operation fails directly and often without a friendly message A structured reason is returned and can be explained interactively
    Cross-platform cost Each operating system requires a separate implementation of isolation primitives One judgment layer can be reused across platforms
    Source of observability Kernel audit logs and sandbox logs Structured records for each tool invocation
    Token budget allocation Spend less on tool definitions, spend more on command assembly and debugging Spend less on debugging, spend more on tool schemas and review prompts
    Multi-agent extension Each subprocess needs its own sandbox layer Centralized control through role permission sets and a scheduling layer

    Once this is clear, the selection decision changes from “comparing parameters” to “choosing a premise”.

    3. Paradigm A: Containment first — constrain what can be done with system capabilities

    Core mechanisms

    • Process-level sandboxing: The agent and all subprocesses it spawns run in a restricted environment, with privileges actively stripped away.
    • Filesystem capability control: Only the working directory is mounted as writable. Other locations are read-only or invisible. Sensitive paths such as credential directories, hook directories, and repository hooks are explicitly denied.
    • Network egress policy: External network access is denied by default. Specific addresses are allowed on demand to prevent data exfiltration and dependency poisoning.
    • System-call filtering: Limit the set of available system calls to reduce kernel attack surface.
    • Three runtime modes: read-only for analysis, review, and patch suggestions; workspace-write for normal coding work; and full access for high-risk tasks explicitly authorized by the user.

    Different operating systems provide different isolation primitives. Desktop systems may offer application-level sandboxing, Unix-like systems may offer filesystem namespaces and system-call filtering, and containerized environments may provide another form of isolation. The implementation details differ, but the semantic goal is the same: turn boundary violations into facts that the kernel rejects.

    A policy declaration is usually a versionable configuration file. The following example expresses a generic structure and does not correspond to any specific product interface:

    1. sandbox:
    2. mode: workspace-write # read-only | workspace-write | full
    3. filesystem:
    4. writable_roots: ["./src", "./tests"]
    5. readable_roots: ["." ]
    6. deny: ["~/.ssh", "~/.config/cloud", "./.git/hooks", "**/secrets/**"]
    7. network:
    8. default: deny
    9. allowlist: ["<internal-artifact-repository>:443", "<internal-model-service>:443"]
    10. process:
    11. drop_privileges: true
    12. syscall_filter: default
    13. on_violation:
    14. fail_closed: true
    15. prompt_user: false

    Advantages and costs

    The main advantage is physical immunity against whole classes of attacks. Prompt injection, encoded payloads, and novel malicious patterns that fall outside distribution ultimately have to manifest as a real system call. If the capability is restricted, even the most carefully engineered inducement has nowhere to land. The judgment is deterministic, so it can be reasoned about formally and audited simply. Once a policy takes effect, it remains effective over time.

    The costs are equally clear:

    1. Cross-platform engineering effort: Each target platform must be adapted separately, and maintaining a capability matrix is expensive.
    2. Unfriendly failures: Operations are silently denied. Users only see that a command did not execute and may misinterpret this as a model capability issue.
    3. Limited expressiveness: Legitimate scenarios that require network access, credentials, or system-level services must be opened one by one in policy. The policy set can expand rapidly.

    4. Paradigm B: Analyze first — constrain what should be done with semantic judgment

    Core mechanisms

    This route does not treat the execution environment as the only line of defense. Instead, it performs multiple layers of judgment at the action level:

    1. Role permission sets: Different task roles have different available tool sets. Write operations, delete operations, and external network access are authorized separately.
    2. Path allowlists and denylists: Paths and command prefixes that are explicitly forbidden for reading or writing are rejected immediately. The rules are explainable and deterministic.
    3. Command and action classifiers: Incoming actions are scored, producing a risk level and an explanation.
    4. Interactive approval: Medium-risk actions are handed to a human for confirmation rather than being allowed by the model itself.

    A representative judgment pipeline looks like this:

    1. def guard(action, ctx):
    2. # Layer 1: role authorization; pure set-membership check
    3. if action.tool not in ALLOWED[ctx.role]:
    4. return Deny("Tool is not in the current role's authorized set")
    5. # Layer 2: deterministic rules first; explainable and reproducible
    6. for rule in STATIC_RULES:
    7. if rule.matches(action):
    8. return Deny(rule.message)
    9. # Layer 3: semantic scoring only as a supplement, not the sole gate
    10. score, why = classifier.score(action, history=ctx.recent_calls)
    11. if score >= BLOCK:
    12. return Deny(why)
    13. if score >= REVIEW:
    14. return Ask(why) # hand it to a human, not let the model decide
    15. return Allow()

    Three attack surfaces for this route

    • Prompt injection: Instructions embedded in repository documentation, code comments, dependency descriptions, or issue content can disguise malicious intent as a routine environment check.
    • Command obfuscation: Encoded payloads, paths assembled from environment variables, nested interpreters, scripts written to disk before execution, and language runtimes used instead of a shell. The surface text may look harmless, but the actual semantics are harmful.
    • Novel attacks: Patterns outside the classifier’s training distribution. This is a structural limit of probabilistic systems: the ceiling of judgment correctness is the ceiling of the classifier. No prompt-level hardening can change this.

    Advantages and costs

    The advantages are engineering efficiency and user experience. One judgment layer can be reused across platforms. Every tool call has structured input and output records, so observability is naturally strong. When an action is denied, the system can give a human-readable reason, allowing users to learn and adjust their instructions. This approach also has much stronger expressiveness for complex scenarios such as calling internal enterprise APIs, starting containers, or invoking language services.

    The costs are that reliability depends on judgment quality, every action adds latency and model-call cost, the rule base requires long-term operation, and approval fatigue can undermine the whole defense. If approvals become too frequent, humans may degrade into mechanically clicking “approve”, and the line of defense effectively disappears.

    5. Structured comparison across key dimensions

    Dimension Containment first Analyze first
    Security boundary layer Operating-system kernel/runtime Pre-execution judgment layer before tool calls
    Resistance to bypass High due to deterministic interception Depends on analysis accuracy; a structural ceiling exists
    Coverage of novel attacks Naturally covered as long as the boundary is crossed Requires sample accumulation and continuous updates
    Cross-platform consistency Poor; implemented separately for each platform Good; unified logic across platforms
    Tool-system form Minimal: one controlled execution entry point plus patch-style file modifications Fine-grained specialized tools: read, write, search, terminal, web fetch, language service, and sub-agent scheduling
    User experience Failures are silent and require extra prompt design Interactive explanations provide a gentler learning curve
    Token cost Low because tool definitions are fewer High because tool schemas and judgment prompts consume context
    Environment dependency Depends on the user machine having the required commands and runtimes Distributed with the tools; the environment is self-contained
    Observability Relies on sandbox and kernel audit logs Relies on structured tool-call logs

    An easily overlooked implication is this: the choice between minimal and fine-grained tools is itself a security design decision. Fewer tools and more atomic actions make the object of judgment clearer. Giving the model a general-purpose execution entry point buys flexibility, but it degrades the judgment target from “structured actions” to “arbitrary text commands”, making evaluation significantly harder.

    The two routes are not mutually exclusive. Mature systems usually stack them into defense in depth:

    • Layer 1: capability constraints — whether it can happen: No matter how the model is induced, boundary-crossing operations are rejected at runtime. This is the only unavoidable layer.
    • Layer 2: intent judgment — whether it should happen or needs human confirmation: In the low-risk region, pre-screen actions and stop clearly harmful operations earlier. This reduces ineffective kernel rejections and user confusion.
    • Layer 3: data-layer guardrails: Keep secrets out of the context, desensitize logs, control external network egress, and scan outputs. Many real incidents are not caused by “corrupting a file” but by “reading credentials into the context”.
    • Dynamic downgrade: Once abnormal patterns are detected, such as repeated unauthorized attempts or unusually long encoded payloads, automatically downgrade the session to read-only mode.
    • Feedback loop: Feed intercepted samples back into the rule base and classifier training set to create an operable defensive asset.

    The hosting layer matters too. Regardless of which route is chosen, isolation and audit retention are usually implemented through general-purpose container platforms, logging services, and monitoring and alerting capabilities. For example, on Baidu AI Cloud, sandbox processes can run on standard container instances, unified log collection can retain a complete action trail, and monitoring alerts can observe trends such as unauthorized-operation rate and interception rate.

    7. Selection checklist: six questions that determine the route

    1. Does the threat model include untrusted content inside the repository, such as third-party dependencies, external contributions, or automatically generated documentation? If yes, the weight of containment-first should be significantly higher.
    2. Do you need uniform delivery across multiple desktop and server environments? If yes, the engineering cost advantage of analyze-first is obvious.
    3. Are there legitimate scenarios that must access the network or must hold credentials? If yes, containment-first needs precise policy openings, or analyze-first needs stronger data-layer guardrails.
    4. Does compliance require an auditable structured action log? Both routes can satisfy this, but analyze-first has a lower forensic cost.
    5. Is the task form interactive exploration or unattended batch execution? The latter requires much stronger determinism than the former.
    6. Does the team have the engineering capability to maintain operating-system isolation feature adaptations?

    A directional conclusion is this: for internal batch tasks, continuous integration, and unattended scenarios, make capability constraints the backbone. For interactive development and exploratory scenarios with fast-changing technology stacks, make fine-grained tools and semantic judgment the backbone. For production, both must be present at the same time.

    8. Five common mistakes

    • Treating the classifier as the boundary: It is a supplemental layer, not the final gate.
    • Treating read-only mode as the end state: Writes may be blocked, but reads can still leak information.
    • Defending only against command injection, not context injection: Most incident entry points are polluted context, not explicit commands.
    • Silent failure: If users do not understand why an action was denied, they will try to bypass the policy, making the defense ineffective.
    • Over-broad approval and approval fatigue: Expanding authorization scope while mechanically clicking “approve” is equivalent to having no approval at all.

    9. Conclusion

    The debate between containment first and analyze first is fundamentally the classic trade-off between determinism and flexibility, where both cannot be maximized at the same time. Containment first turns security into a physical fact, at the cost of engineering complexity and limited expressiveness. Analyze first turns security into an operable process, at the cost of admitting that a probabilistic gap cannot be fully closed. What truly determines the ceiling of the system is not which route was chosen, but whether the team understands which kind of threat it faces — and whether it is willing to reserve one unavoidable wall for the case where the worst outcome does happen.