AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Configuring Terminal Auto-Run Approvals and Sandboxing in Cursor Agent Mode for Autonomous Test-and-Fix Loops

Serene Tay · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Software engineering workflows with AI agents have shifted from passive code autocompletion to autonomous execution loops: edit code, execute test suites, analyze compiler or runtime diagnostics, apply patches, and re-verify until tests pass green. In Cursor Agent mode, this capability unlocks dramatic productivity gains by offloading repetitive test-and-fix cycles to the AI model.

However, autonomous execution introduces a severe operational dilemma. If developers configure the terminal to prompt for every single command execution ("Ask Every Time"), the constant barrage of approval dialogs destroys developer flow and renders autonomous iteration impossible. Conversely, if developers select unconstrained execution ("Run Everything"), a hallucinated shell command or an unvetted script can overwrite local configurations, delete repositories, or expose local environment secrets.

At 365Finds, our institutional position is unequivocal: running autonomous test-and-fix loops under "Run Everything" on local developer machines is an unacceptable operational risk. Software engineers must establish a defense-in-depth boundary. This article provides a comprehensive technical guide to configuring Cursor Agent run modes, tailoring OS-level containment through sandbox.json, steering intelligent auto-approvals via permissions.json, and enforcing session hygiene with Cursor Rules to achieve an autonomous, self-healing development workflow without compromising machine integrity.


The Autonomous Test-and-Fix Dilemma: Approval Fatigue vs. Unconstrained Execution

The core value proposition of an autonomous agent in Cursor is closed-loop problem resolution. In a typical self-healing loop:

  1. The developer instructs Cursor Agent to implement a feature or resolve a failing unit test.
  2. The Agent inspects source code, identifies discrepancies, and applies file modifications.
  3. The Agent triggers a terminal command (e.g., pytest tests/test_auth.py or npm test).
  4. The Agent parses standard error (stderr), pinpoints assertion failures, refactors the code, and re-runs the test suite until zero errors remain.
       +---------------------------------------------+
       |   Autonomous Test-and-Fix Loop in Cursor    |
       +---------------------------------------------+
                              |
                              v
                      [ Edit Source Code ]
                              |
                              v
             +--> [ Execute Test Command ]
             |                |
             |       (Fails)  v  (Passes)
             |          +-----------+
             |          |  Result?  | ----> [ Finish / Commit ]
             |          +-----------+
             |                |
      [ Refactor Code ] <-----+
             ^
             | (Analyze stderr / stack trace)
             +----------------+

When an engineer must click "Approve" for every test run, linter execution, and file inspection, human latency dominates the loop. This phenomenon, known as approval fatigue, causes developers to either abandon autonomous loops altogether or reflexively click approval buttons without inspecting the executed command string.

Worse, when developers become frustrated by repetitive dialogs and toggle on unrestricted execution, they expose their development host to catastrophic failures:

Solving this requires understanding Cursor's layered execution security architecture.


Deconstructing Cursor Agent Terminal Run Modes

Cursor provides distinct run modes that govern how shell commands and tool calls are handled by the Agent engine. Understanding these execution models is essential for constructing a calibrated automation pipeline.

Run ModeApproval MechanismExecution BoundaryAutonomy LevelPrimary Risk & Trade-off
Ask Every TimeManual approval required for every terminal invocationDirect host or sandbox depending on settingsLow; constant user intervention breaks flowExtreme approval fatigue; developers approve blind
AllowlistDeterministic prefix/regex matching against approved commandsDirect host or sandboxModerate; blocks novel commandsHigh maintenance; breakages when flags change
Auto-ReviewHybrid: Allowlist + Sandbox isolation + Classifier evaluationOS-level sandbox with fallback escalationHigh; runs safe commands seamlesslyRequires careful initial sandbox policy tuning
Run EverythingZero approvals required; all commands execute immediatelyDirect host without restrictionFull autonomy; zero human interventionExtreme security hazard; potential local data loss

1. Ask Every Time

Under this default baseline, Cursor requires explicit human interaction before running any command in the integrated terminal. While safe for exploratory prompting or single-file edits, it completely halts iterative test-and-fix workflows while the developer is context-switching or stepping away from the IDE.

2. Allowlist Mode

Allowlist mode inspects incoming command strings against predefined prefixes or explicit regex rules (e.g., allowing npm test, cargo test, git status). While deterministic, it suffers from severe brittleness. A slight modification to an argument flag (e.g., npm test -- --verbose or pytest -k "test_login") can trigger an unexpected approval prompt, pausing the loop mid-execution.

3. Auto-Review Mode (365Finds Recommended)

Auto-review represents Cursor's state-of-the-art hybrid execution engine. Rather than relying on rigid string matching or complete surrender of control, Auto-review evaluates tool calls across a structured decision tree:

  1. Allowlist Bypass: Commands explicitly whitelisted in permissions.json execute instantly.
  2. Deterministic Sandbox Isolation: Eligible commands are routed to an isolated OS sandbox container governed by sandbox.json.
  3. Model Classifier Evaluation: High-risk commands (e.g., network calls, external path writes, environment variable dumps) are routed to a specialized safety classifier (utilizing lightweight fast-inference models such as Gemini Flash or Claude Haiku) to evaluate intent.
  4. Human Escalation: Commands that violate sandbox constraints or fail classification are escalated to the developer with an explicit risk warning.

4. Run Everything

This mode completely disables all safety prompts and sandboxing gates. The Agent executes arbitrary commands directly in the host terminal context. 365Finds advises engineering teams to disable this option across corporate fleets via centralized policies.


Hardening the Execution Boundary with sandbox.json

The cornerstone of enterprise security in Cursor Agent mode is deterministic OS-level sandboxing. Rather than trusting the LLM to "behave," Cursor enforces kernel-level isolation:

Configuration Hierarchy and Merge Precedence

Cursor applies sandbox settings across four distinct tiers. In case of conflicting rules, the more restrictive policy takes precedence:

  1. Per-User Configuration: ~/.cursor/sandbox.json (developer defaults).
  2. Per-Repository Configuration: <workspace-root>/.cursor/sandbox.json (project-specific tuning).
  3. Team Administrative Policy: Enforced via Cursor Business / Enterprise dashboards.
  4. Hardcoded Engine Guardrails: Immutable system rules built into Cursor core.

Hardcoded Protected Paths

Regardless of user or workspace configuration, Cursor permanently blocks the Agent from modifying or tampering with critical security artifacts within the workspace:

Note: Cursor explicitly permits Agent writes to specific operational directories under .cursor/, including rules/, commands/, worktrees/, skills/, and agents/, allowing the Agent to update its contextual instructions without compromising infrastructure.

Production sandbox.json Specification for Autonomous Testing

To enable autonomous test loops without giving the Agent free rein over the file system and network, place the following configuration in .cursor/sandbox.json:

{
  "$schema": "https://cursor.com/schemas/sandbox.json",
  "version": 1,
  "type": "workspace_readwrite",
  "readBoundary": "workspace",
  "disableTmpWrite": false,
  "enableSharedBuildCache": true,
  "additionalReadonlyPaths": [
    "/usr/local/bin",
    "/usr/bin",
    "/bin",
    "/usr/lib",
    "/opt/homebrew/bin",
    "~/.npm",
    "~/.cargo/bin",
    "~/.rustup",
    "~/.pyenv/shims"
  ],
  "additionalReadwritePaths": [
    "/tmp/test-runner-cache",
    ".pytest_cache",
    ".cache"
  ],
  "networkPolicy": {
    "default": "deny",
    "allow": [
      "127.0.0.1",
      "localhost",
      "::1",
      "registry.npmjs.org",
      "pypi.org",
      "files.pythonhosted.org"
    ],
    "deny": [
      "169.254.169.254",
      "metadata.google.internal",
      "*.internal.corp"
    ]
  }
}

Critical Sandbox Parameters Explained


Directing Auto-Review with permissions.json

While sandbox.json enforces physical OS barriers, permissions.json configures Cursor's intelligent Auto-review classifier. This configuration instructs the decision engine on which categories of shell commands can proceed autonomously and which must halt for human review.

Create .cursor/permissions.json at the root of your workspace:

{
  "$schema": "https://cursor.com/schemas/permissions.json",
  "version": 1,
  "autoRun": {
    "allow_instructions": [
      "Allow running unit and integration test runners (e.g., pytest, vitest, npm test, cargo test, go test).",
      "Allow linters and formatters (e.g., eslint, prettier, ruff, black, cargo clippy).",
      "Allow inspect commands that read repo metadata (e.g., git status, git diff, git branch).",
      "Allow compiling and building binaries within the project directory (e.g., tsc --noEmit, cargo check)."
    ],
    "block_instructions": [
      "Block any command that invokes git commit, git push, or git reset --hard.",
      "Block commands attempting to install global packages or modify global system directories (e.g., npm install -g, sudo, chown).",
      "Block destructive file system operations across parent directories (e.g., rm -rf ../, rm -rf /).",
      "Block shell commands executing curl, wget, nc, or bash piping from external URLs."
    ],
    "commandAllowlist": [
      "^npm (test|run test(:[a-z0-9_-]+)?|run lint|run check)$",
      "^vitest (run|--run)( .*)?$",
      "^pytest( .*)?$",
      "^cargo (test|check|clippy)( .*)?$",
      "^go test( .*)?$",
      "^git (status|diff|log( -[0-9]+)?)$"
    ]
  }
}

The Synergy Between permissions.json and sandbox.json

permissions.json and sandbox.json form a complementary security pair:

  1. When the Agent attempts to run vitest run src/auth.test.ts, the command matches commandAllowlist.
  2. The Auto-review engine approves execution without bothering the developer.
  3. The command is launched inside the OS sandbox defined by sandbox.json, ensuring that even if the test suite executes an unvetted third-party dependency, the process cannot access ~/.ssh or probe external network endpoints.
  4. If the Agent attempts to run git push origin main, the block_instructions catch the intent and trigger an immediate human approval modal.

Preventing Terminal Session Zombies and Port Collisions via Cursor Rules

One of the most persistent failure modes in autonomous test-and-fix loops is terminal session proliferation. When left unguided, Cursor Agent often creates a new integrated terminal tab for each command execution.

In full-stack projects, this leads to devastating developer experience bugs:

Structuring .cursor/rules/terminal-workflow.mdc

To eliminate this problem, engineers should define strict terminal execution protocols using Cursor Rules. Place the following rule file in .cursor/rules/terminal-workflow.mdc:

---
description: Terminal execution and test-and-fix loop hygiene
globs: **/*
alwaysApply: true
---

# Autonomous Terminal & Test Workflow Rules

When executing terminal commands for testing, linting, and building, adhere strictly to the following protocols:

## 1. Terminal Session Reuse
* DO NOT spawn a new terminal tab if an existing terminal session is available.
* Reuse the active terminal session to preserve environment variables, virtualenv activation, and working directory state.
* If a background dev server is required, check if the designated port is already listening before executing the start command.

## 2. Test Execution Granularity
* In test-and-fix loops, NEVER execute the entire monorepo or project test suite after a minor single-file edit.
* Always isolate execution to the specific test file or test case related to the modified source code:
  * For Jest/Vitest: `npm test -- path/to/file.test.ts`
  * For Pytest: `pytest tests/unit/test_module.py::test_case_name`
  * For Go: `go test -run TestName ./pkg/...`
  * For Rust: `cargo test test_function_name`
* Only run the full test suite when explicitly commanded by the user or as a final validation step before completing the task.

## 3. Exit Code and Diagnostic Verification
* Always inspect standard error (`stderr`) and the exit code (`$?`) of the test runner.
* If a test fails:
  1. Read the failure stack trace thoroughly.
  2. Locate the exact assertion mismatch.
  3. Formulate a minimal, surgical code modification.
  4. Re-run the targeted test.
* Max Iteration Circuit Breaker: If the same test fails three (3) consecutive times with differing patches, PAUSE execution, summarize the root cause to the user, and request guidance. Do not enter an infinite modification loop.

## 4. Forbidden Shell Patterns
* Do not pipe shell commands into `sh` or `bash` (e.g., `curl ... | bash`).
* Do not run commands using `sudo`.
* Do not execute recursive deletions (`rm -rf`) targeting dynamic paths without explicit path validation.

By enforcing this rule, Cursor Agent acts as an experienced engineer: it reuses terminal tabs, targets only relevant unit tests during the iterative loop, avoids blocking ports, and respects a circuit breaker to prevent token-wasting infinite loops.


End-to-End Enterprise Recipe: The Autonomous Self-Healing Pipeline

To visualize how these systems interact in a production workflow, review the operational lifecycle of a properly configured autonomous test-and-fix session:

[ Developer Prompt ]
"Fix the JWT token expiry bug in src/auth/token.ts and ensure all auth unit tests pass."
        |
        v
[ Cursor Agent ]
Parses workspace, edits src/auth/token.ts
        |
        v
[ Terminal Invocation Plan ]
Agent proposes: "npm test -- tests/auth.test.ts"
        |
        v
[ Execution Engine: permissions.json & Auto-Review ]
Matched against 'commandAllowlist' -> Classified as SAFE -> Auto-Approved (No modal prompt)
        |
        v
[ Kernel Sandbox: sandbox.json ]
Command executed within OS sandbox:
  - Filesystem read restricted to workspace
  - Outbound external network blocked
  - Build cache shared
        |
        v
[ Test Runner Output ]
Tests FAIL (AssertionError: Expected 3600, got 1800)
Exit code: 1 -> Captured by Agent
        |
        v
[ Agent Iteration Loop ]
Agent reads stack trace -> Identifies calculation logic -> Patches src/auth/token.ts
        |
        v
[ Targeted Re-run in Active Terminal ]
Reuses active session -> Runs "npm test -- tests/auth.test.ts" in sandbox
        |
        v
[ Test Runner Output ]
Tests PASS (All 12 assertions green)
Exit code: 0
        |
        v
[ Final Validation ]
Agent runs "git diff" to verify patch cleanliness -> Reports completion to Developer

Throughout this entire session:

  1. Flow was unbroken: The developer did not have to click a single confirmation button.
  2. Machine was protected: Had the model hallucinated a destructive command or attempted an unauthorized network fetch, the sandbox and Auto-review barriers would have intercepted it immediately.
  3. Resources were conserved: The Agent did not flood the workstation with zombie processes or orphan dev servers.

365Finds Institutional Judgment and Recommendations

After evaluating developer productivity metrics and enterprise infrastructure threat surfaces, 365Finds delivers the following firm recommendations:

  1. Reject "Run Everything" on Developer Workstations: While "Run Everything" feels frictionless in short demonstrations, its deployment on machines containing local production credentials, personal SSH keys, or corporate VPN access is an untenable security violation.
  2. Mandate Dual-Layer Security: Never rely solely on model-based prompt classifiers or purely on static regex allowlists. The gold standard is combining Auto-Review mode (classifier steering via permissions.json) with Kernel Sandboxing (sandbox.json). The model evaluates intent; the kernel enforces physical boundaries.
  3. Enforce readBoundary: "workspace": The greatest exfiltration risk in agentic coding is not the agent downloading malware, but reading sensitive host files (~/.ssh, ~/.aws, ~/.zshrc) and including them in context windows or build logs. Isolating the read boundary to the project root eliminates this vector entirely.
  4. Deploy Terminal Rules as Code: Include .cursor/rules/terminal-workflow.mdc in your team's Git repositories. Standardizing terminal session reuse and targeted test execution cuts token consumption in half and prevents multi-process port collisions across developer machines.

References