From 848be952f0e4a0e0e3785bd290a1c6eeb23dd8bf Mon Sep 17 00:00:00 2001 From: Daniel Rossier Date: Sat, 28 Nov 2026 12:33:46 +0100 Subject: [PATCH 1/5] Fail the turn when the stream is cut mid-answer The OpenAI SDK wraps transport errors raised when a request is sent, but not those raised while the stream is read. A connection cut mid-answer (a VPN re-authentication drops the ssh tunnel) surfaced as a bare httpx.RemoteProtocolError and ended spear-chat with a traceback. Both model paths now treat it as a model failure: the core path retries it like a connection error, the standard path returns a failed turn. --- client/models/model_backend.py | 59 +++++++++++++++++------------- client/tests/test_completion.py | 23 ++++++++++++ client/tests/test_model_backend.py | 13 +++++++ 3 files changed, 70 insertions(+), 25 deletions(-) diff --git a/client/models/model_backend.py b/client/models/model_backend.py index 510e043..002e866 100644 --- a/client/models/model_backend.py +++ b/client/models/model_backend.py @@ -16,6 +16,7 @@ from enum import StrEnum from typing import Callable, Literal, Mapping, Protocol, Sequence +import httpx from openai import APIConnectionError, APIStatusError, APITimeoutError @@ -319,40 +320,44 @@ def complete( text, calls, finish_reason = [], {}, None - for chunk in stream: - if not getattr(chunk, "choices", None): - continue + try: + for chunk in stream: + if not getattr(chunk, "choices", None): + continue - choice = chunk.choices[0] - finish_reason = getattr(choice, "finish_reason", None) or finish_reason - delta = getattr(choice, "delta", None) + choice = chunk.choices[0] + finish_reason = getattr(choice, "finish_reason", None) or finish_reason + delta = getattr(choice, "delta", None) - if delta is None: - continue + if delta is None: + continue - if getattr(delta, "content", None): - text.append(delta.content) + if getattr(delta, "content", None): + text.append(delta.content) - if on_token: - on_token() + if on_token: + on_token() - for tool_delta in getattr(delta, "tool_calls", None) or (): - item = calls.setdefault(tool_delta.index, {"id": None, "name": "", "arguments": []}) + for tool_delta in getattr(delta, "tool_calls", None) or (): + item = calls.setdefault(tool_delta.index, {"id": None, "name": "", "arguments": []}) - if getattr(tool_delta, "id", None): - item["id"] = tool_delta.id + if getattr(tool_delta, "id", None): + item["id"] = tool_delta.id - function = getattr(tool_delta, "function", None) + function = getattr(tool_delta, "function", None) - if function is not None: - if getattr(function, "name", None): - item["name"] += function.name + if function is not None: + if getattr(function, "name", None): + item["name"] += function.name - if getattr(function, "arguments", None): - item["arguments"].append(function.arguments) + if getattr(function, "arguments", None): + item["arguments"].append(function.arguments) - if on_token: - on_token() + if on_token: + on_token() + except (APIConnectionError, APITimeoutError, httpx.TransportError) as exc: + return ModelTurn("".join(text), (), StopReason.ERROR, + error=f"{type(exc).__name__}: {exc}") canonical_calls: list[ModelToolCall] = [] @@ -481,7 +486,11 @@ def complete_raw_messages(client, *, model: str, messages, tools, max_tokens: in return RawTurn("", (), None, error=f"HTTP {exc.status_code}: {exc}") failure = f"HTTP {exc.status_code}: {exc}" - except (APIConnectionError, APITimeoutError) as exc: + except (APIConnectionError, APITimeoutError, httpx.TransportError) as exc: + # The SDK wraps transport errors raised when the request is sent, + # not those raised while the stream is read: a connection cut + # mid-answer surfaces as a bare httpx error. + failure = f"{type(exc).__name__}: {exc}" attempt += 1 diff --git a/client/tests/test_completion.py b/client/tests/test_completion.py index b6b6b89..77dc5a4 100644 --- a/client/tests/test_completion.py +++ b/client/tests/test_completion.py @@ -213,6 +213,29 @@ def create(self, **kwargs): self.assertEqual(sent["max_tokens"], 65536) self.assertEqual(sent["timeout"], 1800.0) + def test_a_stream_cut_mid_answer_fails_the_turn(self): + import httpx + from models.model_backend import complete_raw_messages + + def cut(): + yield SimpleNamespace(usage=None, choices=[]) + raise httpx.RemoteProtocolError("peer closed connection") + + class Completions: + calls = 0 + + def create(self, **kwargs): + Completions.calls += 1 + return cut() + + client = SimpleNamespace(chat=SimpleNamespace(completions=Completions())) + turn = complete_raw_messages(client, model="qwen3", + messages=[{"role": "user", "content": "x"}], + tools=[], max_tokens=64, sleep=lambda _: None) + + self.assertIn("RemoteProtocolError", turn.error) + self.assertEqual(Completions.calls, 3) + class AProbedMakefileIsNotAPromiseOfTests(unittest.TestCase): def probe(self, makefile): root = tempfile.mkdtemp() diff --git a/client/tests/test_model_backend.py b/client/tests/test_model_backend.py index 42a2b79..2111f60 100644 --- a/client/tests/test_model_backend.py +++ b/client/tests/test_model_backend.py @@ -150,6 +150,19 @@ def test_invalid_json_is_controlled_and_never_becomes_a_tool_call(self): self.assertEqual(turn.tool_calls, ()) self.assertIn("invalid JSON", turn.error) + def test_a_stream_cut_mid_answer_is_a_failed_turn(self): + import httpx + + def cut(): + yield chunk(content="partial") + raise httpx.RemoteProtocolError("peer closed connection") + + turn = OpenAICompatibleBackend(FakeClient([cut()])).complete( + system="s", conversation=self.conversation, tools=[self.tool], use_tools=True + ) + self.assertEqual(turn.stop_reason, StopReason.ERROR) + self.assertIn("RemoteProtocolError", turn.error) + def test_a_written_tool_call_stays_text(self): """Only a call the API returns as one is a call. Recovered from the text, these ran searches on a turn that had been offered no tool.""" From 298782582d6719dd3c6ed1a3fd53a782d0f0d347 Mon Sep 17 00:00:00 2001 From: Daniel Rossier Date: Sat, 28 Nov 2026 12:35:27 +0100 Subject: [PATCH 2/5] Read a > inside quotes as text, not a redirection The redirection scan ran over the raw command, so a search such as grep -rn "chip->send_ipi" found a redirection to send_ipi" and asked for workspace:write; in --ask or safe mode the read-only search was refused. The scan now runs over the command with quoted text blanked out, and a quoted redirection target is read whole. --- client/harness/command_policy.py | 41 +++++++++++++++++++++++++++-- client/tests/test_command_policy.py | 10 +++++++ 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/client/harness/command_policy.py b/client/harness/command_policy.py index 592fcf1..4f27a1e 100644 --- a/client/harness/command_policy.py +++ b/client/harness/command_policy.py @@ -31,6 +31,33 @@ _FD_DUPLICATE = re.compile(r"[<>]&(?:\d+|-)(?![\w./])") +def _mask_quoted(command: str) -> str: + """`command` with the inside of every quoted string blanked out. + + Lengths are kept, so a match found in the result spans the same text in + `command`. + """ + + out, quote, escaped = [], None, False + + for char in command: + if quote is None: + out.append(char) + + if char in "'\"" and not escaped: + quote = char + + escaped = char == "\\" and not escaped + elif char == quote and not (quote == '"' and escaped): + out.append(char) + quote, escaped = None, False + else: + out.append(" ") + escaped = quote == '"' and char == "\\" and not escaped + + return "".join(out) + + @dataclass(frozen=True) class CommandAssessment: command: str @@ -881,8 +908,18 @@ def _redirect_targets(cls, command: str) -> "list[str]": for match in cls._LITERAL_ASSIGNMENT.finditer(command)} found = [] - for match in re.finditer(r"(?{1,2}\|?(&?)\s*([^\s;|&()<>]*)", command): - duplicate, target = match.groups() + # A `>` inside quotes is text, not an operator: `grep "chip->ops"` + # read as a redirection to `ops"` cost a read-only search the tree. + + for match in re.finditer(r"(?{1,2}\|?(&?)\s*([^\s;|&()<>]*)", + _mask_quoted(command)): + duplicate, _ = match.groups() + start, end = match.span(2) + + if command[start:start + 1] in ("'", '"'): + end = command.find(command[start], start + 1) + 1 or len(command) + + target = command[start:end].strip("'\"") if duplicate and re.fullmatch(r"\d+|-", target): continue diff --git a/client/tests/test_command_policy.py b/client/tests/test_command_policy.py index ef68d0d..ed93ff5 100644 --- a/client/tests/test_command_policy.py +++ b/client/tests/test_command_policy.py @@ -53,6 +53,16 @@ def test_read_only_pipelines_are_allowed_in_safe(self): "cat a.txt | wc -l"): self.assertTrue(self._granted(command, ExecutionMode.SAFE), command) + def test_an_arrow_inside_quotes_is_not_a_redirection(self): + for command in ('grep -rn "chip->send_ipi" a.txt | head', + "grep -n 'dev->ops' a.txt", + 'sed -n 1,2p a.txt; grep -rn "x\\|p->q" a.txt | head'): + self.assertTrue(self._granted(command, ExecutionMode.SAFE), command) + + def test_a_quoted_redirection_target_is_still_a_write(self): + for command in ('echo "->" > "out.txt"', "echo hi >'q.txt'"): + self.assertFalse(self._granted(command, ExecutionMode.SAFE), command) + def test_writing_pipelines_are_still_refused_in_safe(self): for command in ("echo x > a.txt", "cat a.txt | tee copy.txt", From fd092fa8c66e13fbfbe73588124ee3d648d00377 Mon Sep 17 00:00:00 2001 From: Daniel Rossier Date: Sat, 28 Nov 2026 12:36:48 +0100 Subject: [PATCH 3/5] Do not read a write verb used as a noun as a request to write "Explain how an IPI goes from the caller down to the GIC register write" matched the write pattern on "write": the turn was told it had not changed anything, sent back for an edit and asked for a plan, on a question that wanted an explanation. A write verb after a determiner or a hardware noun (the write, a fix, register write) is now taken out before the pattern is read, unless it is the object of do/make/apply/perform ("apply the fix"). --- client/context/request_intent.py | 32 ++++++++++++++++++++++++++++- client/runtime/agent_notes.py | 2 +- client/tests/test_request_intent.py | 24 ++++++++++++++++++++++ 3 files changed, 56 insertions(+), 2 deletions(-) diff --git a/client/context/request_intent.py b/client/context/request_intent.py index c0a37a2..cd09995 100644 --- a/client/context/request_intent.py +++ b/client/context/request_intent.py @@ -109,6 +109,36 @@ _SENTENCE = re.compile(r"[^.?!\n]+(?:[.?!]+|$)") +# The verbs the write pattern lists are also nouns. After a determiner or a +# hardware noun they name a thing, not an order: "down to the GIC register +# write" was read as "write", and an explanation turn was sent back to edit +# the tree. +_NOUN_USE = re.compile( + r"\b(?:a|an|the|this|that|these|those|each|every|one|single|its|their|" + r"register|memory|mmio|atomic|posted|pending|partial|byte|word|disk|" + r"buffered|last|first|next|previous)\s+" + r"(?:writes?|updates?|fix(?:es)?|patch(?:es)?|edits?|moves?|adds?|" + r"removes?|deletes?)\b", + re.I) + + +# "apply the fix", "make these changes": there the noun is what is asked for. +_ACTION_BEFORE = re.compile( + r"\b(?:do|make|apply|carry\s+out|perform)\s+(?:all\s+)?(?:\w+\s+){0,2}$", re.I) + + +def without_noun_uses(text): + """`text` with the write verbs that are used as nouns taken out.""" + text = text or "" + + def drop(match): + if _ACTION_BEFORE.search(text[:match.start()]): + return match.group(0) + + return match.group(0).split()[0] + + return _NOUN_USE.sub(drop, text) + def sentences(text): """The message cut into sentences; a question keeps its mark.""" @@ -138,7 +168,7 @@ def mutation_intent(text, write_pattern, *, answered=False): A sentence only counts toward "write" when it is not itself advisory: "Could we add a flag?" contains `add` and asks nothing to be added. """ - items = sentences(text) + items = sentences(without_noun_uses(text)) advisory = False for item in items: diff --git a/client/runtime/agent_notes.py b/client/runtime/agent_notes.py index 3dd9903..4459f50 100644 --- a/client/runtime/agent_notes.py +++ b/client/runtime/agent_notes.py @@ -436,7 +436,7 @@ def is_write_request(question: str) -> bool: if intent != "unknown": return intent == "write" - return bool(_WRITE_REQUEST_RE.search(question or "")) + return bool(_WRITE_REQUEST_RE.search(request_intent.without_noun_uses(question))) def may_demand_write(context) -> bool: diff --git a/client/tests/test_request_intent.py b/client/tests/test_request_intent.py index bbd964e..a685df5 100644 --- a/client/tests/test_request_intent.py +++ b/client/tests/test_request_intent.py @@ -106,5 +106,29 @@ def test_the_answer_is_decided_once_per_turn(self): self.assertEqual(len(context.backend.calls), 1) + +class AWriteVerbUsedAsANoun(unittest.TestCase): + """"the GIC register write" names a thing; it asks for nothing.""" + + def setUp(self): + from runtime.agent_notes import is_write_request + + self.is_write = is_write_request + + def test_an_explanation_naming_a_write_is_not_a_request(self): + for text in ("Explain how an IPI goes from the caller down to the GIC " + "register write, and how CPU #1 handles it.", + "Why is the write to ICC_SGI1R_EL1 followed by an isb?", + "Explain the fix in commit abc."): + with self.subTest(text=text): + self.assertFalse(self.is_write(text)) + + def test_the_noun_asked_for_is_still_a_request(self): + for text in ("apply the fix", "Fix the register write in gic_send_sgi.", + "make all the required minor fixes", "Please apply this patch.", + "Write a test for gic_send_sgi."): + with self.subTest(text=text): + self.assertTrue(self.is_write(text)) + if __name__ == "__main__": unittest.main() From 3b21e09f0e135072c3f19325ef4b12cc334b06dc Mon Sep 17 00:00:00 2001 From: Daniel Rossier Date: Sat, 28 Nov 2026 12:39:17 +0100 Subject: [PATCH 4/5] Do not read a denied force word as a claim of that force An explanation answer that opened with "there is no requirement to satisfy" was read as claiming a requirement, found stronger than the permission its evidence established, and withheld in full. A force word preceded by a negation (no requirement, not required, does not have to) now claims nothing; a negation after it (must not, shall not) is a prohibition and still a requirement. --- client/normative/normative_claims.py | 9 ++++++++- client/tests/test_normative_claims.py | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/client/normative/normative_claims.py b/client/normative/normative_claims.py index 52b987b..e40d9ab 100644 --- a/client/normative/normative_claims.py +++ b/client/normative/normative_claims.py @@ -82,6 +82,12 @@ r"\b(?:may|can|permitted|allowed|optional|is able to)\b", re.I)), ) +#: A force word the sentence denies: "there is no requirement", "is not +#: required", "does not require". That claims the absence of the force, not +#: the force. A negation AFTER the word ("must not", "shall not") is a +#: prohibition and still a requirement, so only what comes before is read. +_DENIED_FORCE = re.compile(r"(?:\b(?:no|not|never|without)|n't)\W+(?:\w+\W+)?$", re.I) + #: " ... is a binding requirement" -- a claim about what a NAMED #: provision is, rather than a claim the provision supports. Deliberately #: tight: the force word must follow the citation closely and in the same @@ -437,7 +443,8 @@ def claim_level(sentence, question=""): spoken = None for level, pattern in _CLAIM: - if pattern.search(sentence or ""): + if any(not _DENIED_FORCE.search((sentence or "")[:match.start()]) + for match in pattern.finditer(sentence or "")): spoken = level break diff --git a/client/tests/test_normative_claims.py b/client/tests/test_normative_claims.py index 250429c..58830dc 100644 --- a/client/tests/test_normative_claims.py +++ b/client/tests/test_normative_claims.py @@ -291,6 +291,25 @@ def test_the_principal_conclusion_skips_harness_prefaces(self): self.assertEqual(nc.principal(answer), "Yes, it may.") + +class ADeniedForceIsNotClaimed(unittest.TestCase): + """"there is no requirement" asserts the absence of one.""" + + def test_a_force_word_the_sentence_denies_claims_nothing(self): + for sentence in ("No edit is made: there is no requirement to satisfy.", + "A barrier is not required.", + "The PE does not have to issue a DSB."): + with self.subTest(sentence=sentence): + self.assertIsNone(nc.claim_level(sentence)) + + def test_a_prohibition_is_still_a_requirement(self): + self.assertEqual(nc.claim_level("The Controllee must not send an ACK."), + nc.REQUIREMENT) + + def test_the_next_undenied_word_is_the_claim(self): + self.assertEqual(nc.claim_level("It is not mandatory, but the PE should issue a DSB."), + nc.RECOMMENDATION) + if __name__ == "__main__": unittest.main() From f05dd0a7562fa4a385e6852c8eb0925435e78dd4 Mon Sep 17 00:00:00 2001 From: Daniel Rossier Date: Sat, 28 Nov 2026 12:47:04 +0100 Subject: [PATCH 5/5] Let a revision alone name the bound standard that carries it standard.search with revision "H.b" and no standard_id was compared with the active standard (DDI 0487 M.c) and refused, although H.b is the bound companion's revision. The turn retried it until it stalled. A revision that exactly one bound standard carries now selects that standard. --- client/standard/standard_tools.py | 10 ++++++++++ client/tests/test_standard_companions.py | 11 +++++++++++ 2 files changed, 21 insertions(+) diff --git a/client/standard/standard_tools.py b/client/standard/standard_tools.py index 9319b42..4e3387b 100644 --- a/client/standard/standard_tools.py +++ b/client/standard/standard_tools.py @@ -519,6 +519,16 @@ def _binding(context: ToolExecutionContext, arguments: Mapping[str, object]) -> revision = arguments.get("revision") + # A revision alone names the bound standard that carries it: "H.b" is + # the companion's, and comparing it with the active standard's refused + # a correct call until the turn looped on it. + + if wanted is None and revision is not None: + carrying = [item for item in bindings if item.revision == revision] + + if len(carrying) == 1: + binding = carrying[0] + if revision is not None and revision != binding.revision: raise PermissionError( f"requested revision does not equal the active StandardBinding of " diff --git a/client/tests/test_standard_companions.py b/client/tests/test_standard_companions.py index 023d822..7e23864 100644 --- a/client/tests/test_standard_companions.py +++ b/client/tests/test_standard_companions.py @@ -153,6 +153,17 @@ def test_fetch_and_cite_find_the_standard_that_holds_the_source(self): cited = self.execute("standard.cite", {"source_id": source_id}) self.assertTrue(cited.success, cited.text) + def test_a_revision_alone_names_the_standard_that_carries_it(self): + payload = self.search(query="doorbell register", revision="C-1") + + self.assertTrue(payload["results"]) + self.assertEqual({item["standard_id"] for item in payload["results"]}, {"CTRL-STD"}) + + def test_a_revision_no_bound_standard_carries_is_denied(self): + denied = self.execute("standard.search", {"query": "doorbell", "revision": "X-9"}) + + self.assertFalse(denied.success) + def test_a_standard_that_is_not_bound_is_denied(self): denied = self.execute("standard.search", {"query": "doorbell", "standard_id": "NOT-BOUND"})