diff --git a/dokimi/changelog.d/20261128_120000_napetrov_stop-hook-error.md b/dokimi/changelog.d/20261128_120000_napetrov_stop-hook-error.md new file mode 100644 index 000000000..1a7afee72 --- /dev/null +++ b/dokimi/changelog.d/20261128_120000_napetrov_stop-hook-error.md @@ -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. diff --git a/dokimi/docs/run-consistency.md b/dokimi/docs/run-consistency.md index 892a3a206..ed79096be 100644 --- a/dokimi/docs/run-consistency.md +++ b/dokimi/docs/run-consistency.md @@ -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 diff --git a/dokimi/dokimi/context/consistency.py b/dokimi/dokimi/context/consistency.py index 2eae3414a..4b1ccc69b 100644 --- a/dokimi/dokimi/context/consistency.py +++ b/dokimi/dokimi/context/consistency.py @@ -82,7 +82,7 @@ class Run: 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"}) @@ -127,8 +127,10 @@ def parse_run(raw: str, name: str = "", grain: str = "split") -> Run: ``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. @@ -136,12 +138,10 @@ def parse_run(raw: str, name: str = "", grain: str = "split") -> Run: 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 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] = {} @@ -152,16 +152,40 @@ def parse_run(raw: str, name: str = "", grain: str = "split") -> Run: 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": + # 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 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 + except (ValueError, RecursionError): + return None + return rec if isinstance(rec, dict) else None + + +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 + run.passed = rec.get("subtype") == "success" and not rec.get("is_error") def _assistant(run: Run, rec: dict[str, Any], message: dict[str, Any], content: list[Any], main: bool, @@ -184,8 +208,10 @@ def _assistant(run: Run, rec: dict[str, Any], message: dict[str, Any], content: 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) + 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"): @@ -193,6 +219,7 @@ def _user(run: Run, content: list[Any], main: bool, by_id: dict[str, list[Event] # 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: diff --git a/dokimi/tests/test_context_consistency.py b/dokimi/tests/test_context_consistency.py index b8f3a0671..629a244dd 100644 --- a/dokimi/tests/test_context_consistency.py +++ b/dokimi/tests/test_context_consistency.py @@ -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"]