Skip to content

tooling: add rust_tool_guard PreToolUse hook for soldr enforcement (#2871) - #2960

Merged
zackees merged 1 commit into
masterfrom
feat/2871-rust-tool-guard
Jun 7, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/2871-rust-tool-guard

Conversation

@zackees

@zackees zackees commented Jun 7, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Adds `ci/hooks/rust_tool_guard.py` — a Bash PreToolUse hook that blocks bare `cargo` / `rustc` / `rustfmt` / `clippy-driver` invocations and requires the `soldr ` rewrite.
  • Wires the new hook into `.claude/settings.json` alongside `check_pr_merge_reviews.py` under the existing `matcher: "Bash"` chain.
  • Honors `FL_AGENT_ALLOW_BARE_CARGO=1` (command prefix or process env) for legitimate exceptions (`--version` probes, non-Rust scripts that shadow the name).

Why

fbuild's own `tool_guard.py` (fbuild#429) only fires when the session project root is fbuild. When an agent runs in a FastLED session and `cd`s into a fbuild dev checkout for a clud-pr job, the fbuild hook is never consulted, so the agent runs bare `cargo build` and burns minutes that should have been seconds (~15 min observed on the fbuild #424/#427 stack before someone caught it). This hook closes the gap at the session root.

Trigger

Blocks when either:

  1. First token (after any `VAR=value` env-var prefix) is a Rust tool, or
  2. The command contains ` ` mid-chain (catches `cd /x && cargo build` and `(cd y; cargo …)`).

A `soldr` prefix is detected and treated as compliant; mid-chain `soldr cargo …` likewise.

Cargo.toml gate trade-off

The issue suggested a Cargo.toml-proximity gate. I rejected it because Claude Code spawns hooks with cwd pinned to the session root (`cd "$d"` in `.claude/settings.json`), so `os.getcwd()` walks always run from FastLED root, never from where the bash command will execute. That either silently misses cross-project cases or hard-blocks every cargo. The tool-name match is precise enough on its own — substring tests confirm no false positives, and the override env var handles the rare non-Rust shadowing.

Test plan

  • Smoke-tested via a `subprocess.run`-driven harness covering 17 cases:
    • bare cargo/rustc/rustfmt/clippy-driver → exit 2 (block)
    • `soldr cargo …` → exit 0 (allow)
    • command-prefix `FL_AGENT_ALLOW_BARE_CARGO=1 cargo …` → exit 0
    • process-env `FL_AGENT_ALLOW_BARE_CARGO=1` → exit 0
    • mid-chain `cd subdir && cargo build` → exit 2
    • mid-chain `cd subdir && soldr cargo build` → exit 0
    • subshell `(cd subdir; cargo test)` → exit 2
    • substrings (`mycargo`, `./tools/cargo-build`, `CARGO_RUSTFLAGS=`) → exit 0
    • non-Bash tool (e.g. Read) → exit 0
    • empty command → exit 0
  • `bash lint ci/hooks/rust_tool_guard.py` passes.
  • `.claude/settings.json` parses as valid JSON.

Closes #2871.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Chores
    • Added CI validation for Rust development tool invocations that provides error guidance when incorrect usage patterns are detected, with support for bypass scenarios.

…2871)

fbuild ships its own tool_guard.py that rewrites cargo/rustc/rustfmt/
clippy-driver invocations to run under `soldr`, so zccache + soldr's
target-tree cache turn multi-minute cold builds into seconds-long
warm hits (fbuild#429). But Claude Code only loads hooks from the
session project root — when an agent runs in this FastLED session
and `cd`s into a fbuild dev checkout, the fbuild hook is never
consulted and the agent burns minutes on bare cargo builds.

Add a sibling Bash PreToolUse hook at FastLED's root that fires
regardless of cwd. The hook:

  - Matches a leading or mid-chain `cargo`/`rustc`/`rustfmt`/
    `clippy-driver` token. Mid-chain matching catches the
    `cd /elsewhere && cargo build` and `(cd x; cargo …)` patterns.
  - Treats `soldr cargo …` (etc.) as compliant — no block.
  - Refuses with an actionable error message that names the
    matched tool, suggests the soldr-prefixed rewrite, and points
    at #2871 + fbuild#429 for context.
  - Honors `FL_AGENT_ALLOW_BARE_CARGO=1` (command prefix or
    process env) for `--version` capability probes and the rare
    non-Rust shell script that shadows the name.

The issue's suggested Cargo.toml-proximity heuristic was considered
and rejected: Claude Code spawns hooks with cwd pinned to the
session root (`cd "$d"` in settings.json), so any walk-up from
os.getcwd() runs from FastLED root regardless of where the bash
command actually executes. That makes the gate either silently
miss cross-project cases or hard-block any cargo anywhere. The
tool-name match by itself is precise enough — substring tests
(`mycargo`, `cargo-build`, `CARGO_RUSTFLAGS=`) confirm no false
positives, and the override env var handles the rare edge case.

Closes #2871.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a pre-command hook script and registration that blocks bare invocations of Rust tools (cargo, rustc, rustfmt, clippy-driver) unless they run under soldr, with environment-variable-aware command parsing, mid-chain detection, bypass flags, and tailored error messaging.

Changes

Rust tool guard hook

Layer / File(s) Summary
Rust tool guard specification and constants
ci/hooks/rust_tool_guard.py
Module documentation describes blocking bare Rust tool invocations, detection rules (first-token and mid-chain), bypass mechanism (FL_AGENT_ALLOW_BARE_CARGO), and exit codes. Rust tool allowlist (cargo, rustc, rustfmt, clippy-driver) and compiled regex for parsing VAR=value env prefixes are defined.
Command parsing and rust tool detection
ci/hooks/rust_tool_guard.py
strip_env_prefix() parses and removes leading environment-variable assignments from commands, handling both quoted and unquoted values. _matches_rust_tool() detects whether a command invokes a Rust tool as the first token or mid-chain, while exempting soldr-prefixed commands.
Hook entry point and enforcement logic
ci/hooks/rust_tool_guard.py
main() loads JSON payload from stdin, validates tool invocation type and command field, checks FL_AGENT_ALLOW_BARE_CARGO override, invokes detection helpers, blocks with stderr message and exit code 2 when a bare Rust tool is found, and exits 0 on bypass or non-applicable inputs.
Hook registration in settings
.claude/settings.json
New Bash matcher hook registered to run ci/hooks/rust_tool_guard.py via uv run python, with project-root discovery (walking up to pyproject.toml), merge-conflict-marker guard, FL_HOOK_SKIP/FL_HOOK_SOFT escapes, and 10-second timeout.

Sequence Diagram

sequenceDiagram
  participant Agent
  participant PreToolUseHook as PreToolUseHook<br/>(Hook system)
  participant RustGuard as rust_tool_guard.py
  participant JSONInput as JSON Payload
  Agent->>PreToolUseHook: User runs cargo build ...
  PreToolUseHook->>RustGuard: Invoke hook (JSON stdin)
  RustGuard->>JSONInput: Read payload
  RustGuard->>RustGuard: Strip env prefixes from command
  RustGuard->>RustGuard: Detect if rust tool invoked?
  alt Tool detected & no override
    RustGuard->>Agent: Print error: rewrite to soldr cargo build ...
    RustGuard->>Agent: Exit code 2 (block)
  else Tool not detected OR override set
    RustGuard->>Agent: Exit code 0 (allow)
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related issues

Possibly related PRs

  • FastLED/FastLED#2295: Both PRs modify .claude/settings.json hook commands with the same walk-up-for-pyproject.toml + uv run python ci/hooks/<script>.py root-resolution pattern.
  • FastLED/FastLED#2606: The new Bash hook reuses the same .claude/settings.json conventions for root resolution, merge-conflict-marker guarding, and FL_HOOK_SKIP/FL_HOOK_SOFT escape hatches as the retrieved PR.

Poem

🐰 A guard hops in to block the bare Rust commands, _
No more cold cargo builds wasting precious time—
soldr caches shine, zccache warms the rhyme,
Cross-project sessions now work as they should. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes the main change: adding a rust_tool_guard PreToolUse hook for soldr enforcement.
Linked Issues check ✅ Passed The PR fully addresses all coding requirements from issue #2871: adds rust_tool_guard.py hook detecting cargo/rustc/rustfmt/clippy-driver invocations, integrates it into .claude/settings.json, includes soldr-prefix detection and FL_AGENT_ALLOW_BARE_CARGO bypass, and provides appropriate error messaging.
Out of Scope Changes check ✅ Passed All changes are directly aligned with issue #2871 objectives: the new hook implementation, integration into settings, and testing all address the core goal of enforcing soldr-prefixed Rust tool invocations.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/2871-rust-tool-guard

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@ci/hooks/rust_tool_guard.py`:
- Around line 85-101: The function strip_env_prefix currently returns a tuple;
define a `@dataclass` (e.g., EnvPrefixResult) decorated with `@typechecked`
containing fields rest: str and env_vars: dict[str, str], change
strip_env_prefix's signature to return EnvPrefixResult and return an instance of
that dataclass instead of a tuple, and update all callers that currently unpack
the tuple to use the dataclass attributes (result.rest and result.env_vars).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 89201eb3-78b9-4521-b1f9-2d4053821166

📥 Commits

Reviewing files that changed from the base of the PR and between 2347fdf and 300d19d.

📒 Files selected for processing (2)
  • .claude/settings.json
  • ci/hooks/rust_tool_guard.py

Comment on lines +85 to +101
def strip_env_prefix(command: str) -> tuple[str, dict[str, str]]:
"""Strip leading `VAR=value` env-var assignments. Return (rest, vars)."""
env_vars: dict[str, str] = {}
rest = command.lstrip()
while True:
m = _ENV_PREFIX_RE.match(rest)
if not m:
break
name = m.group(1)
value = m.group(2)
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
elif value.startswith("'") and value.endswith("'"):
value = value[1:-1]
env_vars[name] = value
rest = rest[m.end() :]
return rest, env_vars

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Replace tuple return with dataclass per coding guidelines.

Guideline 10 requires: "Return dataclass structs instead of tuples or dicts for functions with multiple return values." This function returns (rest, env_vars) as a tuple; refactor to a dataclass for better type safety and clarity.

As per coding guidelines, use @typechecked with @dataclass for runtime type validation.

♻️ Proposed refactor using dataclass

Add the dataclass definition after imports:

 import sys
+from dataclasses import dataclass
+from typeguard import typechecked


 RUST_TOOLS = ("cargo", "rustc", "rustfmt", "clippy-driver")
+
+
+@typechecked
+@dataclass
+class EnvStripResult:
+    """Result of stripping env-var prefixes from a command."""
+    rest: str
+    env_vars: dict[str, str]

Then update the function signature and return:

-def strip_env_prefix(command: str) -> tuple[str, dict[str, str]]:
+def strip_env_prefix(command: str) -> EnvStripResult:
     """Strip leading `VAR=value` env-var assignments. Return (rest, vars)."""
     env_vars: dict[str, str] = {}
     rest = command.lstrip()
     while True:
         m = _ENV_PREFIX_RE.match(rest)
         if not m:
             break
         name = m.group(1)
         value = m.group(2)
         if value.startswith('"') and value.endswith('"'):
             value = value[1:-1]
         elif value.startswith("'") and value.endswith("'"):
             value = value[1:-1]
         env_vars[name] = value
         rest = rest[m.end() :]
-    return rest, env_vars
+    return EnvStripResult(rest=rest, env_vars=env_vars)

Update call sites (lines 112, 151, 174):

-    rest, _ = strip_env_prefix(command.lstrip())
+    result = strip_env_prefix(command.lstrip())
+    rest = result.rest
-    _, command_env_vars = strip_env_prefix(command)
+    result = strip_env_prefix(command)
+    command_env_vars = result.env_vars
-    rest_no_env, _ = strip_env_prefix(command.lstrip())
+    result = strip_env_prefix(command.lstrip())
+    rest_no_env = result.rest
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ci/hooks/rust_tool_guard.py` around lines 85 - 101, The function
strip_env_prefix currently returns a tuple; define a `@dataclass` (e.g.,
EnvPrefixResult) decorated with `@typechecked` containing fields rest: str and
env_vars: dict[str, str], change strip_env_prefix's signature to return
EnvPrefixResult and return an instance of that dataclass instead of a tuple, and
update all callers that currently unpack the tuple to use the dataclass
attributes (result.rest and result.env_vars).

Source: Coding guidelines

@zackees
zackees merged commit 280ffb1 into master Jun 7, 2026
9 of 10 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 7, 2026
@zackees
zackees deleted the feat/2871-rust-tool-guard branch August 21, 2026 19:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

tooling: enforce soldr cargo for Rust/fbuild builds via FastLED's PreToolUse hook

1 participant