summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/hooks/llm.py
AgeCommit message (Collapse)Author
2026-11-09Merge pull request #7032 from anthropics/mhegazy/sg-refused-verdict-countMohamed Hegazy
security-guidance: count reviewer verdicts the CLI refused
2026-11-09Merge pull request #7031 from anthropics/mhegazy/sg-credential-routingMohamed Hegazy
security-guidance: send a claude.ai token as a bearer, hold back a gateway's
2026-11-07security-guidance: read blank and off variables as not set for the ↵mhegazy/sg-reviewer-oauth-tokenMohamed Hegazy
reviewer's token Co-authored-by: mhegazy <mhegazy@anthropic.com>
2026-11-07security-guidance: count reviewer verdicts the CLI refusedmhegazy/sg-refused-verdict-countMohamed Hegazy
Measure only, for #5746: one key on the commit and push review row when the reviewer's verdict was refused, and how many were wrapped in their own key. Co-authored-by: mhegazy <mhegazy@anthropic.com>
2026-11-07security-guidance: send a claude.ai token as a bearer, hold back a gateway'smhegazy/sg-credential-routingMohamed Hegazy
A claude.ai token that arrives as ANTHROPIC_API_KEY (from an apiKeyHelper) is refused by the API as a key; send it as a bearer. On hosts other than Claude Code, a bearer that is not a claude.ai token is not sent without a base URL. Other hosts' base URLs and cloud providers are left alone. Fixes #6955 Co-authored-by: mhegazy <mhegazy@anthropic.com>
2026-11-06Merge branch 'main' into mhegazy/sg-reviewer-oauth-tokenMohamed Hegazy
2026-11-05Merge main into mhegazy/sg-net-err-on-verdictmhegazy/sg-net-err-on-verdictClaude
Co-authored-by: mhegazy <mhegazy@anthropic.com>
2026-11-05Merge pull request #6965 from anthropics/mhegazy/sg-agentic-stop-on-authMohamed Hegazy
security-guidance: stop the commit reviewer on refused credentials, end hung reviews in time
2026-11-05Merge pull request #6627 from anthropics/mhegazy/sg-review-sessions-not-savedMohamed Hegazy
security-guidance: do not save review runs as session transcripts
2026-11-05Merge pull request #6930 from anthropics/fix/sg-blank-base-urlMohamed Hegazy
security-guidance: treat a blank ANTHROPIC_BASE_URL as unset
2026-11-05Merge pull request #6999 from anthropics/mhegazy/sg-windows-cli-pathMohamed Hegazy
security-guidance: on Windows, name the CLI for the Agent SDK by its full path
2026-11-05security-guidance: keep the native install in sessions started above the ↵mhegazy/sg-windows-cli-pathMohamed Hegazy
home folder Co-authored-by: mhegazy <mhegazy@anthropic.com>
2026-11-04security-guidance: end a commit or push review's single-shot review at the ↵mhegazy/sg-agentic-stop-on-authMohamed Hegazy
hook's time limit A single-shot review that follows a fast agentic failure, or runs with the agentic review off, had no deadline: with no answer it ran 739 s, past Claude Code's 600 s kill, so the session heard nothing. It now ends at 570 s into the hook with the usual notice. The limit counts from hook start, so a push review's wait and the work before the review count. Failed push rows keep inflight_wait_s, and CLAUDE_CODE_REMOTE is read the same way in both places. Co-authored-by: mhegazy <mhegazy@anthropic.com>
2026-11-04security-guidance: keep the state folder to its usermhegazy/sg-state-dir-owner-onlyMohamed Hegazy
Create ~/.claude/security with mode 0700 from every place that makes it, and narrow the default folder on the next run, so a umask such as 002 does not leave the reviewer's venv group-writable. The in-place state write replaces a link instead of following it, and creates a 0600 file. Co-authored-by: mhegazy <mhegazy@anthropic.com>
2026-11-04security-guidance: on Windows, name the CLI for the Agent SDK by its full pathMohamed Hegazy
On Windows the plugin named no CLI for the Agent SDK unless SG_AGENTIC_CLI_PATH was set, so the SDK chose one. With none named, the plugin now chooses there itself and passes a full path: the CLI bundled with the SDK, else the claude.exe in the native installer's folder, else a claude.exe on PATH. When there is none, it passes the bundled path and the start fails. Folders that are not given as full paths are skipped, and so are the working directory, the project root and folders inside them. The macOS and Linux install paths are no longer probed on Windows. The hooks also set NoDefaultCurrentDirectoryInExePath on Windows when it is absent. Co-authored-by: mhegazy <mhegazy@anthropic.com>
2026-11-04security-guidance: clear net_err when a review gets throughMohamed Hegazy
A failed first probe, a lost race fallback or a failed dual leg left its class (and api_error) on the row of a review that got a verdict.
2026-10-31security-guidance: stop the commit reviewer on refused credentials, end hung ↵Mohamed Hegazy
reviews in time
2026-10-28security-guidance: treat a blank ANTHROPIC_BASE_URL as unsetfix/sg-blank-base-urlMohamed Hegazy
A set but empty value left the request URL as /v1/messages, so urllib raised and every Stop, push and single-shot commit review failed. The SDK and Claude Code read a blank value as the default endpoint; the plugin now does too.
2026-10-27Merge branch 'main' into mhegazy/sg-review-sessions-not-savedmhegazy/sg-review-sessions-not-savedMohamed Hegazy
2026-10-27security-guidance: keep the token where the OAuth variable does not fitMohamed Hegazy
A custom base URL, bare mode and cloud sessions keep ANTHROPIC_AUTH_TOKEN.
2026-10-27security-guidance: hand the reviewer a claude.ai token as its OAuth tokenMohamed Hegazy
As ANTHROPIC_AUTH_TOKEN the inner CLI still renews a stored login it does not run on, which can sign the user out. As CLAUDE_CODE_OAUTH_TOKEN it leaves the stored login alone. Cache writes stay at five minutes.
2026-10-26Merge remote-tracking branch 'origin/main' into HEADmhegazy/sg-reviewer-stage-metricsClaude
2026-10-26security-guidance: report how many turns and how much model time a commit ↵Mohamed Hegazy
review took review_ms says how long an agentic commit review took but not why. Add one count-only key, rv_effort, on rows where the agentic reviewer ran: the turns it took and the time it spent waiting on the model, summed over all stages and packed as turns * 10,000,000 + model ms. It is emitted after every other key, so it never displaces one at the metric key cap. No behaviour change.
2026-10-22Merge branch 'main' into mhegazy/sg-review-sessions-not-savedMohamed Hegazy
2026-10-22Merge branch 'main' into mhegazy/sg-network-failure-classMohamed Hegazy
2026-10-21security-guidance: reviews run when the Windows certificate store has an ↵Claude
unreadable entry Older Python releases load each Windows certificate store in one call, so one certificate OpenSSL cannot parse makes the default TLS context fail to build and every review call fails before a request is sent. When that happens the plugin's API calls now use a default context built from the store entries that do parse. Verification of the chain and the host name is unchanged. Review rows carry tls_store_skipped (a count) when this route is in use.
2026-10-20security-guidance: report why a review call got no HTTP responseMohamed Hegazy
A review call that never gets an HTTP response is reported as api_error -1 whatever the cause, so a certificate failure, a refused connection and a timeout look the same. Rows whose last call failed that way now carry a count-only net_err key: the failure class, the TLS verify code, and whether CA files, a proxy or TLS variables are in play. No behaviour change.
2026-10-20Merge branch 'main' into mhegazy/sg-review-sessions-not-savedMohamed Hegazy
The inner CLI retry on main (a start refused over --strict-mcp-config) now also covers a CLI that does not know --no-session-persistence, so one helper handles either refused flag, or both on the same start.
2026-10-20Merge branch 'mhegazy/sg-gateway-login' into mhegazy/sg-sdk-bootstrap-switchesClaude
Resolves the overlap with the bootstrap working-directory change and the gateway sign-in route: the import probe keeps the state-dir working directory, and llm.py keeps both imports.
2026-10-19security-guidance: keep a turn's review when the gateway sign-in check gives ↵Mohamed Hegazy
no answer When `claude auth status` gives no usable answer, the Stop hook skipped the review and dropped the turn's changes, so they were never reviewed even once the check answered. They are now kept for the next Stop review, as for other transient skips. A gateway review that runs out of time is no longer tried again on Sonnet: what makes it do so (a rejected sign-in, an unreachable gateway) does not depend on the model, and the second attempt doubled the wait. The timeout's log line now says which API statuses the CLI retried, and includes the CLI's stderr. The new tests no longer share one state file across sessions when run inside a remote session.
2026-10-19security-guidance: review through Claude Code in a Claude apps gateway sign-inMohamed Hegazy
In a Claude Code session signed in to a Claude apps gateway with /login, Claude Code gives plugin hooks no credential, so the Stop, commit, push and agentic commit reviews were all skipped. When the plugin has no credential of its own, it now asks the user's installed claude (`claude auth status --json`) whether the session is signed in to a gateway. A yes or no is kept for the session; when the CLI gives no usable answer, the next hook asks again. If apiProvider is "gateway" and loggedIn is true, the reviews run through that same CLI, which restores the stored sign-in by itself, so no credential enters the plugin. A review the CLI cannot complete counts as a failed review, never a clean one. The reviews run even with CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC set, as they do on Bedrock and Vertex: the gateway docs suggest setting it, and the review goes through the gateway like the session's own requests. The CLI is found the way the agentic reviewer already finds it: SG_AGENTIC_CLI_PATH, CLAUDE_CODE_EXECPATH, then fixed install paths, with no PATH search, and it must be a full path. The reviews use Claude Code's opus and sonnet aliases, which resolve to the ids Claude Code itself uses on a gateway, and get the 120 s a direct review gets. Review rows set bit 4 of gateway_cfg, so this route's failure rate can be read apart from first-party reviews. Every Claude Code the plugin starts for a review, on any provider, now runs with SECURITY_GUIDANCE_DISABLE=1. If policy settings enable the plugin inside that CLI, its hooks there don't start reviews of their own. The weekly notice that the reviews are not running is no longer shown in a session signed in to a gateway, since the reviews do run there. The edit that would show it asks claude first, and the notice marker is written either way, so that edit waits for claude at most once a week. Sessions the gateway route cannot review still get the notice, unless, in the past week, an edit's check found a session signed in to a gateway. Their skipped reviews still report no_creds.
2026-10-19security-guidance: run reviews on machines with a managed MCP configmhegazy/sg-reviewer-managed-mcpMohamed Hegazy
Since 2.0.14 the plugin starts the reviewing Claude Code with --strict-mcp-config. Claude Code exits at startup with that flag on a machine whose administrator delivers the MCP servers (managed-mcp.json), so the agentic commit review always fell back to the single-shot review, and reviews that only run through Claude Code (Bedrock, Vertex) failed. When the inner CLI refuses the flag, the plugin now starts it once more without it, and leaves it out for the rest of the hook process. Those starts deny every MCP tool (--disallowedTools "mcp__*") instead, so the reviewer still gets only its read tools. Review rows from such a process carry strict_mcp_off: 1.
2026-10-19security-guidance: do not install the agent SDK for reviews that are offMohamed Hegazy
The SessionStart bootstrap and its PostToolUse rescue built a venv of a few hundred MB for the agent SDK whatever the environment said, including under SECURITY_GUIDANCE_DISABLE=1, and the rescue started the bootstrap again every five minutes on machines whose SDK lives in that venv (#5331). - Nothing is installed when the environment turns off every review that loads the SDK: the kill switch, ENABLE_CODE_SECURITY_REVIEW=0, or ENABLE_STOP_REVIEW=0 with ENABLE_COMMIT_REVIEW=0. Reported as sdk_bootstrap 10. A disabled plugin also no longer shows the "reviewer unavailable" notice on a Python below 3.10. - The rescue leaves a finished install under the state dir alone instead of starting the bootstrap for it every five minutes. - New counts on the bootstrap's metrics row, set only when true and only when the install exists: sdk_no_creds and sdk_no_git (the session cannot run the reviews the install serves), sdk_venv_py (the venv was built by another Python version than the one running the hooks, #5706). They size follow-up changes; no behaviour depends on them. With the reviews on, what is built and when is unchanged.
2026-10-19security-guidance: do not save review runs as session transcriptsMohamed Hegazy
The agentic commit reviewer and reviews on 3rd-party providers run an inner Claude Code through the Agent SDK, which saved each run as a session transcript holding the review prompt and diff. Start it with --no-session-persistence; SECURITY_GUIDANCE_PERSIST_SESSIONS=1 keeps the transcripts. An inner CLI that predates the flag is run again without it.
2026-10-15Merge pull request #6593 from anthropics/mhegazy/sg-reviewer-context-telemetryMohamed Hegazy
security-guidance: report commit reviewer context in review telemetry
2026-10-15security-guidance: report commit reviewer context in review telemetrymhegazy/sg-reviewer-context-telemetryMohamed Hegazy
Count-only keys on agentic review rows: Read/Grep/Glob calls made, how many came back as errors, and whether the reviewer's directory was missing before or during the review. Appended last in the row so they never displace an existing key.
2026-10-15security-guidance: give the commit reviewer only read toolsmhegazy/sg-reviewer-read-only-toolsMohamed Hegazy
allowed_tools only pre-approves tools, so the inner Claude Code that runs a review was still offered the shell, file edits, web access and subagents. Pass the exact tool list instead: Read, Grep and Glob for the commit reviewer, none for the single-turn review.
2026-10-14security-guidance: report gateway routing and inner CLI stderr in review ↵mhegazy/sg-review-telemetryMohamed Hegazy
telemetry Review rows gain two diagnostic keys, appended last so they never displace an existing key: - gateway_cfg: 1 when ANTHROPIC_BASE_URL names a host other than api.anthropic.com, 2 when ANTHROPIC_CUSTOM_HEADERS lines are sent, 3 for both. A number only: no host, header name or value. - child_stderr: lines the inner CLI wrote to stderr during a commit or push review.
2026-10-13security-guidance: deliver commit and push findings on stderr (#6379)Mohamed Hegazy
Commit and push findings went only into hookSpecificOutput.additionalContext, which Claude Code's asyncRewake path never reads: it shows Claude stderr, or stdout when stderr is empty. When the agentic reviewer's inner CLI printed a warning to stderr, Claude got that warning instead of the findings (anthropics/claude-code#99839, also anthropics/claude-code#92987). Findings now go to stderr for every event, as the Stop path already did. The inner CLI's stderr and the Agent SDK's own log lines go to the plugin's debug log.
2026-10-13Merge pull request #6378 from anthropics/mhegazy/sg-gateway-headersMohamed Hegazy
security-guidance: send ANTHROPIC_CUSTOM_HEADERS on the plugin's own API calls
2026-10-09security-guidance: never report a failed review as cleanmhegazy/sg-review-failuresMohamed Hegazy
When a commit review got no verdict (an API error, an unexpected error in the call, or a reply that could not be read) it was logged as "no security issues found" and the commit was marked reviewed, so the push review skipped it (anthropics/claude-code#99840, also anthropics/claude-code#81057). - A commit whose review got no verdict is not marked reviewed, so a later push review from Claude Code still checks it, unless the same command pushed it. A failed push review does not mark its range either. - Claude is told once per session for each kind of review and failure. Later failures of the same kind are only logged. - In the agentic race, a single-shot fallback with no verdict no longer wins while the agentic review can still answer, the fallback no longer starts after the agentic review has answered, and it never runs twice. - The Stop and SubagentStop reviews use the same signal, so an unreadable reply no longer records a subagent's diff as reviewed.
2026-10-09security-guidance: send ANTHROPIC_CUSTOM_HEADERS on the plugin's own API callsmhegazy/sg-gateway-headersMohamed Hegazy
The plugin's own API calls (the /v1/models lookup and the review itself) never sent ANTHROPIC_CUSTOM_HEADERS, so a gateway that takes its key in a custom header answered 401 and reviews never ran (anthropics/claude-code#99857). The headers are now parsed the way Claude Code parses them (one `Name: Value` per line, split at the first colon) and sent on every call. A custom line replaces a header of the same name. anthropic-beta lines are not forwarded: the review needs none of the user's betas.
2026-10-09security-guidance: enable prompt caching for review requestsoct/sg-prompt-cacheOctavian Guzu
2026-10-02security-guidance: follow the newest Opus instead of a pinned release (2.0.8 ↵mhegazy/sg-track-latest-opusMohamed Hegazy
→ 2.0.9) The review model was hardcoded to claude-opus-4-7, so the plugin fell behind each time a new Opus shipped. - The diff review asks the configured endpoint (GET /v1/models) for the newest Opus it serves, cached for a day; claude-opus-5-5 if it can't say. - The agentic commit review, and every review on Bedrock, Vertex and Foundry, use Claude Code's `opus` alias. - SECURITY_REVIEW_MODEL and SG_AGENTIC_MODEL still pin a model. - Adds pricing rows for the newer Opus models, and tests. Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-09-09Harden git invocation and repository hint handlingsg-resolve-repo-rootOctavian Guzu
:house: Remote-Dev: homespace
2026-06-11security-guidance: pip --target fallback when venv can't bootstrap pip ↵venv-target-fallbackMohamed Hegazy
(2.0.4 → 2.0.5) Option A, the data-gated fix for venv_ensurepip_fail (#2154 follow-up). v2.0.4 telemetry made the call: of the venv_ensurepip_fail cohort, ~95% HAVE pip (sdk_has_pip=true) and run Python 3.11–3.14 — so it's not the Apple-3.9 problem; it's modern interpreters where `python -m venv` can't bootstrap pip (Debian python3-venv absent, or python.org/pyenv builds without ensurepip) but pip itself works. `pip install --target` needs only pip, so it recovers the agentic reviewer for them instead of degrading to pattern + single-shot review. Producer (ensure_agent_sdk.py): - New outcomes BUILT_TARGET=7, NOOP_TARGET=8; new phase pip_target=5. - _build_via_target(): `pip install --target <state>/agent-sdk-libs --upgrade --prefer-binary claude-agent-sdk`. Failures categorized via _pip_err_from_stderr (sibling of main()'s pip chain — kept separate to avoid disturbing the working venv categorizer); errno embedded for OSError-family exceptions. - _target_sdk_importable(): probes a prior target install → NOOP_TARGET. Dir-check short-circuits before any subprocess, and it's only reached when there's no working venv, so the 81% NOOP_VENV cohort never pays. - main() falls through to the target build ONLY on venv_ensurepip_fail; every other venv/pip failure stays terminal BUILD_FAILED. The sentinel is released before the target build so a retry isn't seen as SKIP_SENTINEL. Consumer (llm.py): - _inject_agent_sdk_venv_into_syspath() adds the flat agent-sdk-libs dir (packages sit directly in it, not under site-packages). The existing pywin32 .pth bootstrap applies (target installs don't run .pth either). No change to the happy path — the new branch is taken only on the ensurepip failure, and the extra candidate dir is a no-op when absent. Verified locally on macOS Python 3.13: - py_compile clean. - 30 new tests (test_venv_target_fallback.py): outcome/phase codes (append-only, 4 stays retired), _pip_err_from_stderr categories, _build_via_target success/CalledProcessError/timeout/exc+errno (mocked subprocess), _target_sdk_importable dir-short-circuit, main() wiring (ensurepip→target fallthrough + NOOP_TARGET probe + sentinel release), consumer adds the flat dir. Full suite 533/533 pass + 2 skipped. - END-TO-END harness (real install, simulated ensurepip failure): main() → BUILT_TARGET, target dir has claude_agent_sdk; 2nd run → NOOP_TARGET; consumer _inject → `import claude_agent_sdk` resolves FROM the --target dir. Full chain proven without needing a broken-ensurepip box. - Real `pip install --target` + import confirmed independently (exit 0, SDK imports from the flat layout). NOT validated in tmux: the ensurepip failure can't be reproduced on macOS (working ensurepip), so the fallback was proven via the real-install harness above instead. The happy path (NOOP_VENV / normal agentic review) is unchanged and covered by the existing hook-smoke suite. Version 2.0.4 -> 2.0.5 per the per-PR-bump policy (#2114). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-31security-guidance: emit HTTP error codes + fix sdk_bootstrap phase/err encodingtelemetry-failure-signalsMohamed Hegazy
Fills two failure-visibility gaps in plugin telemetry. ## Gap 1: HTTP errors from _call_claude invisible Before: a 4xx/5xx response from the LLM API caused `_call_claude` to return None and produce ZERO fingerprint in tengu_hook_plugin_metrics. A failed call looked identical to "no review needed". The recent deprecation-400 outage (PR #2105, output_format → output_config.format, #2098) was invisible in aggregate dashboards until a user manually reported errors from their debug log. Cohort-specific or partial outages would never show up in BQ. Fix: add `http_err_last` (most recent status) and `http_err_count` to the existing `_USAGE` accumulator in `_base.py`. `_usage_metrics()` snapshots them whenever count > 0 (skip-path no-pollute contract preserved when count == 0). All `_call_claude` error sites now call the new `_record_http_error()` helper alongside the existing `_last_call_claude_http_error` module-state assignment. Now any future API failure category is queryable in BQ in real time: SELECT DATE(server_timestamp, "America/Los_Angeles") AS d, CAST(JSON_VALUE(additional_metadata, "$.http_err_last") AS INT64) AS code, COUNT(*) AS n FROM ... WHERE event_name = "tengu_hook_plugin_metrics" AND JSON_VALUE(additional_metadata, "$.pluginId") LIKE "%security-guidance%" AND JSON_VALUE(additional_metadata, "$.http_err_count") IS NOT NULL GROUP BY d, code ORDER BY d, n DESC ## Gap 2: sdk_bootstrap_phase / sdk_bootstrap_err always NULL in BQ Before: ensure_agent_sdk.py emitted these as strings (e.g. "pip", "dns_fail"). CC's plugin-metrics pipeline silently drops plugin-emitted string values — only bool|finite-number plugin metrics reach BigQuery. (CC-core fields like `subscription_type` are exempt because they're injected downstream of plugin validation.) Confirmed empirically: ~185K BUILD_FAILED rows in BQ over the past 2 days had `sdk_bootstrap_phase` = NULL and `sdk_bootstrap_err` = NULL despite the Python code emitting them. ~28K BUILD_FAILED sessions/day had no diagnostic split — flying blind on whether the failures are pip-no-match vs dns-fail vs ssl-verify vs proxy-auth etc. Fix: encode phase + err_kind as stable integers via SDK_BOOTSTRAP_PHASE_CODES and SDK_BOOTSTRAP_ERR_CODES. Phase: 1=pre, 2=venv, 3=pip, 4=main. Err: 10 known categories (1-10), 11-98 reserved, 99 = uncategorized catch-all (covers "exc:<X>", "other:<X>", and unmapped strings). APPEND-ONLY for telemetry stability. Also corrects the misleading "CC accepts string metric values" comment in ensure_agent_sdk.py that led to the bug originally. Verified locally on macOS Python 3.13: - py_compile clean. - 32 new tests in test_telemetry_failure_signals.py (added to internal test suite at sg-staging/tests/, not in this PR): * 4 HTTP-error tracking unit tests: _record_http_error increments count + tracks most-recent; handles None/invalid; -1 for network/timeout. * 4 _usage_metrics emission tests: empty when no activity; successful call has no http_err fields; failure-only has http_err and no api_calls; mixed has both. * 1 contract test: every emitted value is bool|finite-number (catches future regression of the string-dropping bug class). * 13 sdk_bootstrap encoding tests (parametrized over the 10 known err_kind categories + 5 catch-all shapes): each maps to the right integer; unknown phase = 0; unknown err = 99. * 1 static-shape regression catcher: every `err_kind = "..."` string in ensure_agent_sdk.main() must be in SDK_BOOTSTRAP_ERR_CODES (otherwise new err_kinds silently collapse to 99). * 2 emit-shape regression catchers: the assignments in main() go through _encode_phase / _encode_err_kind helpers (no raw strings); no literal string values for sdk_bootstrap_phase/err. * 1 comment-accuracy: the misleading "CC accepts string metric values" comment is gone. - Full suite: 437/437 pass + 2 skipped (live API tests, opt-in). NOT verified end-to-end against BQ — would require shipping + observing in production for 24h to confirm the http_err and sdk_bootstrap_phase/err fields actually appear in tengu_hook_plugin_metrics rows. The unit tests pin the contract; if the wire shape is broken, BQ will show NULL for the new fields and we revisit (with the same diagnostic the BUILD_FAILED bug gave us). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-30security-guidance: migrate from deprecated output_format to ↵fix-2098-output-config-formatMohamed Hegazy
output_config.format (#2098) Fixes #2098. The Anthropic Messages API moved structured-output schema specification from a top-level `output_format` field to a nested `output_config.format` field, per https://platform.claude.com/docs/en/build-with-claude/structured-outputs. Per docs the old form "will continue working for a transition period" — and indeed for api-key + non-streaming auth it still returns HTTP 200 (verified via live API). But OAuth Bearer users with CLI 2.1.158 hit `invalid_request_error: output_format: This field is deprecated. Use 'output_config.format' instead.` consistently — reporter saw 462 errors in one day. The trigger appears to be auth mode + possibly stream:true (their controlled curl bypass used Bearer + stream=true); api-key + non-streaming was my initial repro attempt and didn't fire. The bug only affected `_call_claude` (the legacy direct-urllib path). The agentic `_agentic_review` path goes through claude_agent_sdk → subprocesses to the `claude` CLI binary, which already uses the new `output_config.format` shape correctly (per src/utils/sideQuery.ts:263 in claude-cli-internal). So this PR only needs to fix the plugin's direct HTTP path. This commit: 1. llm.py: rewrite the payload literal in `_call_claude` to use `output_config: { format: { type: 'json_schema', schema: ... } }` instead of top-level `output_format`. 2. llm.py: in the adaptive-thinking branch, MERGE `effort: "high"` into the existing `output_config` dict instead of reassigning. Reassignment would silently clobber the format schema set in (1). The pre-existing code did `payload["output_config"] = {"effort": "high"}` which was correct WHEN output_format was top-level (and output_config wasn't otherwise used). With the migration the existing dict carries the schema, so we extend it not replace it. Verified locally on macOS Python 3.13: - py_compile clean. - Existing 401 tests still pass — 0 regression. - 6 new tests in test_2098_output_config_format.py (added to internal test suite at sg-staging/tests/, not in this PR): * 2 static-shape: the `_call_claude` source no longer contains top-level `"output_format":` AND uses `output_config`. The adaptive-thinking branch does NOT reassign output_config (and DOES set output_config['effort']). Catches the regression class where a future refactor reintroduces either bug. * 2 payload-shape unit (mocked urllib): both thinking_budget=0 and thinking_budget>0+adaptive code paths produce a payload with the correct `output_config.format` shape AND no `output_format` top-level. The adaptive path verifies both `format` and `effort` coexist in output_config (i.e., the merge fix works). * 2 live-API gating (skip-on-no-key): the new shape returns HTTP 200 against api.anthropic.com; the old shape's current status is recorded for canary purposes (still 200 for api-key today, but reporter shows it's 400 for OAuth). - Full suite: 405/405 pass + 2 skipped (live API tests, opt-in). - The reporter's exact deprecation 400 message reproduces if you swap auth to OAuth Bearer + stream:true (could not test locally without extracting the keychain OAuth token, which was out of scope). The fix shape is API-contract-level so it doesn't depend on which auth mode triggers the 400. NOT verified end-to-end via OAuth-authenticated plugin invocation on my machine (auto-mode classifier correctly declined to extract the keychain token). Reporter's 462 production errors + the docs migration notice + the live-API HTTP 200 on the new form are sufficient evidence to ship. Closes #2098. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28security-guidance: respect CLAUDE_CONFIG_DIR for plugin state files (#1868)fix-1868-claude-config-dirMohamed Hegazy
Fixes #1868 — when CLAUDE_CONFIG_DIR is set to a non-default location (e.g. ~/.config/claude for XDG compliance, or a multi-tenant install path), the plugin still wrote state files to the hardcoded ~/.claude/ path, leaving stale state and breaking CLAUDE_CONFIG_DIR's purpose. Resolution precedence (highest first): 1. SECURITY_WARNINGS_STATE_DIR — plugin-specific override (existing) 2. CLAUDE_CONFIG_DIR/security — CC's config-dir env (new — #1868) 3. ~/.claude/security — default fallback (unchanged) Empty-string env vars (e.g. CLAUDE_CONFIG_DIR= in a misconfigured shell) are treated as not-set so the empty path doesn't collide with os.path.join and silently write to /security at the filesystem root. Implementation: a single state_dir() helper in _base.py is the source of truth for resolution. All five modules that previously had inline SECURITY_WARNINGS_STATE_DIR / ~/.claude/security resolutions (_base.py, session_state.py, ensure_agent_sdk.py, llm.py, and one site in security_reminder_hook.py) now call state_dir() instead. Re-implementing the precedence inline risks drift — one module gets a future fix, others don't. The helper is called per-invocation rather than cached at import time so test monkeypatches of the env vars take effect, and so a long- running test or future shared-process scenario can change the env between calls and have the next call observe the new value. The per-call cost is negligible compared to the subprocess-spawn cost the hooks pay every fire in production. Three hardcoded ~/.claude/security strings remain but are NOT functional resolutions: - _base.py:39: the fallback BRANCH inside state_dir() itself - ensure_agent_sdk.py:6, :11: docstring text describing default location for users Verified locally on macOS Python 3.13: - py_compile clean on all 5 modified files. - Existing 45 smoke + extensibility tests still pass. - 14 new tests in test_claude_config_dir.py (added to internal test suite at sg-staging/tests/, not in this PR): * 7 resolution-semantics: default fallback, CLAUDE_CONFIG_DIR override, SECURITY_WARNINGS_STATE_DIR beats both, tilde expansion, empty-string handling (CLAUDE_CONFIG_DIR= must fall back, NOT join to /security). * 4 static-shape: each of session_state / ensure_agent_sdk / llm / security_reminder_hook either imports state_dir from _base OR has zero resolution patterns. Catches the regression where someone adds a new state-file writer and re-implements resolution inline, missing the CLAUDE_CONFIG_DIR branch. * 3 end-to-end: with CLAUDE_CONFIG_DIR set, get_state_file / get_lock_file return paths under <CLAUDE_CONFIG_DIR>/security/; save_state round-trip writes a file to the redirected path and re-reads the same contents. - 59/59 pass total (45 existing + 14 new) in 2.54s. NOT verified end-to-end with a real CC instance setting CLAUDE_CONFIG_DIR. The shape tests catch the regression class (hardcoded ~/.claude/), and the end-to-end test pins the behavior that user state files actually land at the redirected path. Closes #1868. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27Address Windows verification: --prefer-binary + pywin32 bootstrapfix-windows-agentic-reviewerMohamed Hegazy
The first round of this PR removed SKIP_WIN32, fixed venv_py to use Scripts/python.exe, and added Lib/site-packages to the consumer glob — all necessary. Windows verification (Win11 ARM64, Py 3.13, Git Bash) showed two more blockers, both addressed here. 1. Pip dependency resolver picks unbuildable cryptography on ARM64. Without --prefer-binary, pip picks a cryptography version with no published ARM64 wheel and tries to build it from source. That needs Rust/Cargo, almost never present on user machines → BUILD_FAILED with err_kind=other:cryptography. A binary wheel exists for an adjacent version (cryptography-46.0.3-cp311-abi3-win_arm64.whl); --prefer-binary tells pip to pick it. Cross-platform safe (no-op where the latest version already has a wheel). 2. pywin32 .pth files aren't processed by sys.path.insert(). With the venv built, ensure_agent_sdk.py's post-build probe passes (it runs from venv_py, where Python's site.py at startup processes pywin32.pth and registers win32/, win32/lib/ plus runs pywin32_bootstrap.py to set the DLL search dir). But llm.py runs in the hook's SYSTEM Python and adds the venv via sys.path.insert(), which doesn't trigger site.py at all. Without the bootstrap, the SDK's mcp.client.stdio → mcp.os.win32.utilities chain raises ModuleNotFoundError: pywintypes and the agentic reviewer falls back to single-shot silently — exactly the symptom this PR is trying to fix. The probe says NOOP_VENV; the actual consumer fails. Probe and consumer use different Pythons. Replicate what site.py would do: after inserting site-packages, also insert win32/ and win32/lib/, then exec pywin32_bootstrap.py. Pulled into a shared helper _inject_agent_sdk_venv_into_syspath() so both consumer sites (3P SDK fallback, agentic_review fallback) call the same code — Windows handling stays in one place. Verified on macOS (POSIX path unchanged): - Helper end-to-end test: POSIX-layout venv detected + fake package imports successfully via the injected path - Windows-layout venv also detected; win32 branch correctly skipped via sys.platform check - Both files pass py_compile Credit: @mhegazy verified the previous commit on Win11 ARM64 / Py 3.13 / Git Bash, surfaced both issues end-to-end, and provided the exact fix patterns. This commit applies them with the pywin32 part factored into a shared helper (vs. inlining at both consumer sites). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>