cd /news/ai-agents/cursor-cloud-agents-pr-gate-12-steps… · home › topics › ai-agents › article
[ARTICLE · art-177916] src=shattered.io ↗ pub= topic=ai-agents verified=true sentiment=· neutral

Cursor Cloud Agents PR Gate: 12 Steps, 75 Min

A stdlib-only Python pull-request gate of about 180 lines plus a 48-line spend ledger can block protected paths, committed secrets, deleted or skipped tests and oversized changes in Cursor Cloud Agents pull requests, running as a required GitHub check and passing 14 tests on Python 3.12.3, according to Shattered. The guide argues review is now the bottleneck for unattended agents, citing the 2025 Stack Overflow Developer Survey finding that 84% of developers use or plan to use AI tools and that 52% agree AI tools or agents have had a positive effect on productivity. Cursor's Cloud Agents clone repositories from GitHub, GitLab, Azure DevOps Services or Bitbucket Cloud, work on a separate branch in a cloud environment and push changes back for review, and the article notes the product's background agents have been renamed Cloud Agents as of November 28, 2026.

recommendation

Run a required GitHub check on every agent pull request that blocks protected paths, committed secrets, deleted or skipped tests and oversized diffs before a human reviews it.

more in playbook: Securing agents and AI tools
by read42 min views1 publishedNov 28, 2026
Cursor Cloud Agents PR Gate: 12 Steps, 75 Min
Image: Shattered (auto-discovered)

Cursor Cloud Agents open pull requests while your laptop sleeps, and that moves the hard part of the job from writing code to deciding whether to merge it. A first agent run takes minutes to set up. A review process you can trust takes longer, and most teams skip it until an agent touches a workflow file or commits a key.

Adoption keeps climbing, which makes the gap more expensive every month. The 2025 Stack Overflow Developer Survey reported that “84% of developers use or plan to use AI tools in their development process.” Reviewers now face diffs they did not write, produced on a cloud machine they never watched, and a tired human skimming 400 changed lines is the weakest control in the chain.

Teams that still need to connect repositories and build environments can start with the guide to setting up Cloud Agents and their environments, then return here. The build below is a stdlib-only Python gate of about 180 lines plus a 48-line spend ledger. The gate reads the diff of any agent pull request and blocks protected paths, committed secrets, deleted or skipped tests and oversized changes. It runs as a required GitHub check and passes 14 tests on Python 3.12.3.

Don't miss new tech stories on Google

Add Shattered once in the Google app and our stories show up in your news suggestions.

Add now

Why Reviewing Agent Pull Requests Is the New Bottleneck #

A Cloud Agent works the way a contractor works. You hand over a task, it goes away to its own machine, and it comes back with a branch. According to Cursor’s Cloud Agents documentation, the agent clones your repository from GitHub, GitLab, Azure DevOps Services or Bitbucket Cloud, works on a separate branch, runs in a cloud environment and pushes changes back for review. That last phrase carries the weight. Cursor hands the decision to you.

Three failure patterns show up again and again when agents work unattended. The first is scope creep. You ask for a peek() method and get a refactor of the queue module, a new dependency and a tweak to CI. The second is quiet test weakening, where an agent that cannot make a failing test pass decides the test was wrong and deletes it or adds a skip marker. The third is credential leakage, where a hard-coded key from a pasted snippet lands in a commit. None of these need malice. They are the ordinary result of a system optimizing for a green checkmark.

Local controls help but they do not cover this case. A local Cursor hook that guards the agent runs on your machine, while a Cloud Agent runs on someone else’s. The pull request is the one place every agent output must pass through, so that is where a gate belongs. The Stack Overflow survey found that 52% of developers agree AI tools or agents have had a positive effect on their productivity, so the aim is not to slow agents down. The aim is to make the cheap, mechanical checks automatic so human attention goes to the diffs that deserve it. Cursor is one of many agentic tools in the wider coding and dev tools space, but Cloud Agents show the review problem more clearly than most.

A gate also gives you something Cursor cannot: your own policy. Cursor’s controls cover plans, models and usage. Only you know that infra/ is sacred, that .cursor/ rule files steer future runs, or that nobody should add a package without a second pair of eyes. The policy file in Step 3 encodes those decisions in 21 lines of TOML.

What Cursor Cloud Agents Look Like on November 28, 2026 #

The product has changed names and pricing in the past few months, and half the tutorials still online describe the old version. Cursor background agents, the name most older tutorials still use, are now officially called Cloud Agents. According to Cursor’s documentation, the current product names are Cloud Agents, Projects and Apps. Cursor’s Agent SDK, announced October 20, 2026, is the framework behind managed agents such as Bugbot, Security Reviewer and Rollouts.

On plans, Cursor’s pricing documentation now lists Free, Plus, Premium, Super, Ultra, Teams and Enterprise. Free and Plus do not include Cloud Agents. The same documentation lists annual billing at $80 a year for Plus, $300 for Premium, $1,000 for Super and $2,000 for Ultra, with Teams seats at $30, $100 or $200 per seat per month depending on the tier. Prices exclude tax. A thread on Cursor’s community forum about Agent SDK pricing, plan requirements and limits shows users were still hunting for exact limits, so check your own account page before you budget.

Billing for third-party models deserves a close read. Cursor’s documentation says third-party models are excluded from included usage, and on Premium and higher they can be billed at API list price from prepaid credit. On Teams and Enterprise, eligible third-party model requests also carry a Cursor Token Rate of $0.25 per million tokens on top of the model’s API price. Builds that prepare an agent’s environment are included at no additional cost.

Date Change Why it matters for review
Oct 20, 2026 Cursor announced the Agent SDK Agents can now be launched from your own code and CI
Oct 28, 2026 Dialogs explain plan, usage, model or protected-scope blocks on the page where the agent started Fewer silent failures when a run is refused
Nov 24, 2026 Background subagents keep running after the launching tool call returns One run can fan out into more commits than you expect
Nov 24, 2026 SDK 1.0.25 added token usage, billed cost and per-run breakdowns Spend can be audited per run, which Step 12 uses
Nov 28, 2026 Desktop notifications when a Cloud Agent waits for plugin consent Plugin approval is now a human checkpoint

The Nov 24 subagent change matters most for reviewers. Because subagents keep working after the call that launched them returns, a run can fan out into more commits than the prompt suggests, and a verifier subagent helps but never replaces an independent check on the final diff.

One more status note matters for anyone writing automation. Cursor says new integrations should use the current Cloud Agents API, which organizes resources around durable agents and per-prompt runs. Version v0 of that API is labeled legacy, though it stays available during a migration window, and the current API carries a Beta label. Build against the current API and expect small changes.

Prerequisites and Versions #

You need a GitHub repository where you hold admin rights, a Cursor account on a plan that includes Cloud Agents and a machine with Python and Git. Every command below ran on the versions in the table, and the stdlib-only design means there is nothing to install beyond pytest for the tests.

Tool Version used Needed for
Python 3.12.3 (3.11 or newer, for tomllib ) The gate and the ledger
Git Not listed Diff collection and the demo repository
pytest Not listed The 14 tests
GitHub CLI ( gh ) Current release Branch protection in Step 9
Node.js 22.13 or newer Only if you launch runs through the Agent SDK
Cursor plan One that includes Cloud Agents (not Free or Plus) Starting Cloud Agents

An account administrator must connect source control before anyone can start a Cloud Agent from a repository, so ask for that early if you are not the admin. You also need permission to edit branch protection on the repository. If you lack it, the gate still works as an advisory check and you can add enforcement later.

The Python environment is deliberately boring. Create a virtual environment, install pytest and nothing else.

python3 -m venv .venv
source .venv/bin/activate
python -m pip install pytest
python --version
git --version

Part 1: Connect Cursor and Create the Demo Repository #

Step 1: Confirm Your Plan and Connect Source Control

Open your Cursor account page and confirm the plan includes Cloud Agents. If you see Free or Plus, expect Cursor to refuse the run. Since the October 28 release Cursor shows a dialog on the page where you started the run that explains whether the cause is plan, usage, model or a protected scope. Upgrade or switch accounts before you continue.

Next, have an administrator connect your source control provider. The demo uses GitHub because the gate ships as a GitHub Actions workflow, but the Python code only needs Git. The same gate works for GitLab or Bitbucket pipelines, and Cursor’s documentation names all four providers listed earlier.

Pick the model for your first runs with cost in mind. Cursor’s current model documentation lists Claude Haiku 5.5, Claude Sonnet 5.5, Claude Opus 5.5 and Claude Fable 5.2 from Anthropic, along with several Gemini 4 models. For a small task like the one in Step 10, a mid-priced model is plenty. Save the expensive model for the day you point an agent at a hard migration.

Finish the step by writing down three facts you will need later: the repository name, the default branch name and the name of your admin contact. Step 10 asks you to read the branch name that an agent run produces, and Step 9 needs the repository slug.

Step 2: Create the Demo Repository and Baseline Tests

The demo project is a tiny FIFO queue called tinyqueue. Its job is to give the agent something real to change and give the gate a baseline to protect. Create the layout, then add the package.

mkdir agent-pr-gate && cd agent-pr-gate
git init -b main
mkdir -p src/tinyqueue tests gate .github/workflows
touch gate/__init__.py

Create pyproject.toml first. The pythonpath line lets pytest import both tinyqueue from src and gate from the repository root without installing anything.

[project]
name = "agent-pr-gate"
version = "0.1.0"
requires-python = ">=3.11"

[tool.pytest.ini_options]
pythonpath = ["src", "."]
testpaths = ["tests"]

Now add the queue itself and its package marker.

from collections import deque

class TinyQueue:
    def __init__(self, maxsize: int = 0) -> None:
        self._items: deque = deque()
        self.maxsize = maxsize

    def push(self, item) -> None:
        if self.maxsize and len(self._items) >= self.maxsize:
            raise OverflowError("queue is full")
        self._items.append(item)

    def pop(self):
        if not self._items:
            raise IndexError("queue is empty")
        return self._items.popleft()

    def __len__(self) -> int:
        return len(self._items)
python
from .queue import TinyQueue

__all__ = ["TinyQueue"]

Add three baseline tests so the agent has a safety net it must not remove.

import pytest

from tinyqueue import TinyQueue

def test_fifo_order():
    q = TinyQueue()
    q.push(1)
    q.push(2)
    assert q.pop() == 1
    assert q.pop() == 2

def test_pop_empty_raises():
    with pytest.raises(IndexError):
        TinyQueue().pop()

def test_maxsize_enforced():
    q = TinyQueue(maxsize=1)
    q.push("a")
    with pytest.raises(OverflowError):
        q.push("b")

Run pytest and commit the baseline. Everything on main should be green before you ask an agent to touch it.

python -m pytest -q
git add -A && git commit -m "baseline tinyqueue"
...                                                                      [100%]
3 passed in 0.01s

Part 2: Write the Policy and the Rules #

Step 3: Write the Policy File

The policy file is the contract between you and every agent that opens a pull request. Keep it in TOML so it is readable by non-programmers, and keep it small enough that a reviewer remembers it. The file below defines which branches count as agent branches, how big a change may get and which paths an agent may never edit.

[agent]
branch_prefixes = ["cursor/"]
label = "agent-authored"

[limits]
max_files = 25
max_added_lines = 600
max_deleted_lines = 400

[paths]
protected = [
  ".github/workflows/**",
  ".github/CODEOWNERS",
  "infra/**",
  "gate/**",
  "gate_policy.toml",
  ".cursor/**",
]
source = ["src/**"]
tests = ["tests/**"]
dependencies = ["pyproject.toml", "requirements*.txt", "package.json", "package-lock.json", "uv.lock"]

Two entries deserve explanation. The first is .cursor/**. Rule files and configuration under .cursor/ steer every future agent run, so an agent that edits them can change how it behaves tomorrow. If you already maintain Cursor rules migrated from Copilot instructions, treat that directory like a CI config. The second is gate/** together with gate_policy.toml. A checker that its own subject can edit is not a checker, and Step 8 adds a second layer so a pull request cannot rewrite the gate that judges it.

The branch prefix cursor/ is a placeholder. The Cursor material available as of November 28, 2026 does not document a fixed branch naming scheme, so Step 10 has you read the real name from your first run and update this value. The label setting is the fallback, because a person or an automation can add agent-authored to any pull request.

The table below summarizes every rule the engine will enforce, with the severity you get out of the box.

Rule Severity Fires when Why it exists
size block or warn More than 25 files, 600 added lines (block) or 400 deleted lines (warn) Large diffs defeat review
protected-path block Any file matches the protected list CI, infra, rules and the gate itself need human owners
secret block An added line matches an AWS key, private key, GitHub token or inline credential pattern Keys in history are expensive to revoke
deleted-test block A file under tests/ is deleted Agents sometimes remove the test they cannot pass
weakened-test block A skip, xfail or .only( marker appears in an added test line Same failure mode, quieter
dependencies warn A manifest such as pyproject.toml orpackage.json changes New packages are a supply chain decision
no-tests warn Source changed but no test file changed Untested behavior change

Step 4: Collect the Diff in Python

The first module turns a Git range into a list of file changes. It asks Git three questions about the same three-dot range, base...head, which compares the head against the merge base so unrelated commits on main do not pollute the result. One call returns the status of each file, one returns added and deleted line counts, and one returns the zero-context patch so the rules can inspect only the lines the agent added.

from __future__ import annotations

import subprocess
from dataclasses import dataclass, field

@dataclass
class FileChange:
    path: str
    status: str
    added: int = 0
    deleted: int = 0
    added_lines: list[str] = field(default_factory=list)

def run_git(*args: str, cwd: str | None = None) -> str:
    result = subprocess.run(
        ["git", "-c", "core.quotepath=off", *args],
        cwd=cwd, check=True, capture_output=True, text=True,
    )
    return result.stdout

def collect(base: str, head: str, cwd: str | None = None) -> list[FileChange]:
    span = f"{base}...{head}"
    changes: dict[str, FileChange] = {}

    for line in run_git("diff", "--no-renames", "--name-status", span, cwd=cwd).splitlines():
        status, path = line.split("\t", 1)
        changes[path] = FileChange(path=path, status=status[0])

    for line in run_git("diff", "--no-renames", "--numstat", span, cwd=cwd).splitlines():
        added, deleted, path = line.split("\t", 2)
        change = changes[path]
        change.added = 0 if added == "-" else int(added)
        change.deleted = 0 if deleted == "-" else int(deleted)

    current: FileChange | None = None
    for line in run_git("diff", "--no-renames", "-U0", span, cwd=cwd).splitlines():
        if line.startswith("+++ "):
            name = line[4:].split("\t")[0]
            current = changes.get(name[2:]) if name.startswith("b/") else None
        elif current and line.startswith("+") and not line.startswith("+++"):
            current.added_lines.append(line[1:])

    return sorted(changes.values(), key=lambda c: c.path)

Three choices here save you debugging time later. The --no-renames flag keeps every change as a plain add, modify or delete, which sidesteps the old => new syntax in numstat output. The core.quotepath=off setting stops Git from escaping non-ASCII filenames. And the binary-file check turns the - that numstat prints for binaries into zero, so an image added by an agent does not crash the parser.

Step 5: Build the Rule Engine

The rule engine is a single function, evaluate, that takes the changes and the policy and returns findings. A finding is a frozen dataclass with a rule name, a severity of block or warn, a message and an optional path. Frozen findings are safe to compare in tests and to put in sets.

from __future__ import annotations

import re
import tomllib
from dataclasses import dataclass
from fnmatch import fnmatch
from pathlib import PurePosixPath

from .diffing import FileChange

SECRET_PATTERNS = {
    "aws-access-key": re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
    "private-key": re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----"),
    "github-token": re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36,}\b"),
    "inline-credential": re.compile(
        r"(?i)\b(?:api[_-]?key|secret|token|password)\b\s*[:=]\s*['\"][^'\"\s]{16,}['\"]"
    ),
}
WEAKENING = re.compile(r"@pytest\.mark\.(?:skip|xfail)|pytest\.skip\(|\bxit\(|\.only\(")

@dataclass(frozen=True)
class Finding:
    rule: str
    severity: str
    message: str
    path: str | None = None

def load_policy(path: str) -> dict:
    with open(path, "rb") as handle:
        return tomllib.load(handle)

def matches(path: str, patterns: list[str], basename_too: bool = False) -> bool:
    name = PurePosixPath(path).name
    return any(fnmatch(path, p) or (basename_too and fnmatch(name, p)) for p in patterns)

def redact(text: str) -> str:
    return text[:4] + "..." + f"({len(text)} chars)"

def evaluate(changes: list[FileChange], policy: dict) -> list[Finding]:
    findings: list[Finding] = []
    limits, paths = policy["limits"], policy["paths"]

    total_added = sum(c.added for c in changes)
    total_deleted = sum(c.deleted for c in changes)
    if len(changes) > limits["max_files"]:
        findings.append(Finding("size", "block", f"{len(changes)} files changed, limit is {limits['max_files']}"))
    if total_added > limits["max_added_lines"]:
        findings.append(Finding("size", "block", f"{total_added} lines added, limit is {limits['max_added_lines']}"))
    if total_deleted > limits["max_deleted_lines"]:
        findings.append(Finding("size", "warn", f"{total_deleted} lines deleted, soft limit is {limits['max_deleted_lines']}"))

    touched_source = touched_tests = False
    for change in changes:
        if matches(change.path, paths["protected"]):
            findings.append(Finding("protected-path", "block", "agent edited a protected file", change.path))
        if matches(change.path, paths["dependencies"], basename_too=True):
            findings.append(Finding("dependencies", "warn", "dependency manifest changed, review new packages", change.path))
        is_test = matches(change.path, paths["tests"])
        if is_test and change.status == "D":
            findings.append(Finding("deleted-test", "block", "agent deleted a test file", change.path))
        if matches(change.path, paths["source"]) and change.status != "D":
            touched_source = True
        if is_test and change.status != "D":
            touched_tests = True
        for line in change.added_lines:
            for name, pattern in SECRET_PATTERNS.items():
                hit = pattern.search(line)
                if hit:
                    findings.append(Finding("secret", "block", f"{name} pattern matched {redact(hit.group(0))}", change.path))
            if is_test and WEAKENING.search(line):
                findings.append(Finding("weakened-test", "block", "test skip or xfail marker added", change.path))

    if touched_source and not touched_tests:
        findings.append(Finding("no-tests", "warn", "source changed but no test file changed"))
    return findings

Read the secret handling closely. The redact helper never prints a full match, only the first four characters and a length, because a gate that echoes a leaked key into a public CI log creates the very exposure it was meant to prevent. The test in Step 7 asserts that the full string never appears in a message.

Also note what the engine does not do. It does not call a model, it does not fetch anything from the network and it does not execute code from the pull request. Everything is regular expressions and glob matching over text Git already produced. That makes it fast, predictable and cheap to audit, and it means a prompt-injected agent has no way to talk the gate into approving a diff.

Part 3: Command Line, Reports and Tests #

Step 6: Add the CLI, Exit Codes and Markdown Report

The command line wrapper decides whether a pull request is an agent pull request, runs the engine and prints either a Markdown table or JSON. Exit code 1 means at least one blocking finding, which is what a CI step needs to fail the build. Warnings print but never fail.

from __future__ import annotations

import argparse
import json
import sys

from .diffing import collect
from .rules import evaluate, load_policy

def is_agent_pr(branch: str, labels: list[str], policy: dict) -> bool:
    agent = policy["agent"]
    return branch.startswith(tuple(agent["branch_prefixes"])) or agent["label"] in labels

def render_markdown(findings, changes) -> str:
    lines = ["## Agent PR gate", ""]
    lines.append(f"{len(changes)} files, +{sum(c.added for c in changes)} / -{sum(c.deleted for c in changes)} lines")
    lines.append("")
    if not findings:
        lines.append("No findings. Human review still applies.")
        return "\n".join(lines)
    lines += ["| Severity | Rule | Path | Detail |", "| --- | --- | --- | --- |"]
    for f in sorted(findings, key=lambda f: (f.severity != "block", f.rule)):
        lines.append(f"| {f.severity.upper()} | {f.rule} | {f.path or '-'} | {f.message} |")
    return "\n".join(lines)

def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(prog="gate")
    parser.add_argument("--base", required=True)
    parser.add_argument("--head", default="HEAD")
    parser.add_argument("--policy", default="gate_policy.toml")
    parser.add_argument("--branch", default="")
    parser.add_argument("--labels", default="")
    parser.add_argument("--format", choices=["md", "json"], default="md")
    parser.add_argument("--cwd", default=None)
    args = parser.parse_args(argv)

    policy = load_policy(args.policy)
    labels = [x.strip() for x in args.labels.split(",") if x.strip()]
    if not is_agent_pr(args.branch, labels, policy):
        print("Not an agent PR, gate skipped.")
        return 0

    changes = collect(args.base, args.head, cwd=args.cwd)
    findings = evaluate(changes, policy)
    if args.format == "json":
        print(json.dumps([f.__dict__ for f in findings], indent=2))
    else:
        print(render_markdown(findings, changes))
    return 1 if any(f.severity == "block" for f in findings) else 0

if __name__ == "__main__":
    sys.exit(main())

The early return for non-agent branches keeps the check quiet on human pull requests, so your team does not learn to ignore it. It also carries a risk that Pitfall 1 covers below. If an agent pushes under a branch name outside your prefix list and nobody adds the label, the gate skips it. Decide deliberately whether that tradeoff suits your team.

Try the CLI by hand before you build CI around it. Make a branch that looks like an agent run, edit a workflow file, hard-code the AWS documentation example key and add a method without a test. Running the gate against it produces this real output from the demo repository.

## Agent PR gate

3 files, +8 / -0 lines

| Severity | Rule | Path | Detail |
| --- | --- | --- | --- |
| BLOCK | protected-path | .github/workflows/deploy.yml | agent edited a protected file |
| BLOCK | secret | src/tinyqueue/settings.py | aws-access-key pattern matched AKIA...(20 chars) |
| WARN | no-tests | - | source changed but no test file changed |

The command exited with status 1. Run the same range with --branch feature/human and you get Not an agent PR, gate skipped. with status 0. The --format json flag prints the same findings as a JSON array with rule, severity, message and path keys, which is handy if you later post comments through the GitHub API.

Step 7: Test the Gate Against Synthetic Agent Diffs

A gate you have not tested is a rumor. The tests build a real Git repository in a temporary directory, create a base commit on main, switch to a cursor/task-1 branch and apply a change that mimics one agent behavior. A shared fixture does the setup.

import subprocess
from pathlib import Path

import pytest

def git(repo: Path, *args: str) -> str:
    return subprocess.run(
        ["git", *args], cwd=repo, check=True, capture_output=True, text=True
    ).stdout

@pytest.fixture
def repo(tmp_path: Path) -> Path:
    git(tmp_path, "init", "-b", "main")
    git(tmp_path, "config", "user.email", "[email protected]")
    git(tmp_path, "config", "user.name", "ci")
    (tmp_path / "src").mkdir()
    (tmp_path / "tests").mkdir()
    (tmp_path / "src" / "app.py").write_text("def add(a, b):\n    return a + b\n")
    (tmp_path / "tests" / "test_app.py").write_text("def test_add():\n    assert 1 + 1 == 2\n")
    git(tmp_path, "add", ".")
    git(tmp_path, "commit", "-m", "base")
    git(tmp_path, "checkout", "-b", "cursor/task-1")
    return tmp_path

def commit(repo: Path, files: dict[str, str | None]) -> None:
    for name, body in files.items():
        target = repo / name
        if body is None:
            target.unlink()
        else:
            target.parent.mkdir(parents=True, exist_ok=True)
            target.write_text(body)
    git(repo, "add", "-A")
    git(repo, "commit", "-m", "agent change")

Each test then commits one kind of bad behavior and asserts the matching rule fires with the right severity.

from pathlib import Path

from gate.diffing import collect
from gate.rules import evaluate, load_policy

from conftest import commit

POLICY = load_policy(str(Path(__file__).parent.parent / "gate_policy.toml"))

def rules_for(repo):
    return {f.rule: f for f in evaluate(collect("main", "HEAD", cwd=str(repo)), POLICY)}

def test_clean_change_has_no_blocks(repo):
    commit(repo, {
        "src/app.py": "def add(a, b):\n    return a + b\n\n\ndef sub(a, b):\n    return a - b\n",
        "tests/test_app.py": "def test_add():\n    assert 1 + 1 == 2\n\n\ndef test_sub():\n    assert 2 - 1 == 1\n",
    })
    assert not any(f.severity == "block" for f in rules_for(repo).values())

def test_workflow_edit_is_blocked(repo):
    commit(repo, {".github/workflows/ci.yml": "name: ci\n"})
    assert rules_for(repo)["protected-path"].severity == "block"

def test_aws_key_is_blocked_and_redacted(repo):
    commit(repo, {"src/config.py": 'KEY = "AKIAIOSFODNN7EXAMPLE"\n'})
    finding = rules_for(repo)["secret"]
    assert finding.severity == "block"
    assert "AKIAIOSFODNN7EXAMPLE" not in finding.message

def test_deleted_test_is_blocked(repo):
    commit(repo, {"tests/test_app.py": None})
    assert rules_for(repo)["deleted-test"].severity == "block"

def test_skip_marker_is_blocked(repo):
    commit(repo, {"tests/test_app.py": "import pytest\n\[email protected]\ndef test_add():\n    assert False\n"})
    assert rules_for(repo)["weakened-test"].severity == "block"

def test_source_without_tests_warns(repo):
    commit(repo, {"src/app.py": "def add(a, b):\n    return b + a\n"})
    assert rules_for(repo)["no-tests"].severity == "warn"

def test_size_limit_blocks(repo):
    commit(repo, {"src/big.py": "x = 1\n" * 700, "tests/test_big.py": "def test_x():\n    pass\n"})
    assert rules_for(repo)["size"].severity == "block"

def test_dependency_change_warns(repo):
    commit(repo, {"requirements.txt": "requests==2.32.3\n"})
    assert rules_for(repo)["dependencies"].severity == "warn"

The CLI tests cover the branching logic, including the label fallback and the exit codes.

from pathlib import Path

from gate.cli import main

from conftest import commit

POLICY = str(Path(__file__).parent.parent / "gate_policy.toml")

def test_non_agent_branch_is_skipped(repo, capsys):
    commit(repo, {".github/workflows/ci.yml": "name: ci\n"})
    code = main(["--base", "main", "--branch", "feature/human", "--policy", POLICY, "--cwd", str(repo)])
    assert code == 0
    assert "skipped" in capsys.readouterr().out

def test_agent_branch_with_block_exits_one(repo, capsys):
    commit(repo, {".github/workflows/ci.yml": "name: ci\n"})
    code = main(["--base", "main", "--branch", "cursor/task-1", "--policy", POLICY, "--cwd", str(repo)])
    assert code == 1
    assert "BLOCK" in capsys.readouterr().out

def test_label_marks_pr_as_agent(repo):
    commit(repo, {".github/workflows/ci.yml": "name: ci\n"})
    code = main(["--base", "main", "--branch", "feature/x", "--labels", "agent-authored,bug",
                 "--policy", POLICY, "--cwd", str(repo)])
    assert code == 1

Run the whole suite. Expect 14 passing tests in well under a second.

python -m pytest -v
tests/test_cli.py::test_non_agent_branch_is_skipped PASSED
tests/test_cli.py::test_agent_branch_with_block_exits_one PASSED
tests/test_cli.py::test_label_marks_pr_as_agent PASSED
tests/test_rules.py::test_clean_change_has_no_blocks PASSED
tests/test_rules.py::test_workflow_edit_is_blocked PASSED
tests/test_rules.py::test_aws_key_is_blocked_and_redacted PASSED
tests/test_rules.py::test_deleted_test_is_blocked PASSED
tests/test_rules.py::test_skip_marker_is_blocked PASSED
tests/test_rules.py::test_source_without_tests_warns PASSED
tests/test_rules.py::test_size_limit_blocks PASSED
tests/test_rules.py::test_dependency_change_warns PASSED
tests/test_tinyqueue.py::test_fifo_order PASSED
tests/test_tinyqueue.py::test_pop_empty_raises PASSED
tests/test_tinyqueue.py::test_maxsize_enforced PASSED
============================== 14 passed in 0.43s ==============================

Commit the gate and its tests to main before you go further. From here on, any change to them must arrive through a reviewed pull request, since they sit on the protected list.

Part 4: CI Wiring and Branch Protection #

Step 8: Wire the GitHub Actions Workflow Safely

The workflow has to solve two problems that bite teams in practice. The first is script injection. Branch names and labels are attacker-controlled strings, and pasting ${{ github.head_ref }} straight into a shell command lets a crafted branch name run arbitrary commands in your runner. The fix is to pass every such value through an environment variable and quote it in the script, which the file below does for the branch, the labels and both SHAs.

The second problem is self-tampering. For a pull_request event, GitHub runs the workflow from the pull request and checks out a merge of that pull request by default. An agent that edits gate/rules.py to approve everything would then run its own edited judge. The workflow below checks out the pull request into pr/ and the base commit into trusted/, then runs the gate code from trusted/ against the Git history in pr/. Your policy file is read from the base branch too, so a pull request cannot loosen its own limits.

name: agent-gate
on:
  pull_request:
    types: [opened, synchronize, reopened, labeled, unlabeled]

permissions:
  contents: read

jobs:
  gate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          path: pr
          fetch-depth: 0
      - uses: actions/checkout@v4
        with:
          path: trusted
          ref: ${{ github.event.pull_request.base.sha }}
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - name: Run agent PR gate from the base branch
        working-directory: trusted
        env:
          BASE_SHA: ${{ github.event.pull_request.base.sha }}
          HEAD_SHA: ${{ github.event.pull_request.head.sha }}
          HEAD_REF: ${{ github.head_ref }}
          PR_LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }}
        run: |
          set +e
          python -m gate.cli --cwd ../pr --base "$BASE_SHA" --head "$HEAD_SHA" \
            --branch "$HEAD_REF" --labels "$PR_LABELS" | tee gate.md
          code=${PIPESTATUS[0]}
          cat gate.md >> "$GITHUB_STEP_SUMMARY"
          exit $code

We simulated this layout locally by extracting the base commit into a trusted/ folder, then pointing the gate at a separate clone where an agent branch had edited gate/rules.py. The tampered file showed up as a protected-path block, and the run exited with status 1. If you maintain a pipeline that already runs Cursor CLI in GitHub Actions, keep the two workflows separate so the gate never depends on an agent’s output to run.

The job writes the Markdown report to $GITHUB_STEP_SUMMARY, so reviewers see the table on the run page without opening logs. The step disables errexit with set +e, captures the gate’s exit code from PIPESTATUS and exits with it only after the summary is written. Without that dance, a failing gate would stop the step before the summary got appended.

Step 9: Lock It In With CODEOWNERS and Branch Protection

A required check that nobody enforces is decoration. Two files make it real. The first is CODEOWNERS, which routes protected paths to the humans who own them. The second is a branch protection payload that requires the gate check, requires code owner review and applies to administrators too.

/.github/        @your-org/platform-team
/infra/          @your-org/platform-team
/gate/           @your-org/security-team
/gate_policy.toml @your-org/security-team
/.cursor/        @your-org/security-team

Replace the team handles with real ones. Then apply the protection payload through the GitHub CLI. The job id in the workflow, gate, is the check name that branch protection matches.

{
  "required_status_checks": { "strict": true, "contexts": ["gate"] },
  "enforce_admins": true,
  "required_pull_request_reviews": {
    "required_approving_review_count": 1,
    "require_code_owner_reviews": true,
    "dismiss_stale_reviews": true
  },
  "restrictions": null
}
gh auth login
gh api -X PUT repos/YOUR_ORG/YOUR_REPO/branches/main/protection \
  --input protection.json

Open a throwaway pull request afterward and look at the checks list. The gate check should appear as required, and the merge button should stay disabled until a code owner approves when protected files are involved. If the check name does not match, GitHub shows the requirement as “expected” forever, which is the most common reason merges hang. Pitfall 5 covers the fix.

Part 5: Run a Cloud Agent and Read the Verdict #

Step 10: Launch a Bounded Cloud Agent Task

Now give a Cursor Cloud Agent a real job. Start it from whichever Cursor surface your team uses, such as the web app or the desktop agents window, and choose the demo repository, the main branch and a model. The exact button labels change between releases, so follow the current Cloud Agents documentation for the screen you see. Cursor’s own guide describes agents that run on their own cloud machines, work on branches, test their changes and keep going while your laptop is closed.

The prompt matters more than the model. A bounded prompt names the file, the behavior, the tests and, crucially, the things the agent must leave alone. Paste this one.

In the tinyqueue repository, add a peek() method to TinyQueue in
src/tinyqueue/queue.py. It returns the next item without removing it and
raises IndexError("queue is empty") when the queue is empty.

Requirements:
- Add two tests to tests/test_tinyqueue.py: one for peek on a non-empty
  queue, one for peek on an empty queue.
- Run the full test suite and make sure it passes.
- Do not modify any file outside src/ and tests/.
- Do not add dependencies, and do not delete or skip any existing test.
- Open a pull request when you are done and describe what changed.

When the run finishes, find the pull request and read the head branch name. That string is the one to put in branch_prefixes. Teams that run several agents at once will notice the same pattern in every branch, which is exactly why a prefix rule works. If you already run parallel agents in git worktrees locally, remember that those branches come from your machine and follow your naming, not Cursor’s.

Cursor changed background subagents on November 24 so they no longer stop when the launching tool call returns, which means a single run can produce more commits than you expect. That is one more reason to gate on the final diff and not on the prompt. A verifier subagent that double-checks the work before the pull request opens is a cheap complement, never a substitute, because it shares the author’s blind spots.

Step 11: Read the Gate Output and Tune the Policy

Open the pull request and look at the gate check. A clean agent run on the prompt above should produce a short summary with no blocks.

## Agent PR gate

2 files, +17 / -0 lines

No findings. Human review still applies.

That output comes from a hand-written change that mimics a well-behaved run: the peek() method plus two tests, which brings the suite to 16 passing tests. Your numbers will differ, since the agent chooses its own test names and layout. The important property is that the gate says nothing alarming and the diff touches only src/tinyqueue/queue.py and tests/test_tinyqueue.py. A human still reads the change. The gate has simply confirmed the boring things so you can focus on whether peek() is correct.

Now break it on purpose. Re-run the same prompt with one line removed, the sentence about not touching files outside src/ and tests/, and add a second task asking the agent to “also set up a deploy workflow.” You will usually get a pull request that edits .github/workflows/, and the gate will block it with the same table you saw in Step 6. That is the whole point. The policy caught what the prompt failed to prevent.

Tune from evidence. After a week of agent pull requests, list which rules fired and which fired falsely. Raise max_added_lines if legitimate feature work trips it every time. Add paths to protected when a near miss teaches you something. Move a rule from block to warn only with a written reason, because a rule that blocks too often trains people to bypass the gate, and a bypassed gate protects nothing.

Part 6: Track What Agents Cost #

Step 12: Track Spend With a Run Ledger

Security is half the story. The other half is that Cursor Cloud Agents spend money without anyone approving each run. According to Cursor’s documentation, Cloud Agent runs use the same plan usage as the agent in the editor and CLI, billed at the selected model’s rate. With the Cursor SDK, release 1.0.25 on November 24, 2026 added cloud-agent usage reporting that returns token usage, billed cost and per-run breakdowns, and the TypeScript and Python packages (@cursor/sdk and cursor-sdk) have shared a version number since 1.0.24. The Cursor SDK tutorial for a TypeScript review agent covers the client setup. Here you only need to export the numbers into a CSV.

The ledger below reads that CSV, applies a price table you control and compares its estimate with the billed amount. When the two differ by more than 25%, it flags the run. That catches both a stale price table and a run that cost more than its token count suggests.

from __future__ import annotations

import argparse
import csv
import json
from collections import defaultdict

def estimate(row: dict, prices: dict, token_rate: float) -> float:
    p = prices[row["model"]]
    inp, cached, out = (int(row[k]) for k in ("input_tokens", "cached_input_tokens", "output_tokens"))
    base = (inp * p["input"] + cached * p["cache_read"] + out * p["output"]) / 1_000_000
    return base + (inp + cached + out) * token_rate / 1_000_000

def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(prog="ledger")
    parser.add_argument("--runs", required=True)
    parser.add_argument("--prices", required=True)
    parser.add_argument("--token-rate", type=float, default=0.0)
    parser.add_argument("--tolerance", type=float, default=0.25)
    args = parser.parse_args(argv)

    prices = json.load(open(args.prices))
    totals: dict[str, float] = defaultdict(float)
    drift = []
    with open(args.runs, newline="") as handle:
        for row in csv.DictReader(handle):
            if row["model"] not in prices:
                print(f"skip {row['run_id']}: no price for {row['model']}")
                continue
            est = estimate(row, prices, args.token_rate)
            totals[row["model"]] += est
            billed = float(row["billed_usd"]) if row.get("billed_usd") else None
            if billed and abs(est - billed) / billed > args.tolerance:
                drift.append((row["run_id"], est, billed))

    print(f"{'model':<18}{'estimated_usd':>14}")
    for model, usd in sorted(totals.items(), key=lambda kv: -kv[1]):
        print(f"{model:<18}{usd:>14.2f}")
    print(f"{'total':<18}{sum(totals.values()):>14.2f}")
    for run_id, est, billed in drift:
        print(f"DRIFT {run_id}: estimated {est:.2f} vs billed {billed:.2f}")
    return 1 if drift else 0

if __name__ == "__main__":
    raise SystemExit(main())

The columns are run_id, date, model, input_tokens, cached_input_tokens, output_tokens and billed_usd. Map your SDK export into them. The sample data below is invented for this walk-through and is not Cursor billing data. The price file holds list prices per million tokens for four current models, taken from Cursor’s model documentation and the vendors’ pages. Verify them against your own account before you trust the totals.

{
  "claude-opus-5.5":   {"input": 4.00, "cache_read": 0.20, "output": 20.00},
  "claude-sonnet-5.5": {"input": 2.00, "cache_read": 0.10, "output": 10.00},
  "gemini-4-neon":     {"input": 3.00, "cache_read": 0.15, "output": 15.00},
  "grok-4.7":          {"input": 2.00, "cache_read": 0.50, "output": 6.00}
}
run_id,date,model,input_tokens,cached_input_tokens,output_tokens,billed_usd
run-001,2026-11-24,claude-sonnet-5.5,420000,1900000,38000,1.46
run-002,2026-11-24,claude-opus-5.5,310000,2400000,52000,2.77
run-003,2026-11-25,gemini-4-neon,500000,1200000,41000,2.30
run-004,2026-11-26,grok-4.7,610000,2800000,64000,3.05
run-005,2026-11-27,claude-sonnet-5.5,150000,600000,12000,0.95

Run the ledger. The estimate comes from tokens times list price, so runs where Cursor billed something different get flagged.

python -m gate.ledger --runs runs.csv --prices prices.json
model              estimated_usd
grok-4.7                    3.00
claude-opus-5.5             2.76
gemini-4-neon               2.29
claude-sonnet-5.5           1.89
total                       9.95
DRIFT run-005: estimated 0.48 vs billed 0.95

On Teams and Enterprise, add the $0.25 per million token Cursor Token Rate with --token-rate 0.25. The flag adds that rate on the sum of input, cached and output tokens. Treat the result as an estimate, because Cursor documents exemptions, including models whose cache-read price is strictly below $0.10 per million tokens at every pricing tier. A rate that does not apply to some models will push the estimates above the billed number.

python -m gate.ledger --runs runs.csv --prices prices.json --token-rate 0.25

The exit code is 1 whenever a run drifts, so you can schedule the ledger in CI and fail a weekly job when spending stops matching expectations.

Choosing Models for Agent Runs #

Model choice changes both quality and bill, and the lineup moved fast in November. Anthropic released Claude Fable 5.2 and Claude Mythos 5.2, and Fable 5.2 is priced at $8 per million input tokens and $40 per million output. Google shipped Gemini 4 Carbon on November 10, Gemini 4 Hydrogen on November 12 and Gemini 4 Neon on November 18. xAI made Grok 4.7 available through its API on November 19. The table lists the API list prices per million tokens for the models most teams will try first.

Model Input Output Notes
Claude Opus 5.5 $4.00 $20.00 Anthropic positions it for agentic coding
Claude Sonnet 5.5 $2.00 $10.00 Mid-priced default for routine tasks
Claude Fable 5.2 $8.00 $40.00 Newest Fable in Cursor’s model catalog, replacing Fable 5.1
Gemini 4 Neon $3.00 $15.00 1M-token context window
Gemini 4 Hydrogen $1.50 $7.50 Aimed at fast agentic workflows
Gemini 4 Carbon $2.00 $10.00 Introductory rate ends Nov 30, then $4.00 and $20.00
Grok 4.7 $2.00 $6.00 Prompts under 200,000 tokens, $4.00 and $12.00 above that

Note that the Gemini 4 Carbon rate changes in three days. Google lists $4 per million input and $20 per million output from December 1, 2026, so any budget built on the introductory number is already stale. Claude plan details sit on Anthropic’s pricing page, and Google documents Neon’s benchmarks and safety work on the Gemini 4 Neon model card. Your Cursor bill follows Cursor’s own rate card and plan rules, so use these as a guide to relative cost, not as an invoice.

A practical routing rule works well here. Send small, well-specified tasks like the peek() change to a mid-priced model. Escalate to a larger model only when a run fails the gate twice for the same reason. Log the model on every run, which the ledger already does, and after two weeks you will see which tier earns its price on your codebase. Teams that would rather run an open model locally can try an OpenHands local setup with Ollama, and the same gate can read those branches because it reads only Git.

Common Pitfalls #

These six mistakes account for most failed rollouts of agent review gates. Each has a concrete fix.

Pitfall What happens Fix
1. Trusting the branch prefix An agent pushes under another name and the gate skips it Make is_agent_pr returnTrue for every pull request, and rely on CODEOWNERS for human changes
2. Interpolating github.head_ref into shell A crafted branch name runs commands on the runner Pass values through env: and quote them, as the workflow does
3. Running the gate from the PR checkout The agent edits the gate and approves itself Check out the base commit separately and run the code from there
4. Printing secrets in the report The CI log becomes a second leak Redact matches, as redact() does, and never print the full line
5. Wrong required check name Merges hang on “expected” forever Use the job id, gate , and confirm it in the checks list
6. Blocking on warnings Reviewers learn to bypass the check Keep warnings advisory and review the block rate weekly

Pitfall 1 deserves a longer note. The cost of gating every pull request is that human changes to src/ also run through the checker, and the protected-path rule will block your own engineers when they edit workflows. For many teams that is the right outcome, because those paths need a second reviewer anyway. For others it is noise. Decide on purpose, write the decision next to the policy and revisit it after a month of data.

A seventh mistake is quieter. Teams write the policy once and never read the findings again. Treat the gate’s output as a signal about your agents. If no-tests fires on 60% of pull requests, your prompt template is missing a testing requirement, and the fix belongs in a rules file that you keep honest by linting your rules files. If size fires often, your tasks are too big, and splitting them will improve quality before any model upgrade does.

Troubleshooting #

When something breaks, start with the symptom and work backward. These eleven cases cover almost everything the demo setup produced.

  • The gate prints “Not an agent PR, gate skipped.” on a pull request an agent opened. The head branch does not start with any prefix inbranch_prefixes and the label is missing. Read the real branch name from the pull request and update the policy, or add theagent-authored label.
  • git diff exits with status 129. The base ref does not exist in the checkout. In Actions, setfetch-depth: 0 on the checkout ofpr/ , and pass full SHAs, not branch names.
  • KeyError on a path inside collect. A filename contains characters Git quotes by default. Thecore.quotepath=off flag inrun_git fixes that, so confirm you copied it. Names with tabs or newlines still break the parser, which is rare enough to reject outright.
  • ModuleNotFoundError: No module named 'gate'. You ran python gate/cli.py instead ofpython -m gate.cli , or you ran it outside the repository root. In the workflow,working-directory: trusted keeps the module path correct.
  • tomllib import fails. You are on Python older than 3.11. Upgrade, or add thetomli package and change the import.
  • The gate check never appears on the pull request. The workflow file is not on the base branch yet, or itson: block does not include the event. Merge the workflow first, then open a new pull request.
  • Merge is blocked by “Expected” status. The required context inprotection.json does not match the job id. Rename one to match, then re-run the check.
  • False positive on the inline-credential rule. A test fixture contains a string such astoken = "aaaaaaaaaaaaaaaa" . Either change the fixture or add a narrow allowlist to the rule, and keep the allowlist in a protected file.
  • The ledger skips every run. Themodel column does not match a key inprices.json . Model names in your SDK export may differ from the keys you wrote, so normalize them in one place.
  • The ledger flags every run as drift. Cached tokens are probably missing from your export, or you switched on--token-rate for a plan that does not pay it. Individual plans do not pay the Cursor Token Rate.
  • Cursor refuses to start the agent. Check the plan first, since Free and Plus do not include Cloud Agents. Then look at the dialog Cursor shows on the page where you started the run, which names plan, usage, model or protected-scope limits.

Advanced Tips #

Once the basic gate is stable, a few upgrades pay off quickly. Start with policy per directory. Some teams keep a [paths.overrides] table so that docs/ allows 2,000 added lines while src/payments/ allows 80. The engine already takes a policy dictionary, so a small change in evaluate can pick limits per matched path.

Add a rule for new network calls and new subprocess usage. A regular expression for requests., urllib, subprocess and os.system in added source lines will not catch everything, but it turns “the agent quietly added a call to an unknown host” into a warning. Keep it as a warning, since legitimate code does both.

Post the report as a pull request comment instead of only a step summary. The JSON output already carries what you need, and a comment lands where reviewers look. Use the default GITHUB_TOKEN with pull-requests: write on a separate job, so the gate job keeps its read-only permissions.

If your organization has GitHub rulesets, consider requiring the workflow from a central repository, so a pull request cannot delete or neuter .github/workflows/agent-gate.yml. Check your GitHub plan, since availability varies by plan. Without it, CODEOWNERS on .github/ is your fallback and the protected-path rule still reports the edit.

Reduce the blast radius at the source with local controls too. A guide to the Cursor CLI sandbox and permissions shows how to constrain local runs, and the same thinking applies to what you allow a Cloud Agent to touch.

Cursor’s docs also describe self-hosted execution choices, and the Agent SDK ships an agent-sdk serve command that runs as your own Node process with no separate hosting charge. Model usage is billed to the account behind the key you supply. If code must not leave your network, a self-hosted runtime plus this gate gives you both control of where the agent runs and a check on what it produced. Authentication for SDK-launched agents uses CURSOR_API_KEY or CURSOR_SERVICE_ACCOUNT_KEY, and a service account key is the better choice for CI because it does not depend on one person’s login.

Cursor has also reportedly added voice chat with agents and live apps that you can build and share from a Cloud Agent. Both widen what a single run can do, and a live app means an agent can publish something other people can open. Neither changes the gate’s logic, but a live app is a good reason to add a rule that blocks edits to deployment configuration.

The Complete Working Project #

The finished repository has 18 files, and all 14 tests pass on Python 3.12.3 with Git 2.43.0.

agent-pr-gate/
  .github/
    CODEOWNERS
    workflows/agent-gate.yml
  gate/
    __init__.py
    cli.py
    diffing.py
    ledger.py
    rules.py
  src/tinyqueue/
    __init__.py
    queue.py
  tests/
    conftest.py
    test_cli.py
    test_rules.py
    test_tinyqueue.py
  gate_policy.toml
  prices.json
  protection.json
  pyproject.toml
  runs.csv

Bring it up from an empty folder with this sequence. Replace the organization and repository names, then merge the first commit to main before you open any agent pull request.

python3 -m venv .venv && source .venv/bin/activate
python -m pip install pytest
python -m pytest -q
git add -A && git commit -m "agent pr gate"
git remote add origin [email protected]:YOUR_ORG/YOUR_REPO.git
git push -u origin main
gh api -X PUT repos/YOUR_ORG/YOUR_REPO/branches/main/protection --input protection.json

A final checklist for go-live: the policy branch prefix matches a real agent branch, the gate check is required, CODEOWNERS lists real teams, the workflow passes branch names through env: and the ledger runs weekly. If all five hold, a Cursor Cloud Agent that deletes a test, edits CI or commits a key stops at the pull request.

Frequently Asked Questions #

Do Cursor Cloud Agents work on every Cursor plan?

No. Cursor’s pricing documentation says the Free and Plus plans do not include Cloud Agents. Check the current plan page to see which paid tiers do before you budget, and read the usage terms, because third-party models are billed separately from included usage.

What happened to Cursor background agents?

Cursor renamed them. The feature people searched for as Cursor background agents is now called Cloud Agents in the official documentation, and older tutorials still use the previous name. No official Cursor source available on November 28, 2026 reports that the feature was retired or discontinued.

Can this gate work with GitLab or Bitbucket?

Yes. The Python code needs only Git and a base and head reference. Replace the Actions workflow with a pipeline job that checks out the base commit separately and passes the branch name through an environment variable. Confirm in Cursor’s documentation which source control providers your plan supports before you start.

Does the gate replace human code review?

No. It confirms the mechanical things, such as scope, secrets and test integrity, so reviewers spend their time on correctness and design. The report says so itself on a clean run, in a line that reads No findings. Human review still applies.

How do I know which branch name Cursor uses?

Run one agent task, open the resulting pull request and read the head branch. The Cursor documentation available on November 28, 2026 does not describe a fixed naming scheme, so set branch_prefixes from what you observe. Fall back to the agent-authored label if your agents use several patterns.

Will a regex-based secret check catch everything?

No. It catches common token shapes, such as AWS access keys, GitHub tokens, private key headers and quoted credentials, and it will miss unusual formats. Pair it with your platform’s secret scanning and with push protection if your plan includes them. Treat the gate as one layer.

Can I use the SDK instead of the Cursor UI to launch runs?

Yes. Cursor says SDK-created Cloud Agents use the same runtime as Cursor’s own Cloud Agents and can route to any supported model. The SDK needs Node 22.13 or newer for the TypeScript package, and authentication uses CURSOR_API_KEY or CURSOR_SERVICE_ACCOUNT_KEY. The Cloud Agents API carries a Beta label, so pin versions and read release notes.

How much does a Cloud Agent run cost?

It depends on the plan, the model and the task. Cursor documents that third-party model usage on Premium and higher can bill at API list price from prepaid credit, and Teams and Enterprise add a $0.25 per million token Cursor Token Rate on eligible requests. Use the ledger in Step 12 to measure your own average, since a task as small as peek() costs far less than a refactor.

── more in #ai-agents 4 stories · sorted by recency
── more on @cursor 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/cursor-cloud-agents-…] indexed:0 read:42min 2026-11-28 · —