"""Bound pre-write discovery for mutating coder attempts.""" from __future__ import annotations from dataclasses import dataclass DISCOVERY_PROGRESS_REJECTION = "DISCOVERY_PROGRESS_REJECTED:" _PREWRITE_NON_PROGRESS_TOOLS = frozenset( { "read_file", "read_evidence_file", "read_evidence_metadata", "read_evidence_section", "search_evidence_text", "glob_files", "discover_project", "list_directory", "grep_codebase", "run_command", "run_verification", "normalize_line_endings", "task_complete", } ) _WRITE_OR_BLOCK_TOOLS = frozenset({"write_file", "edit_file", "task_blocked"}) _FAILED_RESULT_PREFIXES = ( "Error:", "Tool error:", "REJECTED:", "TASK_", "CHECKPOINT_", "DISCOVERY_PROGRESS_", "VERIFICATION_", ) @dataclass(frozen=True) class GovernorDecision: """A deterministic pre-dispatch decision for one tool call.""" rejection: str = "" terminal: bool = False class DiscoveryProgressGovernor: """Move a mutating attempt from bounded discovery to write-or-block. The governor is per attempt and has no filesystem or backend dependencies. A configured threshold activates *after* that many completed model turns or pre-write non-progress calls. Once active, a worker gets one model turn to react to a rejected call. A prohibited call from a later model turn is a terminal policy violation; multiple calls in one already-generated response are rejected but do not independently consume that grace opportunity. """ def __init__( self, *, turn_limit: int, tool_limit: int, read_only: bool = False, ) -> None: self.turn_limit = max(int(turn_limit), 0) self.tool_limit = max(int(tool_limit), 0) self.enabled = not read_only and bool(self.turn_limit or self.tool_limit) self.completed_turns = 0 self.exploratory_calls = 0 self.failed_lookups = 0 self.has_written = False self.active = False self.activation_reason = "" self.rejection_count = 0 self._nudge_delivered = False self._first_rejection_turn: int | None = None def begin_turn(self, completed_turns: int) -> None: """Record how many model turns completed before the current response.""" self.completed_turns = max(int(completed_turns), self.completed_turns) if ( self.enabled and not self.has_written and not self.active and self.turn_limit and self.completed_turns >= self.turn_limit ): self._activate(f"turn limit {self.turn_limit}") def decision_for(self, tool_name: str) -> GovernorDecision: """Return a rejection before dispatch when write-or-block is active.""" if not self.active or self.has_written or tool_name in _WRITE_OR_BLOCK_TOOLS: return GovernorDecision() if tool_name not in _PREWRITE_NON_PROGRESS_TOOLS: return GovernorDecision() terminal = ( self._first_rejection_turn is not None and self.completed_turns > self._first_rejection_turn ) if self._first_rejection_turn is None: self._first_rejection_turn = self.completed_turns self.rejection_count += 1 return GovernorDecision(self.rejection_message(tool_name), terminal) def record_result(self, tool_name: str, result: str) -> None: """Record an executed tool result and update phase state.""" if not self.enabled or self.has_written: return if tool_name in {"write_file", "edit_file"}: if self.result_succeeded(result): self.has_written = True self.active = False return if tool_name not in _PREWRITE_NON_PROGRESS_TOOLS: return self.exploratory_calls += 1 if tool_name in { "read_file", "read_evidence_file", "read_evidence_metadata", "read_evidence_section", "search_evidence_text", "glob_files", "discover_project", "list_directory", "grep_codebase", } and self._lookup_failed(result): self.failed_lookups += 1 if not self.active and self.tool_limit and self.exploratory_calls >= self.tool_limit: self._activate(f"tool-call limit {self.tool_limit}") def take_nudge(self) -> str: """Return the phase-transition instruction exactly once.""" if not self.active or self.has_written or self._nudge_delivered: return "" self._nudge_delivered = True return self._instruction( f"The bounded discovery phase is over because the {self.activation_reason} was reached." ) def rejection_message(self, tool_name: str) -> str: return ( f"{DISCOVERY_PROGRESS_REJECTION} {tool_name} is unavailable before the first " f"substantive write (completed turns={self.completed_turns}, " f"exploratory calls={self.exploratory_calls}, failed lookups={self.failed_lookups}). " + self._instruction("Use the evidence already gathered.") ) def failure_summary(self) -> str: return ( "DISCOVERY_PROGRESS_STALLED: The worker continued pre-write exploration after " "AFK entered write-or-block mode and returned a policy rejection " f"(completed turns={self.completed_turns}, exploratory calls={self.exploratory_calls}, " f"failed lookups={self.failed_lookups}, rejections={self.rejection_count}). " "Narrow the task or supply the precise missing fact before retrying." ) @staticmethod def result_succeeded(result: str) -> bool: stripped = result.lstrip() return not stripped.startswith(_FAILED_RESULT_PREFIXES) @staticmethod def _lookup_failed(result: str) -> bool: normalized = result.lstrip().lower() return not DiscoveryProgressGovernor.result_succeeded(result) or normalized.startswith( ("no files match", "directory not found", "no matches") ) def _activate(self, reason: str) -> None: self.active = True self.activation_reason = reason @staticmethod def _instruction(prefix: str) -> str: return ( f"{prefix} Write or edit the bounded requested artifact now, or call task_blocked " "with one precise missing fact that prevents writing. Do not perform more broad " "discovery, probing, commands, or verification before a successful write." ) @property def has_rejected(self) -> bool: return self._first_rejection_turn is not None