Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
bump: minor
---

### Added

- `/session-flow:audit-friction` records which tool follows each hook-block denial. The session scanner adds `next_tool` (the next tool call in the same transcript file, `None` when none follows) and `next_ok` (whether that call succeeded) to each hook-block denial event, and `friction.py mine` tallies `next_tool` per event key and side, with ok, failed and unknown counts, in both the JSON and the markdown output. Sessions collected before this change carry no such field. The tally reads stored events, so a session past the per-session event cap contributes only the events it kept.
17 changes: 17 additions & 0 deletions plugins/session-flow/skills/audit-friction/scripts/friction.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,8 @@ def aggregate(records: list[dict]) -> dict:
shapes: Counter = Counter()
flags: Counter = Counter()
perf: Counter = Counter()
# (side, event key) -> next tool -> {count, ok, failed, unknown}, from the stored events (capped per session).
next_tools: dict[tuple[str, str], dict[str, dict[str, int]]] = defaultdict(dict)
events, dropped, active_s, turns = [], 0, 0, 0
classes = Counter(census.session_class(r) for r in records)
for record in records:
Expand All @@ -168,6 +170,12 @@ def aggregate(records: list[dict]) -> dict:
if event.get("kind") in ("denied", "prompt-approved") and event.get("shape"):
shapes[(event["kind"], event.get("cause"), event.get("tool"), event["shape"])] += 1
flags.update(event.get("flags") or [])
if "next_tool" in event and event.get("key"):
tally = next_tools[(event.get("side"), event["key"])].setdefault(
event["next_tool"] or "none", {"count": 0, "ok": 0, "failed": 0, "unknown": 0}
)
tally["count"] += 1
tally["ok" if event.get("next_ok") is True else "failed" if event.get("next_ok") is False else "unknown"] += 1
if len(events) < EVENT_LIMIT:
events.append({"session_id": record.get("session_id"), **event})
else:
Expand All @@ -182,6 +190,7 @@ def aggregate(records: list[dict]) -> dict:
"per_session": round(c["count"] / len(records), 3) if records else 0,
"per_active_hour": round(c["count"] / hours, 3) if hours else None,
"class_hint": class_hint(key),
**({"next_tool": next_tools[(side, key)]} if (side, key) in next_tools else {}),
}
for (side, key), c in counts.items()
]
Expand Down Expand Up @@ -222,6 +231,14 @@ def render_mine(data: dict) -> str:
)
if len(data["rows"]) > TOP:
lines.append(f"\n{len(data['rows']) - TOP} more keys in the JSON output.")
followed = [r for r in data["rows"] if r.get("next_tool")]
if followed:
lines += ["", "Next tool after a hook-block denial (ok/failed/unknown):", "",
"| Side | Key | Next tool | Count | Ok | Failed | Unknown |", "|---|---|---|---|---|---|---|"]
for row in followed[:TOP]:
key = row["key"].replace("|", "\\|")
for tool, t in sorted(row["next_tool"].items(), key=lambda kv: (-kv[1]["count"], kv[0])):
lines.append(f"| {row['side']} | {key} | {tool.replace('|', chr(92) + '|')} | {t['count']} | {t['ok']} | {t['failed']} | {t['unknown']} |")
lines += ["", "Shape flags: " + (", ".join(f"{k} {v}" for k, v in sorted(data["shape_flags"].items())) or "none")]
lines += ["", "Perf: " + (", ".join(f"{k} {v}" for k, v in sorted(data["perf"].items())) or "none")]
return "\n".join(lines)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,40 @@ def test_mine_scopes_to_the_window_and_hints_classes(store):
assert len(data["events"]) == 12


def test_mine_tallies_the_next_tool_after_a_hook_block(store):
data = data_of(friction("mine", "--data-dir", str(store), *WINDOW))
rows = {(r["side"], r["key"]): r for r in data["rows"]}
tally = rows[("main", HOOK_KEY)]["next_tool"]
assert sum(t["count"] for t in tally.values()) == 1
assert all(t["ok"] + t["failed"] + t["unknown"] == t["count"] for t in tally.values())
assert "next_tool" not in rows[("main", "denied/rule/rule")]
markdown = friction("mine", "--data-dir", str(store), *WINDOW, "--format", "md").stdout
assert "Next tool after a hook-block denial" in markdown


def test_aggregate_groups_next_tools_per_key_and_side():
import importlib.util

spec = importlib.util.spec_from_file_location("friction_under_test", SCRIPTS / "friction.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)

def event(side: str, next_tool: str | None, next_ok: bool | None) -> dict:
return {"kind": "denied", "side": side, "cause": "hook", "key": "denied/hook/g/BLOCKED", "next_tool": next_tool, "next_ok": next_ok}

record = {"session_id": "s", "friction": {
"counts": {"main": {"denied/hook/g/BLOCKED": 3}, "sub": {"denied/hook/g/BLOCKED": 1}},
"events": [event("main", "Write", True), event("main", "Bash", False), event("main", None, None), event("sub", "Edit", True)],
}}
rows = {(r["side"], r["key"]): r for r in module.aggregate([record])["rows"]}
assert rows[("main", "denied/hook/g/BLOCKED")]["next_tool"] == {
"Write": {"count": 1, "ok": 1, "failed": 0, "unknown": 0},
"Bash": {"count": 1, "ok": 0, "failed": 1, "unknown": 0},
"none": {"count": 1, "ok": 0, "failed": 0, "unknown": 1},
}
assert list(rows[("sub", "denied/hook/g/BLOCKED")]["next_tool"]) == ["Edit"]


def test_mine_project_and_session_filters(store):
by_project = data_of(friction("mine", "--data-dir", str(store), "--since", "2026-07-01", "--project", "beta"))
assert by_project["sessions"] == 1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

- `denied`: a tool call refused by the classifier, a hook, a permission rule, or the person
(`cause`); a stream-json `result` record's `permission_denials` count once per tool call.
A hook-block denial also carries `next_tool` (the next tool call in the same transcript file, `None`
when none follows) and `next_ok` (whether that call succeeded, `None` while unknown).
- `prompt-approved`: a call the person approved at a permission prompt.
- `agent-ask`: the agent asked the person something (an `AskUserQuestion` call, or a turn whose last
text asks), with the person's `reply` classed `approve`, `correction`, `rejected` or `other`.
Expand Down Expand Up @@ -67,7 +69,7 @@
SUBCOMMAND = re.compile(r"[a-z][a-z0-9-]{0,30}")
GIT_ARG_FLAGS = frozenset({"-C", "-c"})
# Event fields holding transcript or metadata text, scrubbed before storage; the rest are enums this module sets.
SCRUBBED_FIELDS = ("reason", "hook", "shape", "tool", "agent", "source", "reason_type")
SCRUBBED_FIELDS = ("reason", "hook", "shape", "tool", "agent", "source", "reason_type", "next_tool")


def _epoch(value: object) -> float | None:
Expand All @@ -80,6 +82,13 @@ def _epoch(value: object) -> float | None:
return (parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)).timestamp()


def _errored(record: dict) -> bool:
message = record.get("message")
content = message.get("content") if isinstance(message, dict) else None
return any(isinstance(b, dict) and b.get("type") == "tool_result" and b.get("is_error") is True
for b in (content if isinstance(content, list) else ()))


def command_shape(command: str) -> tuple[str, list[str]]:
"""`<program>[ <subcommand>[ <subcommand>]]` of a shell command, and the shape flags that take a
command off a plain-prefix rule match: cd-prefix, env-prefix, compound, redirect, heredoc,
Expand Down Expand Up @@ -160,6 +169,10 @@ def __init__(self, cwd_hint: str | None = None) -> None:
self.dropped = 0
self.calls: dict[str, tuple[str, dict, float | None, str]] = {}
self.denied_ids: set[str] = set()
# Hook-block denials of the current file still waiting for the next tool call, and the calls
# already taken as a next call whose result has not arrived: tool_use id -> denials it answers.
self.awaiting_next: list[dict] = []
self.next_calls: dict[str, list[dict]] = {}
self.side = "main"
self.agent: str | None = None
self.headless = False
Expand All @@ -170,6 +183,7 @@ def __init__(self, cwd_hint: str | None = None) -> None:

def start_file(self, side: str, agent: str | None) -> None:
self.side, self.agent = side, agent
self.awaiting_next = []

def _event(self, kind: str, ts: float | None, **fields) -> dict:
event = {
Expand Down Expand Up @@ -223,6 +237,11 @@ def _assistant(self, record: dict, ts: float | None) -> None:
if not isinstance(tool_input, dict):
tool_input = {}
self.calls.setdefault(block["id"], (name, tool_input, ts, self.side))
if self.awaiting_next:
for denial in self.awaiting_next:
denial["next_tool"] = name
self.next_calls[block["id"]] = self.awaiting_next
self.awaiting_next = []
command = tool_input.get("command") if name in SHELL_TOOLS else None
if isinstance(command, str):
self.perf["ci_wait_calls"] += bool(CI_WAIT_RE.search(command))
Expand Down Expand Up @@ -275,6 +294,8 @@ def _tool_result(self, record: dict, use_id: str, ts: float | None) -> None:
if CONFLICT_RE.search(text[:20000]):
self.perf["merge_conflicts"] += 1
permission = transcript_reader.permission_event(record)
for denial in self.next_calls.pop(use_id, ()):
denial["next_ok"] = not (_errored(record) or (permission and permission["outcome"] == "denied"))
if name == "AskUserQuestion":
reply = "rejected" if permission and permission["outcome"] == "denied" else (
"approve" if "(Recommended)" in text else "other"
Expand All @@ -286,11 +307,15 @@ def _tool_result(self, record: dict, use_id: str, ts: float | None) -> None:
shape, flags, target = tool_shape(name, tool_input, self.cwd)
if permission["outcome"] == "denied":
self.denied_ids.add(use_id)
self._event(
event = self._event(
"denied", ts, tool=name, shape=shape, flags=flags, target=target,
cause=permission["cause"], reason=permission["reason"], hook=permission["hook"],
source=permission["source"], reason_type=permission["reason_type"],
)
if permission["cause"] == "hook":
# next_tool stays None when no call follows; next_ok stays None until that call's result.
event["next_tool"] = event["next_ok"] = None
self.awaiting_next.append(event)
elif (permission["source"] or "").startswith("user") and permission["reason_type"] != "rule":
self._event("prompt-approved", ts, tool=name, shape=shape, flags=flags, target=target, source=permission["source"])

Expand All @@ -304,6 +329,8 @@ def block(self, scrub, excerpt_chars: int) -> dict:
stored[key] = scrub.key(stored[key])
target = event.get("target")
stored["excerpt"] = scrub.excerpt(target, excerpt_chars) if excerpt_chars and target else None
if "next_tool" in event:
stored["key"] = scrub.key(event_key(event)) # the `counts` key, so mine can join the two
events.append(stored)
return {
"events": events,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,61 @@ def test_block_redacts_tool_agent_source_and_reason_type_and_keeps_plain_values(
assert {k: plain[k] for k in ("tool", "source", "reason_type")} == {"tool": "Bash", "source": "config", "reason_type": "rule"}


HOOK_DECISION = {"decision": "reject", "source": "hook", "reasonType": "hook"}
HOOK_TEXT = "Error: PreToolUse:Bash hook error: [guard]: BLOCKED: file write. Use the Write or Edit tool.\n\nThis hook comes from the guardrails@m plugin."


def call(use_id: str, name: str, **tool_input) -> dict:
return {"type": "assistant", "message": {"content": [{"type": "tool_use", "id": use_id, "name": name, "input": tool_input}]}}


def result(use_id: str, *, error: bool = False) -> dict:
return {"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": use_id, "is_error": error, "content": "x"}]}}


def hook_denial_scan(*records: dict) -> friction_scan.FrictionScan:
scan = friction_scan.FrictionScan("/w/repo")
scan.start_file("main", None)
scan.add(call("t1", "Bash", command="echo hi > a.txt"))
scan.add(denial_record(HOOK_TEXT, kind="permission-rule", decision=HOOK_DECISION, use_id="t1"))
for record in records:
scan.add(record)
return scan


def test_hook_denial_followed_by_write_records_the_next_tool_and_its_success():
scan = hook_denial_scan(call("t2", "Write", file_path="/w/repo/a.txt", content="hi"), result("t2"))
assert [(e["next_tool"], e["next_ok"]) for e in scan.events] == [("Write", True)]


def test_hook_denial_followed_by_the_same_shell_form_records_a_failed_retry():
scan = hook_denial_scan(
call("t2", "Bash", command="echo hi > a.txt"),
denial_record(HOOK_TEXT, kind="permission-rule", decision=HOOK_DECISION, use_id="t2"),
)
# The retry is itself a hook denial, so it is a second event with no next call yet.
assert [(e["next_tool"], e["next_ok"]) for e in scan.events] == [("Bash", False), (None, None)]


def test_hook_denial_with_no_next_call_keeps_the_fields_empty():
scan = hook_denial_scan()
assert [(e["next_tool"], e["next_ok"]) for e in scan.events] == [(None, None)]
block = scan.block(collect.Scrubber(redact.load_redactor(), 200), 200)
assert block["events"][0]["next_tool"] is None


def test_next_tool_is_read_per_file_and_only_for_hook_denials():
scan = hook_denial_scan()
scan.start_file("sub", "a")
scan.add(call("s1", "Read", file_path="/w/repo/a.txt"))
assert scan.events[0]["next_tool"] is None
rule = friction_scan.FrictionScan("/w/repo")
rule.start_file("main", None)
rule.add(call("t1", "Bash", command="git push"))
rule.add(denial_record("denied", kind=None, decision={"decision": "reject", "source": "config", "reasonType": "rule"}, use_id="t1"))
assert "next_tool" not in rule.events[0]


@pytest.mark.parametrize(
("decision", "kinds"),
[
Expand Down
Loading