Skip to content
Claude Ship Approvals: Dry-Run Your Policy in Python — ContentBuffer guide

Claude Ship Approvals: Dry-Run Your Policy in Python

K
Kodetra Technologies··17 min read Intermediate

Summary

Test a .claude/approvals.yml merge policy locally before Claude starts approving your PRs.

Anthropic shipped Claude Ship on November 23: three agents that sit on your GitHub pull requests. Code Review (generally available) leaves findings, PR Steward (public beta) pushes fixes for failing checks, merge conflicts and review comments, and Claude Approvals (public beta) reads a policy file you commit and decides whether Claude itself may approve the PR, and how many humans still have to.

Most of the launch chatter has been about the review speed and the /ship command in Claude Code. The part that deserves more attention is the policy file. .claude/approvals.yml is now a piece of your merge security. Write it wrong and you either get an agent that never approves anything, which is annoying, or a PR that slips through with one seat filled by its own author, which is worse.

This guide walks through the policy format using Anthropic's own starter file, then builds a small Python dry-run tool (about 170 lines) that evaluates a policy against a list of changed files. You'll use it to catch four real mistakes before they reach your default branch, and finish with a pytest suite that keeps the policy honest in CI.

What you'll build

  • approvals_sim.py: a local evaluator that validates keys, matches globs, applies if and override conditions, and combines verdicts the way the docs describe (strictest wins).
  • A broken policy and a fixed one, with the simulator output for each so you can see exactly what changed.
  • test_policy.py: regression cases ("a 900-line PR never gets Claude's approval", "payments always needs two people") that run in under a second.

One thing to be clear about up front: the simulator is not Anthropic's evaluator. It models the semantics published in the Approvals policy reference so you can reason about a file offline. The real check, running in observe mode on real PRs, is still the final word. Think of this as a linter plus a unit test harness for your policy.

Prerequisites

  • A Claude Team or Enterprise plan. Claude Ship isn't available to orgs using Zero Data Retention, the HIPAA configuration, or customer-managed keys.
  • A GitHub repository where the Claude GitHub App is installed, and someone with the Owner role to flip the switches under Organization settings > Claude Ship.
  • At least two people with write access to the repo before you move the policy to enforce mode.
  • Python 3.10+ with pyyaml and pytest for the local tooling.
pip install pyyaml pytest

Claude Ship is billed on tokens through usage credits, separately from your plan's included usage. Approvals bills for classifier runs and for any Code Review a policy starts, and that includes observe mode. Set caps under Organization settings > Usage before you experiment on a busy repo.


Step 1: Read the official starter policy

Anthropic's setup page offers two starters. This is the one titled "Let Claude approve when Code Review passes", copied as published:

version: 1
mode: observe
rules:
  - purpose: "A change takes two people. When Claude's review passes, one is enough and Claude approves."
    paths: ["**"]
    verdict: { claude: comments, seats: 2 }
    override:
      - { if: "claude/code_review = pass", verdict: { claude: approves, seats: 1 } }
  - purpose: "A change to the review rules takes two people."
    paths: ["**/.claude/**"]
    nested: inherit
    verdict: { claude: comments, seats: 2 }

Here's how to read it. Every rule needs a purpose and paths. The verdict says what Claude may do (approves, comments or blocks) and how many human seats must be filled. An override list swaps in a different verdict when its condition is true, and the first true override wins. mode: observe means the check reports what it would do without enforcing anything.

Three combining rules matter more than any single line:

  • Strictest verdict wins across every rule and every file: blocks beats comments, which beats approves. Claude approves only if every applying rule says approves and every changed file is covered.
  • Every applying rule's seats must be filled, so the biggest seat count effectively sets the bar.
  • No mode line means enforce. The default is enforce, so deleting mode: observe is the switch that turns the policy on.

Step 2: Build the dry-run evaluator

Save this as approvals_sim.py. It handles the subset of the format you need for most repos: the documented top-level and rule keys, glob patterns (*, **, ?, [ab], {a,b}, and ! exclusions), simple conditions joined by capital AND/OR, overrides, seat lists with from, and the strictest-wins merge.

"""approvals_sim.py - a local dry run for Claude Approvals policy files.

This is NOT Anthropic's evaluator. It models the documented rules
(https://code.claude.com/docs/en/approvals-policy) closely enough to catch
mistakes before you merge a policy: unknown keys, coverage gaps, the
author-seat trap, override order and "strictest verdict wins".
"""
import re
import sys
import yaml

TOP_KEYS = {"version", "rules", "mode", "nested", "run", "locals"}
RULE_KEYS = {"purpose", "paths", "verdict", "if", "override", "advisory",
             "reuse", "findings", "use", "mode", "nested", "run"}
STRICTNESS = {"approves": 0, "comments": 1, "blocks": 2}
NEVER_APPROVE = {".gitattributes", ".gitmodules"}


def glob_to_regex(pattern):
    """Translate *, **, ?, [ab] and {a,b} into a regex anchored on the path."""
    out, i = "", 0
    while i < len(pattern):
        c = pattern[i]
        if pattern.startswith("**/", i):
            out += r"(?:.*/)?"; i += 3; continue
        if pattern.startswith("**", i):
            out += r".*"; i += 2; continue
        if c == "*":
            out += r"[^/]*"
        elif c == "?":
            out += r"[^/]"
        elif c == "[":
            j = pattern.index("]", i)
            out += pattern[i:j + 1]; i = j
        elif c == "{":
            j = pattern.index("}", i)
            alts = pattern[i + 1:j].split(",")
            out += "(?:" + "|".join(re.escape(a) for a in alts) + ")"; i = j
        else:
            out += re.escape(c)
        i += 1
    return re.compile("^" + out + "$")


def rule_matches(rule, path):
    inc = [p for p in rule["paths"] if not p.startswith("!")]
    exc = [p[1:] for p in rule["paths"] if p.startswith("!")]
    return (any(glob_to_regex(p).match(path) for p in inc)
            and not any(glob_to_regex(p).match(path) for p in exc))


def eval_condition(expr, facts):
    """Supports `fact OP value` joined by AND / OR (capitals, as documented).
    Returns None when a fact is unknown, mirroring 'classifier gave no answer'."""
    if expr is None or expr is True:
        return True
    for joiner in (" OR ", " AND "):
        if joiner in expr:
            parts = [eval_condition(p.strip(), facts) for p in expr.split(joiner)]
            if None in parts:
                return None
            return any(parts) if joiner == " OR " else all(parts)
    m = re.match(r"^([\w/]+)\s*(<=|>=|!=|=|<|>)\s*(.+)$", expr.strip())
    if not m:
        raise ValueError(f"cannot parse condition: {expr!r}")
    name, op, raw = m.groups()
    if name not in facts:
        return None
    left, right = facts[name], raw.strip().strip("'\"")
    if isinstance(left, (int, float)):
        right = float(right)
        return {"<": left < right, "<=": left <= right, ">": left > right,
                ">=": left >= right, "=": left == right, "!=": left != right}[op]
    if op == "=":
        return glob_to_regex(right).match(str(left)) is not None
    if op == "!=":
        return glob_to_regex(right).match(str(left)) is None
    raise ValueError(f"operator {op} needs a number: {expr!r}")


def seats_needed(verdict):
    seats = verdict.get("seats", 0)
    if isinstance(seats, list):
        return sum(s.get("count", 1) for s in seats)
    return int(seats)


def excludes_authors(verdict):
    seats = verdict.get("seats", 0)
    if not isinstance(seats, list):
        return False
    return all("!pr/authors" in (s.get("from") or []) for s in seats)


def validate(policy):
    problems = []
    for k in set(policy) - TOP_KEYS:
        problems.append(f"unknown top-level key '{k}' (Claude refuses the file)")
    if policy.get("version") != 1:
        problems.append("version must be 1")
    for n, rule in enumerate(policy.get("rules") or [], 1):
        for k in set(rule) - RULE_KEYS:
            problems.append(f"rule {n}: unknown key '{k}'")
        for req in ("purpose", "paths"):
            if req not in rule:
                problems.append(f"rule {n}: missing required '{req}'")
        if rule.get("paths") and all(p.startswith("!") for p in rule["paths"]):
            problems.append(f"rule {n}: needs at least one non-! pattern")
        v = rule.get("verdict", {})
        if v.get("claude") not in (None, *STRICTNESS):
            problems.append(f"rule {n}: verdict.claude must be approves/comments/blocks")
        for label, vv in [("verdict", v)] + [(f"override {i}", o.get("verdict", {}))
                                             for i, o in enumerate(rule.get("override") or [], 1)]:
            if vv and seats_needed(vv) == 1 and not excludes_authors(vv):
                problems.append(f"rule {n} {label}: seats: 1 can be filled by the PR author alone")
    return problems


def evaluate(policy, pr):
    files, facts = pr["files"], pr.get("facts", {})
    results, uncovered = [], []
    for f in files:
        applying = [r for r in policy["rules"] if rule_matches(r, f)]
        if not applying:
            uncovered.append(f)
            continue
        for r in applying:
            cond = eval_condition(r.get("if"), facts)
            if cond is False:
                continue
            verdict = r.get("verdict", {"claude": "comments", "seats": 0})
            for ov in r.get("override") or []:
                if eval_condition(ov["if"], facts) is True:  # first true wins
                    verdict = ov["verdict"]
                    break
            results.append((f, r["purpose"], verdict))

    if not results:
        return {"check": "neutral (no file covered - GitHub counts this as passing)",
                "uncovered": uncovered}
    claude = max((v.get("claude", "comments") for _, _, v in results),
                 key=STRICTNESS.get)
    seats = max(seats_needed(v) for _, _, v in results)
    if any(f.split("/")[-1] in NEVER_APPROVE for f in files) and claude == "approves":
        claude = "comments"
    if uncovered and claude == "approves":
        claude = "comments"  # Claude only approves when every file is covered
    return {"claude": claude, "human_seats": seats, "uncovered": uncovered,
            "per_file": results}


def main(policy_path, pr_path):
    policy = yaml.safe_load(open(policy_path))
    pr = yaml.safe_load(open(pr_path))
    for p in validate(policy):
        print("WARN ", p)
    mode = policy.get("mode", "enforce")
    print(f"mode: {mode}{'  (no mode line = enforced!)' if 'mode' not in policy else ''}")
    out = evaluate(policy, pr)
    if "check" in out:
        print("check:", out["check"])
    else:
        for f, purpose, v in out["per_file"]:
            print(f"  {f:<32} {v.get('claude','comments'):<9} seats={seats_needed(v)}  <- {purpose}")
        print(f"RESULT: claude={out['claude']}  human seats needed={out['human_seats']}")
    if out["uncovered"]:
        print("UNCOVERED:", ", ".join(out["uncovered"]))


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2])

A few design choices mirror the docs directly. Unknown keys produce a warning because Claude refuses a policy file with keys it doesn't know. When a fact is missing (say there's no Code Review result yet), eval_condition returns None and the override doesn't fire, matching the documented behavior that a classifier with no answer leaves the rule's own verdict in place. Files nobody covers are reported separately, because that's where the nastiest surprise lives.

Step 3: Run the starter against real-looking PRs

Describe a PR as a small YAML file: the changed paths plus whatever facts you want to simulate. Facts use the names from the policy reference, like claude/code_review, pr/diff_lines and pr/files_changed.

files: [src/api/users.py, .claude/approvals.yml]
facts: { claude/code_review: pass, pr/files_changed: 2 }
python approvals_sim.py approvals.yml pr_policy.yml
WARN  rule 1 override 1: seats: 1 can be filled by the PR author alone
mode: observe
  src/api/users.py                 approves  seats=1  <- A change takes two people. When Claude's review passes, one is enough and Claude approves.
  .claude/approvals.yml            approves  seats=1  <- A change takes two people. When Claude's review passes, one is enough and Claude approves.
  .claude/approvals.yml            comments  seats=2  <- A change to the review rules takes two people.
RESULT: claude=comments  human seats needed=2

This is the starter working as intended. The app file alone would get Claude's approval plus one human, but the PR also touches .claude/approvals.yml, so the second rule applies to that file, and its comments verdict with two seats wins for the whole PR. Someone can't weaken the review rules in the same PR that benefits from them.

The warning line is worth a pause. The starter's override drops to seats: 1, and the policy reference says that on a PR opened by a person with write access, the author can fill one seat. Whether that's acceptable depends on your team. We'll fix it explicitly in Step 5.


Step 4: Catch four mistakes in a hand-written policy

Here's a stricter policy of the kind a team writes on day one. It looks reasonable. It has four problems.

version: 1
rules:
  - purpose: "App code needs one reviewer who is not an author."
    paths: ["src/**", "!src/**/*_test.py"]
    verdict:
      claude: comments
      seats: [{ count: 1, from: [humans, "!pr/authors"] }]
    override:
      - { if: "claude/code_review = pass AND pr/diff_lines < 200", verdict: { claude: approves, seats: 1 } }
  - purpose: "Payments always takes two people."
    paths: ["src/payments/**"]
    verdict: { claude: comments, seats: 2 }
  - purpose: "Review rules take two people."
    paths: ["**/.claude/**", "REVIEW.md"]
    verdict: { claude: comments, seats: 2 }
    reviewers: [acme/platform]
files: [src/payments/refund.py, src/api/users.py, .github/workflows/deploy.yml, src/api/users_test.py]
facts: { claude/code_review: pass, pr/diff_lines: 85 }
python approvals_sim.py strict.yml pr_mixed.yml
WARN  rule 1 override 1: seats: 1 can be filled by the PR author alone
WARN  rule 3: unknown key 'reviewers'
mode: enforce  (no mode line = enforced!)
  src/payments/refund.py           approves  seats=1  <- App code needs one reviewer who is not an author.
  src/payments/refund.py           comments  seats=2  <- Payments always takes two people.
  src/api/users.py                 approves  seats=1  <- App code needs one reviewer who is not an author.
RESULT: claude=comments  human seats needed=2
UNCOVERED: .github/workflows/deploy.yml, src/api/users_test.py

Reading the output from the top:

  1. Unknown key. reviewers isn't part of the format. Claude refuses the whole file, which means none of your rules run.
  2. No mode line. The file is enforced the moment it merges. You skipped the observe phase that Anthropic's rollout steps assume.
  3. Author seat. The override uses a bare seats: 1, even though the rule's own verdict carefully excluded authors with "!pr/authors". When the override fires, that protection disappears.
  4. Coverage gaps. The CI workflow and the excluded test file are covered by nothing.

The last one is the dangerous one. Watch what happens with a PR that only edits the deploy workflow:

python approvals_sim.py strict.yml pr_ci_only.yml
WARN  rule 1 override 1: seats: 1 can be filled by the PR author alone
WARN  rule 3: unknown key 'reviewers'
mode: enforce  (no mode line = enforced!)
check: neutral (no file covered - GitHub counts this as passing)
UNCOVERED: .github/workflows/deploy.yml

The docs spell this out: if no rule covers any changed file and GitHub requires the check, it finishes neutral with "Nothing ran, not blocking: no file is covered", and GitHub counts neutral as passing. A PR that rewrites your deploy pipeline would sail through the gate you just set up. The fix is a root rule on ["**"] with no if, which is exactly what the official starter does.

Step 5: Fix it, and hit the trap that comes next

The obvious fix is to add a root rule that requires one non-author on everything, and keep the src/** rule with its approve override. Try that and run a small, reviewed app change through it:

mode: observe
  src/api/users.py                 comments  seats=1  <- Every change needs one reviewer who is not an author.
  src/api/users.py                 approves  seats=1  <- Small app changes: Claude approves after a passing review, one non-author still signs off.
RESULT: claude=comments  human seats needed=1

Claude never approves. The root rule applies to src/api/users.py too, its verdict is comments, and strictest wins. Because the root rule has to cover everything, it also has to carry the approve override, otherwise it vetoes every other rule's approves. This is the mistake people make most often with layered rules, and the simulator shows it in one line.

Here's the corrected policy. The override lives on the root rule, every seat list excludes authors, the payments and review-control rules stay strict, and .github/** and CLAUDE.md get their own rule, because the docs note they are not on the built-in protected list (which does cover policy files, REVIEW.md, CODEOWNERS, .gitmodules, .gitattributes and symlinks).

version: 1
mode: observe
rules:
  - purpose: "Every change needs one non-author. Small reviewed changes: Claude approves too."
    paths: ["**"]
    verdict:
      claude: comments
      seats: [{ count: 1, from: [humans, "!pr/authors"] }]
    override:
      - if: "claude/code_review = pass AND pr/diff_lines < 200"
        verdict:
          claude: approves
          seats: [{ count: 1, from: [humans, "!pr/authors"] }]
  - purpose: "Payments always takes two people."
    paths: ["src/payments/**"]
    verdict: { claude: comments, seats: 2 }
  - purpose: "CI and review rules take two people."
    paths: ["**/.claude/**", "REVIEW.md", ".github/**", "CLAUDE.md"]
    nested: inherit
    verdict: { claude: comments, seats: 2 }
python approvals_sim.py fixed.yml pr_small.yml
python approvals_sim.py fixed.yml pr_mixed.yml
mode: observe
  src/api/users.py                 approves  seats=1  <- Every change needs one non-author. Small reviewed changes: Claude approves too.
RESULT: claude=approves  human seats needed=1
mode: observe
  src/payments/refund.py           approves  seats=1  <- Every change needs one non-author. Small reviewed changes: Claude approves too.
  src/payments/refund.py           comments  seats=2  <- Payments always takes two people.
  src/api/users.py                 approves  seats=1  <- Every change needs one non-author. Small reviewed changes: Claude approves too.
  .github/workflows/deploy.yml     approves  seats=1  <- Every change needs one non-author. Small reviewed changes: Claude approves too.
  .github/workflows/deploy.yml     comments  seats=2  <- CI and review rules take two people.
  src/api/users_test.py            approves  seats=1  <- Every change needs one non-author. Small reviewed changes: Claude approves too.
RESULT: claude=comments  human seats needed=2

Now the small reviewed change gets Claude's approval plus one human who didn't write it, and the mixed PR touching payments and CI needs two people. No warnings, nothing uncovered.


Step 6: Lock the behavior in with tests

A policy is code that decides who can merge. Give it tests. Each case pins the expected Claude verdict and seat count for a type of change, so a future edit that quietly loosens things fails in CI.

import yaml
from approvals_sim import evaluate, validate

POLICY = yaml.safe_load(open("fixed.yml"))

CASES = [
    # (files, facts, expected claude verdict, expected human seats)
    (["src/api/users.py"], {"claude/code_review": "pass", "pr/diff_lines": 85}, "approves", 1),
    (["src/api/users.py"], {"claude/code_review": "fail", "pr/diff_lines": 85}, "comments", 1),
    (["src/api/users.py"], {"claude/code_review": "pass", "pr/diff_lines": 900}, "comments", 1),
    (["src/payments/refund.py"], {"claude/code_review": "pass", "pr/diff_lines": 5}, "comments", 2),
    ([".claude/approvals.yml"], {"claude/code_review": "pass", "pr/diff_lines": 3}, "comments", 2),
    (["README.md"], {}, "comments", 1),  # no review result -> rule's own verdict
]

def test_policy_is_clean():
    assert validate(POLICY) == []

def test_cases():
    for files, facts, claude, seats in CASES:
        out = evaluate(POLICY, {"files": files, "facts": facts})
        assert not out["uncovered"], files
        assert (out["claude"], out["human_seats"]) == (claude, seats), (files, facts, out["claude"], out["human_seats"])
python -m pytest -q test_policy.py
..                                                                       [100%]
2 passed in 0.02s

Note the last case: a README edit with no review result falls back to the root rule's own verdict. That's the documented no-answer behavior, and it's a good one to pin because it proves your strict verdict is on the rule and the lenient one is on the override, which is the order the docs recommend.

Step 7: Roll it out the documented way

Once the simulator and tests are green, follow Anthropic's rollout order. Turn on one agent at a time in one repo: Code Review first, then PR Steward, then Approvals.

  1. Add .claude/approvals.yml in its own PR with mode: observe. Merge when Claude comments that it found the policy file valid. Policies are read only from the default branch.
  2. Open normal PRs and look for the check titled with "(observe mode)". Compare what it says against what your reviewers actually did.
  3. Delete the mode: observe line and merge. Comment @claude approvals rerun on open PRs still showing observe-mode titles.
  4. In GitHub branch rules, require the Claude Approvals check with the Claude app as its source.
  5. Test it by changing a file under .claude/. The check should wait on two human reviews.

Keep your simulator cases in sync with what observe mode reports. If they disagree, trust the real check and adjust the simulator, since it's a model of the rules rather than the rules themselves.

A note on /ship and PR Steward

If you're testing all three agents together, the /ship command in Claude Code (v2.1.330 or later, with gh 2.63+ signed in) commits your work, pushes, opens the PR, runs a review and then keeps a watch running. Two things from the docs catch people out. It proceeds with no confirmation prompt and commits every uncommitted file, new ones included, so run git status first. And the watch acts with your own gh and git credentials, so its commits show up under your name.

# review effort low, existing PR 41, also read comments from a lint bot
/ship low 41 +my-lint-bot

# stop the watch
/ship stop

On GitHub, PR Steward responds to @claude steward (or the claude-pr-steward-watching label in Manual mode) and steps back on @claude stop. It pushes fixes but is designed never to approve or merge. Approval is the policy file's job, which is why getting that file right matters.


Common pitfalls

  • Unknown keys kill the whole file. A typo like reviewers: or verdicts: doesn't just skip one rule. Claude refuses the policy. Lint every change.
  • Forgetting that enforce is the default. A first policy without mode: observe is live on merge.
  • Uncovered files pass silently. Required check plus no matching rule equals a neutral result that GitHub treats as passing. Always keep a root ["**"] rule with no if.
  • The root rule vetoes approvals. Because strictest wins, a root rule with comments and no override means Claude never approves anything. Put the approve override on the root rule.
  • Bare seats: 1 lets the author count. Use seats: [{ count: 1, from: [humans, "!pr/authors"] }] wherever one approval should mean someone else.
  • Strict verdicts on overrides. If a classifier returns no answer, the rule's own verdict applies. Put the strict verdict on the rule and the lenient one on the override, never the reverse.
  • Unprotected agent config. .github/, CLAUDE.md, AGENTS.md and .mcp.json aren't built-in protected files. Anything that changes how agents behave should need two people.
  • Billed reviews from conditions. A claude/code_review inside an if can start a billed review on every push. If you only want it as a signal, list it under advisory so reviews follow your Code Review settings.
  • Turning it off in the wrong order. Stop requiring the check in GitHub first, then turn off Approvals. Uninstalling the GitHub app while the check is still required can block every merge.
  • Policy edits apply after merge. Changes to policy files only take effect once they land on the default branch, so you can't test a policy change on the PR that introduces it. That's what the simulator is for.

Quick reference

ThingValue / syntaxNote
Policy file.claude/approvals.yml.yaml read only if .yml is absent
Required top-level keysversion: 1, rulesUnknown keys refuse the file
Modesobserve | enforceDefault is enforce
Verdictsapproves | comments | blocksStrictest wins
Exclude authorsfrom: [humans, "!pr/authors"]Quote the ! entry
Condition joinersAND / ORCapitals only
Useful factspr/diff_lines, pr/files_changed, pr/basePlus claude/code_review
Rerun after enforce@claude approvals rerunOn PRs still in observe titles
Ask for a review@claude review@claude review always subscribes
Start PR Steward@claude steward@claude stop to step back
Local ship/ship [effort] [PR] [+bot]Claude Code v2.1.330+
Limits512 rules, 448 KiB per file2,000+ files: too large to evaluate

Next steps

  • Add a CI job that runs approvals_sim.py on every policy change and pytest test_policy.py on every PR.
  • Extend the simulator for subdirectory policies (for example services/billing/.claude/approvals.yml, where the nearest enforcing file decides) if you run a monorepo.
  • Write a REVIEW.md to tune what Code Review flags, since its pass or fail result is what your overrides lean on.
  • Run the real policy in observe mode for a week and diff its titles against your simulator cases before enforcing.

Sources: Introducing Claude Ship, Claude Ship docs, Approvals setup, Approvals policy reference, /ship and /steward.

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,605 newsletter subscribers.

Also get