diff options
| author | Mohamed Hegazy <8000722+mhegazy@users.noreply.github.com> | 2026-11-11 11:40:34 -0800 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-11-11 11:40:34 -0800 |
| commit | e37d307bd9f85dab6fea5dfb5e3dc146753b2d2d (patch) | |
| tree | 22dcc409a5331961148a84351d3ab17948bd47ee /plugins | |
| parent | acf6cc517bb9c83e992da0a057d07f31024920d2 (diff) | |
| parent | 523bcac761cece1e5694cb316aed95e1ac0db7e1 (diff) | |
Merge pull request #7081 from anthropics/mhegazy/sg-one-model-setting
security-guidance: take the review model from one place, default to the newest listed
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/README.md | 8 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 197 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 2 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_base_url.py | 2 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_inflight_reviews.py | 3 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_review_model.py | 153 |
6 files changed, 277 insertions, 88 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md index d2d36442..46049569 100644 --- a/plugins/security-guidance/README.md +++ b/plugins/security-guidance/README.md @@ -30,8 +30,10 @@ All configuration is via environment variables. None are required for default be By default both reviews run on the newest Claude Opus, and move to the next one when it is released — there is no model version to bump: -- The LLM diff review asks your API endpoint (`GET /v1/models`) which Opus models it serves and uses the newest. The answer is cached for a day in the plugin's state directory. If the endpoint can't answer, the review uses `claude-opus-5-5`. -- The agentic commit reviewer, and every review in a session signed in to a Claude apps gateway with `/login`, run through your installed Claude Code. Other reviews on Bedrock, Vertex, and Foundry run through the copy of Claude Code bundled with the Agent SDK, or `SG_AGENTIC_CLI_PATH` if set. On Windows the agentic commit reviewer runs through the bundled copy too, unless `SG_AGENTIC_CLI_PATH` is set. Where the Agent SDK has no bundled copy for Windows, those reviews run through `~\.local\bin\claude.exe`, or else a `claude.exe` on `PATH`; if there is neither, set `SG_AGENTIC_CLI_PATH`. All of them use Claude Code's `opus` alias: the model `/model opus` selects, including any `ANTHROPIC_DEFAULT_OPUS_MODEL` you have set. On a gateway that alias may name an older Opus than the newest one. +- The plugin asks your API endpoint (`GET /v1/models`) which Opus models it serves and uses the newest. The answer is cached for a day in the plugin's state directory. +- A diff review call that fails is retried on the newest Sonnet the endpoint lists. +- If the endpoint can't answer, the diff review uses `claude-opus-5-5` (retrying on `claude-sonnet-5-5`), and the agentic commit reviewer uses Claude Code's `opus` alias. When it does use the listed Opus, the agentic commit reviewer runs at medium effort unless you set `CLAUDE_CODE_EFFORT_LEVEL`. +- The agentic commit reviewer runs through your installed Claude Code. Every review in a session signed in to a Claude apps gateway with `/login` also does, and they use Claude Code's `opus` and `sonnet` aliases. On Bedrock, Vertex, and Foundry reviews use those aliases too, through the copy of Claude Code bundled with the Agent SDK, or `SG_AGENTIC_CLI_PATH` if set. On Windows the agentic commit reviewer runs through the bundled copy too, unless `SG_AGENTIC_CLI_PATH` is set. Where the Agent SDK has no bundled copy for Windows, those reviews run through `~\.local\bin\claude.exe`, or else a `claude.exe` on `PATH`; if there is neither, set `SG_AGENTIC_CLI_PATH`. If you set `ANTHROPIC_DEFAULT_OPUS_MODEL`, the agentic commit reviewer uses the `opus` alias so that setting applies. On a gateway that alias may name an older Opus than the newest one. To pin a model, or to use a cheaper one: @@ -138,7 +140,7 @@ Review usage: review=stop session=<session id> model=claude-opus-5-5 calls=1 in= ``` - `review` is `stop`, `commit` or `push`; `session` is the Claude Code session that triggered it. -- `calls` counts API requests for the diff review and reviewer runs for the agentic commit/push review, where `model` is the model that was asked for (`opus` by default). +- `calls` counts API requests for the diff review and reviewer runs for the agentic commit/push review, where `model` is the model that was asked for (`opus` if the endpoint can't list its models). - `est_cost_usd` is an estimate at list prices, not a bill: on a subscription the review counts against your usage limits instead. A trailing `~` means the model had no entry in the plugin's price table and a default rate was used. A review cut short (timeout, session exit) may not be counted. - The log rotates at 1 MB, so copy these lines out if you need a longer history. diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index a76738e4..793da3c3 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -181,14 +181,23 @@ HAS_API_CREDENTIALS = bool( # driver, so the default favors precision over recall and over latency. # Override via the SECURITY_REVIEW_MODEL env var (see README). # -# Without an override the review follows the newest Opus rather than a -# release named here: default_review_model() resolves it per call path. -# _PINNED_REVIEW_MODEL is only what a review uses when that lookup fails. +# Every review gets its model from default_review_model(), retry_review_model() +# or agentic_review_model(); nothing else in this plugin picks one. Without an +# override they follow the newest Opus (and Sonnet, for a retry) the endpoint +# lists rather than a release named here. +# +# These two names are only what a direct API call uses when the endpoint can't +# list its models, because the API takes no alias. _PINNED_REVIEW_MODEL = "claude-opus-5-5" -# Claude Code's own alias. The CLI the Agent SDK spawns resolves it to the -# newest Opus it knows how to drive, in the provider's id form on 3P. +_PINNED_RETRY_MODEL = "claude-sonnet-5-5" +# Claude Code's own aliases, for reviews that run through a CLI. The CLI +# resolves them to the newest model it knows how to drive, in the provider's +# id form on 3P. A CLI that is out of date resolves them to an old model. _CLI_OPUS_ALIAS = "opus" -SECURITY_REVIEW_MODEL = os.environ.get("SECURITY_REVIEW_MODEL", "").strip() or _PINNED_REVIEW_MODEL +_CLI_SONNET_ALIAS = "sonnet" +# What a named model runs at: a CLI older than the model doesn't know the +# effort it should default to. +_REVIEWER_EFFORT = "medium" # OAuth subscriber tokens (ANTHROPIC_AUTH_TOKEN) require this exact system prompt # for api.anthropic.com/v1/messages — the API checks for one of the known Claude @@ -635,6 +644,9 @@ _LEGACY_THINKING_MODELS = ( "claude-sonnet-4-0", "claude-sonnet-4-5", "claude-haiku-4-5", + # Dated ids of the first 4.0 releases, which a listing can name. + "claude-opus-4-2", + "claude-sonnet-4-2", ) @@ -700,19 +712,23 @@ _REVIEW_MODEL_RETRY_SECONDS = 3600 _REVIEW_MODEL_LOOKUP_TIMEOUT = 5 _REVIEW_MODEL_LISTING_MAX_BYTES = 4 * 1024 * 1024 -# claude-opus-<major>[-<minor>][-<yyyymmdd>]. Anything else a listing or the +# claude-<family>-<major>[-<minor>][-<yyyymmdd>]. Anything else a listing or the # cache file holds (other families, gateway-prefixed names, free text) is # never sent as a model id. -_OPUS_ID = re.compile(r"claude-opus-(\d{1,2})(?:-(\d{1,2}))?(?:-(\d{8}))?") +_MODEL_ID = { + family: re.compile(rf"claude-{family}-(\d{{1,2}})(?:-(\d{{1,2}}))?(?:-(\d{{8}}))?", re.ASCII) + for family in ("opus", "sonnet") +} -_review_model_memo: Optional[str] = None +# The newest models this process knows the endpoint lists; None before the lookup. +_review_model_memo: Optional[Dict[str, Optional[str]]] = None -def _newest_opus(model_ids) -> Optional[str]: - """The highest-versioned Opus id in `model_ids`, or None.""" +def _newest_in_family(model_ids, family) -> Optional[str]: + """The highest-versioned id of `family` in `model_ids`, or None.""" best = None for model_id in model_ids: - m = _OPUS_ID.fullmatch(model_id) if isinstance(model_id, str) else None + m = _MODEL_ID[family].fullmatch(model_id) if isinstance(model_id, str) else None if not m: continue version = (int(m.group(1)), int(m.group(2) or 0), m.group(3) or "") @@ -721,8 +737,8 @@ def _newest_opus(model_ids) -> Optional[str]: return best[1] if best else None -def _fetch_newest_opus() -> Optional[str]: - """Newest Opus the configured endpoint lists; None if it can't say.""" +def _fetch_newest_models() -> Dict[str, Optional[str]]: + """Newest Opus and Sonnet the configured endpoint lists; {} if it can't say.""" # Newest first, so one modest page is enough; an org with many models # otherwise returns a megabyte-sized listing. url = _anthropic_base_url() + "/v1/models?limit=100" @@ -739,58 +755,69 @@ def _fetch_newest_opus() -> Optional[str]: entries = listing.get("data") if isinstance(listing, dict) else None if not isinstance(entries, list): debug_log("review model lookup: no model list in response") - return None + return {} ids = [e.get("id") for e in entries if isinstance(e, dict)] - if listing.get("has_more"): - # A truncated page may hold no current Opus at all (an org's - # own models can fill it); never let it pick an older one. - ids.append(_PINNED_REVIEW_MODEL) - return _newest_opus(ids) + def newest(family, pinned): + if not listing.get("has_more"): + return _newest_in_family(ids, family) + # A truncated page may hold no current model at all (an org's + # own models can fill it). Never let it pick an older one. + found = _newest_in_family(ids + [pinned], family) + return None if found == pinned and pinned not in ids else found + return {"opus": newest("opus", _PINNED_REVIEW_MODEL), + "sonnet": newest("sonnet", _PINNED_RETRY_MODEL)} except urllib.error.HTTPError as e: if e.code == 401 and not use_token and ANTHROPIC_AUTH_TOKEN: use_token = True continue debug_log(f"review model lookup: HTTP {e.code}") - return None + return {} except Exception as e: debug_log(f"review model lookup failed: {type(e).__name__}") - return None - return None + return {} + return {} def _read_review_model_cache(path, endpoint_key, now): - """(hit, model) from the cache file. `model` is None for a remembered - failed lookup. The file is user-writable state: every field is checked - and a model id is accepted only if it has the shape of an Opus id.""" + """(hit, models) from the cache file. `models` has no "opus" for a + remembered failed lookup. The file is user-writable state: every field is + checked and a model id is accepted only if it has the shape of its family's + ids.""" try: with open(path, "r", encoding="utf-8") as f: entry = json.loads(f.read(4096)) except (OSError, ValueError): - return False, None - if not isinstance(entry, dict) or entry.get("endpoint") != endpoint_key: - return False, None + return False, {} + # Without "sonnet" it was written by a version that didn't look that up. + if (not isinstance(entry, dict) or entry.get("endpoint") != endpoint_key + or "sonnet" not in entry): + return False, {} at = entry.get("at") if isinstance(at, bool) or not isinstance(at, (int, float)): - return False, None + return False, {} model = entry.get("model") if model is None: ttl = _REVIEW_MODEL_RETRY_SECONDS - elif isinstance(model, str) and _OPUS_ID.fullmatch(model): + elif isinstance(model, str) and _MODEL_ID["opus"].fullmatch(model): ttl = _REVIEW_MODEL_TTL_SECONDS else: - return False, None + return False, {} if not 0 <= now - at < ttl: - return False, None - return True, model + return False, {} + sonnet = entry.get("sonnet") + if not (isinstance(sonnet, str) and _MODEL_ID["sonnet"].fullmatch(sonnet)): + sonnet = None + return True, {"opus": model, "sonnet": sonnet} -def _write_review_model_cache(path, endpoint_key, model, now): +def _write_review_model_cache(path, endpoint_key, models, now): tmp = None try: make_state_dir(os.path.dirname(path)) fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".review_model.") with os.fdopen(fd, "w", encoding="utf-8") as f: - json.dump({"endpoint": endpoint_key, "model": model, "at": now}, f) + json.dump({"endpoint": endpoint_key, "model": models.get("opus"), + "sonnet": models.get("sonnet"), "at": now}, f) os.replace(tmp, path) except OSError as e: debug_log(f"review model cache not written: {type(e).__name__}") @@ -801,16 +828,39 @@ def _write_review_model_cache(path, endpoint_key, model, now): pass +def _listed_models() -> Dict[str, Optional[str]]: + """Newest models the endpoint lists, looked up at most once per + _REVIEW_MODEL_TTL_SECONDS. {} (or no "opus") when it can't answer. Never + raises.""" + global _review_model_memo + if _review_model_memo is not None: + return _review_model_memo + try: + path = os.path.join(_resolve_state_dir(), _REVIEW_MODEL_CACHE_FILE) + # Hashed: a gateway URL can carry credentials. + endpoint_key = hashlib.sha256( + _anthropic_base_url().encode("utf-8") + ).hexdigest()[:16] + now = time.time() + hit, models = _read_review_model_cache(path, endpoint_key, now) + if not hit: + models = _fetch_newest_models() + _write_review_model_cache(path, endpoint_key, models, now) + except Exception as e: + debug_log(f"review model resolution failed: {type(e).__name__}") + models = {} + _review_model_memo = models + return models + + def default_review_model() -> str: """Model for a review the user hasn't pinned with SECURITY_REVIEW_MODEL. 3P providers and Claude apps gateway sign-ins go through the Agent SDK, so the CLI alias does the work. 1P and LLM gateways set with - ANTHROPIC_BASE_URL get the newest Opus the endpoint lists, looked up at - most once per _REVIEW_MODEL_TTL_SECONDS; _PINNED_REVIEW_MODEL when the - lookup can't answer. Never raises. + ANTHROPIC_BASE_URL get the newest Opus the endpoint lists; + _PINNED_REVIEW_MODEL when the lookup can't answer. Never raises. """ - global _review_model_memo explicit = os.environ.get("SECURITY_REVIEW_MODEL", "").strip() if explicit: return explicit @@ -818,24 +868,36 @@ def default_review_model() -> str: return _CLI_OPUS_ALIAS if not HAS_API_CREDENTIALS: return _PINNED_REVIEW_MODEL - if _review_model_memo: - return _review_model_memo - try: - path = os.path.join(_resolve_state_dir(), _REVIEW_MODEL_CACHE_FILE) - # Hashed: a gateway URL can carry credentials. - endpoint_key = hashlib.sha256( - _anthropic_base_url().encode("utf-8") - ).hexdigest()[:16] - now = time.time() - hit, model = _read_review_model_cache(path, endpoint_key, now) - if not hit: - model = _fetch_newest_opus() - _write_review_model_cache(path, endpoint_key, model, now) - except Exception as e: - debug_log(f"review model resolution failed: {type(e).__name__}") - model = None - _review_model_memo = model or _PINNED_REVIEW_MODEL - return _review_model_memo + return _listed_models().get("opus") or _PINNED_REVIEW_MODEL + + +def retry_review_model() -> str: + """Model a review retries on when the default model's call fails: the CLI + alias through the Agent SDK, else the newest Sonnet the endpoint lists.""" + if _is_3p_provider() or _gateway_cli: + # Through the user's CLI, the alias gives the Sonnet id the user's own + # sessions use, including any ANTHROPIC_DEFAULT_SONNET_MODEL. + return _CLI_SONNET_ALIAS + if not HAS_API_CREDENTIALS: + return _PINNED_RETRY_MODEL + return _listed_models().get("sonnet") or _PINNED_RETRY_MODEL + + +def agentic_review_model() -> Tuple[str, bool]: + """(model, listed) for the agentic reviewer, which always runs through a + CLI. `listed` is True for the newest Opus the endpoint lists, named so that + a CLI that is out of date (the copy bundled with the Agent SDK is frozen + when the SDK is installed) still uses it. Otherwise the model is + SG_AGENTIC_MODEL, or the CLI alias where the plugin can't list models or + the user has told the CLI what `opus` means. Never raises.""" + explicit = os.environ.get("SG_AGENTIC_MODEL", "").strip() + if explicit: + return explicit, False + if (_is_3p_provider() or _gateway_cli or not HAS_API_CREDENTIALS + or os.environ.get("ANTHROPIC_DEFAULT_OPUS_MODEL", "").strip()): + return _CLI_OPUS_ALIAS, False + model = _listed_models().get("opus") + return (model, True) if model else (_CLI_OPUS_ALIAS, False) # A session signed in to a Claude apps gateway with /login gives hooks no @@ -1387,9 +1449,8 @@ def _call_claude_dual_or(prompt, output_schema, *, bool_key: str, list_key: str, explicit = os.environ.get("SECURITY_REVIEW_MODEL", "").strip() primary = default_review_model() - # Through the user's CLI, the alias gives the Sonnet id the user's own - # sessions use on the gateway, including any ANTHROPIC_DEFAULT_SONNET_MODEL. - fallback = "sonnet" if _gateway_cli else "claude-sonnet-4-6" + # Not looked up for a pinned model, which is never retried on another. + fallback = None if explicit else retry_review_model() if not _dual_or_enabled(): # Single-call path. Reuse the same sonnet-fallback retry as a dual_or @@ -2193,8 +2254,10 @@ def _agentic_review( return None, [], {"agentic_fallback": f"import:{type(e).__name__}"} _send_sdk_logs_to_debug_log() - # Overridable via SG_AGENTIC_MODEL. - model = os.environ.get("SG_AGENTIC_MODEL") or _CLI_OPUS_ALIAS + model, listed = agentic_review_model() + spawn_env = _agentic_spawn_env() + if listed and not os.environ.get("CLAUDE_CODE_EFFORT_LEVEL", "").strip(): + spawn_env["CLAUDE_CODE_EFFORT_LEVEL"] = _REVIEWER_EFFORT max_turns = int(os.environ.get("SG_AGENTIC_MAX_TURNS", "18")) # In production repo_dir is the user's working tree (full repo). Under the # eval harness it's a temp dir with ONLY touched_paths — the agent can't @@ -2288,10 +2351,8 @@ def _agentic_review( # # Identical --model/--fallback-model is rejected by the inner CLI # at startup ("Fallback model cannot be the same as the main - # model", exit 1 → ProcessError). The default model here IS - # _CLI_OPUS_ALIAS, so an unconditional fallback_model would - # kill every spawn before the first API call. Omit the fallback - # when it would equal the primary. + # model", exit 1 → ProcessError). The check compares the two + # strings, so a listed id may fall back to the alias. fallback_model=( _CLI_OPUS_ALIAS if model != _CLI_OPUS_ALIAS else None ), @@ -2316,7 +2377,7 @@ def _agentic_review( # versions. Clearing WEBSOCKET_AUTH_FILE_DESCRIPTOR alone lets # the review run end-to-end; the others are belt-and-suspenders # for the same fd-passing pattern. - env=_agentic_spawn_env(), + env=spawn_env, stderr=_on_child_stderr, ) n = 0 diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index d0c82f6c..fcd20a7f 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -145,7 +145,7 @@ import gitutil # noqa: E402 module ref for per-run counters import llm # noqa: E402 module ref for reassignable globals (_last_call_claude_http_error etc.) from llm import ( # noqa: E402,F401 ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, HAS_API_CREDENTIALS, - SECURITY_REVIEW_MODEL, CLAUDE_CODE_SYSTEM_PROMPT, + CLAUDE_CODE_SYSTEM_PROMPT, _last_call_claude_http_error, ensure_anthropic_reachable, _last_review_truncated_bytes, _auth_prefer_token, diff --git a/plugins/security-guidance/tests/test_base_url.py b/plugins/security-guidance/tests/test_base_url.py index 26317549..fa49067f 100644 --- a/plugins/security-guidance/tests/test_base_url.py +++ b/plugins/security-guidance/tests/test_base_url.py @@ -65,7 +65,7 @@ def test_requests_go_to_the_default_endpoint(monkeypatch, value): monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", True) monkeypatch.setattr(llm, "_urlopen", urlopen) assert llm._probe_anthropic() - llm._fetch_newest_opus() + llm._fetch_newest_models() llm._call_claude("prompt", {"type": "object"}, thinking_budget=0, model="claude-x") assert urls == [f"{DEFAULT}/", f"{DEFAULT}/v1/models?limit=100", f"{DEFAULT}/v1/messages"] diff --git a/plugins/security-guidance/tests/test_inflight_reviews.py b/plugins/security-guidance/tests/test_inflight_reviews.py index fa998501..3bc57087 100644 --- a/plugins/security-guidance/tests/test_inflight_reviews.py +++ b/plugins/security-guidance/tests/test_inflight_reviews.py @@ -461,8 +461,9 @@ def test_single_shot_after_a_fast_agentic_failure_ends_in_time( repo, _ = _repo_with_remote(tmp_path) _, commit_out = commit_file(repo, "handlers.py", "def h(x):\n return x\n") stub_api.delay = 6 + # The model is pinned so the stub's delay doesn't also hold up the model lookup. env = {**hook_env, "SG_AGENTIC_COMMIT_REVIEW": "1", "SG_AGENTIC_CLI_PATH": failing_inner_cli, - "SG_AGENTIC_RACE_DELAY_S": "60"} + "SG_AGENTIC_RACE_DELAY_S": "60", "SG_AGENTIC_MODEL": "opus"} took, r = _run_with_limit(bash_payload(repo, "git commit -m change", commit_out), env, 4) assert 4 <= took < 10, r.stderr assert r.returncode == 2 and "did not finish in time" in r.stderr diff --git a/plugins/security-guidance/tests/test_review_model.py b/plugins/security-guidance/tests/test_review_model.py index e290f35e..a2df7c71 100644 --- a/plugins/security-guidance/tests/test_review_model.py +++ b/plugins/security-guidance/tests/test_review_model.py @@ -64,7 +64,8 @@ def api(tmp_path, monkeypatch): ) threading.Thread(target=srv.serve_forever, daemon=True).start() for var in ("SECURITY_REVIEW_MODEL", "SG_AGENTIC_MODEL", "SG_DUAL_OR", - "CLAUDE_CODE_EXECPATH", "SG_AGENTIC_CLI_PATH", *llm._PROVIDER_ENV_VARS): + "CLAUDE_CODE_EXECPATH", "SG_AGENTIC_CLI_PATH", "ANTHROPIC_DEFAULT_OPUS_MODEL", + "CLAUDE_CODE_EFFORT_LEVEL", *llm._PROVIDER_ENV_VARS): monkeypatch.delenv(var, raising=False) monkeypatch.setenv("ANTHROPIC_BASE_URL", f"http://127.0.0.1:{srv.server_port}") monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state")) @@ -81,6 +82,10 @@ def api(tmp_path, monkeypatch): srv.shutdown() +def _newest_opus(ids): + return llm._newest_in_family(ids, "opus") + + def _new_process(monkeypatch): """Each hook fire is a fresh process: only the on-disk cache carries over.""" monkeypatch.setattr(llm, "_review_model_memo", None, raising=False) @@ -96,15 +101,15 @@ def _review(): class TestNewestOpus: def test_highest_version_wins_whatever_the_order(self): ids = ["claude-opus-4-7", "claude-opus-5-5", "claude-opus-5", "claude-opus-4-8"] - assert llm._newest_opus(ids) == "claude-opus-5-5" - assert llm._newest_opus(reversed(ids)) == "claude-opus-5-5" + assert _newest_opus(ids) == "claude-opus-5-5" + assert _newest_opus(reversed(ids)) == "claude-opus-5-5" def test_minor_version_compares_as_a_number(self): - assert llm._newest_opus(["claude-opus-5-9", "claude-opus-5-10"]) == "claude-opus-5-10" + assert _newest_opus(["claude-opus-5-9", "claude-opus-5-10"]) == "claude-opus-5-10" def test_snapshot_date_is_not_a_version(self): ids = ["claude-opus-4-20250514", "claude-opus-4-1-20250805", "claude-opus-4-5-20251101"] - assert llm._newest_opus(ids) == "claude-opus-4-5-20251101" + assert _newest_opus(ids) == "claude-opus-4-5-20251101" def test_other_families_and_malformed_ids_are_ignored(self): ids = [ @@ -112,10 +117,10 @@ class TestNewestOpus: "claude-opus-9-preview", "bedrock/claude-opus-9", "claude-opus-9 --flag", "us.anthropic.claude-opus-9", None, 7, "claude-opus-4-7", ] - assert llm._newest_opus(ids) == "claude-opus-4-7" + assert _newest_opus(ids) == "claude-opus-4-7" def test_no_opus_listed(self): - assert llm._newest_opus(["claude-sonnet-5-5", "gpt-x"]) is None + assert _newest_opus(["claude-sonnet-5-5", "gpt-x"]) is None class TestReviewRequestModel: @@ -322,22 +327,142 @@ def fake_sdk(monkeypatch): return spawned -class TestSdkPaths: - """Reviews that run through the Agent SDK name the CLI's own `opus` alias, - so the CLI that drives the model is the one that picks it.""" +class TestAgenticReviewer: + """The agentic reviewer always runs through a CLI, which may be far older + than the newest model, so it is told the model by name when it can be.""" - def test_agentic_review_defaults_to_the_cli_alias(self, api, fake_sdk, tmp_path): + def _run(self, tmp_path): llm.agentic_review(str(tmp_path), [("a.py", "+x = 1\n")], ["a.py"]) + + def test_uses_the_newest_opus_the_endpoint_lists(self, api, fake_sdk, tmp_path): + self._run(tmp_path) + assert fake_sdk[0]["model"] == "claude-opus-5-5" + assert fake_sdk[0]["fallback_model"] == "opus" + assert fake_sdk[0]["env"]["CLAUDE_CODE_EFFORT_LEVEL"] == "medium" + + def test_a_new_release_needs_no_change_to_the_plugin(self, api, fake_sdk, tmp_path): + api.models_body = _models("claude-opus-6", "claude-opus-5-5") + self._run(tmp_path) + assert fake_sdk[0]["model"] == "claude-opus-6" + + def test_shares_the_lookup_with_the_diff_review(self, api, fake_sdk, tmp_path): + llm.default_review_model() + self._run(tmp_path) + assert len(api.gets) == 1 + + def test_lookup_failure_leaves_the_choice_to_the_cli(self, api, fake_sdk, tmp_path): + api.models_status = 500 + self._run(tmp_path) assert fake_sdk[0]["model"] == "opus" assert fake_sdk[0]["fallback_model"] is None + assert "CLAUDE_CODE_EFFORT_LEVEL" not in fake_sdk[0]["env"] + + def test_truncated_listing_with_no_opus_leaves_the_choice_to_the_cli(self, api, fake_sdk, tmp_path): + api.models_body = {**_models("org-model-2", "org-model-1"), "has_more": True} + self._run(tmp_path) + assert fake_sdk[0]["model"] == "opus" + + def test_no_credentials_leaves_the_choice_to_the_cli(self, api, fake_sdk, tmp_path, monkeypatch): + monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", False) + self._run(tmp_path) + assert fake_sdk[0]["model"] == "opus" + assert api.gets == [] + + def test_users_opus_setting_is_kept(self, api, fake_sdk, tmp_path, monkeypatch): + monkeypatch.setenv("ANTHROPIC_DEFAULT_OPUS_MODEL", "my-opus") + self._run(tmp_path) + assert fake_sdk[0]["model"] == "opus" assert api.gets == [] - def test_agentic_review_override_falls_back_to_the_alias(self, api, fake_sdk, - tmp_path, monkeypatch): + @pytest.mark.parametrize("provider_var", [ + "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", + ]) + def test_3p_keeps_the_alias(self, api, fake_sdk, tmp_path, monkeypatch, provider_var): + monkeypatch.setenv(provider_var, "1") + self._run(tmp_path) + assert fake_sdk[0]["model"] == "opus" + assert "CLAUDE_CODE_EFFORT_LEVEL" not in fake_sdk[0]["env"] + assert api.gets == [] + + def test_users_effort_setting_is_kept(self, api, fake_sdk, tmp_path, monkeypatch): + monkeypatch.setenv("CLAUDE_CODE_EFFORT_LEVEL", "low") + self._run(tmp_path) + assert fake_sdk[0]["model"] == "claude-opus-5-5" + assert "CLAUDE_CODE_EFFORT_LEVEL" not in fake_sdk[0]["env"] + + def test_override_is_used_as_is(self, api, fake_sdk, tmp_path, monkeypatch): monkeypatch.setenv("SG_AGENTIC_MODEL", "claude-sonnet-5") - llm.agentic_review(str(tmp_path), [("a.py", "+x = 1\n")], ["a.py"]) + self._run(tmp_path) assert fake_sdk[0]["model"] == "claude-sonnet-5" assert fake_sdk[0]["fallback_model"] == "opus" + assert "CLAUDE_CODE_EFFORT_LEVEL" not in fake_sdk[0]["env"] + assert api.gets == [] + + +class TestRetryModel: + def _fail_first_post(self, api): + calls = [] + original = api.RequestHandlerClass.do_POST + def do_POST(handler): + calls.append(1) + if len(calls) == 1: + handler.rfile.read(int(handler.headers.get("Content-Length") or 0)) + return handler._send(400, {"type": "error"}) + return original(handler) + api.RequestHandlerClass.do_POST = do_POST + return lambda: setattr(api.RequestHandlerClass, "do_POST", original) + + def test_retry_uses_the_newest_sonnet_listed(self, api): + restore = self._fail_first_post(api) + try: + api.models_body = _models("claude-opus-5-5", "claude-sonnet-6", "claude-sonnet-5-5") + _review() + finally: + restore() + assert [p["model"] for p in api.posts] == ["claude-sonnet-6"] + + def test_listing_failure_gives_the_named_fallback(self, api): + api.models_status = 500 + assert llm.retry_review_model() == llm._PINNED_RETRY_MODEL + + @pytest.mark.parametrize("provider_var", [ + "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", + ]) + def test_3p_retry_uses_the_alias(self, api, monkeypatch, provider_var): + monkeypatch.setenv(provider_var, "1") + assert llm.retry_review_model() == "sonnet" + assert api.gets == [] + + def test_cache_from_an_older_version_is_looked_up_again(self, api, monkeypatch, tmp_path): + assert llm.default_review_model() == "claude-opus-5-5" + cache = tmp_path / "state" / llm._REVIEW_MODEL_CACHE_FILE + entry = json.loads(cache.read_text()) + del entry["sonnet"] + cache.write_text(json.dumps(entry)) + _new_process(monkeypatch) + assert llm.retry_review_model() == "claude-sonnet-5-5" + assert len(api.gets) == 2 + + def test_dated_first_release_gets_the_thinking_form_it_takes(self): + assert not llm._model_supports_adaptive_thinking("claude-sonnet-4-20250514") + assert llm._model_supports_adaptive_thinking("claude-sonnet-5-5") + + def test_non_ascii_digits_are_not_an_id(self): + assert llm._newest_in_family(["claude-sonnet-\u0665"], "sonnet") is None + + @pytest.mark.parametrize("value", ["claude-sonnet-9 --flag", "../x", "claude-opus-6", 7]) + def test_tampered_sonnet_entry_is_ignored(self, api, monkeypatch, tmp_path, value): + assert llm.default_review_model() == "claude-opus-5-5" + cache = tmp_path / "state" / llm._REVIEW_MODEL_CACHE_FILE + entry = json.loads(cache.read_text()) + entry["sonnet"] = value + cache.write_text(json.dumps(entry)) + _new_process(monkeypatch) + assert llm.retry_review_model() == llm._PINNED_RETRY_MODEL + + +class TestSdkPaths: + """Other reviews through the Agent SDK name the CLI's own `opus` alias.""" @pytest.mark.parametrize("provider_var", [ "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", |
