Repository navigation
tooling: add rust_tool_guard PreToolUse hook for soldr enforcement (#2871) - #2960
Conversation
…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]>
📝 WalkthroughWalkthroughAdds 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. ChangesRust tool guard hook
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
.claude/settings.jsonci/hooks/rust_tool_guard.py
| 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 |
There was a problem hiding this comment.
🛠️ 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
Summary
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:
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
Closes #2871.
🤖 Generated with Claude Code
Summary by CodeRabbit