Skip to content

fix(discover): log real hook decisions instead of guessing coverage retroactively - #3206

Merged
KuSh merged 17 commits into
developfrom
fix/discover-hook-decision-log
Sep 2, 2026
Merged

KuSh merged 17 commits into
developfrom
fix/discover-hook-decision-log

Conversation

@KuSh

@KuSh KuSh commented Jul 25, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

rtk discover re-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 misses permissions.deny and doesn't gate the RTK_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's tool_use/tool_result blocks (verified empirically, not assumed) — so discover can 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.

  • New hook_decisions SQLite table + HookOutcome enum (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.
  • ExtractedCommand now carries tool_use_id so transcript entries can join against the log.
  • Coverage::Measured/Coverage::Estimated: prefers the real log; the estimate fallback checks PermissionVerdict::Deny against the full raw command (not an isolated chain segment — a deny rule matching a sibling segment must still deny the whole chain), and stops crediting RTK_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).
  • Report gains 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_since reflects the oldest currently-retained log entry, not an install date — hook_decisions is 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-table cleanup_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.
  • Permission rules, exclude-pattern regexes, and hook-install status are loaded/compiled once per discover run 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) and cargo 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 via CLAUDE_CONFIG_DIR (Claude config dir) and RTK_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 rewritable
  • git status — Supported, cleanly rewritable
  • git status $(whoami) — Supported but contains an unattestable construct (command substitution), which the hook always defers on
  • rtk proxy grep foo bar.py — already rtk-prefixed, but via the escape hatch that must not count as coverage

Scenario 1 — hook never installed (no settings.json in the synthetic CLAUDE_CONFIG_DIR, empty hook_decisions table):

Already using RTK: 0 commands (0.0%)
MISSED SAVINGS -- Commands RTK already handles
Command                  Count    RTK Equivalent     Status        Est. Savings
git status                   2    rtk git            existing      ~4 tokens
grep foo                     1    rtk grep           existing      ~2 tokens

git status (both instances, including the unattestable one) and grep correctly show as missed; rtk proxy doesn't appear in either bucket.

Scenario 2 — hook installed, with real decisions logged: wrote a settings.json registering rtk hook claude as the PreToolUse hook, then piped the matching real PreToolUse JSON payload for each of the four commands (same tool_use_ids as the transcript) through the actual built rtk hook claude binary, populating hook_decisions for 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 ran rtk discover against the same DB/transcript:

Already using RTK: 2 commands (50.0%)
MISSED SAVINGS -- Commands RTK already handles
Command                  Count    RTK Equivalent     Status        Est. Savings
git status                   1    rtk git            existing      ~2 tokens
  • Coverage jumped to 2/4 (50%), matching the two commands that were actually rewritable.
  • 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 proxy still doesn't inflate either bucket.
  • JSON output (--format json) confirmed already_rtk_estimated: 0 and measured_since set 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 100000000 no longer panics; a real PreToolUse payload piped through the built binary still writes a correct hook_decisions row with the response written before the log entry.

Test plan

  • cargo fmt --all && cargo clippy --all-targets && cargo test --all (2749 passed, 0 failed)
  • Manual e2e run against a synthetic transcript, hook-absent vs hook-installed-with-real-decisions (see above)
  • Verified hook_decisions rows persist correctly via direct sqlite inspection
  • Merged and resolved conflicts against upstream/develop

@pszymkowiak

Copy link
Copy Markdown
Collaborator

Perf note: log_hook_decision adds a SQLite round-trip to every PreToolUse call

Nice fix for the retroactive-guessing problem — measuring the real decision instead of re-deriving it is clearly the right approach.

One thing worth flagging before merge: log_hook_decision() now calls Tracker::new() on every single PreToolUse hook invocation (both the Rewrite and Skip paths) — i.e. every Bash tool call Claude Code makes, not just the ones rtk ends up covering. hook_cmd.rs never touched the tracking DB before this PR. Tracker::new() opens a SQLite connection, sets PRAGMA journal_mode=WAL, and runs several CREATE TABLE/INDEX IF NOT EXISTS + an ALTER TABLE + a SELECT EXISTS — all of that on the hook's hot path, which is explicitly called out elsewhere in this repo as being under a <10ms budget.

I benchmarked it with hyperfine (rtk hook claude fed a realistic payload with session_id/tool_use_id/cwd, warm DB, 200+ runs, --warmup 20):

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.)

@KuSh

KuSh commented Jul 26, 2026

Copy link
Copy Markdown
Collaborator Author

@pszymkowiak Thanks for the benchmark — you're right that log_hook_decision() shouldn't be re-running the full schema-init sequence on every PreToolUse call. I don't want to add a second persistence mechanism alongside SQLite though (a jsonl log plus SQLite means two places to reason about retention, concurrent-write safety, and schema evolution going forward). Instead I have a POC that keeps everything in SQLite but removes the redundant per-call work — proposing this for discussion before I push it.

Proposed fix: gate schema migration behind PRAGMA user_version

Tracker::new() currently re-runs all 13 DDL statements (2×CREATE TABLE IF NOT EXISTS, 2×ALTER TABLE ADD COLUMN, a SELECT EXISTS scan, 5×CREATE INDEX IF NOT EXISTS, plus the two table/index blocks for hook_decisions) on every call — not just from log_hook_decision, but from the two pre-existing hot paths TimedExecution::track/track_passthrough too (every single rtk <cmd> invocation already paid this before this PR).

The fix: store a SCHEMA_VERSION constant, stamp it into SQLite's built-in user_version pragma once migrations run, and check that pragma (a single scalar read, no sqlite_master lookup) before deciding whether to run the DDL block at all:

const SCHEMA_VERSION: i64 = 1;

fn run_schema_migrations(conn: &Connection) -> Result<()> {
    // ...unchanged CREATE TABLE/INDEX/ALTER statements, byte-for-byte...
    conn.pragma_update(None, "user_version", SCHEMA_VERSION)?;
    Ok(())
}

impl Tracker {
    pub fn new() -> Result<Self> {
        let db_path = get_db_path()?;
        if let Some(parent) = db_path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let conn = Connection::open(&db_path)?;
        let _ = conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;");

        let current_version: i64 = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?;
        if current_version < SCHEMA_VERSION {
            run_schema_migrations(&conn)?;
        }
        Ok(Self { conn })
    }
}

The first Tracker::new() after a fresh install or a version bump pays the full migration cost once and stamps user_version; every call after that — every hook invocation, every rtk <cmd> — is just Connection::open + 2 pragmas + 1 scalar read. Bumping SCHEMA_VERSION is how future migrations get added (mirrors how the existing ALTER TABLE migrations already no-op safely once applied — same idea, just gated instead of unconditional).

I also added a pre-warm call (let _ = Tracker::new();, best-effort, matching this repo's fallback pattern) at the end of rtk init's install path, so the one-time migration happens synchronously during install/upgrade rather than on whichever Bash call happens to run first afterward.

new_in_memory() (the #[cfg(test)]-only in-memory path) is untouched — every test DB is fresh, so there's no repeated-call cost there to optimize.

Benchmark

Same methodology as your comment: hyperfine on rtk hook claude fed the same realistic payload shape, warm DB, --warmup before measuring. I built three release binaries — develop (pre-#3206, no Tracker touch at all in run_claude), this PR as-is (unconditional schema-init), and the POC — and ran them side by side:

Benchmark 1: develop (no DB write)
  Time (mean ± σ):  18.5 ms ± 1.1 ms   (1000 runs)

Benchmark 2: PR as-is (unconditional schema-init)
  Time (mean ± σ):  19.3 ms ± 1.2 ms   (1000 runs)

Benchmark 3: POC (user_version gate)
  Time (mean ± σ):  19.2 ms ± 1.5 ms   (1000 runs)

Full transparency: my environment is noisier than yours (baseline here is ~18.5ms vs your ~12.6ms — sounds like a more virtualized/shared box), and at that noise level (σ ~1.2-1.5ms) a ~0.1-0.3ms gap between "PR as-is" and "POC" isn't something I can call statistically conclusive from a single machine. I re-ran it three separate times (200/500/1000 samples each) and POC's mean landed at or slightly below "PR as-is" every time, consistent with the gate doing less work, but I'd rather be honest that the effect size here is close to my noise floor than round up.

What I can confirm precisely (no timing noise involved): with the gate, the on-disk DB's PRAGMA user_version is stamped to 1 after the first call and stays there — I verified via a direct SQLite read that a second Tracker::new() against the same file does not re-touch sqlite_master for the DDL statements (only hook_decisions row count changes, no schema churn). So the mechanism is confirmed working as designed even where the wall-clock delta is within noise on this box. Given your own measurement showed a clean, real ~0.9ms gap on your machine, I'd expect this gate to recover most or all of it there too — happy to have you (or anyone else) re-run your existing methodology against the POC if you want a tighter number than I can produce here.

Also, per your nit: the doc-comment duplication on record_hook_decision is fixed in the POC too.

Not pushing this yet — wanted to get eyes on the approach first, per feedback from whoever's driving this fix. If the user_version gate + rtk init pre-warm direction looks right, I'll commit and push it as a follow-up on this branch.

@KuSh

KuSh commented Jul 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

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).

Benchmark 1: develop (no DB write)
  Time (mean ± σ):   6.7 ms ± 0.5 ms   (500 runs)

Benchmark 2: PR as-is (unconditional schema-init)
  Time (mean ± σ):   7.1 ms ± 0.4 ms   (500 runs)

Benchmark 3: POC (user_version gate)
  Time (mean ± σ):   7.0 ms ± 0.4 ms   (500 runs)

So: +0.4ms for the PR as it stands, +0.3ms with the user_version gate. That +0.3ms lines up with the +0.3ms you measured for the jsonl prototype — same practical hot-path cost, without a second persistence mechanism.

Dug into where that remaining +0.3ms actually comes from, since the gate only removes the DDL re-run (12 statements down to 1 PRAGMA user_version read) and I wanted to know if there was more to get: it isn't the DDL. On a warm, page-cached DB those CREATE TABLE/INDEX IF NOT EXISTS checks are already cheap (~0.1ms for all 12 combined). The rest is Connection::open() + the per-connection pragmas + the actual INSERT into hook_decisions — costs that are identical between "PR as-is" and "POC" because both open a connection and log a row. I checked whether any single rtk invocation opens more than one Tracker (which would make an in-process cache worth adding) — it doesn't; every call site (log_hook_decision, discover, gain, cc_economics) opens exactly one Tracker per process. So there's no redundant open to dedupe within a process, and the remaining cost is the inherent floor of touching SQLite from a fresh CLI invocation at all — the same floor any persistence approach (including jsonl) pays. Removing it further would mean a resident daemon process holding a connection across hook calls, which is a much bigger architectural change than this fix warrants (and cuts against this repo's single-threaded, one-shot-CLI design) — not proposing that here.

Net: the user_version gate gets this to the same hot-path cost as the jsonl idea while keeping one storage mechanism, and there's no further low-risk optimization available on top of it.

@KuSh
KuSh force-pushed the fix/discover-hook-decision-log branch from fbce926 to 2aef8e8 Compare August 2, 2026 14:21
@KuSh

KuSh commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

@pszymkowiak rebased with the schema migration gated behind PRAGMA user_version + some more iteration on it:

  1. hook_cmd.rs audit prefix regression — fixed: restored skip:deny_rule/skip:defer audit-log reasons instead of bare HookOutcome::Display.
  2. Chained-command coverage attribution — investigated deeply, found the "fix" was based on a wrong assumption (rewrite is per-segment, not all-or-nothing); reverted the premature change and documented the real limitation instead, since it naturally fades out as hook_decisions backfills history.
  3. rtk proxy counted as adopted — fixed: session_cmd.rs now reuses discover::is_already_rtk instead of its own diverging starts_with("rtk ") check.
  4. Self-healing schema migration — discussed with you, landed on your simpler idea: rtk init now unconditionally re-runs migrations (bypassing the user_version gate), healing a dropped/corrupted table without a new flag; added a diagnostic pointing at rtk init on write failure. Also fixed an unrelated pre-existing test-isolation bug (per-function static ENV_LOCKs that didn't actually share a lock) surfaced while testing this.
  5. Duplicated Config::load() boilerplate — fixed: extracted core::config::hook_rewrite_params(), used by all 4 call sites.
  6. Test schema duplication — fixed: new_in_memory() now calls run_schema_migrations directly instead of hand-duplicated DDL.
  7. TimedExecution test flakiness from shared on-disk DB races under parallel cargo test — fixed. Root cause: several tests called Tracker::new() with no RTK_DB_PATH override, so they all hit the same real default DB file concurrently — get_recent(N) then raced against other tests' concurrent inserts, occasionally missing the test's own row (or erroring outright under heavy concurrent file access). Switched the tests that don't need real on-disk behavior to Tracker::new_in_memory(), and isolated the two TimedExecution tests (which hardcode Tracker::new() internally) via a private temp-file RTK_DB_PATH under the shared lock. Verified stable across 14 repeated runs, including 6 at 16 threads, with zero failures.

@aeppling

Copy link
Copy Markdown
Contributor

Hey @KuSh

Since no news from Patrick i've went through the PR so we can go forward with it.
Before going deeper in code review, some first observations and questions.

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 grep -n ×4251 and git diff ×2448, both hook-rewritten every time.

Pain on the estimate path (not the measured one):

  • 80s vs 2.5s on base. Filled the log with my real tool_use_ids and it drops to 1.2s. It's check_command_for reloading settings per command, and the verdict is computed eagerly so the hook_installed short-circuit never fires.
  • 100s with no hook installed, and that never improves, since no hook means no rows.
  • RTK_DISABLED section goes empty once the log fills, because the hook always defers on a bypassed command.

Also observed a crash with "rtk discover --since 100000000"

Questions on direction:

tool_use_id is Claude-only (Droid/Vibe send session_id, nobody else sends tool_use_id), so this can't extend to other agents.
RTK is agent agnostic everywhere else, so tying the fix to a Claude-only field feels like it'll be a problem later.

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.

@KuSh KuSh closed this Aug 23, 2026
@KuSh KuSh reopened this Aug 23, 2026
KuSh added a commit that referenced this pull request Aug 23, 2026
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
@KuSh

KuSh commented Aug 23, 2026

Copy link
Copy Markdown
Collaborator Author

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. estimate_hook_coverage_with_verdict's hook_installed && check couldn't short-circuit anything because the caller computed the permission verdict before calling it, unconditionally. And check_command_for was re-reading every settings file from disk on every single command. Fixed both: permission rules are now loaded once per discover run, and hook_installed is checked before touching rules/lexer/registry at all. Found and fixed the same "settings-file-per-command" and "no short-circuit" pattern didn't leave any other hot loop behind.

RTK_DISABLED= section going empty: root cause was that a bypassed command's real logged hook decision is always Defer (RTK_DISABLED= makes get_rewritten return None unconditionally), so once real hook_decisions rows existed, checking the measured log for that bucket made it collapse toward zero — the log correctly says "the hook stepped aside," which isn't the question being asked ("would this have been covered absent the bypass?"). That bucket now always uses the estimate, since the measured log can never answer the counterfactual.

Crash on rtk discover --since 100000000: was Utc::now() - Duration::days(...) overflowing. Fixed, with regression tests for the huge-value and u64::MAX cases. While hunting this down I found the identical overflow pattern in two sibling spots — discover_sessions_in_projects_dir's days * 86400 and rtk hook audit --since's own cutoff computation — both would've hit the same crash, so I fixed those too and pulled the clamping logic into one shared core::utils::days_ago_cutoff helper.

Also found (separately from your review) that the branch didn't compile its own test suite — HookDecision::AskRewrite is a tuple variant but a test still constructed it as a struct literal. Fixed.

Ran /code-review high twice more after the above. No further correctness issues surfaced. It did flag:

  • A pre-existing (not from this PR) redundant lexer scan in the estimate path — filed as perf(discover): estimate_hook_coverage double-scans for unattestable constructs #3650 rather than folded in here, since a real fix touches permissions::check_command_with_rules's contract and its other callers.
  • Two SQLite-write-on-every-hook-call / unbounded-hook_decisions-growth observations that are really inherent tradeoffs of ground-truth logging itself (writing on every call is the whole point; growth is bounded in practice by the existing cleanup_old() cadence unless a user's commands are almost entirely denied/deferred) — noting these for you rather than unilaterally changing the logging behavior.
  • One maintainability nit (too many positional bool/Vec params threaded through hook_coverage/estimate_hook_coverage) — bundled into a CoverageContext struct, no behavior change.

On your direction questions — not mine to settle, but for what it's worth on current state: the already_rtk_estimated/rtk_disabled_estimated counters aren't silently blended into the totals — they're tracked separately and the text/JSON report surfaces an explicit "~N estimated from current hook/config state" caveat whenever any estimate contributes, so a reader can tell measured from guessed. The tool_use_id-is-Claude-only limitation is real and unaddressed by this round — Estimated remains the permanent fallback for other hosts, by design, not just a transitional one for those.

All tests pass (cargo test --all), clippy clean.

@KuSh

KuSh commented Aug 23, 2026

Copy link
Copy Markdown
Collaborator Author

Following up on #3657 (closed — agreed it belongs here, not deferred): both points are now fixed in this PR.

  • Per-hook-call SQLite write cost: `Tracker::new()`'s `open_and_prepare()` was paying 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, on every single call — this now runs on every PreToolUse hook invocation, not just RTK-covered ones, where before this PR that path did at most a JSON audit-log append. `set_owner_only` now skips its chmod syscall once permissions already match (still self-heals a genuinely-wrong-permission legacy file, just doesn't reconfirm it every call), and the pre-create open/close is skipped once the DB file already exists. No behavior change on the first-run/healing paths, fewer syscalls after that.
  • Unbounded `hook_decisions` growth: `record_hook_decision` deliberately skips the full 3-table `cleanup_old()` (hot-path budget), and a user whose commands are mostly `Deny`/`Defer`'d rarely triggers `record()`'s/`record_parse_failure()`'s own cleanup either. Added a sampled (~1-in-500 calls) single-table `hook_decisions` sweep as a backstop, via a pure/testable sampling core (`should_sample_cleanup`) so it doesn't need a real 1-in-500 chance to test.

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.

@KuSh

KuSh commented Aug 23, 2026

Copy link
Copy Markdown
Collaborator Author

Ran another /code-review high pass (multi-angle, 227 tool calls) over the full branch. It found real issues this time — fixed all of them, plus merged and resolved conflicts against `upstream/develop` (base had drifted, 39 commits):

  • Security regression in my own previous fix: `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`.
  • Exposure-window regression, also mine: skipping the pre-create dance for an already-existing DB also skipped the only chmod that ran before `Connection::open` — a file with drifted permissions would get opened/migrated before `restrict_db_files` healed it at the end. Now re-chmods (cheaply, via the same optimized path) before opening, for the existing-file case too.
  • Sampling reliability, also mine: `should_sample_cleanup`'s 1-in-500 sampling read `Utc::now().timestamp_subsec_nanos()`, which silently breaks on any clock source whose resolution doesn't hit every residue mod 500 (coarse virtualized/Windows timers) — could sample ~100% or ~0% of calls depending on tick size. Now hashes `tool_use_id` instead.
  • Silent error swallowing: `discover::run` was masking `hook_decisions` read failures instead of warning like every write path does — could report "no hook-decision log yet" for an actually-corrupted DB. Fixed.
  • RTK_DISABLED= permission-check command mismatch: the bypass path was checking permission rules against the env-prefix-stripped command, but the real hook checks against the full raw command (prefix intact) — a rule anchored on the literal prefixed string would behave differently. `estimate_hook_coverage` now takes separate permission-check and rewrite-check command params (they must differ here, for opposite reasons), and a new `would_be_covered_without_bypass` wrapper makes the correct call reachable by name rather than only by doc comment — a prior round already had to catch the hook_coverage-vs-estimate mixup once, so this closes the "doc-comment-only guard" gap too.
  • Perf: `registry::rewrite_command` recompiled its exclude-pattern regexes on every call; `estimate_hook_coverage` now calls it once per historical command in `discover`'s scan loop, turning a previously-rare cost into a hot-loop one — the same "recompute per command" class this PR's own `PermissionRules`/`hook_status` caching already fixed elsewhere. Split into `rewrite_command` (compiles, thin wrapper) and `rewrite_command_precompiled`, with patterns precompiled once per `discover` run.
  • Fixed a stale comment in `provider.rs` referencing a function name that had been refactored away in an earlier commit.

`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.

KuSh added a commit that referenced this pull request Aug 23, 2026
…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
@KuSh

KuSh commented Aug 23, 2026 •

Copy link
Copy Markdown
Collaborator Author

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:

  • Latency: `run_claude()` was calling `log_hook_decision` (a synchronous SQLite write, 5s `busy_timeout`) before writing the hook's stdout response Claude Code is synchronously blocked on. Reordered — the response goes out first, logging is genuinely best-effort now (as its own doc comment already claimed but the code didn't honor). Worth noting: SQLite's WAL mode only serializes writer-vs-writer, not reader-vs-writer, so hitting the full 5s in practice would need real pathological contention — but the fix is free and removes the dependency entirely regardless.
  • Correctness: the coverage estimate's permission-verdict check ran against an isolated chain segment 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. Threaded the full unsplit command through for the permission check specifically, while keeping the per-segment command for the rewrite check (they need to differ, for opposite reasons — see the updated doc comments).
  • Correctness: `format_text`'s "no missed savings, looks good!" early return didn't account for `rtk_disabled_count`, so a user whose every command ran under `RTK_DISABLED=` got a false "all good" message.
  • Correctness: the RTK_DISABLED branch always `continue`d after resolving the bypass question, even when the command genuinely wouldn't have been covered anyway (hook not installed / excluded) — such a command vanished from the whole report instead of showing as a real missed-savings opportunity.
  • Self-inflicted design flaw: the sampled retention sweep I added in an earlier round prunes `hook_decisions` by the same 90-day window as the rest of the tracking DB — so `earliest_hook_decision_timestamp()` (and the report's "measured logging began {date}" text) never reflects an install date, just a rolling ~90-day boundary, directly contradicting an earlier comment of mine claiming Estimated "fades out" over time. Corrected the text and comments to state this honestly: Estimated is a permanent fallback beyond the retention window, not transitional.
  • Correctness: `record_hook_decision` propagated the retention sweep's error via `?` as if it were the INSERT's own failure, even though the INSERT had already committed. Now best-effort or, per rust-patterns.md's anti-pattern rule.
  • `rtk init`'s schema self-heal call silently discarded its `Result` (the exact anti-pattern the project's own rules call out) — now warns.
  • Perf: `get_rewritten`/`Tracker::new()` each independently called `Config::load()` per hook invocation — two disk-read-plus-TOML-parse round trips instead of one. Added a process-wide cache for the read-only hot-path callers (never used by config-mutating paths, which must keep seeing fresh writes).
  • A few minor ones: an avoidable per-call allocation, a two-pass loop that didn't need to be two passes, a test that only exercised session_id-missing when it claimed to test tool_use_id-missing.

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.

KuSh and others added 6 commits September 2, 2026 01:40
…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]>
KuSh and others added 7 commits September 2, 2026 01:40
…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
@KuSh
KuSh force-pushed the fix/discover-hook-decision-log branch from 3fc249d to c4b25d2 Compare September 1, 2026 23:42
@aeppling

aeppling commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Thanks for the quick turnaround. Ran a fuzz pass against develop before going further.

~28k differential invocations: hook claude payloads plus 17 hostile DB states, rewrite decisions across rewrite/hook check/hook claude with 43 config and 40 permission variants, discover args and malformed transcripts, and 60 concurrent hooks on one DB.

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: rtk hook-audit --since 100000000 SIGABRTs on develop, and rtk discover --since 2^63 reports Scanned: 0 sessions ... RTK usage looks good! because days * 86400 wraps.

LGTM on the behaviour side.

@KuSh
KuSh merged commit f57af35 into develop Sep 2, 2026
15 of 16 checks passed
@rtk-release-bot rtk-release-bot Bot mentioned this pull request Sep 2, 2026
@KuSh
KuSh deleted the fix/discover-hook-decision-log branch September 3, 2026 05:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

rtk discover counts hook-rewritten commands as misses

3 participants