summaryrefslogtreecommitdiff
path: root/plugins
AgeCommit message (Collapse)Author
2026-09-09Harden git invocation and repository hint handlingsg-resolve-repo-rootOctavian Guzu
:house: Remote-Dev: homespace
2026-09-09Adjust SubagentStop handling and repository precedenceOctavian Guzu
- SubagentStop reviews without consuming or advancing the session's Stop state; an identical diff is not reviewed twice. - SubagentStop from a different working tree than the project is skipped. - An explicit `git -C <dir>` / `cd <dir>` naming another repository takes precedence over the hook cwd. - Narrows the `git -C … commit` matcher; keeps Windows path separators when tokenizing; adds `--no-textconv` to diff/show invocations. - Adds tests. :house: Remote-Dev: homespace
2026-09-09security-guidance: resolve repository from command and edited paths (2.0.7 ↵Octavian Guzu
→ 2.0.8) - Adds repository resolution from `git -C <dir>` / `cd <dir>` in the hook command, from the commit SHA, and from edited file paths when the hook cwd is not a git repository. - Adds PostToolUse matchers for `git -C … commit|push`. - Registers SubagentStop. - Adds `repo_resolution` / `cwd_is_repo` metric fields. - Adds tests. :house: Remote-Dev: homespace
2026-09-01Merge pull request #5729 from anthropics/warronbebster-patch-1Barron Webster
Update /frontend-design SKILL.md
2026-09-01Update /frontend-design SKILL.md Barron Webster
Updates to address manatee slop measures [source](https://ant-core-systems.slack.com/archives/C0B9JE2JQQL/p1787999846377369?thread_ts=1787703438.210159&cid=C0B9JE2JQQL)
2026-09-01Claude Security Plugin - v0.11.0claude-security-v0.11.0mmoore
2026-08-24Claude Security Plugin - v0.10.2.3claude-security-v0.10.2.3mmoore
2026-08-21Claude Security Plugin - v0.10.2claude-security-v0.10.2mmoore
2026-08-17Update plugin.jsonMichael Moore
2026-08-17Claude Security Plugin - v0.10.1-rc7 (#5403)Michael Moore
2026-08-12project-artifact: document headless limitations and registry enumeration (#3110)Dickson Tsai
2026-08-12security-guidance: probe for a non-PATH 3.10+ interpreter on ↵Mohamed Hegazy
HOOK_PY_INCOMPATIBLE (2.0.6 → 2.0.7) (#2854) Instrument-first for the macOS Python-3.9 cohort. v2.0.6 telemetry: ~13.6% of macOS sessions (~6,337 users) run on Apple's Python 3.9 → HOOK_PY_INCOMPATIBLE → the agentic reviewer can't load (needs 3.10+ syntax). That's ~12x macOS's build-failure rate and the single biggest macOS degradation. sg-python.sh only probes `python3.1x` on PATH, so these users have nothing newer ON PATH — but they may still have a 3.10+ installed at a standard location that isn't on the hook's PATH (Homebrew /opt/homebrew, python.org framework, etc.). Before building an explicit-path interpreter search, size the RECOVERABLE fraction: `_probe_alt_python()` checks Homebrew / python.org / distro locations for a 3.10+ binary and emits the highest found as `sdk_alt_py` (major*100+minor, or 0 = genuinely 3.9-only). Telemetry-only; probed ONLY on the HOOK_PY_INCOMPATIBLE path, so healthy sessions never run it. After a data cycle: non-zero sdk_alt_py = recoverable by an explicit-path search in sg-python.sh; 0 = needs a user-side Python install (the one-time notice is the only lever). That decides whether the search is worth building. Verified locally on macOS Python 3.13: - py_compile clean; probe returns 314 on this Mac (homebrew 3.14 present). - 7 new tests (test_altpython_probe.py): highest-version selection, 0-when-none (mocked os.access), framework/distro path parsing, only counts 3.10+, and emit gated on outcome==HOOK_PY_INCOMPATIBLE. - Full suite 575/575 + 2 skipped. No behavior change — purely additive telemetry on the incompatible path. Version 2.0.6 -> 2.0.7 per the per-PR-bump policy (#2114). Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-08-12Update install instructions to the one-command plugin installMohamed Hegazy
Claude Code's /plugin install now registers the official marketplace automatically and activates the plugin in the same session, so the /reload-plugins step these READMEs document is no longer needed. discord and telegram keep a conditional note because their MCP servers can't always be activated mid-session.
2026-08-06Migrate Asana plugin to V2 MCP server (#4895)Bryan Thompson
* Migrate Asana plugin to V2 MCP server The V1 beta server (https://mcp.asana.com/sse) is deprecated and shuts down on 2026-08-05. Asana's V2 server (https://mcp.asana.com/v2/mcp) requires each user to register their own Asana OAuth app and does not support Dynamic Client Registration. A plugin manifest cannot carry per-user OAuth credentials, so the bundled MCP server entry is removed in favor of a documented one-time `claude mcp add` setup (per Asana's official Claude Code instructions). - Remove dead V1 sse .mcp.json - Add README with V2 OAuth setup + troubleshooting - Add /asana-setup slash command to guide the one-time setup - Update plugin + marketplace descriptions to reference V2 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * plugin-dev: stop using deprecated Asana V1 SSE endpoint in examples The Asana V1 SSE server (https://mcp.asana.com/sse) is deprecated and shuts down on 2026-08-05, and Asana V2 is streamable HTTP with manual OAuth — not SSE with automatic (DCR) OAuth. Replace the Asana SSE examples in the mcp-integration skill with neutral placeholders so the tutorial no longer teaches a dead endpoint or implies Asana is a zero-config SSE/OAuth server. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Greg Dardis <86272347+greg-dardis@users.noreply.github.com> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22Claude Security Plugin for Claude Code 0.10.0claude-security-0.10.0mmoore
:house: Remote-Dev: homespace
2026-07-20receipts: show a sample receipt in the README (#4295)Morgan Lunt
You can't tell what this produces from a description, and the obvious way to show it — screenshot a real run — would put someone's actual repo names in a public README. So the sample is generated: assets/make-sample.mjs builds a throwaway HOME of invented repos, invented files and invented sessions, and the real miner runs against that. The picture is what the tool genuinely produces, from data that never existed. The generator ships next to the asset so the next person can regenerate rather than edit a screenshot. Also widen validate's path filter. It's a required check, so a PR that only touches a plugin's README or assets matched no pattern, never reported, and could not be merged — the same trap the workflow-file and policy-file entries above already work around. Adding the plugin doc paths lets this PR (and the next one) clear the gate on its own. No-Verification-Needed: docs asset, dev-only generator, and CI trigger paths — no plugin runtime surface
2026-07-17receipts: trim the README to what a user needsMorgan Lunt
It had grown into an argument with a reviewer — three sections of rationale for decisions a reader doesn't have to agree with in order to use the thing. Lead with a copy-pasteable install command, then how to run it and what comes out. The reasoning is still in the code comments and SKILL.md, where whoever maintains this next will look for it.
2026-07-17Add receipts plugin (#4176)Morgan Lunt
First-party skills-only plugin (author: Anthropic). MCP Directory audit: combined 89 PASS (static 82 / AI 96). Privacy verified local-only, aggregate-JSON output, no network egress.
2026-07-08code-modernization: pilot-first uplift migration, brief-driven execution, ↵morganl/code-mod-experiment-firstMorgan Lunt
deeper preflight /modernize-uplift migrates one representative project end-to-end and writes its lessons to analysis/<system>/PLAYBOOK.md before touching the rest. The remaining projects then fan out through a new uplift-migrate workflow, one uplift-migrator agent per project, in dependency-aware escalating batches behind a per-batch circuit breaker. A recorded per-test baseline (analysis/<system>/BASELINE.md) gates the migration, and the delta catalog reports a test framework whose runner does not support the target as its own highest-blast-radius dependency. The three execution commands (uplift, transform, reimagine) read MODERNIZATION_BRIEF.md and treat their phase's scope and entry and exit criteria as gates, so editing the brief steers execution. For a same-stack uplift the brief requires the delta catalog and applies the same ordering overrides the execution command does. /modernize-preflight opens with a short interview (scope, local build and test, bespoke build infrastructure, prior attempts, what is off limits) without blocking on the answers, reads the CI/build definition for how the system builds, escalates the smoke test to a whole-project restore and build, and adds a scope-boundary check that enumerates inbound and outbound dependencies when the system directory is a slice of a larger repository. Workflow scripts accept args delivered as either a JSON string or an object.
2026-06-19Trim project-artifact README to usage essentialsdickson/add-project-artifact-pluginDickson Tsai
2026-06-19Add project-artifact plugin: living project status pages published as artifactsDickson Tsai
2026-06-17Merge pull request #2536 from anthropics/codemod-dynamic-workflowsMorgan Lunt
code-modernization: dynamic workflow orchestration + untrusted-content hardening
2026-06-14Update frontend-design skill (#2540)william qian
2026-06-12security-guidance: handle signal-killed venv builds (memory) + cooldown ↵venv-signal-kill-cooldownMohamed Hegazy
(2.0.5 → 2.0.6) The real dominant Linux failure, identified by a CCR Linux repro. A CCR container reproduced the production signature — non-zero exit + EMPTY stdout + EMPTY stderr (~60k fires/day, 4,485 Linux users on 2.0.4): running `python -m venv` under a tight memory limit (ulimit -v) kills the memory-heavy venv+ensurepip/pip subprocess with SIGSEGV (-11, RLIMIT_AS) or SIGKILL (-9, kernel OOM-killer) BEFORE it writes anything. This is NOT the ensurepip/packaging case (that always writes to stderr, code 11) and NOT fixable by --target (a --target pip install is also memory-heavy and gets killed too). Three earlier hypotheses (stdout, packaging, Option A fixes Linux) were wrong — the repro corrected them. Changes: - Detect the signal kill (rc<0, or 128+sig: 134/137/139) in the venv/pip and --target paths → err_kind "signal_killed:<rc>" (new code 16). The returncode rides in a new sdk_bootstrap_rc metric so prod confirms which signal dominates (-9 OOM-killer vs -11 RLIMIT_AS). - Cooldown: on a signal kill, write a marker and return the new SKIP_COOLDOWN outcome (9) on subsequent sessions for 24h — stops the retry storm (every session was re-attempting a build that just gets re-killed, burning the user's memory/CPU). Retries once per window so a machine that frees memory still recovers. - --no-cache-dir on both pip installs (venv + --target) trims pip's peak memory; may get marginal machines under the OOM threshold. No happy-path change: signal detection is at the top of the existing failure handler; cooldown is checked only after all no-op probes (NOOP_SYSTEM/VENV/TARGET short-circuit first). Verified locally on macOS Python 3.13: - py_compile clean. - 35 new tests (test_signal_kill_cooldown.py): _is_signal_kill across signals/exit-codes, rc decode, signal_killed→code 16, cooldown lifecycle (none→write→expire), and an integration flow — simulated SIGKILL'd venv → BUILD_FAILED/signal_killed:-9 + cooldown written → 2nd run SKIP_COOLDOWN without re-attempting → retry after window; non-signal failure does NOT cool down; --no-cache-dir present on both pip paths; sdk_bootstrap_rc emitted conditionally. - End-to-end harness: the full kill→categorize→cooldown→skip→retry chain confirmed in-process. The original CCR repro (ulimit -v ≤7000 KB → rc=-11, empty streams) is the ground truth this fix is built on. Can be re-validated on CCR with the same ulimit approach. Version 2.0.5 -> 2.0.6 per the per-PR-bump policy (#2114). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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-06-10Merge pull request #2313 from anthropics/exc-failure-encodingMohamed Hegazy
security-guidance: encode exception type + errno + ensurepip instrumentation for venv BUILD_FAILED (#2154 follow-up) — 2.0.3 → 2.0.4
2026-06-10code-modernization: simplify README; give uplift its own modernized/ rootcodemod-dynamic-workflowsMorgan Westlee Lunt
Adversarial re-audit of the current (post-uplift) state found the plugin internally consistent (no blocker/high issues). Two follow-ups: README rewrite for clarity (209 -> 122 lines, ~halved): - Reorder so a newcomer goes what-it-is -> install -> quickstart -> command reference -> deeper notes, instead of hitting two dense design essays before the command list. - Lead with what it produces; add a 3-command teaser. - Collapse the 'Dynamic workflow orchestration' and 'Untrusted code & prompt injection' essays and the COCOMO note into short, plain sections at the bottom; drop the internal 'Bash isn't a tool-lock' hedging and per-defense enumeration (kept the load-bearing points: untrusted-code threat model, secrets quarantine, COCOMO-is-not-a-timeline). - Remove cross-section redundancy (build methods, read-only caveat, scaffolder write-scope, dir convention each stated once now); gloss strangler-fig/JOBOL inline. Path nit from the audit: uplift now writes to modernized/<system>-uplifted/ (mirroring reimagine's -reimagined/) so the three build paths occupy disjoint roots and status can't mis-detect an uplift copy as transform modules. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-09code-modernization: fix findings from adversarial auditMorgan Westlee Lunt
Code/security: - extract-rules.js: guard null agent() verdicts in the verify + P0 loops (a skipped/dead referee made {rule,v:null} survive .filter(Boolean) and then crashed on v.injectionSuspected / v.every) — sibling scripts already had the guard. - topology viewer XSS: the map injector embedded untrusted JSON (node names from filenames, etc.) into a <script> island unescaped — a name containing </script> executed on open. Escape < > & in the injected data and add a CSP to the template. - Second-order injection: citation/identifier fields (source / cwe / source_site / correctedSource) were interpolated UNFENCED into the verifier prompts that are supposed to be the trust anchor. Fence them in extract-rules, harden-scan, uplift-deltas. uplift design (audit of the new feature): - Working-copy model: copy the WHOLE solution to modernized/ once and edit in place (relative project refs survive; result is a reviewable git diff) — the incremental per-project copy broke multi-project builds. - Dual-run honesty: reframed as 'if both runtimes run here' (net48 needs Windows; JUnit/pytest don't multi-target); dummy-test gate now binds a real SUT under both targets; per-stack harness notes. - Tooling honesty: present/runnable/actually-ran distinction; never fold in a tool that couldn't run; apiport/2to3 demoted; py2->3 removed from 'preserve' examples. - Delta classes: name the high-blast-radius landmines (JPMS strong encapsulation, .NET trimming/AOT, ICU globalization, hosting/runtime-config, analyzer/nullable) in the finder briefs + agent. - Rewrite-vs-uplift signal: weigh by touched sites (siteCount), not delta-card count; judgment-share demoted to secondary. Docs/consistency: brief reads topology.json (not TOPOLOGY.html); README 'five commands'; credential-masking claim split (analysts mask+cite vs code-writers substitute fakes); read-only/write-scope claims softened to match enforcement (Bash retained -> discipline, not tool-lock); reimagine nested blockers/pendingRuleIds; status splits transform vs reimagine markers; portfolio enumeration basenames; plugin.json description updated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-09code-modernization: add /modernize-uplift for same-stack version migrationsMorgan Westlee Lunt
Adds a third build method alongside transform (cross-stack rewrite) and reimagine (greenfield): uplift, for same-stack version bumps (.NET Framework 4.8 -> .NET 8, Spring Boot 2->3, Python 2->3) where the right move is to PRESERVE the code and fix only the version deltas, not extract intent and rewrite. - commands/modernize-uplift.md: delta-catalog-driven, dual-target test harness (one suite on both runtimes; baseline-on-old is the oracle), leaf-first build graph ordering, minimal-diff discipline (architecture-critic flags gratuitous divergence), and a 'this is a rewrite, use transform' escape hatch. - agents/version-delta-analyst.md: finds the source->target breaking changes that THIS code hits; drives the ecosystem migration tool (upgrade-assistant / OpenRewrite / pyupgrade / ng update) and owns the residue; read-only. - workflows/uplift-deltas.js: parallel finder per delta category, each verified against the cited code so deltas that don't apply here are dropped. - Wired into assess (recommended-pattern routing), brief (per-phase command + leaf-first ordering), preflight (dual-run + tool readiness), status, README. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-09code-modernization: COCOMO is a complexity index, never a modernization timelineMorgan Westlee Lunt
COCOMO's constants encode human-team productivity; presenting its person-months as how long an agentic modernization will take (or cost) is a claim we should not make. Reframe COCOMO everywhere as a RELATIVE complexity/scale index for ranking and sequencing systems only: - assess: capture COCOMO as a complexity index; explicitly ignore scc's 'Estimated Schedule Effort' and cost-in-dollars; ASSESSMENT 'Effort Estimation' section becomes 'Relative Scale' with a not-a-timeline note; portfolio heat-map column renamed Complexity (COCOMO index). - brief: phase plan uses relative T-shirt sizing, not person-months/weeks; phases render as a dependency flowchart, not a gantt (gantt = calendar). - portfolio-assess.js: field cocomoPm -> complexityIndex; return label carries the not-a-duration caveat. - README: 'A note on COCOMO' explains the index framing and points at better intrinsic-complexity proxies. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-09code-modernization: second-order injection fencing, path guards, scoped ↵Morgan Westlee Lunt
scaffolder agent Addresses automated security review of the workflow conversion: - Agent-produced text (rule specs, finding descriptions, dedup lists) is fenced as untrusted data when interpolated into downstream agent prompts, with embedded fence markers stripped so the fence can't be escaped; referees and judges are told to re-derive claims from the cited code. - system/service/subdir names that land in filesystem paths inside prompts are validated against a strict pattern — traversal-shaped values throw before any agent spawns. - Reimagine scaffolding now uses a dedicated 'scaffolder' agent with an explicit minimal tool list, a single-directory write scope, and the untrusted-content discipline extended to the generated spec/architecture docs it builds from (they derive from untrusted legacy code). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-09code-modernization: dynamic workflow orchestration + untrusted-content hardeningMorgan Westlee Lunt
Four commands gain a Workflow-tool path (with direct-fan-out fallback for older builds): extract-rules loops until dry with per-rule citation referees and a P0 two-judge panel; harden runs class-scoped finders with adversarial per-finding refutation; assess --portfolio pipelines one survey agent per system with COCOMO computed uniformly in script; reimagine Phase E drops the 3-service scaffolding cap. Workflow agents return schema-validated data and only the orchestrating session writes artifacts — analysis agents are structurally read-only. All five agents gain an untrusted-content discipline section (source code is data, never instructions; comment-only claims are findings, not facts), and the README documents the prompt-injection threat model for analyzed code. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-09Merge pull request #2467 from anthropics/morganl/code-mod-secrets-redactionMorgan Lunt
code-modernization: never write discovered credential values into findings
2026-06-09code-modernization: legacy toolchain is advisory, not a transform blockermorganl/code-mod-interactive-mapMorgan Lunt
Legacy code often cannot build locally by nature — CICS/IMS programs have no local translator and the real runtime may be a mainframe the user doesn't have. Stopping transform on a failed legacy smoke compile would block exactly those systems. - transform Step 0a: the target toolchain remains required (its tests cannot run without it); a failed or impossible legacy compile no longer stops the run — the equivalence strategy switches to recorded traces / golden-master fixtures, and that downgrade is stated in the plan and in TRANSFORMATION_NOTES.md so reviewers know the strength of the proof - preflight: a red legacy toolchain now yields Ready-with-gaps for transform/reimagine instead of Not-ready
2026-06-09code-modernization: add topology viewer screenshot to READMEMorgan Lunt
Rendered from AWS CardDemo (the public mainframe sample app) by running /modernize-map end to end and capturing the resulting TOPOLOGY.html.
2026-06-09code-modernization: vendor d3, viewer robustness, status command, pipeline fixesMorgan Lunt
Viewer (assets/topology-viewer.html): - inline a minified d3 subset (hierarchy/pack, zoom, selection, interpolateZoom, ease; ISC license) instead of loading from a CDN — the page is now fully self-contained and works on air-gapped networks - handle duplicate node ids (unique-suffix; edges bind to the first occurrence) and store parent references directly, fixing level-of-detail and selection corruption with messy generated data - share one reveal rule between drawing, edge culling, and hit-testing so edges no longer draw into collapsed containers - pre-bucket edges by kind and keep a per-node adjacency map; the hover/selection pass no longer scans every edge each frame - cancel in-flight fly-to animations when a new one starts; clamp fly-to zoom to the zoom extent; derive max zoom from the smallest leaf so deep estates stay reachable - render dead-end candidates (new deadEnds field) with a dashed outline and a sidebar badge - clicking a node during a flow walkthrough exits the walkthrough; search results clear on selection and Escape; surrogate-safe label truncation; clearer stats line; explicit empty-topology message Commands: - new /modernize-status: read-only progress report — artifact inventory with timestamps, staleness flags, secrets-hygiene checks, next step - map: deadEnds in the topology schema; datastore names must be logical identifiers with credentials stripped from URLs/DSNs - brief: read topology.json + .mmd files (not the interactive HTML); staleness check against inputs; effort unit aligned to person-months - transform: secret-safe characterization-test prompt; diff -y fallback when delta is missing; credential-safe diff selection - reimagine: target vision is everything after the first argument (was silently truncated to one word); masking rules in spec/scaffold/ handoff prompts - brief/transform/reimagine: human-approval gates phrased as explicit stop-and-wait instead of 'enter plan mode' - preflight: delta in the tool table; brief added to the verdict list - README: preflight/status in the workflow; legacy/ deny list also covers Write; plugin + marketplace descriptions updated
2026-06-09code-modernization: harden topology viewer and template injectionMorgan Lunt
Fixes from an adversarial review of the new viewer: - pin d3 to 7.9.0 and load it via dynamic import with an explicit error panel when the CDN is unreachable (previously a blocked CDN produced a silent dark page — a real concern for restricted networks) - coerce ids/names/loc at intake: a single missing name or non-numeric loc previously threw inside the render loop or propagated NaN through the pack layout, blanking the canvas with no error - normalize flows/steps/edges defensively (null entries, missing steps, numeric ids vs string lookups) - mirror the level-of-detail reveal rule in the hit test so clicks can't select nodes that aren't drawn - scope the Escape shortcut so clearing the search box doesn't reset the viewport; set zoom clickDistance(4) so trackpad jitter doesn't swallow selection clicks - round canvas backing-store size (fractional devicePixelRatio caused a reallocation every frame on 125%/150% display scaling) - modernize-map: use braced ${CLAUDE_PLUGIN_ROOT} so substitution actually happens, assert the injection marker exists in the template, and correct the documented failure mode
2026-06-09code-modernization: interactive topology map, preflight command, persona flowsMorgan Lunt
modernize-map previously rendered the call graph and data lineage as static Mermaid diagrams, which become unreadable once a node has ~10+ edges — exactly the shape of real legacy systems. It now builds an interactive viewer from a shipped template (assets/topology-viewer.html): a zoomable circle-pack of domains/modules sized by LOC, rendered to canvas with level-of-detail reveal, dependency edges with per-kind toggles, search with fly-to, a per-node detail sidebar, and a flow walkthrough mode. Small domain-level .mmd exports remain for docs. - topology.json now has a documented schema (hierarchy + edges + entry points + observations + flows) consumed by the viewer - map traces 2-4 business flows anchored to personas (claimant, operator, auditor), each step in plain business language mapped to the modules that implement it; the viewer plays them as numbered paths - brief gains a Business Walkthroughs section connecting each persona flow to the phase that replaces it - new modernize-preflight command: detects the stack, checks analysis tooling, smoke-compiles a real source file with the legacy toolchain, inventories missing copybooks/descriptors/binary-only artifacts, and writes a per-command readiness verdict - transform now verifies legacy + target toolchains before its plan gate instead of failing at test time - README: commands updated, optional-tooling section reframed as 'what to give Claude'
2026-06-09code-modernization: assess writes the full quarantine ignore setmorganl/code-mod-secrets-redactionMorgan Lunt
assess only added SECRETS.local.md to analysis/.gitignore, leaving *.local.patch uncovered until harden's own Step 0 ran. Both patterns are now written by whichever command runs first.
2026-06-09code-modernization: close remaining credential-leak pathsMorgan Lunt
A red-team pass found four ways credential values still reached shareable artifacts after the initial redaction: - the remediation patch: a diff removing a hardcoded secret carries the raw value on its '-' lines by construction. harden now splits output: non-credential hunks in the shareable security_remediation.patch, credential hunks in a gitignored security_remediation.local.patch with comment-only placeholders in the shareable file - the other four agents had no secret-handling rules. legacy-analyst (hardcoded-config evidence in tech-debt findings), business-rules-extractor (credentials recorded as rule parameters), test-engineer (legacy literals becoming committed test fixtures), and architecture-critic (quoted code in notes files) now all mask values and cite file:line; assess's tech-debt prompt and ASSESSMENT.md masking now cover every section, not just Security Findings - non-git projects: a .gitignore protects nothing under SVN/Mercurial. Both commands now refuse --show-secrets without git and write the quarantine file to ~/.modernize/<system>/ outside the project tree - the patch-apply instruction was wrong in both documented layouts (symlinked legacy/ broke relative paths). Patches are now written with project-root-relative paths and applied from the project root Also: --show-secrets is now position-independent in both commands, and the README documents the full model.
2026-06-09code-modernization: never write discovered credential values into findingsMorgan Lunt
Legacy systems often contain live credentials, and assessment/findings files get committed and shared. Previously the security-auditor agent reported hardcoded secrets verbatim into ASSESSMENT.md and SECURITY_FINDINGS.md. - security-auditor: mandatory secret-handling rules — mask all credential values (file:line + 2-4 char preview), redact secrets from echoed tool output, recommend rotation for anything that looks live - assess/harden: gitignore-verified SECRETS.local.md quarantine file for the per-credential inventory; findings files get masked entries and a pointer only - new --show-secrets flag opts into raw values in the quarantine file (and only there) - README: document the behavior and advise users of earlier versions to check for already-committed findings and rotate
2026-06-04security-guidance: encode exception type + errno + ensurepip instrumentation ↵exc-failure-encodingMohamed Hegazy
for venv BUILD_FAILED (2.0.3 → 2.0.4) Follow-up to #2154. v2.0.3 telemetry showed the venv BUILD_FAILED bucket splits into two unexplained groups; this PR instruments both. ## 1. The exc: bucket — exception type + errno The dominant remaining venv BUILD_FAILED (phase=venv, err=99) is ~99% sdk_bootstrap_stderr_sig=NULL — Python exceptions caught by the generic `except Exception` ("exc:<TypeName>"), not CalledProcessErrors with categorizable stderr. ~56k/30h, all opaque (stderr_sig only covers "other:<tail>"). - Handler embeds errno for OSError-family: "exc:OSError:28", etc. - SDK_BOOTSTRAP_EXC_CODES maps the type → sdk_bootstrap_exc (FileNotFoundError=1 … OSError=6 … 99=other). - errno decoded → sdk_bootstrap_errno (ENOENT/EACCES/ENOSPC/…). ## 2. venv_ensurepip_fail instrumentation (the other category) venv_ensurepip_fail (code 11) is the top categorizable venv failure, and telemetry flipped the naive assumption: it's NOT just Debian/Ubuntu — macOS has the MOST distinct affected users (466 vs 121 linux), and linux is a retry storm (~172 fires/user). Before committing to a `pip install --target` fallback (Option A) we need to know (a) which interpreter these users run and (b) whether that interpreter even has pip (→ whether --target would work, vs needing a system package). - sdk_hook_py (always emitted): interpreter version as major*100+minor (309/312). Disambiguates Apple-3.9 vs a 3.10+-with-broken-ensurepip, and also recovers the version for HOOK_PY_INCOMPATIBLE (whose "py_3.9" err_kind otherwise collapses to err=99). - sdk_has_pip (only on err==11, to avoid an extra subprocess per healthy session): whether `<interpreter> -m pip --version` works. has_pip=true → the --target fallback would fix them; has_pip=false → they need a system package (python3-venv / a complete Python). Both #1 and #2 are purely additive telemetry on the existing BUILD_FAILED path — no behavior change to the bootstrap. They de-risk the Option A decision: ship A only if the affected cohort has pip. Verified locally on macOS Python 3.13: - py_compile clean. - 39 tests in test_exc_failure_encoding.py (34 exc/errno + 5 ensurepip instrumentation): type-code map, errno extraction + round-trip, APPEND-ONLY stability, handler-embeds-errno, _probe_has_pip returns bool + true-on-this-machine, sdk_hook_py always-emitted as major*100+minor, sdk_has_pip gated on err==11. - Full suite: 503/503 pass + 2 skipped. Version 2.0.3 -> 2.0.4 per the per-PR-bump policy (#2114). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-02security-guidance: emit schema-valid Stop-hook output (#2159) — 2.0.2 → ↵fix-2159-stop-hook-schemaMohamed Hegazy
2.0.3 Fixes #2159. The Stop hook emits feedback via `hookSpecificOutput: {hookEventName: "Stop", additionalContext}`, but `Stop`/`SubagentStop` are NOT members of CC's `hookSpecificOutput` discriminated union (coreSchemas.ts — valid members are PreToolUse, PostToolUse, UserPromptSubmit, SessionStart, etc.). So the emitted shape violates CC's documented hook-output schema. Impact is CC-version-dependent — important nuance, established empirically: - Reporter (array0224-cloud) on CLI 2.1.150 / 2.1.152: CC rejects the Stop feedback; the block/reason never reaches the model, so the auto-rewake/fix loop is lost. (Detection still runs + logs.) - On CLI 2.1.160 (current) the asyncRewake completion path is lenient: its gate is `isSyncHookJSONOutput` (hooks.ts) which is just `!(json.async === true)` — NOT a strict schema parse. So the invalid hookSpecificOutput is tolerated: metrics + rewakeSummary are still consumed and the model still receives the findings. I could NOT reproduce the rejection on 2.1.160, and BQ confirms Stop-path vulns_found metrics are recorded normally (~21k with-vuln fires / 3d), i.e. NOT dropped. (An earlier draft of this message claimed metrics were dropped — that was wrong; corrected after checking telemetry + repro'ing the old plugin on 2.1.160.) So this is defensive schema-correctness: the plugin should emit output that conforms to CC's documented union regardless of how strictly a given CC version validates it. The reporter's environment validates strictly; relying on the current version's leniency is fragile. Fix (CC's documented asyncRewake "clean pattern" — hooks.ts: "error text on stderr, JSON on stdout"): - For Stop/SubagentStop, emit_metrics writes guidance to stderr (the asyncRewake body channel CC delivers via `stderr || stdout`) and sets top-level `decision: "block"` + `reason` (valid SyncHookJSONOutput fields; also the documented sync Stop-hook contract for the `-p` fallback). It does NOT emit a Stop hookSpecificOutput. - PostToolUse (commit-review, push-sweep) is unchanged — valid union member, keeps the modern hookSpecificOutput protocol. Verified locally on macOS Python 3.13: - py_compile clean. - 11 new tests (test_2159_stop_hook_schema.py) pin the contract: Stop output carries no hookSpecificOutput, uses top-level decision/reason, writes guidance to stderr; the emitted hookEventName (when present) is a valid union member. 2 existing tests that asserted the buggy Stop->hookSpecificOutput shape were corrected. Full suite 464/464 pass + 2 skipped. - END-TO-END in /tmux on CLI 2.1.160: * FIXED plugin (2.0.3): staged pickle.loads + os.system, benign edit pulls the file into review_set; Stop LLM review found 2 critical vulns; CC delivered a clean rewake ("Background security review found issues" + both findings). All hooks (UPS, PostToolUse[Edit] pattern, PostToolUse[Bash] commit-review, Stop) fired clean; zero schema rejections / errors / http_err in the debug log. * OLD plugin (2.0.2) on the SAME 2.1.160: also delivered Stop feedback (confirming the no-repro-on-latest finding above) — which proves the fix carries NO regression risk on current CC while making the output robust for the stricter versions where it actually breaks. Version bumped 2.0.2 -> 2.0.3 per the per-PR-bump policy (#2114: a bump is the only way the fix reaches the existing fleet — relevant for users still on the CC versions where this breaks). Closes #2159. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-01security-guidance: 5 venv-specific err_kind categories + stderr_signature ↵venv-failure-deepdiveMohamed Hegazy
bucket (2.0.1 → 2.0.2) PR #2112's telemetry visibility surfaced an immediate finding from the first 3h of v2.0.1 data: **2,406 phase=2 / err=99 sessions** — "venv stage / uncategorized" — dominating BUILD_FAILED. The original err_kind detection patterns were all pip-flavored (pip_no_match, dns_fail, ssl_verify, etc.) and didn't catch venv-creation failure modes, so they all collapsed to the catch-all _uncategorized (99) bucket. This PR fills the gap on two axes. ## 1. Five new venv-specific err_kind categories (codes 11-15) Each gated on `err_phase == "venv"` so the same substring doesn't mis-fire in pip-phase failures: - 11 `venv_ensurepip_fail` — Debian/Ubuntu without python3-venv installed; stderr matches "ensurepip is not available" or "ensurepip ... returned non-zero". Predicted to be the biggest chunk based on Linux distro market share. - 12 `venv_path_too_long` — Windows MAX_PATH (260) or POSIX ENAMETOOLONG. Triggered when state_dir + venv layout exceeds the path limit (deep Lib/site-packages/<pkg>/<...> paths). - 13 `venv_no_module` — `python3 -m venv` itself missing ("No module named 'venv'"). Rare but distinctive. - 14 `venv_already_exists` — Errno 17 / "file exists" — sentinel race past O_EXCL or stale dir survived `--clear`. - 15 `venv_setup_failed` — generic "virtual environment was not created successfully" catch-all for venv setup failures that don't match a more specific category. All 5 occupy reserved slots in SDK_BOOTSTRAP_ERR_CODES per the APPEND-ONLY contract from PR #2112. ## 2. `sdk_bootstrap_stderr_sig` integer hash For "other:<tail>" err_kinds (which encode to _uncategorized = 99), emit a bounded integer hash (0-999) of the first ~30 chars of the stderr tail. This restores cardinality to the _uncategorized bucket in BQ aggregation without unbounded keyspace — same stderr message always maps to the same bucket, so a real failure mode replicating across thousands of machines clusters cleanly. Bounded at 1000 buckets: well below any "high cardinality" alarm but wide enough to distinguish ~30 distinct dominant patterns (birthday-paradox collision probability ~50% at ~37 distinct inputs). The field auto-omits (`if sig:` gate) when err_kind is categorized — no key-budget cost on the common-case categorized failures. ## Version bump 2.0.1 → 2.0.2 PR #2114 confirmed the version-bump mechanism is the only way to propagate code changes to the existing fleet — without a bump, CC's plugin updater short-circuits on string-equality of installation version vs marketplace version. Following the policy we established: **bump patch on every functional PR**. By 17:31:42Z on 2026-06-01 (1m22s after #2114 merged), v2.0.1 was already appearing in BQ. v2.0.2 should follow the same propagation curve — ~30% adoption within 3 hours, full convergence within a few days. ## Verified locally - py_compile clean. - 15 new tests in test_venv_failure_deepdive.py (added to internal test suite at sg-staging/tests/, not in this PR): * 5 parametrized: each new err_kind maps to its expected code (11-15). * 1 APPEND-ONLY regression: existing codes 1-10 + 99 unchanged. * 6 stderr_sig: non-other inputs → 0; None/empty → 0; deterministic same-input → same-output; bounded to 0-999; distinct inputs → distinct hashes (5/5 with P(collision) ≈ 1%); leading-chars focus (path-varying stderr with shared 30-char prefix collide as designed). * 1 static-shape catcher: every new `err_kind = "venv_..."` branch in main() is guarded by `err_phase == "venv"`. Catches the regression where someone adds a venv pattern without the phase gate and starts mis-categorizing pip-phase failures. * 1 map-coverage: all err_kind strings assigned anywhere in ensure_agent_sdk.main() are present in SDK_BOOTSTRAP_ERR_CODES (catches new categories added in code but forgotten in the map). * 1 emit-shape: the metric block uses `_encode_stderr_sig`, the `sdk_bootstrap_stderr_sig` key is written conditionally on `if sig:`. Catches the regression where someone removes the helper or makes the emit unconditional (would pad every categorized BUILD_FAILED row with a zero-valued field). - Full suite: 452/452 pass + 2 skipped (live API tests, opt-in). ## What this unblocks in BQ ```sql -- For the 2,406 sessions/3h that were phase=2/err=99 on v2.0.1, -- v2.0.2+ will split them across the new categories. Query: SELECT CAST(JSON_VALUE(additional_metadata, "$.sdk_bootstrap_err") AS INT64) AS err, CAST(JSON_VALUE(additional_metadata, "$.sdk_bootstrap_stderr_sig") AS INT64) AS sig, COUNT(*) AS sessions FROM `proj-product-data-nhme.raw_events.claude_code_internal_event` WHERE _PARTITIONTIME >= ... AND CAST(JSON_VALUE(additional_metadata, "$.sdk_bootstrap") AS INT64) = 3 AND CAST(JSON_VALUE(additional_metadata, "$.sdk_bootstrap_phase") AS INT64) = 2 -- venv GROUP BY err, sig ORDER BY sessions DESC ``` Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-01Merge pull request #2112 from anthropics/telemetry-failure-signalsMohamed Hegazy
security-guidance: emit HTTP error codes + fix sdk_bootstrap phase/err encoding (telemetry visibility)
2026-05-31security-guidance: bump 2.0.0 → 2.0.1 to propagate 8 weeks-of-fixes to the ↵bump-2-0-1-propagate-fixesMohamed Hegazy
existing fleet The 8 PRs we shipped since 2026-05-26 (#2076, #2077, #2078, #2086, #2091, #2100, #2101, #2105) all changed plugin code without bumping the version. CC's plugin updater uses string equality for the freshness check (pluginOperations.ts:1835): const isUpToDate = installation.version === newVersion || installation.installPath === versionedPath || installation.installPath === zipPath if (isUpToDate) return { alreadyUpToDate: true } Users who installed v2.0.0 anywhere between 2026-05-26 and 2026-05-31 have `installation.version === "2.0.0"` in their installed_plugins.json. The marketplace also advertises "2.0.0" (until this commit), so isUpToDate returns true and the plugin cache directory is never refreshed — they keep running whatever 2.0.0 code was current on the day they installed. The marketplace git pull happens; the per-user cache install does NOT. Empirical evidence: in BQ today (5/31) on Windows v2.0.0 fires, **73% emit sdk_bootstrap outcome 4 (SKIP_WIN32)** — a code path retired in PR #2055's Windows-enable fix. Those users are running a plugin tree that pre-dates the fix, even though their telemetry shows pv=20000. The fix is a one-line version bump. Once the marketplace advertises 2.0.1, every CC autoupdate cycle sees installation.version (2.0.0) != newVersion (2.0.1), installs the new version, and the user's next session loads the fixed code. This PR: 1. plugins/security-guidance/.claude-plugin/plugin.json: 2.0.0 → 2.0.1 2. .claude-plugin/marketplace.json security-guidance entry: 2.0.0 → 2.0.1 What 2.0.1 carries (versus 2.0.0 as published 5/26): - #2076 — Graphite gt commit/push detection - #2077 — hookSpecificOutput.additionalContext on async-rewake exit-2 - #2078 — CLAUDE_CONFIG_DIR support - #2086 — core.quotePath=false on diff feeders (Arabic/Hebrew/CJK paths) - #2091 — fix Bash(...|...) if-clause regression from #2076 - #2100 — drop text=True from subprocess.run, bake PYTHONUTF8=1 (Windows non-cp1252 path crash) - #2101 — core.quotePath=false on GIT_CMD globally - #2105 — output_format → output_config.format API migration (#2098) Verified locally: - plugin.json + marketplace.json both valid JSON. - _read_plugin_version_int() returns 20001 (was 20000). - Existing test suite passes — 408 tests, no regressions caused by the version bump itself. (29 unrelated failures are from test_telemetry_failure_signals.py which expects PR #2112's not-yet-merged code.) Going forward: bumping `patch` on every functional PR closes this gap entirely. Without that policy, every fix only reaches NEW installs, never the existing fleet. 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-30security-guidance: move core.quotePath=false to GIT_CMD globally (#2099 ↵fix-2099-quotepath-globalMohamed Hegazy
followup) Followup to PR #2086 (which added the flag to 4 specific git call sites) and PR #2100 (text=True purge for #2099). The Windows reporter for #2099 noticed more git invocations still lacked the flag — rev-parse path queries (--show-toplevel, --git-dir, --git-common-dir), reflog %gs subjects, and `git show <sha>:<path>` all output paths but the per-site PR #2086 approach missed them. The result: an Arabic-named directory shows up via _git_diff_range but rev-parse-emitted paths get C-quoted, breaking downstream os.path.isabs() checks. Fix: add `-c core.quotePath=false` to GIT_CMD itself as the 4th config-set. Every subprocess.run using the *GIT_CMD splat picks it up automatically — diff feeders, rev-parse path queries, reflog log, ls-files, status, git show. No more per-site flag duplication. This commit: 1. gitutil.py: add -c core.quotePath=false to GIT_CMD. 2. Remove the now-redundant per-site flags at the 7 call sites that previously had inline -c core.quotePath=false (cleanup, since the global setting subsumes them): gitutil.py: _git_diff_range, _git_name_only, _git_status_porcelain, get_git_diff (4 sites) diffstate.py: _list_untracked git ls-files (1 site) security_reminder_hook.py: commit-review git diff + git show (2 sites) Verified locally on latest main (post PR #2100 merge) with macOS Python 3.13: - py_compile clean on all 3 modified files. - Bare main BEFORE my fix: 400/401 pass — 1 failure proves the gap (test_git_cmd_contains_quotepath_false catches the missing flag). - Main + my fix: 401/401 pass. - 23 new tests in test_quotepath_global.py (added to internal test suite at sg-staging/tests/, not in this PR): * 1 GIT_CMD-level: GIT_CMD list contains core.quotePath=false as a (-c, value) pair. Single source of truth — single place a future PR will be caught if the flag gets dropped. * 10 static-shape (one per hooks/*.py): every subprocess.run uses the *GIT_CMD splat (no bare git invocation that would bypass the global flag). * 12 end-to-end (parametrized over Arabic, Hebrew, CJK directory names): real git repo, _git_diff_range emits unquoted diff, extract_file_paths_from_diff and parse_diff_into_files keep the non-ASCII path in their output, _git_toplevel returns the non-ASCII path intact. - 1 staleness fix in test_diff_parser_non_ascii.py (test_no_bare_git_diff_or_show_without_flag): updated to accept EITHER inline core.quotePath=false OR *GIT_CMD splat (which globally provides it). NOT verified end-to-end on Windows with a non-ASCII repo root path. The new global-flag test pins the contract permanently, and the parametrized macOS tests confirm parser behavior on ASCII-control paths in non-ASCII directories. The Windows-specific rev-parse quoting behavior follows from the same git contract our macOS test environment exercises (POSIX git always emits raw UTF-8 regardless of quotePath; on Windows the flag is what makes output raw). Closes the #2099 followup specifically about _git_diff_range / rev-parse --show-toplevel / git log %gs paths slipping past. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-30security-guidance: purge text=True from subprocess.run + bake PYTHONUTF8=1 ↵fix-2099-text-true-pythonutf8Mohamed Hegazy
(#2099) URGENT WINDOWS FIX. Sibling of #2056 / PR #2075 but covering 14 more sites that PR #2075 missed. The bug class: on Windows with cp1252 default encoding (typical en-US locale), `subprocess.run(..., text=True)` decodes child stdout AND stderr via `locale.getpreferredencoding()`. When git emits a UTF-8 byte that's undefined in cp1252 (e.g. `0x81` from ف, present in any path/filename/branch ref/commit message containing Arabic/Hebrew/CJK), Python's internal `_readerthread` raises UnicodeDecodeError. The thread crash is silent in Python 3.13+ (only printed to stderr), but `subprocess.run` returns `stdout=None` and the caller AttributeErrors on `.strip()`. The user sees a misleading "WinError 267" or similar catch-all message instead of the real decode failure. PR #2075 fixed 6 specific helpers in `diffstate.py` / `gitutil.py`. This commit covers the 14 survivors. Plus a defense-in-depth belt: `PYTHONUTF8=1` exported by sg-python.sh. This commit: 1. sg-python.sh: `export PYTHONUTF8=1` (PEP 540). No-op on macOS/Linux (already UTF-8). On Windows, makes Python's `locale.getpreferredencoding()` return UTF-8 instead of cp1252 — so even if a future regression slips in text=True, the decode succeeds. Must be set BEFORE Python starts; changing it from inside the interpreter has no effect. 2. gitutil.py: convert 8 subprocess.run sites from `capture_output=True, text=True` to `capture_output=True` + manual `r.stdout.decode("utf-8", errors="replace")`: - _git_rev_parse_head (stdout = SHA, stderr risk) - _find_git_index (stdout = PATH, primary bug site) - _temp_index git add (returncode only, stderr risk) - _git_toplevel (stdout = PATH, primary bug site) - _git_dir (stdout = PATH, primary bug site) - _git_rev_list_range (stdout = SHAs, stderr risk) - _detect_main_branch (stdout = ref, stderr risk) - merge-base --is-ancestor (returncode only, stderr risk) 3. security_reminder_hook.py: convert 6 subprocess.run sites (rev-parse @{u}/@{u}@{1}/local_ref, merge-base, HEAD lookup, reflog SHA resolution) — same pattern. 4. security_reminder_hook.py: fix the misleading log line in handle_user_prompt_submit. Was: debug_log("Failed to capture git baseline (not a git repo?)") Now includes the cwd in the message so the next reporter doesn't waste an hour grepping for the real WinError, per reporter's secondary finding. Verified locally on macOS Python 3.13: - py_compile clean on all modified files. - bash -n sg-python.sh clean. - sg-python.sh actually propagates PYTHONUTF8=1 to child Python (verified via probe — sys.flags.utf8_mode=1). - Existing 353 tests still pass — 0 regression. - 25 new tests in test_2099_subprocess_text_true.py: * 10 static-shape catchers (one per hooks/*.py file). Any future PR that reintroduces text=True OR encoding= in subprocess.run fails this check at PR time. Single source of truth for the regression class. * 2 sg-python.sh verifiers (literal export + actual propagation to child Python). * 5 macOS end-to-end against a real git repo containing non-cp1252 content (`ف.py` filename): _git_toplevel, _git_dir, _find_git_index, _git_rev_parse_head, _git_rev_list_range all return clean values without AttributeError / UnicodeDecodeError. * 7 round-trip bytes-decode pattern verifiers (parametrized over Arabic ف, Hebrew א, Japanese 案, raw 0x81, multiple cp1252-undefined bytes, real-world git diff headers). * 1 sanity check that cp1252 strict DOES raise on 0x81 (proves the test environment can catch the bug class). - Full suite: 378/378 pass in 5.56s. - End-to-end tmux smoke test driving real claude 2.1.145 CLI: Made a git commit via Bash tool call. All 4 hooks fired through the fixed plugin path: 11:28:16.730 Hook called with args: …/plugin/hooks/security_reminder_hook.py 11:28:16.734 Processing: hook_event=UserPromptSubmit 11:28:16.825 Captured git baseline: 445f7f213256 11:28:19.923 Hook called with args: … 11:28:19.923 Processing: hook_event=PostToolUse, tool=Bash 11:28:19.971 Commit review: detected git commit in command 11:28:20.020 Commit review: 1/1 sha(s) resolved, 1 files 11:28:26.415 Hook called with args: … 11:28:26.416 Processing: hook_event=Stop 11:28:26.550 Stop hook: empty review set Confirms: PYTHONUTF8=1 export doesn't break anything; converted helpers (_git_rev_parse_head, _git_toplevel, _git_dir, _find_git_index) run end-to-end without issue on the happy path. NOT verified end-to-end on Windows with actual non-cp1252 content in path/filename/stderr. The static-shape catcher pins the regression class permanently. Reporter's PYTHONUTF8=1 workaround empirically proves the encoding-mode fix works for the affected scenario; this commit just bakes it in. Closes #2099. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>