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 @@
schema: spec-driven
created: 2026-11-14
skip_specs: false
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Design

## Decisions

**The digest is `argument_digest`, which the trace already computes.** It hashes the tool name and the normalized arguments, so a changed argument has another digest, and the log has one digest of a call for its line and its trace.

**The set holds the first reason of each digest.** A later failure of the same call adds no second reason, and the model reads the reason of the call that failed first. `setdefault` keeps the first and needs no order.

**The refusal is a tool result, not a raised error.** The model reads the earlier reason as the result of the call and takes another step, as the issue asks. A raised `ModelRetry` would use one of the tool's retries, and a repair round that repeats a call would end sooner than a round that tries a new call.

**A successful call is not recorded.** The same read twice is a normal step, and the guard is about a failed action.

**The reason is the masked text of `logged_reason`.** A path outside the checkout is already `<path>`, so the refusal cannot show what the log hid.

## Rejected alternatives

- **A set of failed tool names.** A changed argument is a new attempt, and the rule refuses only an unchanged repeat.
- **A `ModelRetry` with the refusal.** It spends a retry of the tool and ends a run that the model could have repaired.
- **A new executor hook.** `_execute` is the one place that sees every call and already computes the digest.
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Proposal: #3570

## Why

The agent of a repair round can send the same failed tool call again. #3053 asks that no attempt repeats a previous failed action unchanged, and nothing in the tool executor stops it. The step then spends turns and tokens on a call that already failed. `ToolCallLog` already computes the digest of each call for the trace, but it keeps no set of the failed ones. Closes #3570.

## What Changes

- `ToolCallLog` keeps the digest of each call that ends as a retry or as a failure, with the reason that the log masked for it.
- `_execute` refuses a call whose digest is in that set: it returns the earlier reason to the model as a tool result, and the handler does not run. A call that changes one argument has another digest and runs.
- A call that returns a result is not recorded, so the model may read the same file twice.
- The refusal text carries the masked reason, so a path outside the checkout stays hidden.
- The change fits one pull request.

## Capabilities

### New Capabilities

None.

### Modified Capabilities

- `roadmap-implement-step/trace`: A repeated failed tool call is refused with its earlier reason.

## Impact

- Code: `src/devops_cli/roadmap/implement/implement_tool_log.py`, `src/devops_cli/lang/en/messages.py`
- Tests: `tests/roadmap/implement/test_roadmap_implement_tool_log.py`

## Feasibility

Read on 2026-11-14 against `origin/main` at `04107728d`.

- The digest exists: `src/devops_cli/roadmap/implement/implement_trace.py:136:def argument_digest`.
- The log already computes it for each outcome: `src/devops_cli/roadmap/implement/implement_tool_log.py:493` (retry), `:497` (failed) and `:505` (ok), and `_note` at `:417` writes the line and the trace event.
- The masked reason exists: `logged_reason` at `:290` replaces a path outside the checkout with `implement_tool_path_hidden` (`src/devops_cli/lang/en/messages.py:3282`).
- The execute hook is one place: `_execute` at `src/devops_cli/roadmap/implement/implement_tool_log.py:460`.
- The new tests pass on the branch: `uv run devops ci test tests/roadmap/implement/test_roadmap_implement_tool_log.py`.

## Existing Tool Considered

pydantic-ai's `ModelRetry` returns a message but keeps no set of failed actions across rounds, and the harness registers one executor hook, `_execute`, so the project builds the guard there. The cost is about 30 lines of code and 90 lines of tests.
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
## ADDED Requirements

### Requirement: A failed tool call is remembered by its digest
The step SHALL record `argument_digest` of every tool call that ends as a retry or as a failure, with the reason that the log masked for it. It SHALL NOT record a call that returns a result.

#### Scenario: A retried call is remembered
- **WHEN** a tool call raises a retry error
- **THEN** the failed map of the `ToolCallLog` holds the digest that `argument_digest` gives for that call

#### Scenario: A repeated successful call runs
- **WHEN** the model sends again a call that returned a result
- **THEN** the tool handler runs again and the call returns its result with no refusal

### Requirement: An unchanged repeat of a failed call is refused
The executor SHALL refuse a tool call whose digest equals the digest of an earlier failed call of the same step, and SHALL return the earlier reason to the model as the result. The handler SHALL run once. A call whose digest differs SHALL run.

#### Scenario: An unchanged repeat gets the earlier reason
- **WHEN** the model sends the same failing call in two replies
- **THEN** the second call returns the refusal text with the earlier reason, and the tool handler has run once

#### Scenario: A changed argument runs
- **WHEN** the model changes one argument of the failed call
- **THEN** the tool handler runs and the call returns its result

#### Scenario: A path outside the checkout stays hidden
- **WHEN** the earlier retry names a path outside the checkout
- **THEN** the refusal text shows the text of `MESSAGES.roadmap.implement_tool_path_hidden` in place of that path
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Tasks

## 1. Refuse an unchanged repeat of a failed call

Kind: behavior. Reads: `src/devops_cli/roadmap/implement/implement_tool_log.py`, `src/devops_cli/roadmap/implement/implement_trace.py`. Changes: `src/devops_cli/roadmap/implement/implement_tool_log.py`, `src/devops_cli/lang/en/messages.py`, `tests/roadmap/implement/test_roadmap_implement_tool_log.py`.

- [x] 1.1 Keep the digest and the masked reason of each retry and failure, and refuse a call whose digest is in the map before its handler runs
- Verification: `$ uv run devops ci test tests/roadmap/implement/test_roadmap_implement_tool_log.py` passes
- [x] 1.2 Add the cases: the earlier reason with a hidden path, a changed call, a repeated successful call, and the recorded digest
- Verification: `$ uv run devops ci test tests/roadmap/implement/test_roadmap_implement_tool_log.py` passes

## 2. Run the gates

Kind: other. Reads: `tests/roadmap/implement/`. Changes: none.

- [x] 2.1 Run the gate of the branch
- Verification: `$ uv run devops ci test tests/roadmap/implement` passes
- Verification: `$ uv run devops ci --check --only lint,format,typecheck` passes
26 changes: 26 additions & 0 deletions openspec/specs/roadmap-implement-step/trace/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -315,3 +315,29 @@ The `tool` event of a `run_command` call SHALL hold `status`, the exit code of t
#### Scenario: A shell call with no status
- **WHEN** the result of a `run_command` call ends with the line of the timeout
- **THEN** the `tool` event holds no `status`

### Requirement: A failed tool call is remembered by its digest
The step SHALL record `argument_digest` of every tool call that ends as a retry or as a failure, with the reason that the log masked for it. It SHALL NOT record a call that returns a result.

#### Scenario: A retried call is remembered
- **WHEN** a tool call raises a retry error
- **THEN** the failed map of the `ToolCallLog` holds the digest that `argument_digest` gives for that call

#### Scenario: A repeated successful call runs
- **WHEN** the model sends again a call that returned a result
- **THEN** the tool handler runs again and the call returns its result with no refusal

### Requirement: An unchanged repeat of a failed call is refused
The executor SHALL refuse a tool call whose digest equals the digest of an earlier failed call of the same step, and SHALL return the earlier reason to the model as the result. The handler SHALL run once. A call whose digest differs SHALL run.

#### Scenario: An unchanged repeat gets the earlier reason
- **WHEN** the model sends the same failing call in two replies
- **THEN** the second call returns the refusal text with the earlier reason, and the tool handler has run once

#### Scenario: A changed argument runs
- **WHEN** the model changes one argument of the failed call
- **THEN** the tool handler runs and the call returns its result

#### Scenario: A path outside the checkout stays hidden
- **WHEN** the earlier retry names a path outside the checkout
- **THEN** the refusal text shows the text of `MESSAGES.roadmap.implement_tool_path_hidden` in place of that path
5 changes: 5 additions & 0 deletions src/devops_cli/lang/en/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -3274,6 +3274,11 @@ class RoadmapMessages:
implement_tool_cut: str = " ..."
implement_tool_reason: str = "{outcome} ({reason})"
implement_tool_reason_path: str = "Path: {path}"
implement_tool_repeat_refusal: str = (
"This call failed earlier with the same arguments, and the step did not run it again. "
"Earlier result: {reason}. Change the call or take another step."
)
implement_tool_repeat_no_reason: str = "the call failed"
implement_tool_path_hidden: str = "<path>"
implement_stop_retries: str = "Last retries of {tool}: {reasons}"
implement_stop_reasons_separator: str = " | "
Expand Down
18 changes: 15 additions & 3 deletions src/devops_cli/roadmap/implement/implement_tool_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,9 @@ class ToolCallLog:
fail_to_pass: BaseReplay | None = None
verified: list[VerifiedCommand] = field(default_factory=list[VerifiedCommand])
parser_failures: int = 0
# The digest of each failed or retried call of the step, and the reason that the log masked
# for it (#3570). A repeat of the same call is not run again.
failed: dict[str, str] = field(default_factory=dict[str, str])
replied: set[int] = field(default_factory=set[int])
asked: float = 0.0
recent: deque[tuple[str, ToolOutcome]] = field(default_factory=deque[tuple[str, ToolOutcome]])
Expand Down Expand Up @@ -429,6 +432,8 @@ def _note(
if self.trace is not None:
self.trace.tool_call(tool, program, digest, str(outcome), reason, status)
self.recent.append((tool, outcome))
if digest and outcome in (ToolOutcome.RETRY, ToolOutcome.FAILED):
self.failed.setdefault(digest, reason)
if outcome is ToolOutcome.REFUSED:
self.refused[program] += 1
self.retried += outcome is ToolOutcome.RETRY
Expand Down Expand Up @@ -472,6 +477,13 @@ async def _execute(
that passes a limit of refusals ends the run in the same way."""
shown = self._shown(args)
program = logged_program(command_word(shown))
digest = argument_digest(call)
if digest in self.failed:
# The step does not spend another turn on a call that failed before (#3570).
self._note(call.tool_name, program, ToolOutcome.REFUSED, digest=digest)
return MESSAGES.roadmap.implement_tool_repeat_refusal.format(
reason=self.failed[digest] or MESSAGES.roadmap.implement_tool_repeat_no_reason
)
if command := logged_command(shown):
print_muted(
MESSAGES.roadmap.implement_tool_started.format(
Expand All @@ -490,19 +502,19 @@ async def _execute(
program,
ToolOutcome.RETRY,
logged_reason(error, args, self.root),
digest=argument_digest(call),
digest=digest,
)
raise
except ToolFailedError:
self._note(call.tool_name, program, ToolOutcome.FAILED, digest=argument_digest(call))
self._note(call.tool_name, program, ToolOutcome.FAILED, digest=digest)
raise
refused = call.tool_call_id in self.refusals
self.refusals.discard(call.tool_call_id)
outcome = ToolOutcome.REFUSED if refused else ToolOutcome.OK
self.refused_run = self.refused_run + 1 if refused else 0
shell = call.tool_name == IMPLEMENT_SHELL_TOOL
status = shell_exit_status(result) if shell and not refused else None
self._note(call.tool_name, program, outcome, digest=argument_digest(call), status=status)
self._note(call.tool_name, program, outcome, digest=digest, status=status)
in_a_row = self.limits.max_consecutive_refusals
if refused and self.refused_run >= in_a_row:
raise UnexpectedModelBehavior(
Expand Down
14 changes: 10 additions & 4 deletions tests/roadmap/implement/test_roadmap_implement_step.py
Original file line number Diff line number Diff line change
Expand Up @@ -1355,7 +1355,7 @@ def test_a_model_that_sends_invalid_arguments_stops_with_the_count_of_other_retr
def test_a_model_that_asks_for_a_path_outside_the_root_counts_other_retries_not_refused_commands(
store: InMemoryRoadmapStore, checkout: Path, programs: ProcessFake
) -> None:
script = ModelScript(tool_call("read_file", path="/etc/passwd"))
script = ModelScript(*(tool_call("read_file", path=f"/etc/passwd{n}") for n in range(6)))

outcome = _step(store, checkout, script)

Expand Down Expand Up @@ -1391,7 +1391,7 @@ def test_a_tool_that_ends_the_run_on_retries_names_its_last_reasons(
def test_the_last_reasons_of_a_run_hold_no_secret(
store: InMemoryRoadmapStore, checkout: Path, programs: ProcessFake
) -> None:
script = ModelScript(_edit_missing(f"src/{TOKEN}.py"))
script = ModelScript(*(_edit_missing(f"src/{TOKEN}{n}.py") for n in range(6)))

outcome = _step(store, checkout, script)

Expand All @@ -1406,7 +1406,7 @@ def test_the_last_reasons_of_a_run_hold_no_plain_secret_that_the_model_chose_as_
"""A password has no form that the mask of secrets finds. The stop comment is public, so the
reason shows a path only when it names a file of the checkout."""
secret = "hunter2-Sup3rS3cretPassw0rd"
script = ModelScript(*(_edit_missing(secret) for _ in range(6)))
script = ModelScript(*(_edit_missing(f"{secret}{n}") for n in range(6)))

outcome = _step(store, checkout, script)

Expand All @@ -1420,7 +1420,13 @@ def test_the_last_reasons_of_a_run_are_cut_to_the_constant_length(
limit = constants.CONST_ROADMAP_IMPLEMENT_LOG_REASON_CHARS
long_name = "d" * (limit - 10)
path = f"src/{long_name}.py"
script = ModelScript(tool_calls(write_call(path, "X = 1\n")), _edit_missing(path))
script = ModelScript(
tool_calls(write_call(path, "X = 1\n")),
*(
tool_call("edit_file", path=path, old_text=f"SENTINEL-OLD-TEXT-{n}", new_text="x")
for n in range(6)
),
)

outcome = _step(store, checkout, script)

Expand Down
105 changes: 104 additions & 1 deletion tests/roadmap/implement/test_roadmap_implement_tool_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,25 @@

from __future__ import annotations

import asyncio
import hashlib
import re
from collections import Counter
from pathlib import Path

import pytest
from pydantic_ai import Agent
from pydantic_ai.exceptions import ModelRetry, ToolFailed
from pydantic_ai.exceptions import ModelRetry, ToolFailed, ToolRetryError
from pydantic_ai.messages import RetryPromptPart, ToolCallPart
from pydantic_ai.tools import ToolDefinition

from devops_cli.config import constants
from devops_cli.lang import MESSAGES
from devops_cli.roadmap.implement.implement_shell_policy import IMPLEMENT_SHELL_REPLACEMENTS
from devops_cli.roadmap.implement.implement_shell_refusal import ShellRefusal
from devops_cli.roadmap.implement.implement_step import StepOutcome, run_step
from devops_cli.roadmap.implement.implement_tool_log import ToolCallLog, logged_program
from devops_cli.roadmap.implement.implement_trace import argument_digest
from tests.support.fakes.process import ProcessFake
from tests.support.fakes.roadmap_store import InMemoryRoadmapStore
from tests.support.implement_step import TEST_BODY, WINDOW, write_call
Expand Down Expand Up @@ -694,3 +699,101 @@ def test_the_log_names_the_program_after_the_prefix_cd_checkout_and_not_the_cd(
"Tool call: run_command, started: python -V",
"Tool call: run_command, program python, refused.",
]


# ── A repair attempt cannot repeat a failed call (#3570) ─────────────────────


def _repeat_log(checkout: Path, call: ToolCallPart, retry: ToolRetryError) -> ToolCallLog:
"""A log whose one call failed with `retry`, ready for the same call again."""
log = ToolCallLog(root=checkout)

async def handler(_args: dict[str, object]) -> str:
raise retry

async def first() -> None:
with pytest.raises(ToolRetryError) as raised:
await log._execute(
None,
call=call,
tool_def=ToolDefinition(name=call.tool_name),
args=dict(call.args or {}),
handler=handler,
)
assert raised.value is retry

asyncio.run(first())
return log


def test_a_repeated_failed_call_returns_the_masked_reason(checkout: Path) -> None:
call = ToolCallPart(tool_name="read_file", args={"path": "/etc/passwd"})
retry = ToolRetryError(
RetryPromptPart(content="cannot read /etc/passwd", tool_name="read_file", tool_call_id="1")
)
log = _repeat_log(checkout, call, retry)

async def repeat() -> str:
return await log._execute(
None,
call=call,
tool_def=ToolDefinition(name="read_file"),
args=dict(call.args or {}),
handler=lambda _args: None,
)

refusal = asyncio.run(repeat())

assert "failed earlier" in refusal
assert MESSAGES.roadmap.implement_tool_path_hidden in refusal
assert "/etc/passwd" not in refusal


def test_a_changed_failed_call_runs(checkout: Path) -> None:
call = ToolCallPart(tool_name="read_file", args={"path": "/etc/passwd"})
retry = ToolRetryError(
RetryPromptPart(content="cannot read it", tool_name="read_file", tool_call_id="1")
)
log = _repeat_log(checkout, call, retry)
changed = ToolCallPart(tool_name="read_file", args={"path": "src/sample.py"})

async def run() -> str:
return await log._execute(
None,
call=changed,
tool_def=ToolDefinition(name="read_file"),
args=dict(changed.args or {}),
handler=lambda _args: _ok(),
)

assert asyncio.run(run()) == "the result"


async def _ok() -> str:
return "the result"


def test_a_repeated_successful_call_runs(checkout: Path) -> None:
call = ToolCallPart(tool_name="read_file", args={"path": "src/sample.py"})
log = ToolCallLog(root=checkout)

async def run() -> str:
return await log._execute(
None,
call=call,
tool_def=ToolDefinition(name="read_file"),
args=dict(call.args or {}),
handler=lambda _args: _ok(),
)

assert (asyncio.run(run()), asyncio.run(run())) == ("the result", "the result")


def test_a_failed_call_is_remembered_by_its_digest(checkout: Path) -> None:
call = ToolCallPart(tool_name="read_file", args={"path": "/etc/passwd"})
retry = ToolRetryError(
RetryPromptPart(content="cannot read it", tool_name="read_file", tool_call_id="1")
)
log = _repeat_log(checkout, call, retry)

assert argument_digest(call) in log.failed