Repository navigation
fix(discover): log real hook decisions instead of guessing coverage retroactively - #3206
Conversation
Perf note:
|
| mean | |
|---|---|
develop (no DB write) |
~12.6 ms |
| this PR as-is (SQLite write/call) | ~13.5 ms (+0.9 ms, ~7%) |
| prototype below (jsonl append) | ~12.9 ms (+0.3 ms, ~2%) |
Confirmed with ls/sqlite3 that develop and the prototype never create a .db file on this path at all, while this PR's binary does, on every call.
Suggested alternative
Instead of a SQLite table, log to a plain append-only hook_decisions.jsonl (same cost class as the existing plaintext audit log — just an OpenOptions::append write, no connection/DDL), and have discover read that file back directly instead of querying SQL:
// src/core/tracking.rs
fn hook_decisions_log_path() -> Result<PathBuf> {
Ok(get_db_path()?.with_file_name("hook_decisions.jsonl"))
}
pub fn append_hook_decision(
session_id: &str,
tool_use_id: &str,
project_path: &str,
raw_cmd: &str,
decision: HookOutcome,
rewritten_cmd: Option<&str>,
rtk_version: &str,
) -> Result<()> {
let path = hook_decisions_log_path()?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let mut file = std::fs::OpenOptions::new().create(true).append(true).open(&path)?;
let line = serde_json::json!({
"timestamp": Utc::now().to_rfc3339(),
"session_id": session_id,
"tool_use_id": tool_use_id,
"project_path": project_path,
"raw_cmd": raw_cmd,
"decision": decision.to_string(),
"rewritten_cmd": rewritten_cmd,
"rtk_version": rtk_version,
});
use std::io::Write;
writeln!(file, "{line}")?;
Ok(())
}
pub type HookDecisionsLog = (HashMap<String, HookDecisionRecord>, Option<DateTime<Utc>>);
pub fn read_hook_decisions_since(cutoff: DateTime<Utc>) -> Result<HookDecisionsLog> {
let path = hook_decisions_log_path()?;
let content = match std::fs::read_to_string(&path) {
Ok(c) => c,
Err(_) => return Ok((HashMap::new(), None)),
};
let mut map = HashMap::new();
let mut earliest: Option<DateTime<Utc>> = None;
for line in content.lines() {
let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else { continue };
let Some(ts) = v.get("timestamp").and_then(|t| t.as_str())
.and_then(|s| DateTime::parse_from_rfc3339(s).ok())
.map(|dt| dt.with_timezone(&Utc)) else { continue };
earliest = Some(match earliest { Some(e) if e <= ts => e, _ => ts });
if ts < cutoff { continue; }
let (Some(tool_use_id), Some(decision)) = (
v.get("tool_use_id").and_then(|t| t.as_str()),
v.get("decision").and_then(|d| d.as_str()).and_then(|s| s.parse::<HookOutcome>().ok()),
) else { continue };
map.insert(tool_use_id.to_string(), HookDecisionRecord { decision });
}
Ok((map, earliest))
}And the two call sites become:
--- a/src/hooks/hook_cmd.rs
+++ b/src/hooks/hook_cmd.rs
@@ fn log_hook_decision(v: &Value, cmd: &str, decision: HookOutcome, rewritten: Option<&str>) {
- let Ok(tracker) = crate::core::tracking::Tracker::new() else {
- return;
- };
- if let Err(e) = tracker.record_hook_decision(
+ if let Err(e) = crate::core::tracking::append_hook_decision(
session_id,
tool_use_id,
project_path,--- a/src/discover/mod.rs
+++ b/src/discover/mod.rs
@@ pub fn run(
- Tracker::new()
- .map(|t| {
- let log = t.hook_decisions_since(cutoff).unwrap_or_default();
- let measured_since = t.earliest_hook_decision_timestamp().ok().flatten();
- (log, measured_since)
- })
- .unwrap_or_default();
+ crate::core::tracking::read_hook_decisions_since(cutoff).unwrap_or_default();The tradeoff: discover's cutoff filtering and measured_since become a linear scan over the jsonl file instead of an indexed SQL query. For the actual data volume here (one line per Bash tool call, and discover already runs once per invocation, not in a hot loop) that's negligible — but worth being explicit about the tradeoff since it's a real one.
I have this fully working as a prototype on top of this branch (builds clean, cargo clippy --all-targets clean, full cargo test --all passes — including rewritten versions of the 4 tests that exercised record_hook_decision/hook_decisions_since/earliest_hook_decision_timestamp directly, now driven against a temp file instead of the shared RTK_DB_PATH env var to avoid the parallel-test race already flagged elsewhere in tracking.rs). Happy to open it as a PR against this branch, or just paste the full diff here, whichever is more useful — let me know.
(Small unrelated nit I noticed while in there: record_hook_decision's doc comment is currently duplicated — two /// blocks with #[allow(clippy::too_many_arguments)] sandwiched in between. Worth a quick cleanup regardless of which direction this perf question goes.)
|
@pszymkowiak Thanks for the benchmark — you're right that Proposed fix: gate schema migration behind
|
|
Follow-up with a cleaner measurement: I re-ran the same three binaries/methodology on quieter, better hardware (my earlier numbers had σ ~1.2-1.5ms of noise, which was too close to the effect size to draw a real conclusion from). So: +0.4ms for the PR as it stands, +0.3ms with the Dug into where that remaining +0.3ms actually comes from, since the gate only removes the DDL re-run (12 statements down to 1 Net: the |
fbce926 to
2aef8e8
Compare
|
@pszymkowiak rebased with the schema migration gated behind PRAGMA user_version + some more iteration on it:
|
12fb8dd to
c26cda7
Compare
|
Hey @KuSh Since no news from Patrick i've went through the PR so we can go forward with it. The fix works. On my 30d history (473 sessions, ~43k commands) coverage goes 2.2% → 27.9%, and the ~3.19M "saveable" tokens drop to ~201K. Top base misses were Pain on the estimate path (not the measured one):
Also observed a crash with "rtk discover --since 100000000" Questions on direction:
Also now measured and estimated get blended into one number, so you can't tell which part actually happened and which part is a guess. The fallback re-derives old history from today's config, which is the same kind of guessing the PR set out to remove. |
Addresses aeppling's review comment on #3206: - estimate_hook_coverage now short-circuits on hook_installed before touching permissions/lexer/registry, and check_command_for's per-command settings-file I/O is replaced with a one-time load (permissions:: load_rules_for) threaded through as PermissionRules. This is what made the estimate path 80s vs 2.5s on the measured path, and made "hook never installed" histories cost ~100s for no reason. - RTK_DISABLED= bypass counting now always uses estimate_hook_coverage directly instead of hook_coverage's measured-log lookup: a bypassed command's real hook decision is always Defer (get_rewritten short- circuits to None whenever RTK_DISABLED= is present), so consulting the measured log made this section silently report zero once hook-decision logging backfilled — exactly the "goes empty" bug reported. - rtk discover --since <huge> crashed with "DateTime - TimeDelta overflowed"; cutoff computation is now a small pure helper (hook_decisions_cutoff) that clamps instead of panicking. - Fixed a pre-existing test compile error in hook_cmd.rs (HookDecision::AskRewrite is a tuple variant, a test still constructed it as a struct literal). Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XRnm5rkvrkzt8UPLkjSQzN
|
Thanks for the deep review, @aeppling — pushed fixes for everything concrete you found: Perf (80s vs 2.5s / the 100s-with-no-hook case): two compounding bugs. RTK_DISABLED= section going empty: root cause was that a bypassed command's real logged hook decision is always Crash on Also found (separately from your review) that the branch didn't compile its own test suite — Ran
On your direction questions — not mine to settle, but for what it's worth on current state: the All tests pass ( |
|
Following up on #3657 (closed — agreed it belongs here, not deferred): both points are now fixed in this PR.
Verified end-to-end with a real PreToolUse payload (row lands correctly in `hook_decisions`) and `cargo test --all` (2693 passed, clippy clean). Local `hyperfine` before/after on fast local storage (ext4) showed no measurable difference, as expected at this syscall scale — the win is on slower/network-backed home directories, same caveat this file already notes elsewhere for WAL mode. |
|
Ran another
`cargo test --all`: 2746 passed (post-merge with develop). `cargo clippy`: clean. Verified end-to-end with a real PreToolUse payload and the `--since` crash repro. |
…run) The first `/code-review max pr 3681` run targeted the wrong branch; rerun against the actual PR #3206 worktree found a large, mostly-legitimate set of issues (10 finder angles + 6 verification agents + 1 sweep, ~365K tokens). Addressed the real ones: - run_claude() called log_hook_decision (a synchronous SQLite write with a 5s busy_timeout) BEFORE writing the hook's stdout response Claude Code is synchronously blocked on. Reordered: write the response first, log after — log_hook_decision is documented as a best-effort side channel that must never affect the hook's real output, so it must never sit in front of it. - estimate_hook_coverage's permission-verdict check ran against an isolated chain segment (`part`, from discover's pre-split parts) instead of the full raw command, so a Deny rule matching only a *sibling* segment (`cd /sensitive && grep -rn foo .`) was invisible when evaluating the other segment alone — check_command_with_rules only re-derives the chain from whatever string it's given. hook_coverage/estimate_hook_coverage now take the permission-check command and the rewrite-check command as separate params: the former must always be the full unsplit command line, the latter is genuinely per-segment. Applies to both the normal path and the RTK_DISABLED= bypass path. - format_text's "no missed savings" early return didn't account for rtk_disabled_count, so a user whose *every* command ran under RTK_DISABLED= (never populating supported/unsupported) got told "RTK usage looks good!" while the RTK_DISABLED bypass section — which doesn't depend on supported/unsupported — silently never rendered. - The RTK_DISABLED= branch in run() always `continue`d after resolving the bypass question, even when the underlying command genuinely wouldn't have been covered anyway (hook not installed / excluded by config) — such a command vanished from the entire report, counted only in total_commands. Now falls through to normal missed-savings classification in that case, using the env-stripped command. - maybe_cleanup_hook_decisions' sampled retention sweep prunes hook_decisions by the same 90-day DEFAULT_HISTORY_DAYS window as the rest of the tracking DB — so earliest_hook_decision_timestamp() (and the report's "measured hook-decision logging began {date}" text) never actually reflects an install date, just a rolling ~90-day boundary, contradicting this PR's own comment that Estimated coverage "fades out" and "after ~90 days only Measured should remain". Corrected the report text, field docs, and code comments to describe this honestly: Estimated is a permanent fallback for anything beyond the retention window, not a transitional state. - record_hook_decision propagated maybe_cleanup_hook_decisions' error via `?` as if it were the INSERT's own failure, even though the INSERT had already committed as its own autocommit statement — misattributing a retention-sweep hiccup as "hook_decisions logging failed". Now best-effort (warns, doesn't fail the write that already succeeded). - rtk init's ensure_schema_fresh() call discarded its Result with a silent `let _ = ...`, the exact anti-pattern rust-patterns.md calls out, and an outlier next to this same function's other failure paths which do warn. Now warns (still never fails rtk init over it, per the existing comment's intent). - get_rewritten (via hook_rewrite_params) and Tracker::new() (via get_db_path, now called by log_hook_decision on every single hook invocation) each independently called Config::load() — two full disk-read-plus-TOML-parse round trips per Bash tool call instead of one. Added a process-wide OnceLock-cached config reader, used only by these read-only hot-path callers (never by config-mutating paths like save_telemetry_consent, which must keep observing fresh writes). - Minor: HookOutcome::as_str() avoids a per-call to_string() allocation in record_hook_decision; hook_decisions_since does one pass instead of collecting into an intermediate Vec first; a test that claimed to isolate "tool_use_id missing" actually only exercised "session_id missing" (which short-circuits first) — added a properly isolated case. Deliberately not fixed here (noted, not silently dropped): - split_command_chain's stop-at-pipe truncation (a command after `|` is invisible to the whole classification loop, not just the new coverage estimate) predates this PR entirely and is a bigger scope than this fixup — rtk discover's pipe handling in general, not just hook_coverage. - session_cmd.rs's count_rtk_commands (rtk session) doesn't use the new hook_coverage/measured-log machinery discover::run() now does, so `rtk session` and `rtk discover` can disagree on the same transcript — a different command's counting logic, out of this PR's stated scope. - warn_if_missing_table's self-heal hint isn't wired into plain `rtk gain`'s read paths (get_recent/get_summary/etc.) — pre-existing gap unrelated to hook_decisions. - The redundant restrict_file stat on db_path (once explicitly, once again inside restrict_db_files) is real but sub-microsecond and touches an already-tested restrict_db_files contract for no meaningful gain. cargo test --all: 2749 passed. clippy clean. Verified end-to-end: RTK_DISABLED section no longer hidden, RTK_DISABLED-but-uncovered command now shows as missed savings, real hook payload still writes hook_decisions correctly. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XRnm5rkvrkzt8UPLkjSQzN
|
Ran `/code-review max`. 10 finder angles + 6 verification agents + a completeness sweep, ~365K tokens. This one found real issues, several of them in code I'd already touched in prior rounds: Fixed:
Deliberately not fixed here (filed as separate issues rather than silently dropped, since they're either pre-existing or a different command's scope):
`cargo test --all`: 2749 passed. clippy clean. Verified end-to-end (synthetic transcripts + real hook payloads): the RTK_DISABLED section no longer hides itself, a bypassed-but-uncovered command now shows as missed savings instead of vanishing, hook_decisions still writes correctly. |
…etroactively rtk discover previously re-derived whether a historical transcript command would have been covered by the hook using *today's* hook-install state and registry, applied uniformly across the whole scan window. That mis-classifies history that predates the hook being installed or a registry/permission change (PR #3164 attempted a fix but had this same gap, plus missed permissions.deny and the RTK_DISABLED= bypass bucket). Log the real PreToolUse decision (allow/ask/deny/defer) at the moment the Claude Code hook actually runs, keyed by tool_use_id -- the same id Claude Code stores on the transcript's tool_use/tool_result blocks -- so discover can join real hook outcomes back to transcript entries instead of guessing. Falls back to a corrected heuristic (now permission-deny aware) only for history that predates logging, and labels that portion of the report as an estimate. Fixes #3148
- Stop running the 3-table cleanup_old() sweep on every PreToolUse hook call: record_hook_decision() now only INSERTs, since this fires on every Bash command (the <10ms hot path), not just RTK-covered ones. Retention for hook_decisions piggybacks on the existing record()/record_parse_failure() cleanup cadence instead. - Split process_claude_payload into a thin JSON-extraction wrapper plus a pure process_claude_payload_from_decision(cmd, decision), mirroring the copilot_cli_response_from_decision/droid_response_from_decision pattern already used elsewhere in this file. Makes the Allow/Ask/Deny/Defer decision matrix unit-testable without depending on real permission config. - Track rtk_disabled_estimated alongside rtk_disabled_count so the RTK_DISABLED= bypass bucket gets the same "this portion is an estimate" disclosure as already_rtk_estimated, instead of silently dropping the Estimated/Measured distinction when a bypass is counted. The Copilot CLI auto-allow-for-simple-Default-verdict divergence from the Claude host path (copilot_cli_response_from_decision's is_simple check) predates this branch and is out of scope here.
Tracker::new() runs on every rtk <cmd> invocation and every PreToolUse hook call, but was re-running the full CREATE TABLE/INDEX/ALTER migration sequence on every single call. Gate it behind a cheap user_version pragma read so migrations only run once per database. Also pre-warms the schema during rtk init so install/upgrade absorbs the one-time migration cost instead of the first live hook call. Co-Authored-By: Claude Sonnet 5 <[email protected]>
The Deny/Defer -> Skip refactor for hook-decision logging switched the
audit-log action string to HookOutcome::Display ("deny"/"defer"),
dropping the "skip:" prefix rtk hook audit's per-reason breakdown
filters on. Map the Skip decision to the audit-log reason explicitly
instead of reusing the tracking-DB Display string.
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Investigated making the Estimated coverage fallback chain-level to match Measured: the real hook's Allow/Ask/Deny verdict is chain-wide, but the actual rewrite (registry::rewrite_command) is best-effort per segment, so neither Measured (one hook_decisions row per tool_use_id, no per-segment detail) nor Estimated can fully attribute coverage to the right segment of a chained command. Fixing this properly needs per-segment logging in hook_decisions, out of scope here. Document the limitation instead — Estimated is a transitional fallback that fades out as hook_decisions backfills history, so this converges on its own. Co-Authored-By: Claude Sonnet 5 <[email protected]>
session_cmd.rs's count_rtk_commands treated any "rtk "-prefixed part as covered, including "rtk proxy <cmd>" — the deliberate unfiltered escape hatch discover::is_already_rtk was already excluding for the same adoption-counting purpose. Reuse that shared helper instead of duplicating (and diverging from) its logic. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…in tests The 8 flagged remove_file calls are all inside #[cfg(test)] mod tests, cleaning up each test's own throwaway temp DB file under env::temp_dir() — not reachable in the compiled binary and never touching user data. Mirrors the existing nosemgrep convention already used in hooks/init.rs. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Addresses aeppling's review comment on #3206: - estimate_hook_coverage now short-circuits on hook_installed before touching permissions/lexer/registry, and check_command_for's per-command settings-file I/O is replaced with a one-time load (permissions:: load_rules_for) threaded through as PermissionRules. This is what made the estimate path 80s vs 2.5s on the measured path, and made "hook never installed" histories cost ~100s for no reason. - RTK_DISABLED= bypass counting now always uses estimate_hook_coverage directly instead of hook_coverage's measured-log lookup: a bypassed command's real hook decision is always Defer (get_rewritten short- circuits to None whenever RTK_DISABLED= is present), so consulting the measured log made this section silently report zero once hook-decision logging backfilled — exactly the "goes empty" bug reported. - rtk discover --since <huge> crashed with "DateTime - TimeDelta overflowed"; cutoff computation is now a small pure helper (hook_decisions_cutoff) that clamps instead of panicking. - Fixed a pre-existing test compile error in hook_cmd.rs (HookDecision::AskRewrite is a tuple variant, a test still constructed it as a struct literal). Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XRnm5rkvrkzt8UPLkjSQzN
/code-review high on the previous commit found: - discover_sessions_in_projects_dir did an unguarded `days * 86400` u64 multiply — same overflow class as the hook_decisions_cutoff crash, hit earlier in the same run() before that fix was ever reached. Fixed with checked_mul. - rtk hook audit --since <huge> panicked with the identical "DateTime - TimeDelta overflowed" crash rtk discover --since had. Extracted the clamping cutoff logic into a shared core::utils::days_ago_cutoff, used by both rtk discover and rtk hook audit now. - rtk_disabled_estimated is now always equal to rtk_disabled_count (a bypassed command's real hook decision is always Defer, so this bucket can never be "measured" even in principle) — documented that invariant on the field and fixed the one test that exercised a count>0/estimated==0 state run() can no longer produce. - Documented on hook_coverage itself (not just at the call site) that it must not be used for RTK_DISABLED-bypassed commands, so a future change doesn't silently reintroduce the bug this fixes. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XRnm5rkvrkzt8UPLkjSQzN
Low-hanging fruit from the second /code-review high pass (no correctness issues found; the other two findings — the hook's per-call SQLite write and hook_decisions' unbounded growth for deny/defer-heavy users — are architectural tradeoffs inherent to the ground-truth-logging feature, filed separately if they need addressing rather than folded in here). hook_coverage/estimate_hook_coverage/estimate_hook_coverage_with_verdict threaded 5-7 positional params (hook_log, hook_installed, rules, excluded, transparent_prefixes) through every call site. With excluded and transparent_prefixes both Vec<String>, a swapped argument order at a call site would compile silently and misclassify RTK_DISABLED bypass coverage. Bundled into one CoverageContext built once in run(), leaving only the actual per-command args (cmd, tool_use_id) positional. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XRnm5rkvrkzt8UPLkjSQzN
Addresses both points from #3657 (filed after the second /code-review high pass) directly in this PR, since they're new cost introduced by this PR's own hook_decisions ground-truth logging, not pre-existing debt: - log_hook_decision now calls Tracker::new() on every single PreToolUse hook invocation (not just RTK-covered ones), where before this PR that path did at most a JSON audit-log append. Tracker::new()'s open_and_prepare() paid a full create_private_dir + a redundant pre-create open()/close() (on top of the real Connection::open right after it) + an unconditional chmod across the db/-wal/-shm files, every single call. set_owner_only now skips the chmod syscall once permissions already match (self-healing a genuinely-wrong-permission legacy file still works — it just isn't reconfirmed on every call), and the pre-create open()/close() is skipped entirely once the DB file already exists. No behavior change for the first-ever-run / permission-drift-healing paths, fewer syscalls on every call after that. - hook_decisions could grow unbounded for a user whose commands are almost entirely Deny/Defer'd: record_hook_decision deliberately skips the full 3-table cleanup_old() (hot-path budget), and those decisions rarely trigger record()'s/record_parse_failure()'s own cleanup either. Added maybe_cleanup_hook_decisions: a single-table DELETE sweep sampled at roughly 1-in-500 calls (via should_sample_cleanup, a pure/testable core), bounding growth without paying a DELETE on every hook invocation. Verified end-to-end with a real PreToolUse payload (hook_decisions row written correctly) and cargo test --all (2693 passed). Local hyperfine before/after on fast local storage showed no measurable difference (as expected — these are microsecond-scale syscalls on ext4/tmpfs); the reduction matters on the slower/network-backed home directories the original review comment's NFS caveat already calls out elsewhere in this file for WAL mode. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XRnm5rkvrkzt8UPLkjSQzN
Multi-angle review of the full branch surfaced several real issues on top of the previous two rounds: - set_owner_only's fast-path masked the mode with & 0o777 before comparing, so a file with setuid/setgid/sticky set (e.g. 0o4600) read as "already 0o600" and permanently skipped the chmod that would clear it — defeating the self-heal for exactly the tampered/restored-backup files it exists to catch. Mask is now 0o7777. The regression test round-trips through the pure comparison logic (mode_already_correct) rather than a real chmod, since an unprivileged chmod setting setuid isn't reliably honored across every environment (this sandbox's filesystem silently drops it, which made an earlier filesystem-based version of the test flaky). - open_and_prepare's skip-when-file-exists optimization (previous round) removed the only pre-Connection::open chmod for an existing DB, so a file whose permissions had drifted would get opened/migrated before restrict_db_files healed it at the very end. Now re-chmods (via the now-cheap restrict_file) before Connection::open for the existing-file case too, preserving the original "never let SQLite touch a loosely-permissioned file" invariant without paying open_private's redundant open()/close(). - should_sample_cleanup's 1-in-500 sampling read Utc::now(). timestamp_subsec_nanos(), which silently breaks on any clock source whose resolution isn't fine enough to hit every residue mod 500 (e.g. a coarse virtualized/Windows timer) — could fire on nearly 100% or ~0% of calls depending on tick size, with no visible symptom short of profiling. Now hashes tool_use_id (always distinct per call) instead of the wall clock. - discover::run silently swallowed Tracker::hook_decisions_since/ earliest_hook_decision_timestamp errors via unwrap_or_default()/ ok().flatten(), reporting "no hook-decision log yet" for what could actually be a corrupted database. Now warns consistently with every other hook_decisions-touching path's warn_if_missing_table pattern. - The RTK_DISABLED= bypass path checked permission rules against the env-prefix-stripped actual_cmd, while the real hook checks against the full raw command (prefix intact) — a permission rule anchored on the literal prefixed string would evaluate differently. estimate_hook_coverage now takes the permission-check command and the rewrite-check command as separate params (they must differ for the bypass case, for opposite reasons — see its doc comment), and a new would_be_covered_without_bypass wrapper makes the correct call reachable by name instead of only by doc comment (a prior round already had to catch the hook_coverage-vs-estimate mixup once). - registry::rewrite_command recompiled its exclude-pattern regexes on every call; estimate_hook_coverage_with_verdict now calls it once per historical command inside discover's scan loop, turning a previously-rare cost into a hot-loop one — exactly the class of bug this PR's own PermissionRules/ hook_status caching already fixed elsewhere. Split into rewrite_command (compiles, thin wrapper) and rewrite_command_precompiled (the real work), with CoverageContext now holding precompiled patterns built once per discover run. - provider.rs's overflow-safe cutoff comment referenced a function name (discover::hook_decisions_cutoff) that had already been refactored away into core::utils::days_ago_cutoff in a later commit — fixed the stale reference and documented why the two implementations are legitimately separate (SystemTime vs chrono DateTime<Utc>) rather than unified. cargo test --all: 2697 passed. clippy clean. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XRnm5rkvrkzt8UPLkjSQzN
…run) The first `/code-review max pr 3681` run targeted the wrong branch; rerun against the actual PR #3206 worktree found a large, mostly-legitimate set of issues (10 finder angles + 6 verification agents + 1 sweep, ~365K tokens). Addressed the real ones: - run_claude() called log_hook_decision (a synchronous SQLite write with a 5s busy_timeout) BEFORE writing the hook's stdout response Claude Code is synchronously blocked on. Reordered: write the response first, log after — log_hook_decision is documented as a best-effort side channel that must never affect the hook's real output, so it must never sit in front of it. - estimate_hook_coverage's permission-verdict check ran against an isolated chain segment (`part`, from discover's pre-split parts) instead of the full raw command, so a Deny rule matching only a *sibling* segment (`cd /sensitive && grep -rn foo .`) was invisible when evaluating the other segment alone — check_command_with_rules only re-derives the chain from whatever string it's given. hook_coverage/estimate_hook_coverage now take the permission-check command and the rewrite-check command as separate params: the former must always be the full unsplit command line, the latter is genuinely per-segment. Applies to both the normal path and the RTK_DISABLED= bypass path. - format_text's "no missed savings" early return didn't account for rtk_disabled_count, so a user whose *every* command ran under RTK_DISABLED= (never populating supported/unsupported) got told "RTK usage looks good!" while the RTK_DISABLED bypass section — which doesn't depend on supported/unsupported — silently never rendered. - The RTK_DISABLED= branch in run() always `continue`d after resolving the bypass question, even when the underlying command genuinely wouldn't have been covered anyway (hook not installed / excluded by config) — such a command vanished from the entire report, counted only in total_commands. Now falls through to normal missed-savings classification in that case, using the env-stripped command. - maybe_cleanup_hook_decisions' sampled retention sweep prunes hook_decisions by the same 90-day DEFAULT_HISTORY_DAYS window as the rest of the tracking DB — so earliest_hook_decision_timestamp() (and the report's "measured hook-decision logging began {date}" text) never actually reflects an install date, just a rolling ~90-day boundary, contradicting this PR's own comment that Estimated coverage "fades out" and "after ~90 days only Measured should remain". Corrected the report text, field docs, and code comments to describe this honestly: Estimated is a permanent fallback for anything beyond the retention window, not a transitional state. - record_hook_decision propagated maybe_cleanup_hook_decisions' error via `?` as if it were the INSERT's own failure, even though the INSERT had already committed as its own autocommit statement — misattributing a retention-sweep hiccup as "hook_decisions logging failed". Now best-effort (warns, doesn't fail the write that already succeeded). - rtk init's ensure_schema_fresh() call discarded its Result with a silent `let _ = ...`, the exact anti-pattern rust-patterns.md calls out, and an outlier next to this same function's other failure paths which do warn. Now warns (still never fails rtk init over it, per the existing comment's intent). - get_rewritten (via hook_rewrite_params) and Tracker::new() (via get_db_path, now called by log_hook_decision on every single hook invocation) each independently called Config::load() — two full disk-read-plus-TOML-parse round trips per Bash tool call instead of one. Added a process-wide OnceLock-cached config reader, used only by these read-only hot-path callers (never by config-mutating paths like save_telemetry_consent, which must keep observing fresh writes). - Minor: HookOutcome::as_str() avoids a per-call to_string() allocation in record_hook_decision; hook_decisions_since does one pass instead of collecting into an intermediate Vec first; a test that claimed to isolate "tool_use_id missing" actually only exercised "session_id missing" (which short-circuits first) — added a properly isolated case. Deliberately not fixed here (noted, not silently dropped): - split_command_chain's stop-at-pipe truncation (a command after `|` is invisible to the whole classification loop, not just the new coverage estimate) predates this PR entirely and is a bigger scope than this fixup — rtk discover's pipe handling in general, not just hook_coverage. - session_cmd.rs's count_rtk_commands (rtk session) doesn't use the new hook_coverage/measured-log machinery discover::run() now does, so `rtk session` and `rtk discover` can disagree on the same transcript — a different command's counting logic, out of this PR's stated scope. - warn_if_missing_table's self-heal hint isn't wired into plain `rtk gain`'s read paths (get_recent/get_summary/etc.) — pre-existing gap unrelated to hook_decisions. - The redundant restrict_file stat on db_path (once explicitly, once again inside restrict_db_files) is real but sub-microsecond and touches an already-tested restrict_db_files contract for no meaningful gain. cargo test --all: 2749 passed. clippy clean. Verified end-to-end: RTK_DISABLED section no longer hidden, RTK_DISABLED-but-uncovered command now shows as missed savings, real hook payload still writes hook_decisions correctly. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XRnm5rkvrkzt8UPLkjSQzN
3fc249d to
c4b25d2
Compare
|
Thanks for the quick turnaround. Ran a fuzz pass against develop before going further. ~28k differential invocations: Zero behavioural divergence, no new panic or hang. Rewrite behaviour is unchanged, which is the invariant that mattered here. It also fixes two develop bugs for free: LGTM on the behaviour side. |
Summary
rtk discoverre-derives whether a historical transcript command would have been covered by the PreToolUse hook using today's hook-install state and registry, applied uniformly across the whole scan window (default 30 days). PR #3164 attempted a fix along these lines but has the same gap: history that predates the hook being installed, or a registry/permission change, gets mis-classified — plus it missespermissions.denyand doesn't gate theRTK_DISABLED=bypass bucket the same way.This PR logs the real PreToolUse decision (allow/ask/deny/defer) at the moment the Claude Code hook actually runs, keyed by
tool_use_id— the same id Claude Code stores on the transcript'stool_use/tool_resultblocks (verified empirically, not assumed) — sodiscovercan join real hook outcomes back to transcript entries instead of guessing. Falls back to a heuristic estimate only for history that predates logging (or exceeds the tracking DB's retention window — see below), and labels that portion of the report as an estimate rather than blending it in silently.hook_decisionsSQLite table +HookOutcomeenum (Display/FromStr), shared between the writer (hooks::hook_cmd) and reader (discover). Logging happens after the hook's real stdout response is written, never in front of it — it's a best-effort side channel and must never add latency to the tool call it's recording.ExtractedCommandnow carriestool_use_idso transcript entries can join against the log.Coverage::Measured/Coverage::Estimated: prefers the real log; the estimate fallback checksPermissionVerdict::Denyagainst the full raw command (not an isolated chain segment — a deny rule matching a sibling segment must still deny the whole chain), and stops creditingRTK_DISABLED=as a "bypass" when the hook wouldn't actually have covered the command anyway (that case now shows as a genuine missed-savings opportunity instead of disappearing from the report).already_rtk_estimated/rtk_disabled_estimated+measured_since, with a text-mode caveat explaining when/why part of a coverage number is an estimate.measured_sincereflects the oldest currently-retained log entry, not an install date —hook_decisionsis pruned by the same retention window as the rest of the tracking DB, so the estimate fallback is a permanent fact of scanning far enough back, not a transitional one.record_hook_decision()skips the full 3-tablecleanup_old()sweep on its hot path (every Bash tool call, not just RTK-covered ones), but still gets a lightweight sampled retention sweep of its own so a user whose commands are mostly denied/deferred doesn't grow the table unbounded.discoverrun instead of once per scanned command, and config is cached per-process for the hook's hot path — a large history (tens of thousands of commands) was previously dominated by this redundant I/O.rtk discover --since <very large>no longer crashes; the cutoff computation is clamped instead of overflowing.Fixes #3148
End-to-end validation
Beyond
cargo test --all(2749 passed) andcargo clippy --all-targets(clean), ran the built release binary against a synthetic Claude Code transcript to validate the fix's actual runtime behavior, isolating state viaCLAUDE_CONFIG_DIR(Claude config dir) andRTK_DB_PATH(tracking DB) so nothing touched real user data.Setup: one synthetic session transcript with four Bash tool calls, each with its own
tool_use_id:grep foo bar.py— Supported, cleanly rewritablegit status— Supported, cleanly rewritablegit status $(whoami)— Supported but contains an unattestable construct (command substitution), which the hook always defers onrtk proxy grep foo bar.py— alreadyrtk-prefixed, but via the escape hatch that must not count as coverageScenario 1 — hook never installed (no
settings.jsonin the syntheticCLAUDE_CONFIG_DIR, emptyhook_decisionstable):git status(both instances, including the unattestable one) andgrepcorrectly show as missed;rtk proxydoesn't appear in either bucket.Scenario 2 — hook installed, with real decisions logged: wrote a
settings.jsonregisteringrtk hook claudeas the PreToolUse hook, then piped the matching real PreToolUse JSON payload for each of the four commands (sametool_use_ids as the transcript) through the actual builtrtk hook claudebinary, populatinghook_decisionsfor real. Verified via direct sqlite read that all four rows landed with the expected decisions (grep→ask,git status→ask, the$(whoami)variant→defer,rtk proxy→defer). Then ranrtk discoveragainst the same DB/transcript:git status $(whoami)still correctly shows as a genuine MISS (the hook really did defer on it — this isn't just "it was estimated as uncovered", it's a measured defer).rtk proxystill doesn't inflate either bucket.--format json) confirmedalready_rtk_estimated: 0andmeasured_sinceset to the log's timestamp — proving the measured path drove the result end-to-end, not the heuristic fallback.Additional scenarios verified since: an RTK_DISABLED= bypass on a command the hook wouldn't have covered anyway now shows as missed savings rather than vanishing from the report; a chain-wide deny rule (
cd /sensitive && grep -rn foo .) matching only one segment correctly denies the whole chain in the estimate;rtk discover --since 100000000no longer panics; a real PreToolUse payload piped through the built binary still writes a correcthook_decisionsrow with the response written before the log entry.Test plan
cargo fmt --all && cargo clippy --all-targets && cargo test --all(2749 passed, 0 failed)hook_decisionsrows persist correctly via direct sqlite inspectionupstream/develop