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
32 changes: 31 additions & 1 deletion client/context/request_intent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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:
Expand Down
41 changes: 39 additions & 2 deletions client/harness/command_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"(?<![=])\d*>{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"(?<![=])\d*>{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
Expand Down
59 changes: 34 additions & 25 deletions client/models/model_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from enum import StrEnum
from typing import Callable, Literal, Mapping, Protocol, Sequence

import httpx
from openai import APIConnectionError, APIStatusError, APITimeoutError


Expand Down Expand Up @@ -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] = []

Expand Down Expand Up @@ -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
Expand Down
9 changes: 8 additions & 1 deletion client/normative/normative_claims.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

#: "<Provision X> ... 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
Expand Down Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion client/runtime/agent_notes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
10 changes: 10 additions & 0 deletions client/standard/standard_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "
Expand Down
10 changes: 10 additions & 0 deletions client/tests/test_command_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
23 changes: 23 additions & 0 deletions client/tests/test_completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
13 changes: 13 additions & 0 deletions client/tests/test_model_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
19 changes: 19 additions & 0 deletions client/tests/test_normative_claims.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
24 changes: 24 additions & 0 deletions client/tests/test_request_intent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
11 changes: 11 additions & 0 deletions client/tests/test_standard_companions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"})
Expand Down
Loading