summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/hooks/_base.py
AgeCommit message (Collapse)Author
2026-11-06Merge pull request #6997 from anthropics/mhegazy/sg-net-err-on-verdictMohamed Hegazy
security-guidance: clear net_err when a review gets through
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 main into mhegazy/sg-interp-reparse-telemetrymhegazy
Both sides add a metric after the launcher probe timings on the SessionStart row; keep launcher_direct, then interp_reparse as the last key.
2026-11-05Merge pull request #6918 from anthropics/mhegazy/sg-launcher-alias-real-pathMohamed Hegazy
security-guidance: stop starting the packaged Python alias on every hook
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-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-27security-guidance: count Windows sessions whose Python is behind a linkmhegazy
Measurement only. On Windows the SessionStart row gains one key, interp_reparse, saying whether the interpreter that runs the hooks is reached through a symbolic link or junction: 1 executable path, 2 standard library path, 4 that path is under AppData, 8 could not be checked; 0 when neither is. Inside the packaged Claude Desktop app Windows leaks kernel memory on every file opened through such a link under AppData (a uv-managed Python is one), and every hook starts an interpreter. This sizes how many users that is. See anthropics/claude-code#96870. No process is started, no hook behaves differently, and no other row changes. The key is the last one of its row, so it never displaces another.
2026-10-27security-guidance: stop starting the packaged Python alias on every hookmhegazy/sg-launcher-alias-real-pathmhegazy
On Windows with the Python Install Manager, python, python3 and py are packaged aliases under ...\Microsoft\WindowsApps, and each start of one makes Windows run an App Installer update check for the package. The launcher started the chosen alias twice per hook (probe, then the hook), on every Edit, prompt and Stop. See anthropics/claude-code#98929. When the name that answers is such an alias and its interpreter is a regular python*.exe elsewhere, the launcher now checks that interpreter once (same version, reads the hook script when started by itself), runs the hook with it, and keeps its path in the state folder for a day. Later hooks start it directly: one process, none through the alias. The remembered path is used only while PATH and the hook folder are unchanged and the file is still there. A hook that fails on it empties the entry so the next hook searches again. Not used while VIRTUAL_ENV is set. Other systems, regular installs and Microsoft Store Python are unchanged. Hooks report launcher_direct (1 remembered, 2 just checked) as the last metric key on rows they already send.
2026-10-22Merge branch 'main' into mhegazy/sg-network-failure-classMohamed Hegazy
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-launcher-probe-timingmhegazy/sg-launcher-probe-timingClaude
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: run SDK bootstrap subprocesses from the state dirmhegazy/sg-bootstrap-spawn-cwdMohamed Hegazy
`python -c` and `python -m` put the working directory first on the import path, and hooks run in the user's repository. A repository file named claude_agent_sdk.py, venv.py or pip.py was imported in place of the real module by the SessionStart check and the venv build. Run those subprocesses from the plugin's state dir, and make state_dir() return an absolute path as its docstring says, so a relative override isn't resolved twice.
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: report how long the launcher waits for interpreter probesMohamed Hegazy
sg-python.sh asks each candidate interpreter for its version before running a hook, and waits as long as that takes. Nothing recorded how long. The launcher now times each probe with bash builtins (no extra process) and passes the result to the hook, which reports two keys when the probes of one launch took a second or more together: - launcher_probe_ms: all probes of this launch - launcher_probe_max_ms: the slowest one The keys go last on a row, so they never displace an existing key. Measurement only: the launcher still waits for every probe and picks the same interpreter.
2026-10-15Merge pull request #6589 from anthropics/mhegazy/sg-review-cost-logMohamed Hegazy
security-guidance: log each review's token use and estimated cost
2026-10-15security-guidance: log each review's token use and estimated costmhegazy/sg-review-cost-logMohamed Hegazy
The plugin computed a review's usage but kept it only in its metrics. Each review now writes one line to the plugin's debug log with the kind of review, the Claude Code session, model, tokens and estimated cost.
2026-10-15security-guidance: print one JSON document from the SessionStart hook on ↵mhegazy/sg-portable-session-startMohamed Hegazy
other hosts On a host other than Claude Code the SessionStart hook printed an async declaration line and then a metrics line. A host that reads hook output as one JSON document with a closed schema rejects that. In portable mode the hook now skips the async line and prints one object with only the standard fields. The portable-mode helpers move to _base.py so both hook scripts share them, and the mode is decided once at start-up. Output under Claude Code is unchanged.
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-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-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-26Update security-guidance pluginsecurity-guidance-updateMohamed Hegazy