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,3 @@
### Fixed

- **`trace consistency` reports a Stop hook that could not run** as a failed `Hook:Stop-error` step. Before, a hook whose command did not start (typically a relative path such as `sh .claude/hooks/stop.sh` after the agent ran `cd` into a subdirectory) left no step, so the run read as if the check had passed. Write hook commands with `"$CLAUDE_PROJECT_DIR"`; `docs/run-consistency.md` has the example.
16 changes: 13 additions & 3 deletions dokimi/docs/run-consistency.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,19 @@ syntax, `( )` and case labels are peeled off; `sudo`, `env`, `time`, `nohup`,
`tool_calls_*` and `failed_calls_mean` count tool calls, so one chained command is
one call however many steps it has; the JSON records the `shell` grain.

A Stop hook that blocked the stop is a failed `Hook:Stop` step. A hook that
passed leaves nothing in the trace, so a check the harness enforces is not
visible as a step; count it from the harness configuration.
A Stop hook that blocked the stop is a failed `Hook:Stop` step. A Stop hook
that failed without blocking (it could not start, exited non-zero other than 2,
timed out) leaves no feedback, only a `stop-hook-error` notification, and is a
failed `Hook:Stop-error` step: the stop passed without the check passing. A
hook that passed leaves nothing in the trace, so a check the harness enforces
is not visible as a step; count it from the harness configuration.

Write the hook command with an absolute path, for example
`sh "$CLAUDE_PROJECT_DIR"/.claude/hooks/stop.sh`, and call scripts from the hook
the same way. A relative path (`sh .claude/hooks/stop.sh`) resolves from the
shell's current directory, which follows the agent's own `cd`: once the agent
has run `cd subdir`, the hook fails to start and the stop passes unchecked. The
`Hook:Stop-error` step is how such a run shows up here.

## Where the outcome comes from

Expand Down
55 changes: 41 additions & 14 deletions dokimi/dokimi/context/consistency.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@
def calls(self) -> int:
"""Tool calls made: a chained command (``a && b``) is several steps but one call.

A blocked Stop hook is a step, not a call, so it is not counted.
A Stop hook step (blocked or failed without blocking) is not a call, so it is not counted.
"""
return len({e.call if e.call >= 0 else id(e) for e in self.events if e.tool != "Hook"})

Expand Down Expand Up @@ -127,21 +127,21 @@
``grain="split"`` turns one ``Bash`` call into one step per command it chains (``a && b; c``),
and a command that writes a file (``sed -i``, ``>``, ``tee``) carries that file as
``file_path``, so an edit made through the shell is an edit. ``grain="call"`` keeps one step
per tool call. A Stop hook that blocked the stop is a failed ``Hook:Stop`` step; a hook that
passed leaves nothing in the trace.
per tool call. A Stop hook that blocked the stop is a failed ``Hook:Stop`` step. A hook that
failed without blocking (it could not start, exited non-zero other than 2, timed out) gives no
feedback, only a ``stop-hook-error`` notification with no feedback in the same stop: a failed
``Hook:Stop-error`` step. A hook that passed leaves nothing in the trace.

A run that made tool calls but wrote no ``result`` event (it crashed, timed out, was cut off)
did not finish: it counts as failed, so it cannot drop out of the pass rate.
"""
run = Run(name)
by_id: dict[str, list[Event]] = {}
seen_messages: dict[str, int] = {}
stop_blocked = False # a Stop hook blocked since the last assistant message: its notification is its own

Check warning on line 141 in dokimi/dokimi/context/consistency.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: flip-bool `False` -> `True`
for line in raw.split(chr(10)):
try:
rec = json.loads(line) if line.strip() else None
except (ValueError, RecursionError):
continue
if not isinstance(rec, dict):
rec = _record(line)
if rec is None:
continue
raw_message = rec.get("message")
message: dict[str, Any] = {}
Expand All @@ -152,16 +152,40 @@
main = rec.get("parent_tool_use_id") is None
kind = rec.get("type")
if kind == "assistant":
stop_blocked = stop_blocked and not main # a subagent's message does not end the stop
_assistant(run, rec, message, content, main, by_id, seen_messages, grain)
elif kind == "user":
_user(run, content, main, by_id)
if _user(run, content, main, by_id):
stop_blocked = True
elif kind == "system" and main and rec.get("key") == "stop-hook-error":

Check warning on line 160 in dokimi/dokimi/context/consistency.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `kind == "system" and main and rec.get("key") == "stop-hook-error"` -> `(main and rec.get('key') == 'stop-hook-error')`
# Shown for a blocked stop too (right after its feedback); alone, the hook did not run.
if not stop_blocked:
run.events.append(Event("Hook", "Hook:Stop-error", "Hook:Stop-error", {}, failed=True))
stop_blocked = False

Check warning on line 164 in dokimi/dokimi/context/consistency.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: flip-bool `False` -> `True`
elif kind == "result":
run.num_turns = rec.get("num_turns") if isinstance(rec.get("num_turns"), int) else None
run.passed = rec.get("subtype") == "success" and not rec.get("is_error")
_result(run, rec)
_finish(run, seen_messages)
return run


def _finish(run: Run, seen_messages: dict[str, int]) -> None:
run.output_tokens = sum(seen_messages.values()) if seen_messages else None
if run.passed is None and run.events:
run.passed = False
return run


def _record(line: str) -> dict[str, Any] | None:
"""The JSON object a stream-json line holds; None for a blank, unparsable or non-object line."""
try:
rec = json.loads(line) if line.strip() else None

Check warning on line 180 in dokimi/dokimi/context/consistency.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: take-branch `json.loads(line) if line.strip() else None` -> `(json.loads(line))`
except (ValueError, RecursionError):
return None
return rec if isinstance(rec, dict) else None

Check warning on line 183 in dokimi/dokimi/context/consistency.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: take-branch `rec if isinstance(rec, dict) else None` -> `(rec)`


def _result(run: Run, rec: dict[str, Any]) -> None:
run.num_turns = rec.get("num_turns") if isinstance(rec.get("num_turns"), int) else None

Check warning on line 187 in dokimi/dokimi/context/consistency.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: take-branch `rec.get("num_turns") if isinstance(rec.get("num_turns"), int) else None` -> `(rec.get("num_turns"))`

Check warning on line 187 in dokimi/dokimi/context/consistency.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: take-branch `rec.get("num_turns") if isinstance(rec.get("num_turns"), int) else None` -> `(None)`

Check warning on line 187 in dokimi/dokimi/context/consistency.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: delete-statement `run.num_turns = rec.get("num_turns") if isinstance(rec.get("num_turns"), int) else None` -> `pass`
run.passed = rec.get("subtype") == "success" and not rec.get("is_error")

Check warning on line 188 in dokimi/dokimi/context/consistency.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `rec.get("subtype") == "success" and not rec.get("is_error")` -> `(not rec.get("is_error"))`


def _assistant(run: Run, rec: dict[str, Any], message: dict[str, Any], content: list[Any], main: bool,
Expand All @@ -184,15 +208,18 @@
by_id[str(block.get("id") or "")] = evs


def _user(run: Run, content: list[Any], main: bool, by_id: dict[str, list[Event]]) -> None:
if main and any(_text(b).startswith("Stop hook feedback") for b in content):
def _user(run: Run, content: list[Any], main: bool, by_id: dict[str, list[Event]]) -> bool:
"""Returns True when the record is a blocked Stop hook's feedback."""
blocked = main and any(_text(b).startswith("Stop hook feedback") for b in content)

Check warning on line 213 in dokimi/dokimi/context/consistency.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `main and any(_text(b).startswith("Stop hook feedback") for b in content)` -> `(any(_text(b).startswith("Stop hook feedback") for b in content))`
if blocked:
run.events.append(Event("Hook", "Hook:Stop", "Hook:Stop", {}, failed=True))
for block in content:
if isinstance(block, dict) and block.get("type") == "tool_result" and block.get("is_error"):
# The trace does not say which chained command failed, so all of them may have:
# a failed `make check && git diff` must not read as a passing `git diff`.
for hit in by_id.get(str(block.get("tool_use_id") or ""), []):
hit.failed = True
return blocked


def run_from_events(events: list[dict[str, Any]], name: str = "") -> Run:
Expand Down
60 changes: 60 additions & 0 deletions dokimi/tests/test_context_consistency.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,66 @@ def test_blocked_stop_hook_is_not_a_tool_call():
assert (only.calls(), only.failed_calls()) == (0, 0) and only.kinds() == ["Hook:Stop"]


def _stop_feedback():
return json.dumps({"type": "user", "parent_tool_use_id": None, "message": {
"content": [{"type": "text", "text": "Stop hook feedback:\n[sh hook]: Not done"}]}})


STOP_ERROR = json.dumps({"type": "system", "subtype": "notification", "key": "stop-hook-error",
"text": "stop hook problem \u00b7 ctrl+o to see"})


def test_stop_hook_that_could_not_run_is_a_failed_error_step():
"""The Stop hook command did not start (a path that does not resolve from the shell's cwd):
no feedback reaches the agent, only the stop-hook-error notification. Counted as a failed step,
not as a hook that passed."""
run = parse_run(_trace(EDIT) + "\n" + STOP_ERROR)
assert run.kinds() == ["Edit", "Hook:Stop-error"] and run.events[-1].failed
assert (run.calls(), run.failed_calls()) == (1, 0)


def test_blocked_stop_notification_is_not_an_error():
"""A blocking hook prints its feedback and then the same notification: one Hook:Stop step only."""
run = parse_run(_trace(EDIT) + "\n" + _stop_feedback() + "\n" + STOP_ERROR)
assert run.kinds() == ["Edit", "Hook:Stop"]


def test_error_in_a_later_stop_is_its_own_step():
"""A stop that was blocked, then a later stop where the hook could not run."""
raw = "\n".join([_trace(EDIT), _stop_feedback(), STOP_ERROR,
json.dumps({"type": "assistant", "parent_tool_use_id": None, "message": {
"content": [{"type": "text", "text": "ok"}]}}), STOP_ERROR])
assert parse_run(raw).kinds() == ["Edit", "Hook:Stop", "Hook:Stop-error"]


def test_subagent_message_does_not_end_a_blocked_stop():
"""A background Task still writing between the feedback and its notification: one step only."""
sub = json.dumps({"type": "assistant", "parent_tool_use_id": "toolu_task", "message": {
"content": [{"type": "text", "text": "still working"}]}})
raw = "\n".join([_trace(EDIT), _stop_feedback(), sub, STOP_ERROR])
assert parse_run(raw).kinds() == ["Edit", "Hook:Stop"]


def test_subagent_stop_hook_error_is_not_a_main_step():
sub_error = json.dumps({**json.loads(STOP_ERROR), "parent_tool_use_id": "toolu_task"})
assert parse_run(_trace(EDIT) + "\n" + sub_error).kinds() == ["Edit"]


def test_main_message_ends_a_blocked_stop_without_its_notification():
"""A blocked stop with no notification, then the agent answers: the next stop's error is a step."""
main_msg = json.dumps({"type": "assistant", "parent_tool_use_id": None, "message": {
"content": [{"type": "text", "text": "ok"}]}})
raw = "\n".join([_trace(EDIT), _stop_feedback(), main_msg, STOP_ERROR])
assert parse_run(raw).kinds() == ["Edit", "Hook:Stop", "Hook:Stop-error"]


def test_subagent_message_does_not_hide_a_lone_stop_error():
sub = json.dumps({"type": "assistant", "parent_tool_use_id": "toolu_task", "message": {
"content": [{"type": "text", "text": "still working"}]}})
raw = "\n".join([_trace(EDIT), sub, STOP_ERROR])
assert parse_run(raw).kinds() == ["Edit", "Hook:Stop-error"]


def test_quoted_newlines_stay_one_command():
cmd = 'cd /w && python3 -c "\nfrom a import b\n# note\nprint(b(1); 2)\n" && make check \\\n -j2\n# done'
assert _run("r", ("Bash", {"command": cmd})).kinds() == ["Bash:python3", "Bash:make"]
Expand Down
Loading