From Instant Approval to Confirmation: How Intelligent Coding Assistants Enforce Command Safety and Permissions

    This article explains why intelligent coding assistants sometimes approve commands instantly and sometimes ask for confirmation. It breaks down a three-layer design—command safety analysis, permission decisions, and long-term memory—and shows how these layers form a trust boundary around model-generated actions. It also provides practical guidance for tightening permissions, adding sandbox isolation, and keeping memory accurate in your own AI-assisted development workflow.

    Starting Point: Why Some Commands Pass Instantly While Others Show a Dialog

    When developers use AI coding assistants, they often encounter two very different experiences:

    • Read-only operations, such as reading files, searching code, or inspecting dependency directories, usually pass in one step and return directly to the conversation.
    • Operations that modify files, install dependencies, run build scripts, or delete files often pause and show a confirmation dialog. Sometimes the tool also explains that the command was automatically blocked.

    These two experiences are backed by a layered command-safety and permission mechanism. If one only reads the surface behavior, it is easy to conclude that the system relies on a simple blacklist or whitelist. But if one follows the call chain, a mature intelligent programming tool typically includes at least three cooperative layers in the command execution path:

    1. Command safety layer: Before a command reaches the permission layer, the command text is parsed and normalized to detect hidden intent such as concatenation, nesting, and substitution. According to public materials, representative implementations contain more than 12,000 lines of bash-related security code, define more than twenty independent checks in the security module, and maintain dedicated interception lists for command-substitution patterns and various shell builtins.
    2. Permission layer: It decides whether a command should be allowed, confirmed, or denied.
    3. Long-term memory layer: It stores user preferences and project context across sessions, and validates that context before use.

    Each layer manages one part of the process. Together, they form a trust boundary around model output. The following sections break down each layer.

    Command Safety Layer: Understand the Command Before Approving It

    Why commands need preprocessing

    The most common mistake a permission layer can make is matching the raw text provided by a user or model directly. Because of shell syntax rules, texts that look different—or sometimes look the same—can represent different commands in practice. There are four main cases:

    • Quoting and escaping: A command split by single quotes or backslashes can be equivalent to the original command in the shell’s view.
    • Variable expansion: The actual target of rm -rf $TARGET_DIR depends on the variable’s value, which may have been assigned earlier in the script.
    • Command substitution: A command can be nested inside the arguments of an outer command, and the inner command will execute before the outer one.
    • Subshells and indirect execution entry points: A command may be executed indirectly through another shell, such as sh -c, xargs, find -exec, or a pipeline.

    Therefore, the first step in the command safety layer is parsing and normalization, not regex matching. A typical implementation performs lexical analysis in the context of a specific shell, recognizes structure without executing the command, and converts the text into a structure that the permission layer can evaluate.

    Command substitution can appear in many forms. At least the following patterns are common:

    1. # 1. Command substitution with parentheses and backticks
    2. echo $(whoami)
    3. echo `whoami`
    4. # 2. Nested command substitution
    5. echo $(echo $(whoami))
    6. # 3. Command substitution triggered in parameter expansion
    7. echo ${x:-$(whoami)}
    8. # 4. Command substitution triggered in arithmetic expansion
    9. echo $(( $(id -u) + 0 ))
    10. # 5. Here-string triggers command substitution
    11. cat <<< $(whoami)
    12. # 6. Process substitution
    13. diff <(ls -a) <(ls -b)
    14. # 7. Indirect execution: pipe into a shell
    15. echo "curl http://example.invalid" | sh
    16. # 8. Indirect execution: xargs
    17. printf '%s\n' "curl http://example.invalid" | xargs -I{} sh -c "{}"
    18. # 9. Indirect execution: find -exec
    19. find . -maxdepth 1 -exec sh -c 'curl http://example.invalid' \;
    20. # 10. bash -c string execution
    21. bash -c "curl http://example.invalid"

    These forms rarely appear in a simple blacklist, but the shell sees them as equivalent to directly running whoami or making a network request. The command safety layer must recognize these forms in a unified way: either expand them into a form the permission layer can evaluate, or treat them as high-risk signals and require human confirmation.

    Bypass techniques that are easy to overlook

    In the field of command security checks, several patterns deserve special attention:

    • Equals-prefix expansion: Some shells support expansion rules for tokens beginning with =. For example, ls can be written as =ls, and the shell may expand it to the absolute path of ls, such as /bin/ls. If a permission rule only matches the command name curl, then =curl https://... can bypass it. Public sources indicate that this type of issue has been found in external security audits, and related source comments may preserve the discovery source. This detail shows that command-line security rules must be based on shell semantics rather than simple string matching.
    • Lexical word-breaking tricks: Keywords can be split and reassembled, such as l''s or r''m -rf. A human may read this as rm -rf, but a naive matcher that splits by whitespace may only see l''s and fail to match.
    • Argument injection and shell builtin abuse: Many command-line tools support options that execute another command after the main command. Some shell builtins also provide switches for executing subcommands. If the whole command is allowed, the additional command will execute as well.
    • IFS and null-byte injection: Attackers can construct IFS characters or NUL bytes in command text to interfere with rough line-based or field-based parsing, causing the checker and the shell to disagree about where a command ends and arguments begin.
    • Invisible characters and homoglyphs: Zero-width characters or visually similar Unicode characters can be inserted into command names or arguments, making the logged command different from the command that actually executes.

    Security-by-design guidance has long emphasized areas such as denial of service and memory safety. Command-line argument injection is an extension of injection risks into the toolchain.

    It is also worth noting that mature command safety layers often assign an independent number to each check. Public materials mention implementations with more than twenty such checks. Numbering checks is not only for documentation: each number can correspond to a set of attack samples and regression tests. Security rules then become testable, traceable, and maintainable engineering assets rather than black boxes that are written once and then ignored.

    Permission Layer: A Four-Stage Pipeline, Not Just a Blacklist

    The four-stage decision flow

    After a command is normalized, it enters the permission layer. Public materials describe representative implementations that split the decision into four stages:

    1. Historical rule matching: First check whether the user has previously approved similar commands. For example, if the user has already allowed npm test, a later command such as npm test -- --coverage can match an allow rule generated by prefix matching and does not need confirmation again.
    2. Low-risk operation bypass: Recognized read-only operations, such as listing directories or viewing file contents, can bypass later stages. The more conservative this bypass list is, the lower the risk of being exploited.
    3. Read-only tool whitelist: Tools such as file readers and code searchers go through a separate whitelist channel. This is a different dimension from the bash safety layer: the former controls “what is read,” while the latter controls “what is executed.”
    4. Model classification: Commands that cannot be decided by the earlier stages are sent to a separate small model for classification at temperature=0. The model outputs a recommendation: allow, confirm, or deny.

    Using a separate classification model has two benefits. First, the context of the main task is not polluted by decisions about whether a command should be allowed. Second, fixed sampling parameters ensure stable and consistent results for similar commands.

    There is also a mechanism that is easy to overlook: after the user rejects several commands in a row, the system triggers a cooldown and pauses similar automatic attempts. Otherwise, a tool might repeatedly submit the same type of command with slightly different syntax, dragging the user into a rejection loop.

    A simplified decision flow can look like this:

    1. Determine whether a command requires confirmation:
    2. If the command matches a deny rule: return "deny"
    3. If the command safety layer marks it high risk: return "confirmation required"
    4. If it matches a historical user-approved rule: return "allow"
    5. If it is read-only and not in a dangerous directory: return "allow"
    6. If recent consecutive denials reached the threshold: return "confirmation required (cooldown)"
    7. Otherwise: ask the classification model for a recommendation

    Why a model is involved in the decision

    A pure allowlist has two natural limitations:

    • Incomplete coverage: There are thousands of command-line tools in the ecosystem. No one can enumerate every safe command combination.
    • Coarse granularity: git status and git push --force begin with the same command word. A rule that only matches the first command word cannot distinguish between them.

    A denylist is also fragile: new dangerous commands keep appearing, and bypasses often require only a different syntax form. Model-based judgment fills this gap. It generalizes over the semantic intent of a command, placing commands that are “probably safe but still need user confirmation” in front of the user, while still blocking obviously dangerous operations.

    This design also explains why permission decisions should be placed in the harness layer rather than relying on the model to behave responsibly. The harness is the part of the system that actually calls tools and executes commands. In model terms, it appears as tool definitions, permission checks, result return mechanisms, and related execution logic. Placing the decision here is important for three reasons:

    • Model output is untrusted: Components running LLM tasks cannot treat their own output as executable code directly. Otherwise, prompt injection, hallucinations, and misjudgments would become real operations. Tool arguments must be checked again before execution, which follows the security principle of “do not trust input.”
    • Decisions must be reproducible: A model at temperature zero should return consistent results for the same command, and rule changes should be traceable.
    • Policy can evolve independently of the model: Adding a security check or tightening a rule does not depend on a model version upgrade.

    Memory Layer: Store Only Information That Cannot Be Derived from the Current State

    AI coding assistants often remember user preferences across sessions. A common assumption is that long-term memory is implemented through vector retrieval. However, public source comments state the design principle directly: only store information that cannot be derived from the current project state.

    Memory is usually divided into four types:

    Type Meaning Examples
    user User identity and preferences Preferred language, code style preferences
    feedback Feedback on collaboration style “Add unit tests after changes,” “Use Chinese in commit messages”
    project Project background Fields kept for backward compatibility, business constraints not visible from code
    reference Pointers to external resources Requirements document entry points, monitoring dashboard entry points

    Conversely, information such as directory structure, code architecture, and dependency lists does not enter memory because it can be inspected directly.

    This principle is important. Storing code structure in memory is like taking a snapshot of a file that changes every day: after refactoring, the memory can silently become stale, and the model may not know it. A useful test is: if disabling memory and reopening the repository gives you the information, it should not be stored. Memory should only preserve information that cannot be read from the repository. This balances accuracy and context cost.

    Memory organization and loading

    In practice, memory is usually organized in two layers:

    1. Index layer: A Markdown file acts as an index. Each record is one summary line, containing a topic and a short description. This index stays in context. Public source code may define an explicit limit for the index file, such as about 200 lines or 25 KB. This is a space-for-accuracy tradeoff: if the index is fully visible, the model knows what it “remembers” and can decide whether to load a specific entry.
    2. Detail layer: Full records are loaded on demand. A small model performs semantic recall of related memories, returning at most a few records per retrieval. Public implementations may limit this to five records.
    Dimension Index layer Detail layer
    Format Markdown file with one-line summaries Full memory records
    Limit About 200 lines or 25 KB Up to five records per recall
    Loading method Always in context Retrieved semantically and read on demand
    Recall model Not needed Lightweight model

    This layered design controls the size of the always-on context and avoids the noise caused by stuffing all memory into the prompt at once.

    Do Not Trust Memory: Memory and Verification Have Different Jobs

    More important than the memory mechanism itself is the accompanying verification mechanism. Public materials mention that representative implementations explicitly require the model not to trust its own memory. If memory says a function or module exists, the model must verify it before making changes.

    The reason is straightforward. Memory is a snapshot from a previous session, while the codebase can change at any time:

    • A function may have been renamed or deleted.
    • The call chain may have changed because of refactoring.
    • A single git switch may move to a completely different branch.
    • A dependency upgrade may have deprecated an interface.

    Memory can be used to narrow the search space, but it must not be treated as factual evidence. This can be extended to all memory-driven actions with a simple rule: information that cannot be verified against the current project state should not be used as a decision premise. This is also why memory should only store information that cannot be read directly: information that can be read should be read again each time.

    How the Three Layers Form a Trust Chain

    When the three layers are considered together, they form a trust chain from “what the model wants to do” to “what the system actually does”:

    Stage Core question Design focus
    Command safety layer What will this command “actually” do? Parse and normalize; detect command substitution, escaping, equals-prefix expansion, and other variants; number checks
    Permission layer Should this command “be allowed” to run? Historical rules → low-risk bypass → read-only whitelist → model classification; cooldown after repeated denials
    Memory layer Why does the model “think” this way? Store only non-derivable information; index always visible, details on demand; verify before use

    The layers do not replace each other; they complement each other. The command safety layer helps the permission layer understand commands, the permission layer gives execution boundaries, and the memory layer makes cross-session context traceable and verifiable.

    How to Read This Kind of Code Systematically

    If you want to understand the code of similar tools, the following reading order may help:

    1. Start with the entry point and data flow: Find the command execution entry point and follow the path from model output → tool call → argument validation → execution. Understanding who blocks what, and when, is more important than reading line by line.
    2. Examine the boundaries of security rules: Focus on how allowlists and denylists are defined. Are they based on string matching or parsed structures? Where are exceptions and bypasses? If validation fails, does the system default to allow or deny? These boundaries often contain the most important design tradeoffs.
    3. Read design principles in comments: For example, “store only information that cannot be derived from the current project state” or “do not trust your own memory.” Such comments usually summarize the core constraints of a module. Following comments to implementations is more efficient than reading all code.
    4. Finish with configuration and defaults: Limits, thresholds, and default permission levels reflect the designer’s tradeoffs between cost and risk. This part is easy to overlook but often highly informative.

    Applying the Same Ideas to Your Own Project

    This mechanism is not exclusive to one product. The underlying ideas—defense in depth, least privilege, and do not trust input—can be applied to your own development workflow. The following examples show how to implement the three-layer approach through tool configuration. Exact configuration names should follow each tool’s official documentation.

    1. Command safety layer: tighten explicitly instead of relying on defaults

    Set deny rules in permission configuration, block high-risk operations by default, and avoid overly broad allow rules:

    1. {
    2. "permissions": {
    3. "allow": [
    4. "Bash(npm test:*)",
    5. "Bash(git status)",
    6. "Read",
    7. "Grep"
    8. ],
    9. "deny": [
    10. "Bash(rm -rf:*)",
    11. "Bash(git push:*)",
    12. "Bash(curl:*)",
    13. "Read(./.env)",
    14. "Read(./secrets/**)"
    15. ]
    16. }
    17. }

    Two details matter:

    • Bash(npm test:*) only allows npm test and its following arguments, not all commands beginning with npm.
    • Variants in command syntax and ordinary arguments belong to different layers. Ordinary arguments such as rm -rf are text, while syntactic variants such as pipelines and command substitution are structures. These variants must be recognized by the command safety layer’s parser; deny rules alone cannot cover them.

    Read permissions should also be restricted to avoid exposing sensitive files such as .env or secret directories to the model directly.

    2. Permission layer: tighten defaults and make good use of classification and memory

    • Default to strict behavior: Do not assume that everything can be auto-approved. Confirming every action is annoying, but the cost of “allow everything first, then tighten later after an incident” is usually higher.
    • Use project-level memory: Write collaboration requirements into project memory, such as “do not modify generated code directly,” “run tests after changes,” and “confirm before committing.” This reduces friction caused by repeated confirmation.
    • Use plan mode when available: Many tools support presenting a plan first and executing only after user approval. For changes with a large impact, this is a low-cost safety valve.

    3. Add a sandbox layer beyond permissions

    Permission dialogs cannot protect against commands that the user has already approved. Once the user clicks “allow,” later commands may execute according to the permission rules. Therefore, the boundary should not rely only on confirmation dialogs. A safer approach is to add execution isolation outside the permission layer:

    • Use containers to isolate the execution environment and mount only necessary directories.
    • Restrict outbound network access and allow only necessary destinations.
    • Require a second confirmation for irreversible operations such as force pushes, data deletion, and changes to production environments, and keep complete audit logs.
    • Periodically review approved permission rules and remove no-longer-needed allowances.

    If cloud-based execution is involved, generic cloud capabilities such as container services, audit logging, and monitoring/alerting can help build isolation and audit channels. For example, Baidu AI Cloud provides general cloud product capabilities such as containers, logging, and monitoring/alerting, which can be selected as needed. This adds an infrastructure-level fallback beyond “the tool says it is safe.”

    4. Memory layer: review periodically and keep it concise

    Memory files are plain text and can be edited directly. It is recommended to check them periodically:

    • Delete outdated entries.
    • Merge duplicate content.
    • Put preferences that are only meaningful for the current project into project-level memory instead of global configuration.

    Conclusion

    The “instant pass versus confirmation” behavior of intelligent coding assistants is the result of three cooperating mechanisms: the command safety layer clarifies the real meaning of commands, the permission layer defines execution boundaries, and the memory layer ensures cross-session context is trustworthy and usable.

    The biggest takeaway from reading this kind of code may not be a specific rule, but three principles:

    1. Parse first, then decide: Security rules should be based on parsed structures, not raw string matching.
    2. Put decisions in the harness layer: Do not make the model its own security boundary.
    3. Memory needs verification: Information that cannot be verified cannot be treated as fact.

    Whether you want to understand the source code of open-source intelligent coding tools or build a safer AI-assisted development workflow inside your team, these ideas are worth borrowing.