# Cursor Mastery: Composer, Rules & Background Agents

> Ship faster in Cursor with Agent/Composer workflows, scoped .cursor/rules/ & AGENTS.md, Cloud/Background Agents, Bugbot PR reviews, MCP servers, and multi-model cost control.

- **Topic:** [AI Code Editors & IDEs](https://twelve-pages.com/topics/ai-ides)
- **Web Edition:** https://twelve-pages.com/guides/ai-ides/cursor-mastery-composer-rules-and-agents
- **Printable 12-Page PDF:** https://twelve-pages.com/guides/ai-ides/cursor-mastery-composer-rules-and-agents/Cursor_Mastery_Composer_Rules_and_Agents_Complete_How_To_Guide.pdf (980 KB)
- **Version:** v1.0 (Updated 2026-11)
- **Reading Time:** 12 minutes (12 pages)
- **Authorship:** AI-authored under human editorial direction & print QA (https://twelve-pages.com/editorial)
- **Tags:** Agent & Composer 2.5 · .cursor/rules/*.mdc · Cloud Agents & Worktrees · Bugbot PR Review · .cursor/mcp.json · Privacy & Cost Control

## Core Takeaways

- **Agent-First Execution:** Move cleanly from Tab autocomplete to Plan Mode, Composer multi-file edits, parallel Git worktrees, and async Cloud Agents.
- **Deterministic Context:** Scope .cursor/rules/*.mdc by glob, keep AGENTS.md portable across IDEs, and wire live Figma, Linear, and Supabase MCPs.
- **Enterprise Guardrails:** Enforce Privacy Mode, .cursorignore, Bugbot PR gates, sandboxed CLI allowlists, and weekly pool vs. API spend budgets.

## 1. The Cursor Autonomy Ladder: From Keystrokes to Cloud Agents

Modern Cursor (v2.x–3.x) is no longer just an autocomplete editor—it is an agent-first development environment with a dedicated Agents Window, Composer 2.5 fast reasoning, local Git worktree parallelism, remote Cloud Agents, and automated Bugbot PR reviews. Mastery means matching each task to the lowest-friction autonomy rung.

**Core Rule: Plan First, Scope Tight, Verify**

### The 5-Rung Cursor Execution Pipeline

High-velocity engineers escalate up the ladder only when scope demands it—avoiding slow agent loops for single-line edits and avoiding manual edits for multi-file refactors or repetitive bug fixes:

#### 1 Why the Agent Harness Matters

Cursor's agent harness combines three pillars: **Instructions** (`.cursor/rules/`, `AGENTS.md`), **Tools** (terminal, semantic search, browser, MCP), and **Verification** (tests, linters, Bugbot). Weak results almost always stem from missing rules or missing test loops—not a weak model.

#### 2 Local vs. Cloud Agents (2026 Shift)

Background Agents were renamed **Cloud Agents** and run in isolated remote VMs with full dev environments and multi-repo support. Keep interactive design work local (IDE + Git worktrees) and offload well-scoped bug fixes, test suites, and migrations to Cloud Agents.

#### The 80/20 Rule of Cursor Mastery

Start complex tasks in **Plan Mode** (`Shift+Tab`) so the agent clarifies edge cases and writes a markdown plan before touching code. Execute inside a **Git worktree** or **Cloud Agent**, verify with automated tests, and let **Bugbot** audit every PR before human review.

## 2. Choosing the Right Mode, Model & Late-2026 Plan

Sending every prompt to a heavy reasoning model burns budget and slows iteration. Match Cursor's seven execution surfaces to the right model tier and late-2026 billing pool.

### Cursor Execution Modes Comparison

| Mode | Trigger | Capabilities & Tools | Ideal Use Cases | Best Model |
| --- | --- | --- | --- | --- |
| **Tab** | `Tab` / `Esc` | Multi-line completion, next-edit jump, auto-imports. | Active typing & boilerplate in flow state. | Cursor Tab (fast) |
| **Inline Edit** | `Cmd+K` | Targeted diff on highlighted code or terminal prompt. | Single-function edits, regex, SQL, types. | Composer 2.5 |
| **Ask** | `Shift+Tab` | Read-only Q&A with `@Codebase`, `@Docs`, `@Git`. | Architecture discovery & call-graph tracing. | Composer 2.5 / Sonnet |
| **Plan** | `Shift+Tab` | Clarifies edge cases & writes editable plan before coding. | Multi-file features, migrations, refactors. | Frontier reasoning |
| **Agent / Composer** | `Cmd+I` | Autonomous loop: multi-file edits, terminal, browser, MCP. | End-to-end features & test-driven bug fixes. | Composer 2.5 / Router |
| **Cloud Agents** | `&` / Web / Slack | Async remote isolated VM; multi-repo builds & PRs. | Backlog tickets, parallel runs, cross-repo PRs. | Composer 2.5 / Frontier |
| **Bugbot** | Auto / `bugbot run` | Automated PR audit via `.cursor/BUGBOT.md` + Autofix. | Catching logic, race & auth bugs pre-merge. | Composer 2.5 (~90s) |

### Late-2026 Cursor Plans & Multi-Model Billing Reality (Nov 2026)

| Plan Tier | Price (Nov 2026) | Included Usage & Features | Best Fit & Cost Strategy |
| --- | --- | --- | --- |
| **Free / Plus** | $0 / $8 mo | Limited AI (Free) or shared weekly pool (Plus) for Tab & Agent. | Evaluation, hobby repos, light Tab & `Cmd+K`. |
| **Premium** | $30 / mo | Weekly pool for Cursor models (Composer 2.5), Cloud Agents & Automations. | Daily solo devs running Composer 2.5 primarily. |
| **Super / Ultra** | $100 / $200 mo | Expanded weekly pools for parallel worktrees, multi-agents & Cloud Agents. | Power users running concurrent agents & Automations. |
| **Teams / Enterprise** | $30–$200/seat • Custom | Org Privacy Mode, Team Rules/MCPs, Cursor Router, SSO/SCIM, spend caps. | Orgs requiring ZDR governance, audit logs & Bugbot. |
| **Legacy Plans** | Pro $20 • Pro+ $60 • Teams $40/$120 | Grandfathered monthly credit budgets for existing legacy subscribers only. | Benchmark weekly Composer pool before switching. |

#### Critical Late-2026 Billing Shift: Weekly Cursor Pools vs. Third-Party API Metering

On Cursor's late-2026 subscription family (sold alongside The X Subscription), paid tiers include a **weekly usage pool** for Cursor's native models (Composer 2.5 & Cursor Router), whereas third-party frontier models (**Claude, GPT, Gemini**) are billed separately at API list prices from the first request. Use **Composer 2.5** for 85% of implementation loops and reserve third-party reasoning models strictly for **Plan Mode** and hard root-cause debugging.

## 3. 7-Control HUD of the Cursor Agent Panel

Master these seven controls inside Cursor's Agents Window & Composer panel to keep context razor-sharp, run isolated worktrees safely, and roll back bad edits in one click.

Cursor 3.x — Agents Window • repo: acme-billing-api

Worktree: feat/webhooks Privacy: ZDR ON

Active Rules & Context Pills

@stripe-webhooks.mdc @src/billing/webhook.ts @Docs: Stripe v17 MCP: Linear, Supabase

Checkpoint #3 • Tests Passed (14/14) Restore

Implemented idempotent webhook handler + Vitest suite. Ran `pnpm test webhook` (sandboxed) — 0 failures.

"Add exponential backoff retry for `invoice.payment_failed` using our queue helper and verify with Vitest."

Agent Composer 2.5

& Cloud Send &crarr;

Diff Review: src/billing/webhook.ts (+24 / -6)

Keep All Reject

- await processEvent(event);

+ const seen = await redis.set(`evt:${event.id}`, '1', 'NX', 'EX', 86400);

+ if (!seen) return res.status(200).json({ deduped: true });

+ await enqueueWithBackoff(event, { maxAttempts: 5 });

Sandboxed Tool & Terminal Runner

$ pnpm vitest run src/billing/webhook.test.ts &check; allowlisted (sandbox: ON)

#### 1 Mode Switcher (Agent / Plan / Ask)

Cycle modes via `Shift+Tab`. Start complex features in **Plan** to review steps before file writes; switch to **Agent** to execute; use **Ask** for zero-risk Q&A.

#### 2 Context Pills & Active Rules Bar

Shows every attached `@File`, `@Docs`, MCP server, and auto-triggered `.mdc` rule. Remove stale pills before follow-ups to prevent context dilution.

#### 3 Model Selector & Cursor Router

Pin **Composer 2.5** for fast weekly-pool edits, **Cursor Router** for automatic task-based selection, or a frontier third-party model for tough debugging.

#### 4 Worktree & Cloud Agent Toggle

Select **Worktree** to isolate changes on a fresh branch without touching your active checkout, or prefix your prompt with `&` to offload to a remote Cloud Agent.

#### 5 Sandboxed Terminal & MCP Approvals

Auto-run read-only test/lint commands inside the OS sandbox while requiring explicit click approval for destructive shell calls or write-enabled MCP tools.

#### 6 Multi-File Diff Review Bar

Step through changes hunk-by-hunk across all edited files. Accept clean logic, reject speculative refactors, and keep PR diffs minimal.

#### 7 Checkpoints (Instant State Time-Travel)

Every Agent turn creates a snapshot before writing files. If an iteration veers off course, click **Restore Checkpoint** instead of arguing with the model for three more turns—tighten the prompt and re-run cleanly from the known-good state.

## 4. Scoped .cursor/rules/*.mdc, AGENTS.md & Context Hygiene

The biggest mistake teams make in Cursor is dumping 1,500 lines of guidelines into a single global rule. Scoped .mdc files inject only the rules relevant to the files being edited, keeping the context window crisp and adherence high.

*[Illustration: Modular layered crystalline rule cards channeling electric blue and violet light streams into a central AI coding engine prism]*

**Layered Context Architecture:** Team Rules -> Project `AGENTS.md` -> Glob-Scoped `.cursor/rules/*.mdc` -> On-demand `@Docs` & MCP tools, filtered by `.cursorignore`.

### The 4 Activation Modes of `.cursor/rules/*.mdc`

| Activation Mode | YAML Frontmatter Config | When Cursor Injects It | Best Use Case |
| --- | --- | --- | --- |
| **Always Apply** | `alwaysApply: true` | Every Agent & Inline Edit turn in the repo. | Short (<40 lines) stack invariants, package manager, error style. |
| **Apply to Specific Files** | `globs: ["src/api/**/*.ts"]` `alwaysApply: false` | Automatically when matching files are open or referenced. | API validation, React component conventions, SQL migration rules. |
| **Apply Intelligently** | `description: "Use when..."` `alwaysApply: false` | Agent decides based on task intent matching `description`. | Workflows like "writing Playwright E2E tests" or "creating PRs". |
| **Apply Manually** | No `globs`, no `description`, `alwaysApply: false` | Only when explicitly invoked via `@rule-name` in chat. | Heavy checklists, release runbooks, or security audit templates. |

#### `AGENTS.md` Standard

Cross-IDE Markdown file at repo root (or subdirectories) read by Cursor, Claude Code, and Codex. Store universal build/test commands and repo map here; put Cursor-specific globs in `.cursor/rules/`.

#### `@Docs` & `@Codebase`

Index third-party API docs once in Settings -> Indexing & Docs, then cite `@Docs` so agents stop hallucinating outdated SDK signatures. Use `@Git` to diff against `main`.

#### `.cursorignore` Shield

Uses `.gitignore` syntax to block `.env*`, keys, generated artifacts, and vendor bundles from Tab, Agent, and indexing—improving both security and retrieval signal.

#### Rule Precedence & Size Budget

Cursor merges rules in order: **Team Rules (Admin) -> Project `.cursor/rules/*.mdc` & `AGENTS.md` -> User Rules**. Keep each `.mdc` file under **80–120 lines** and link to one canonical reference file instead of pasting huge boilerplate.

## 5. Anatomy of a High-Precision .mdc Rule & Agent Prompt

Vague rules like “write clean TypeScript” waste tokens and get ignored. High-precision rules and prompts follow a five-part contract: Scope, Role, Hard Invariants, Concrete Anchor, and Verification Gate.

### Part A: Color-Coded 5-Part `.cursor/rules/api-handlers.mdc` Blueprint

1. Frontmatter Scope `---`
 description: "Enforce Zod validation, typed errors, and auth guards on Next.js API routes"
 globs: ["src/app/api/**/*.ts"] • alwaysApply: false `---`

2. Role & Boundary You are modifying production HTTP route handlers. Keep handlers thin: parse input, check session, delegate business logic to `src/services/`.

3. Hard Invariants (NEVER / ALWAYS) ALWAYS validate request bodies with `zod` before DB calls. NEVER return raw Prisma errors or stack traces. ALWAYS wrap mutations in `withAuth()` and return `{ data, error }` envelope.

4. Canonical Code Anchor Mirror the exact error mapping and status codes in `@src/app/api/invoices/route.ts` (lines 12–48). Do not invent new response helpers.

5. Verification Gate After editing any route, run `pnpm vitest run src/app/api` and `pnpm tsc --noEmit`. Fix all failures before summarizing.

### Part B: The 5-Part High-Precision Agent Prompt Formula

[1. Outcome] Add rate-limited webhook retry handling for `invoice.payment_failed`. [2. Explicit @Context] Reference `@src/billing/webhook.ts`, `@src/lib/queue.ts`, and `@Docs: Stripe v17`. [3. Constraints] Keep idempotency keys in Redis (24h TTL); do not modify DB schema or touch unrelated billing routes. [4. Plan Gate] First enter Plan Mode: list the exact files you will edit and edge cases for duplicate deliveries. Wait for approval. [5. Definition of Done] Add unit tests covering 1st success, duplicate event skip, and 5th-attempt dead-letter queue; run `pnpm test billing` until green.

#### &check; High-Signal Patterns (Do This)

- **Point to 1 real file** (`@src/services/orders.ts`) instead of writing 60 lines of abstract prose.
- **State negative constraints** ("Do NOT add new npm packages") to curb over-engineering.
- **Start fresh chats per task** (`Cmd+N`) once a feature merges so old diffs don't pollute context.
- **Include a runnable verifier** (unit test, typecheck, curl, or Playwright script) in every task.

#### &times; Context Anti-Patterns (Avoid)

- **Mega-rules (>300 lines)** set to `alwaysApply: true`—models silently drop middle instructions.
- **Pasting entire stack traces + 15 files** when only 2 files matter—hurts retrieval precision.
- **Skipping Plan Mode** on cross-cutting refactors, causing 4–5 expensive retry loops.
- **Asking "fix it"** without pasting the failing test output or expected invariant.

#### Pro Tip: Auto-Generate Rules from PR Review Feedback

Whenever a human reviewer or Bugbot catches a recurring mistake, run one Agent prompt: *"Turn this PR comment into a concise, glob-scoped `.cursor/rules/` file under 40 lines."* Your repo gets smarter every sprint.

## 6. Scaling Out: Cloud Agents, Git Worktrees & Cursor CLI

Single-threaded prompting caps your throughput at one task at a time. Combine local Git worktrees, remote Cloud Agents (formerly Background Agents), and headless Cursor CLI to run 3–6 engineering streams in parallel.

#### 1 Parallel Local Git Worktrees

Cursor creates isolated Git worktrees per Agent chat (via the Worktree picker or `/worktree`) so multiple agents edit, build, and run tests simultaneously without branch collisions.

```
<code>// .cursor/worktrees.json
{
  "setup-worktree": [
    "cp $ROOT_WORKTREE_PATH/.env.local .env.local",
    "pnpm install <span class="nowrap">--frozen-lockfile</span>"
  ]
}</code>
```

**Best-of-N pattern:** Launch 2–3 worktree agents on the same hard refactor (e.g., Composer 2.5 + Claude) and merge the cleanest diff.

#### 2 Cloud Agents (Async Remote VMs)

Each Cloud Agent boots an isolated cloud VM, clones your repo (or **multi-repo** frontend + backend + shared libs), installs dependencies, runs tests, and opens a GitHub PR—even after you close your laptop.

- **Handoff from IDE/CLI:** Prefix any prompt with `&` to push the session to a Cloud Agent.
- **Multi-surface triggers:** Launch from Cursor Web, iOS voice chat, Slack `@Cursor`, or Linear/GitHub issues.
- **Ideal tasks:** Test coverage gaps, dependency upgrades, lint/type migrations, well-specified bug tickets.

### Cursor CLI (`agent` / `cursor-agent`): Terminal & CI Automation

Cursor CLI runs the exact same agent harness, rules, and MCP config from any terminal, SSH box, or GitHub Actions runner:

| CLI Command | Behavior | Production Workflow |
| --- | --- | --- |
| `agent` / `agent "refactor auth"` | Starts interactive terminal session; `Shift+Tab` cycles Agent/Plan/Ask. | SSH remote boxes, tmux panes, fast keyboard-only coding. |
| `agent --worktree "add caching"` | Spins up an isolated Git worktree and runs setup from `worktrees.json`. | Parallel local branches without disturbing your current IDE state. |
| `agent -p "prompt" --model composer-2.5 --output-format text` | Headless non-interactive run returning clean stdout for piping. | GitHub Actions docs-sync, release notes, automated triage scripts. |
| `agent --mode=ask -p "audit diff"` | Strictly read-only exploration with zero file modification rights. | CI security checks, PR summaries, architecture Q&A bots. |
| `agent --sandbox enabled` | Restricts shell execution to workspace sandbox; `/sandbox` sets network. | Safe autonomous runs in untrusted branches or CI pipelines. |
| `agent ls` / `agent --resume="id"` | Lists or resumes prior CLI sessions; `/open` opens repo in Cursor IDE. | Start in terminal, hand off to IDE for visual diff review. |

#### Decision Rule: Local Worktree vs. Cloud Agent vs. Cursor CLI

Use **Local Worktrees** when you need rapid visual review, local Docker DBs, or browser preview. Use **Cloud Agents** when tasks take 10–45 minutes or span multiple repos asynchronously. Use **Cursor CLI (`-p`)** when triggering deterministic agent steps inside GitHub Actions or shell scripts.

## 7. Bugbot Automated PR Reviews & .cursor/mcp.json Wiring

Shipping faster with agents increases PR volume. Pair Bugbot (automated PR bug & security auditing) with Model Context Protocol (MCP) servers so Cursor reads live specs, issues, schemas, and PR checks directly.

*[Illustration: Four obsidian and glass modules connected by electric blue and violet fiber-optic conduits to a central faceted crystal prism core]*

**Live Tool Fabric:** Cursor connects to Figma, Linear, Supabase, and GitHub via `.cursor/mcp.json` (stdio & Streamable HTTP), while Bugbot guards every PR before merge.

#### B Bugbot PR Review Engine

- **Fast Composer 2.5 engine:** Reviews PRs in ~90 seconds on average, flagging logic bugs, null dereferences, race conditions, and auth flaws.
- **Separate rules file:** Bugbot reads `.cursor/BUGBOT.md` (and Automation rules)—it does *not* read `.cursor/rules/*.mdc`.
- **Manual trigger & Autofix:** Comment `cursor review` or `bugbot run` on any PR; click **Fix in Cursor** or Autofix to patch inline.
- **Noise control:** Document intentional patterns in `BUGBOT.md` so Bugbot stays high-signal and reviewers never scroll past it.

#### M `.cursor/mcp.json` Architecture

- **Project vs. Global:** Commit `.cursor/mcp.json` for team-shared tools; keep personal tokens in `~/.cursor/mcp.json` or env vars.
- **Two transports:** `stdio` (local child process via `command` + `args`) and `Streamable HTTP` / SSE (remote `url` + OAuth).
- **Team MCPs:** Enterprise/Teams admins can distribute vetted MCP servers centrally via Settings -> Tools & MCP.
- **Least privilege:** Start every new MCP server in read-only mode and require explicit tool-call approval for write mutations.

### High-Leverage MCP Stack for Engineering Teams

| MCP Server | Transport | What Cursor Agent Can Do Live | Recommended Guardrail |
| --- | --- | --- | --- |
| **Figma MCP** | Streamable HTTP | Inspect design tokens, spacing, frames, and component props directly from Figma URLs. | Read-only by default; pair with design-system `.mdc` rule. |
| **Linear MCP** | Streamable HTTP | Read issue acceptance criteria, link PR branches, update status on completion. | Allow reads automatically; require approval for status/comment writes. |
| **Supabase / Postgres** | stdio or HTTP | Inspect live dev schema, verify migrations, explain slow SQL queries. | **Never** connect production write creds; use read-only dev/staging DSN. |
| **GitHub MCP** | Streamable HTTP | Fetch PR comments, CI failure logs, issue threads, and release diffs. | Scope PAT/OAuth to repo; block force-push or merge tools in Agent. |

## 8. 5 Production Copy-Paste Rules, MCPs & Prompt Recipes

Drop these five battle-tested configurations straight into your repository to standardize Agent output, wire MCP tools cleanly, and automate PR quality gates.

| # | Recipe | Target File / Surface | Operational Impact |
| --- | --- | --- | --- |
| **1** | Scoped UI Component Rule | `.cursor/rules/ui-components.mdc` | Enforces design tokens, accessibility, and zero inline styles on React files. |
| **2** | Cross-IDE `AGENTS.md` | `/AGENTS.md` | Shared build, lint, and test contract for Cursor, CLI, and Cloud Agents. |
| **3** | Multi-Server MCP Config | `.cursor/mcp.json` | Connects Linear, Figma, and read-only Postgres via HTTP & stdio. |
| **4** | High-Signal Bugbot Spec | `.cursor/BUGBOT.md` | Focuses PR reviews on auth, N+1 queries, and idempotency; cuts noise. |
| **5** | TDD Cloud Agent Prompt | Agent / `&` Cloud Handoff | Forces failing test first, minimal fix, and green CI verification. |

Recipe 1 • .cursor/rules/ui-components.mdc

```
<code>---
description: "React UI component & Tailwind token standards"
globs: ["src/components/**/*.tsx"]
alwaysApply: false
---
- Use semantic tokens from `@src/styles/tokens.css`; never raw hex.
- Every interactive control needs keyboard focus + `aria-label`.
- Mirror `@src/components/ui/Button.tsx` for variant props.
- Verify with `pnpm typecheck && pnpm test:ui`.</code>
```

Recipe 2 • /AGENTS.md (Cross-IDE Root Contract)

```
<code># Repo Agent Contract
- Package manager: `pnpm` only (never `npm` or `yarn`).
- Commands: `pnpm dev`, `pnpm test`, `pnpm lint`, `pnpm typecheck`.
- Architecture: HTTP routes in `src/app/api/`, logic in `src/services/`.
- Before finishing: run `pnpm typecheck && pnpm test` and report output.</code>
```

Recipe 5 • TDD Cloud Agent Prompt (Prefix with &)

```
<code>& Pick up Linear issue ENG-412. First write a failing Vitest test
reproducing the expired-token refresh race in @src/auth/session.ts.
Implement the minimal lock fix without adding packages. Run
`pnpm test auth && pnpm typecheck`, then open a draft PR.</code>
```

Recipe 3 • .cursor/mcp.json (HTTP + stdio)

```
<code>{
  "mcpServers": {
    "linear": {
      "url": "https://mcp.linear.app/mcp"
    },
    "figma": {
      "url": "https://mcp.figma.com/mcp"
    },
    "postgres-dev": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "POSTGRES_URL": "${env:DEV_READONLY_DB_URL}"
      }
    }
  }
}</code>
```

Recipe 4 • .cursor/BUGBOT.md (PR Audit Rules)

```
<code># Bugbot PR Review Policy
Prioritize ONLY high-confidence bugs:
1. Missing `withAuth()` or tenantId filter on DB queries.
2. Unbounded loops, N+1 queries, or missing webhook idempotency.
3. Breaking changes to exported API response schemas.
Ignore: formatting, comment wording, and test fixture verbosity.</code>
```

## 9. Privacy Mode, Team Security Hardening & Spend Control

Enterprise adoption succeeds when security and finance teams have verifiable controls. Understand exactly what Cursor's Privacy Mode guarantees, where retention exceptions exist, and how to cap multi-model spend.

#### 1 What Privacy Mode Guarantees

- **No model training:** Prompts, diffs, and codebase snippets are never used to train Cursor or third-party foundation models.
- **Zero Data Retention (ZDR):** Cursor maintains ZDR agreements with supported Cursor-routed inference providers.
- **Org enforcement:** Teams & Enterprise admins lock Privacy Mode ON org-wide so individual seats cannot disable it.

#### ! What Privacy Mode Does NOT Do

- **Not local inference:** Prompts and relevant code context still traverse Cursor servers to model providers over TLS.
- **Cloud Agent retention:** Cloud Agent transcripts persist by default and VM snapshots expire after 30 days of inactivity.
- **Exceptions:** Non-ZDR models (opt-in) and BYOK provider keys follow the external provider's own retention terms.

### Defense-in-Depth Governance Controls

| Control Layer | Exact Configuration | Risk Mitigated |
| --- | --- | --- |
| **Secret Exclusion** | Commit `.cursorignore` blocking `.env*`, `*.pem`, `secrets/`, `terraform.tfstate`. | Prevents API keys and PII fixtures from entering Tab, Agent, or codebase embeddings. |
| **Command Sandboxing** | Enable OS sandbox (`--sandbox enabled`); allowlist only `pnpm test`, `vitest`, `tsc`, `eslint`. | Blocks runaway shell commands, accidental `rm -rf`, or unauthorized network exfiltration. |
| **MCP Approval Gates** | Restrict Team MCPs to vetted servers; require click confirmation on all write/delete tools. | Stops prompt-injection attacks via external GitHub issues or tickets from mutating prod systems. |
| **Spend & Pool Caps** | Set per-seat monthly third-party API caps; route routine loops to Cursor weekly pool (Composer 2.5). | Prevents unexpected API overages when engineers leave frontier reasoning models selected all day. |

### Multi-Model Cost Control Playbook (Cut Spend 40–65%)

#### 1. Default to Composer 2.5

Draws from your included weekly Cursor pool at 4&times; faster speed. Switch to third-party Claude/GPT/Gemini only for Plan Mode or thorny root-cause bugs.

#### 2. Reset Chats Per Task

Long 40-turn threads resend tens of thousands of stale tokens on every message. Open a new chat (`Cmd+N`) for each sub-task or PR.

#### 3. Trim Global Rules

Move framework guidelines out of `alwaysApply: true` into glob-scoped `.mdc` files so backend edits never pay for frontend prompt tokens.

#### Security Rule of Thumb for Regulated Repos (SOC 2 / HIPAA / GDPR)

Pair **Admin-Enforced Privacy Mode** + **`.cursorignore`** + **Disabled Non-ZDR Models** + **Read-Only Dev MCPs**. Review Cloud Agent transcript retention policy with Legal before enabling Cloud Agents on regulated repositories.

## 10. End-to-End Shipping Pipeline: Spec to Production

Cursor delivers compounding leverage when wired into your full delivery loop—pulling design and issue truth via MCP, executing in parallel worktrees or Cloud Agents, auditing with Bugbot, and verifying in CI.

#### 1 Phase 1: Zero-Drift Spec Ingestion

Pull Linear ticket acceptance criteria and Figma frames directly via MCP in **Plan Mode**. Have the agent map exact files, API contracts, and test cases before writing a single line of code.

#### 2 Phase 2: Parallel Multi-Stream Build

Run UI implementation in Worktree A, backend migration + tests in Worktree B, and offload E2E test authoring to a remote **Cloud Agent** (`&`). Keep each diff scoped to one reviewable PR.

#### 3 Phase 3: Automated Bugbot Gate

Open draft PRs and let **Bugbot** run first. Resolve all high-severity Bugbot findings via Autofix before pinging human teammates—cutting human review cycles in half.

#### 4 Phase 4: CI Automation & Compounding Rules

Trigger headless `agent -p` in GitHub Actions to keep OpenAPI docs and changelogs synced on merge. Feed any escaped production bugs back into `.cursor/rules/` and `BUGBOT.md`.

#### Compounding Team Velocity Metric

Track **PR Cycle Time**, **Bugbot Catch Rate**, and **First-Pass CI Green Rate** weekly. Teams that maintain crisp `.cursor/rules/` and `AGENTS.md` see agents pass CI on the first push instead of burning 4–5 review rounds.

## 11. Troubleshooting Clinic (Top 7 Fixes) & Pre-Flight Checklist

Diagnose the seven most common Cursor workflow failures in seconds, then run the 6-point pre-flight checklist before shipping any agent-authored PR.

### Top 7 Cursor Failure Modes & Fast Fixes

| Symptom | Root Cause | Fast Fix |
| --- | --- | --- |
| **1. Agent ignores project rules** | `.mdc` file is >250 lines, lacks matching `globs`, or uses vague prose without examples. | Split into <80-line glob-scoped `.mdc` files; point to 1 canonical file via `@path`; verify pill appears in HUD. |
| **2. Bugbot ignores `.cursor/rules/`** | Bugbot is a separate system that reads `.cursor/BUGBOT.md`, not IDE `.mdc` rules. | Create `.cursor/BUGBOT.md` with high-signal PR bug rules and trigger re-run via `bugbot run` comment. |
| **3. All MCP servers vanish** | A single malformed entry or bad transport field in `.cursor/mcp.json` drops the entire file. | Validate JSON syntax, isolate the failing server, and check Settings -> Tools & MCP logs for OAuth/stdio errors. |
| **4. Worktree fails to build/test** | New Git worktree lacks gitignored `.env.local` or `node_modules`. | Add `.cursor/worktrees.json` with `setup-worktree` commands copying `.env.local` and running `pnpm install`. |
| **5. Context drift & hallucinated APIs** | 40-turn mega-chat full of stale diffs, or outdated SDK knowledge in base weights. | Start a fresh chat (`Cmd+N`), attach only target files + `@Docs`, and restore Checkpoints instead of arguing. |
| **6. Unexpected API bill spike** | Third-party frontier model left selected for routine edits instead of weekly Composer pool. | Default to **Composer 2.5** / Cursor Router; reserve Claude/GPT/Gemini for Plan Mode; set org spend caps. |
| **7. Secrets appear in AI context** | `.env` or key files weren't excluded from indexing and Agent file-read tools. | Add secret globs to `.cursorignore`, rotate exposed keys, and verify `@` mentions can no longer read them. |

### 6-Point Pre-Flight Checklist Before Every Agent PR

&check;

**1. Privacy & `.cursorignore` Verified:** Privacy Mode is ON (org-locked for teams) and `.env*`, keys, and PII fixtures are blocked.

&check;

**2. Scoped Rules & `AGENTS.md` Active:** Relevant `.cursor/rules/*.mdc` pills loaded cleanly with zero bloated global mega-prompts.

&check;

**3. Plan Approved Before Edits:** Multi-file changes passed a Plan Mode review and executed in a clean branch or isolated Git worktree.

&check;

**4. Diff Reviewed Hunk-by-Hunk:** Zero unintended refactors, stray console logs, or unrequested dependency additions in the diff bar.

&check;

**5. Automated Tests & Typecheck Green:** Unit/integration tests, linter, and `tsc --noEmit` passed inside the sandboxed runner.

&check;

**6. Bugbot PR Audit Clean:** Bugbot completed its ~90s review against `.cursor/BUGBOT.md` with all high-severity findings resolved.

#### Cursor Mastery Golden Principle

Treat Cursor like a fast, literal engineering team: **give clear scoped rules, isolate work in worktrees, verify with tests, and gate every PR with Bugbot.**

Edition: Nov 2026

---

## Edition Note & Attribution

This 12-page handbook, its topic structure, and its illustrations were generated with AI under human editorial direction and print-layout QA. Verify commands, pricing tiers, and security settings against official vendor documentation before production use.

- AI & Editorial Disclosure: https://twelve-pages.com/editorial
- Terms & Licensing: https://twelve-pages.com/terms
- Privacy & Cookie Notice: https://twelve-pages.com/privacy
