From ac9eb84457ead0cc5b0340afb0c1f387a91a28c0 Mon Sep 17 00:00:00 2001 From: Daniel Rossier Date: Thu, 26 Nov 2026 17:45:45 +0100 Subject: [PATCH 1/3] Show the repair the whole rejected answer, and label only what the user saw The normative repair prompt cut the rejected answer at 1200 characters and told the model to keep everything the findings did not touch. The model kept it, copied the answer up to the cut, and stopped there: the two truncated answers seen in use ("If you want, I can pull the", and a source id cut in half) were the originals' first 1200 characters, rewritten. The prompt now carries the rejected answer in full. The fragment was then accepted and shown in place of a complete answer. As a second line of defence, a repair now fails when its draft carries a tool call, stops at the token limit, or ends mid-sentence, so the original is withheld as before. The episode labelled that fragment final_success: the repair was recorded as a primary_agent turn and the label went to the last turn whatever the user was shown. The repair call is now recorded with the purpose normative_repair, and final_success goes to the last turn only when it is a primary turn whose output is the visible answer, so a withheld or replaced answer no longer becomes a positive example. --- client/runtime/agent_finalization.py | 19 +++++++--- client/runtime/agent_model_turn.py | 4 ++- client/runtime/answer_repair.py | 26 ++++++++++++-- client/tests/test_answer_repair.py | 33 ++++++++++++++++++ client/tests/test_repair_wiring_parity.py | 42 +++++++++++++++++++++++ client/tests/test_training_data.py | 33 ++++++++++++++++++ client/training/training_data.py | 20 ++++++++++- 7 files changed, 169 insertions(+), 8 deletions(-) diff --git a/client/runtime/agent_finalization.py b/client/runtime/agent_finalization.py index 4f81a76..0e3ef42 100644 --- a/client/runtime/agent_finalization.py +++ b/client/runtime/agent_finalization.py @@ -7,8 +7,8 @@ from runtime.failure_policy import FailureKind from models.model_backend import ( - ConversationMessage, ModelTurn, TextBlock, ToolResultBlock, ToolUseBlock, - textual_tool_call, + ConversationMessage, ModelTurn, StopReason, TextBlock, ToolResultBlock, + ToolUseBlock, textual_tool_call, ) from runtime.tracing import EventStatus, EventType from evidence import project_build @@ -214,11 +214,22 @@ def _repair_ask(self, context: AgentContext, text: str) -> str: turn = self.complete_model_turn( context, use_tools=False, conversation=(ConversationMessage("user", (TextBlock(text),)),), - grace=True) + grace=True, purpose="normative_repair") except Exception: return "" # a failed repair withholds, exactly as before - return (turn.text or "") if turn is not None else "" + if turn is None: + return "" + + # A draft that reached for a tool, or ran out of tokens, stops where + # the call or the limit began: what is left is a fragment, not a + # repair. + + if (turn.tool_calls or textual_tool_call(turn.text) + or turn.stop_reason == StopReason.MAX_TOKENS): + return "" + + return turn.text or "" @staticmethod def _result( diff --git a/client/runtime/agent_model_turn.py b/client/runtime/agent_model_turn.py index 9a4bdcf..7a4db19 100644 --- a/client/runtime/agent_model_turn.py +++ b/client/runtime/agent_model_turn.py @@ -283,6 +283,7 @@ def complete_model_turn( on_token: Callable[[], None] | None = None, only_tools: Sequence[str] | None = None, grace: bool = False, + purpose: str | None = None, ) -> ModelTurn: conversation = tuple(conversation or context.conversation) @@ -321,7 +322,8 @@ def complete_model_turn( recorder.begin_model_turn( system=system, conversation=selected_conversation, tools=context.tools, role=context.role, - purpose="primary_agent" if context.role == "main" else context.role, + purpose=purpose or ("primary_agent" if context.role == "main" + else context.role), mutation_generation=context.working_state.mutation_generation, memory_provenance_ids=tuple( item.item_id for item in snapshot.selected_items diff --git a/client/runtime/answer_repair.py b/client/runtime/answer_repair.py index 5252d70..43f57d4 100644 --- a/client/runtime/answer_repair.py +++ b/client/runtime/answer_repair.py @@ -137,6 +137,28 @@ def repeats_flagged_identifier(repaired, problems): return None +#: How a sentence reads when it was cut off: a plain word, a comma or an opening +#: bracket as the last thing on its last line of prose. A repair that stops +#: there is a fragment, whatever made it stop. + +_CUT_OFF = re.compile(r"(?)") + + +def interrupted(text): + """Does the draft stop in the middle of a sentence?""" + + lines = [line for line in (text or "").splitlines() if line.strip()] + + if not lines or _UNPUNCTUATED.match(lines[-1]): + return False + + return bool(_CUT_OFF.search(lines[-1].rstrip())) + + def outcome(original, repaired, problems): """What the repair did, as a fact about the two drafts. @@ -145,7 +167,7 @@ def outcome(original, repaired, problems): finding was repairable, that is a worse outcome than the original, and accepting it hid a correct conclusion behind a refusal. """ - if not repaired: + if not repaired or interrupted(repaired): return REPAIR_FAILED if repeats_flagged_identifier(repaired, problems): @@ -232,7 +254,7 @@ def prompt(question, rejected, evidence, problems): f"QUESTION: {question}", "", "YOUR REJECTED ANSWER:", - f" {(rejected or '').strip()[:1200]}", + f" {(rejected or '').strip()}", "", "WHY IT WAS REJECTED:", *_finding_lines(problems), diff --git a/client/tests/test_answer_repair.py b/client/tests/test_answer_repair.py index 4955935..e45a615 100644 --- a/client/tests/test_answer_repair.py +++ b/client/tests/test_answer_repair.py @@ -82,6 +82,16 @@ def test_it_carries_the_rejected_conclusion_and_the_reason(self): self.assertIn("Yes, a Reply may carry two tags.", text) self.assertIn("contradicts", text) + def test_it_carries_the_whole_rejected_answer(self): + """The repair must keep what was not rejected, so it must see all of + it: a cut-off answer came back copied up to the cut, and ended there.""" + long_answer = "Yes, a Reply may carry two tags. " * 80 + "The last sentence." + + text = ar.prompt("May a Reply carry two tags?", long_answer, + self.evidence, self.problems) + + self.assertIn(long_answer, text) + def test_it_forbids_further_retrieval_in_words(self): self.assertIn("cannot retrieve more", self.prompt()) @@ -468,3 +478,26 @@ def ask(text): ask=ask) self.assertEqual(len(asked), 1) + + +class ACutOffDraftIsNoRepair(unittest.TestCase): + """A repair that stops mid-sentence is a fragment; accepting it showed + the reader half a sentence in place of a complete answer.""" + + def test_a_sentence_stopped_on_a_word_is_interrupted(self): + self.assertTrue(ar.interrupted("It does not.\n\nIf you want, I can pull the")) + self.assertTrue(ar.interrupted("The handler calls foo(")) + self.assertTrue(ar.interrupted("It applies to both,")) + + def test_finished_prose_lists_code_and_references_are_not(self): + for text in ("Rule 5.2-1 applies.", "Which one do you want?", + "- the last item", "1. step one", "```\ncode\n```", + "see smp.c:1231", "the value is 0x10", "**Summary**", + "see ICC_SGI1R_EL1", ""): + self.assertFalse(ar.interrupted(text), text) + + def test_a_cut_off_rewrite_fails_instead_of_answering(self): + self.assertEqual( + ar.outcome("No. Rule 5.2-1 applies.", "No. Rule 5.2-1 says that", + [{"kind": nc.INCOHERENT_CONCLUSION}]), + ar.REPAIR_FAILED) diff --git a/client/tests/test_repair_wiring_parity.py b/client/tests/test_repair_wiring_parity.py index 288b502..1428fe5 100644 --- a/client/tests/test_repair_wiring_parity.py +++ b/client/tests/test_repair_wiring_parity.py @@ -101,3 +101,45 @@ def ask(text): if __name__ == "__main__": unittest.main() + + +class AFragmentIsNotARepair(unittest.TestCase): + """What the runtime hands back when the tool-less draft reached for a + tool or ran out of tokens: nothing, so the original is withheld.""" + + def ask(self, turn): + from unittest.mock import patch + + runtime = agent_runtime.AgentRuntime() + + with patch.object(agent_runtime.AgentRuntime, "complete_model_turn", + return_value=turn) as complete: + text = runtime._repair_ask(object(), "rewrite it") + + return text, complete.call_args.kwargs + + def test_a_draft_with_a_tool_call_is_dropped(self): + from models.model_backend import ModelToolCall, ModelTurn, StopReason + + text, _ = self.ask(ModelTurn( + "I can pull the", (ModelToolCall("c1", "standard.search", {}),), + StopReason.TOOL_USE)) + + self.assertEqual(text, "") + + def test_a_draft_that_hit_the_limit_is_dropped(self): + from models.model_backend import ModelTurn, StopReason + + text, _ = self.ask(ModelTurn("It says", (), StopReason.MAX_TOKENS)) + + self.assertEqual(text, "") + + def test_a_finished_draft_is_returned_and_recorded_as_a_repair(self): + from models.model_backend import ModelTurn, StopReason + + text, kwargs = self.ask(ModelTurn("Rule 5.2-1 applies.", (), + StopReason.END_TURN)) + + self.assertEqual(text, "Rule 5.2-1 applies.") + self.assertEqual(kwargs["purpose"], "normative_repair") + self.assertFalse(kwargs["use_tools"]) diff --git a/client/tests/test_training_data.py b/client/tests/test_training_data.py index bd2d200..2669e0f 100644 --- a/client/tests/test_training_data.py +++ b/client/tests/test_training_data.py @@ -250,6 +250,39 @@ def test_auxiliary_role_is_not_default_candidate(self): self.assertFalse(episode.turns[0].primary_candidate) self.assertEqual(episode.training_metadata["default_sft_turns"], []) + def _labels(self, final_response, *, purpose=None): + with tempfile.TemporaryDirectory() as directory: + store = TrainingStore(Path(directory) / "training") + context = make_context(ScriptedBackend([text_turn("the answer")])) + recorder = TrainingRecorder( + store, task_id=context.task_id, session_id=None, + objective="answer", workspace=directory, + ) + context.training_recorder = recorder + result = AgentRuntime().run(context) + if purpose is not None: + recorder.turns[-1].purpose = purpose + recorder.turns[-1].primary_candidate = False + episode = recorder.finalize( + state=context.working_state, task_status="completed", + terminal_reason=result.terminal_reason.value, + verification_status="not_required", checkpoint_status=None, + final_response=final_response, + ) + return episode.turns[-1].labels + + def test_final_success_marks_the_answer_the_user_saw(self): + self.assertIn("final_success", self._labels("the answer")) + self.assertIn("final_success", self._labels("VERDICT: NOT DEMONSTRATED\n\nthe answer")) + + def test_a_withheld_or_replaced_answer_is_not_a_success_of_the_turn(self): + self.assertNotIn("final_success", + self._labels("The evidence does not support this answer.")) + + def test_a_repair_turn_is_never_the_positive_example(self): + self.assertNotIn("final_success", + self._labels("the answer", purpose="normative_repair")) + def test_two_tasks_do_not_leak_state_and_disabled_creates_nothing(self): with tempfile.TemporaryDirectory() as directory: store = TrainingStore(Path(directory) / "training") diff --git a/client/training/training_data.py b/client/training/training_data.py index 9322d2d..7057caf 100644 --- a/client/training/training_data.py +++ b/client/training/training_data.py @@ -344,6 +344,23 @@ def _tool_view(tools: Sequence[ToolDefinition]) -> tuple[str, Mapping[str, objec return hashlib.sha256(encoded).hexdigest(), snapshot +def _answered_by(turn: TrainingTurn, final_response: str) -> bool: + """Is the user-visible answer this primary turn's own output? + + A guard may withhold or replace the model's answer, and a tool-less repair + may rewrite it from a prompt the conversation never held. Neither is the + turn's output, so neither may make it a positive example. The response + may carry a verdict header, hence containment rather than equality. + """ + + if not turn.primary_candidate: + return False + + output = " ".join(turn.assistant_output.split()) + + return bool(output) and output in " ".join((final_response or "").split()) + + def _opaque_id(prefix: str, task_id: str, session_id: str | None) -> str: value = f"{task_id}\0{session_id or ''}".encode() return f"{prefix}_{hashlib.sha256(value).hexdigest()[:32]}" @@ -631,7 +648,8 @@ def finalize(self, *, state: WorkingState, task_status: str, checkpoint_status=checkpoint_status, ) - if eligibility == TrainingEligibility.POSITIVE_CANDIDATE and self.turns: + if (eligibility == TrainingEligibility.POSITIVE_CANDIDATE and self.turns + and _answered_by(self.turns[-1], final_response)): labels = list(self.turns[-1].labels) labels.append("final_success") self.turns[-1].labels = tuple(dict.fromkeys(labels)) From 237df1c7d01646f2036075ac00f89e777451eb48 Mon Sep 17 00:00:00 2001 From: Daniel Rossier Date: Thu, 26 Nov 2026 18:01:19 +0100 Subject: [PATCH 2/3] Bind companion standards beside the active one A question can need two documents: the Arm Architecture Reference Manual names the GIC system registers and defers their fields to the GIC architecture specification, so an answer about raising an SGI needs both, and only one standard could be bound. /standard add binds another document beside the active one, /standard drop removes it. Companions are kept in the active binding file, held to the same canonical-source check, carried in the session's binding as "companions", shown on the banner, in status and list, and staged into an image only with their documents. standard.search covers every bound standard when no standard_id is given, interleaving the results by rank since scores from two corpora are not on one scale; fetch and cite find the standard holding the source; standard_id selects one. The model is told which companions are bound, and the guards recognise their names. A conformance verdict is still judged against the active standard alone. --- client/cli/standard_session.py | 33 ++++- client/cli/startup_banner.py | 7 + client/evidence/conformance_guard.py | 19 ++- client/runtime/task_controller.py | 19 +++ client/standard/standard_commands.py | 147 ++++++++++++++++++- client/standard/standard_tools.py | 173 ++++++++++++++++------ client/tests/test_standard_companions.py | 176 +++++++++++++++++++++++ doc/source/reasoning/standards.rst | 30 +++- scripts/docker/stage-standards.py | 31 +++- 9 files changed, 575 insertions(+), 60 deletions(-) create mode 100644 client/tests/test_standard_companions.py diff --git a/client/cli/standard_session.py b/client/cli/standard_session.py index 8bbac5d..712913c 100644 --- a/client/cli/standard_session.py +++ b/client/cli/standard_session.py @@ -144,9 +144,23 @@ def standard_binding_for(question): context, STANDARD_READ_CONTEXT = STANDARD_READ_CONTEXT, "" - if not standard_scope.engages(binding, question, - engaged_before=STANDARD_ENGAGED_BEFORE, - context=context): + if binding is None: + return None + + try: + companions = STANDARD_OPERATOR.companion_bindings() + except StandardCommandError as exc: + print(f" {C_DIM}⎿ {exc}; answering with the active standard " + f"alone{C_RST}") + companions = [] + + # A question about a companion engages the binding as much as one about + # the active standard: that is what binding it beside was for. + + if not any(standard_scope.engages(item, question, + engaged_before=STANDARD_ENGAGED_BEFORE, + context=context) + for item in (binding, *companions)): return None # Follow-ups to a bound turn are part of it. "can you validate the @@ -155,8 +169,15 @@ def standard_binding_for(question): STANDARD_ENGAGED_BEFORE = True + beside = "".join(f" + {item.standard_id} {item.revision}" + for item in companions) print(f" {C_DIM}⎿ bound standard: {binding.standard_id} " - f"{binding.revision} — normative claims are grounded in it and " - f"cited{C_RST}") + f"{binding.revision}{beside} — normative claims are grounded in " + f"{'them' if companions else 'it'} and cited{C_RST}") + + payload = binding.to_dict() + + if companions: + payload["companions"] = [item.to_dict() for item in companions] - return binding.to_dict() + return payload diff --git a/client/cli/startup_banner.py b/client/cli/startup_banner.py index 5efccf2..767b23f 100644 --- a/client/cli/startup_banner.py +++ b/client/cli/startup_banner.py @@ -222,7 +222,14 @@ def standard_row(): # How it is searched follows the document, so switching documents # switches it; the banner is where that has to be visible. + try: + beside = "".join(f" + {item.standard_id} {item.revision}" + for item in STANDARD_OPERATOR.companion_bindings()) + except StandardCommandError as exc: + beside = f" {C_WARN}(companion unavailable — {exc}){C_RST}" + return (f"{C_DIM}standard:{C_RST} {binding.standard_id} {binding.revision}" + f"{beside}" f" {C_DIM}·{C_RST} {binding.data_origin.lower()}" f" {C_DIM}·{C_RST} " + retrieval_summary(STANDARD_STORE, binding.standard_id, diff --git a/client/evidence/conformance_guard.py b/client/evidence/conformance_guard.py index 14c5d31..3345026 100644 --- a/client/evidence/conformance_guard.py +++ b/client/evidence/conformance_guard.py @@ -187,10 +187,23 @@ def _identity_terms(binding): from standard import standard_scope - subject = _Named(binding) if isinstance(binding, dict) else binding + # Companions bound beside the active standard travel inside its dict, and + # a sentence naming any of them speaks for a bound standard. - return tuple(term for term in standard_scope.identity_terms(subject) - if len(term) > 3) + subjects = [binding] + + if isinstance(binding, dict): + subjects += [item for item in binding.get("companions") or () + if isinstance(item, dict)] + + terms = [] + + for item in subjects: + subject = _Named(item) if isinstance(item, dict) else item + terms += [term for term in standard_scope.identity_terms(subject) + if len(term) > 3 and term not in terms] + + return tuple(terms) # A clause identifier sitting immediately before the standard's name, which diff --git a/client/runtime/task_controller.py b/client/runtime/task_controller.py index 04bb14f..33fd4e6 100644 --- a/client/runtime/task_controller.py +++ b/client/runtime/task_controller.py @@ -172,8 +172,12 @@ def run(self, request: TaskRequest) -> TaskResult: if ((persisted.retrieval_fingerprint or persisted.index_fingerprint) != (current.retrieval_fingerprint or current.index_fingerprint)): + companions = context.standard_binding.get("companions") context.standard_binding = current.to_dict() + if companions: + context.standard_binding["companions"] = companions + if context.session is not None: AgentRuntime.persist_session_event( context, SessionEventType.STANDARD_RETRIEVAL_CHANGED, @@ -209,6 +213,21 @@ def run(self, request: TaskRequest) -> TaskResult: "Do not invent values or silently switch revisions; report insufficient or conflicting sources.", )) + "\n" + # Companions are searched, read and cited like the bound standard; + # the model is told which they are so it can say where a clause + # comes from. + + companions = [item for item in context.standard_binding.get("companions") or () + if isinstance(item, dict)] + + if companions: + identity += "\n".join(( + "\nCOMPANION STANDARDS (bound beside it; standard.search covers them too)", + *[f"{item.get('standard_id')} revision {item.get('revision')}" + for item in companions], + "Cite each clause with the standard it comes from.", + )) + "\n" + # What outranks what, and what may speak for the standard. Both # are attached to the BINDING, which is the one place a rule # reaches every bound turn whatever prompt the project carries. diff --git a/client/standard/standard_commands.py b/client/standard/standard_commands.py index 33778ba..84ccfa6 100644 --- a/client/standard/standard_commands.py +++ b/client/standard/standard_commands.py @@ -90,6 +90,90 @@ def use(self, standard_id: str, revision: str) -> StandardBinding: return binding + def companion_bindings(self) -> list[StandardBinding]: + """The standards bound beside the active one, each still honoured. + + A companion is read, searched and cited like the active standard, and + it is held to the same rule: a corpus that moved underneath it is + refused, never silently rebound. + """ + + companions = [] + + for raw in self._read_raw().get("companions") or (): + try: + persisted = StandardBinding.from_dict(raw) + current = self.store.binding(persisted.standard_id, + persisted.revision, + bound_at=persisted.bound_at) + except Exception as exc: + raise StandardCommandError( + f"companion standard binding is invalid: {exc}") from exc + + if (persisted.pdf_sha256 != current.pdf_sha256 + or persisted.corpus_manifest_sha256 + != current.corpus_manifest_sha256): + raise StandardCommandError( + f"companion standard {persisted.standard_id} canonical " + "source changed; rebind refused") + + self._register_profile(current) + companions.append(current) + + return companions + + def add_companion(self, standard_id: str, revision: str) -> StandardBinding: + """Bind one more standard beside the active one.""" + + active = self.active_binding() + + if active is None: + raise StandardCommandError( + "no active standard: bind one with /standard use first") + + if standard_id == active.standard_id: + raise StandardCommandError( + f"{standard_id} is already the active standard") + + binding = self.store.binding( + standard_id, revision, + bound_at=datetime.now(timezone.utc).isoformat(timespec="seconds"), + ) + companions = [item for item in self.companion_bindings() + if item.standard_id != standard_id] + self._write_active(active, [*companions, binding]) + self._register_profile(binding) + + return binding + + def drop_companion(self, standard_id: str) -> bool: + active = self.active_binding() + companions = self.companion_bindings() + kept = [item for item in companions if item.standard_id != standard_id] + + if active is None or len(kept) == len(companions): + return False + + self._write_active(active, kept) + + return True + + def session_binding(self) -> dict | None: + """The active binding as a session carries it, companions included.""" + + active = self.active_binding() + + if active is None: + return None + + payload = active.to_dict() + companions = self.companion_bindings() + + if companions: + payload["companions"] = [item.to_dict() for item in companions] + + return payload + def stale_binding_status(self, exc: StandardCommandError) -> str: """Explain a binding the store can no longer honour, without guessing.""" @@ -181,11 +265,32 @@ def unbind(self) -> None: "active": None, })) - def _write_active(self, binding: StandardBinding) -> None: - self._atomic_write(self._active_path, canonical_json({ - "schema_version": 1, - "active": binding.to_dict(), - })) + def _read_raw(self) -> dict: + try: + raw = json.loads(self._active_path.read_text("utf-8")) + except (FileNotFoundError, ValueError): + return {} + + return raw if isinstance(raw, dict) else {} + + def _write_active(self, binding: StandardBinding, + companions: list[StandardBinding] | None = None) -> None: + # Rebinding the active standard keeps its companions, except the one + # that has just become active. + + if companions is None: + kept = [raw for raw in self._read_raw().get("companions") or () + if isinstance(raw, dict) + and raw.get("standard_id") != binding.standard_id] + else: + kept = [item.to_dict() for item in companions] + + document = {"schema_version": 1, "active": binding.to_dict()} + + if kept: + document["companions"] = kept + + self._atomic_write(self._active_path, canonical_json(document)) @staticmethod def _atomic_write(path: Path, content: bytes) -> None: @@ -221,6 +326,8 @@ def _atomic_write(path: Path, content: bytes) -> None: ("ingest", " --id --revision [--retain-pdf] " "[--origin LICENSED_STANDARD|PUBLIC] [--allow-offload]"), ("use", " "), + ("add", " "), + ("drop", ""), ("status", ""), ("rebuild", "[ ] [--allow-offload]"), ("retrieval", "[ ] [lexical|vector|hybrid] [--completion ]"), @@ -434,10 +541,18 @@ def handle_standard_command(command: str, operator: StandardOperator) -> str: active = ((bound.standard_id, bound.revision) if bound is not None else (None, None)) + + try: + companions = {(item.standard_id, item.revision) + for item in operator.companion_bindings()} + except Exception: + companions = set() lines = ["Available standards:"] for standard_id, revision in values: - mark = " <- bound" if (standard_id, revision) == active else "" + mark = (" <- bound" if (standard_id, revision) == active + else " <- companion" if (standard_id, revision) in companions + else "") lines.append(f"\n {standard_id} {revision}{mark}") # A manifest that cannot be read is reported as such rather than @@ -554,6 +669,8 @@ def handle_standard_command(command: str, operator: StandardOperator) -> str: binding.revision), f"Validation: {manifest.human_validation_status.value}", operator.candidate_summary(binding.standard_id, binding.revision), + *[f"Companion: {item.standard_id} {item.revision}" + for item in operator.companion_bindings()], )) if action == "use": @@ -572,6 +689,24 @@ def handle_standard_command(command: str, operator: StandardOperator) -> str: return "Standard binding cleared." + if action == "add": + if len(args) != 2: + raise StandardCommandError("usage: /standard add ") + + binding = operator.add_companion(*args) + + return (f"Bound {binding.standard_id} revision {binding.revision} beside " + "the active standard.") + + if action == "drop": + if len(args) != 1: + raise StandardCommandError("usage: /standard drop ") + + if not operator.drop_companion(args[0]): + raise StandardCommandError(f"{args[0]} is not a companion standard") + + return f"Dropped {args[0]}." + if action == "rebuild": if len([item for item in args if item != "--allow-offload"]) not in {0, 2}: raise StandardCommandError( diff --git a/client/standard/standard_tools.py b/client/standard/standard_tools.py index 4345505..bb6c3e5 100644 --- a/client/standard/standard_tools.py +++ b/client/standard/standard_tools.py @@ -346,15 +346,20 @@ def _source_id(arguments: Mapping[str, object]) -> str: def standard_tool_specs() -> tuple[ToolSpec, ...]: string = {"type": "string"} binding_properties = { - "standard_id": {"type": "string", "description": "optional; must equal active binding"}, - "revision": {"type": "string", "description": "optional; must equal active binding"}, + "standard_id": {"type": "string", "description": + "optional; one of the bound standards. Omitted, search " + "covers every bound standard and the other tools use " + "the one that holds the source"}, + "revision": {"type": "string", "description": + "optional; must equal that standard's bound revision"}, } return ( ToolSpec( "standard.search", - "Search the currently bound standard/revision using local hybrid retrieval. " - "Returns bounded canonical snippets and stable source IDs.", + "Search the bound standards (the active one and any companions) " + "using local hybrid retrieval. Returns bounded canonical snippets, " + "each with its standard and a stable source ID.", {"type": "object", "properties": { "query": string, "section": string, "limit": {"type": "integer"}, **binding_properties, @@ -429,26 +434,68 @@ def standard_tool_specs() -> tuple[ToolSpec, ...]: ) -def _binding(context: ToolExecutionContext, arguments: Mapping[str, object]) -> StandardBinding: +def _bindings(context: ToolExecutionContext) -> list[StandardBinding]: + """The active binding first, then the companions bound beside it.""" + raw = context.metadata.get("standard_binding") if not isinstance(raw, Mapping): raise PermissionError("no standard is bound to this task") - binding = StandardBinding.from_dict(raw) + bindings = [StandardBinding.from_dict(raw)] + + for companion in raw.get("companions") or (): + if isinstance(companion, Mapping): + bindings.append(StandardBinding.from_dict(companion)) + + return bindings + + +def _binding(context: ToolExecutionContext, arguments: Mapping[str, object]) -> StandardBinding: + """The bound standard the arguments name, or the active one.""" - for key in ("standard_id", "revision"): - supplied = arguments.get(key) + bindings = _bindings(context) + wanted = arguments.get("standard_id") + binding = bindings[0] - if supplied is not None and supplied != getattr(binding, key): + if wanted is not None: + named = [item for item in bindings if item.standard_id == wanted] + + if not named: raise PermissionError( - f"requested {key} does not equal the active StandardBinding; " - "the bound standard and revision are supplied by the task -- " - "omit standard_id and revision instead of restating them") + f"requested standard {wanted} is not an active StandardBinding; " + "the bound standards are " + + ", ".join(item.standard_id for item in bindings) + + " -- omit standard_id and revision to use them all") + + binding = named[0] + + revision = arguments.get("revision") + + if revision is not None and revision != binding.revision: + raise PermissionError( + f"requested revision does not equal the active StandardBinding of " + f"{binding.standard_id}; the bound revisions are supplied by the " + "task -- omit standard_id and revision instead of restating them") return binding +def _interleave(rankings, limit): + """Results of several standards, alternating by rank, at most `limit`. + + Scores from different corpora are not on one scale, so no standard's + first hit may be buried under another's tenth. + """ + + merged = [] + + for position in range(max((len(items) for items in rankings), default=0)): + merged.extend(items[position] for items in rankings if position < len(items)) + + return merged[:limit] + + class StandardToolService: def __init__(self, store: StandardStore, *, embedder=None) -> None: self.store = store @@ -462,6 +509,27 @@ def __init__(self, store: StandardStore, *, embedder=None) -> None: self.retrieval = StandardRetrieval(store, embedder) self.structures = StandardStructureAccess(store) + def _owner(self, context: ToolExecutionContext, + arguments: Mapping[str, object], source_id: str) -> StandardBinding: + """The bound standard holding a source, unless the arguments name one. + + Source ids are content hashes, so at most one bound standard holds a + given id; the active standard is asked first. + """ + + if arguments.get("standard_id") is not None or len(_bindings(context)) == 1: + return self._active_binding(context, arguments) + + for binding in _bindings(context): + try: + self.retrieval.cite(binding.standard_id, binding.revision, source_id) + except KeyError: + continue + + return self._active_binding(context, {"standard_id": binding.standard_id}) + + return self._active_binding(context, {}) + def _active_binding( self, context: ToolExecutionContext, arguments: Mapping[str, object], ) -> StandardBinding: @@ -481,7 +549,14 @@ def _active_binding( return binding def search(self, context: ToolExecutionContext, arguments: Mapping[str, object]): - binding = self._active_binding(context, arguments) + if (arguments.get("standard_id") is not None + or arguments.get("revision") is not None): + searched = [self._active_binding(context, arguments)] + else: + searched = [self._active_binding(context, {"standard_id": item.standard_id}) + for item in _bindings(context)] + + binding = searched[0] query = str(arguments.get("query") or "") section = arguments.get("section") @@ -501,32 +576,33 @@ def search(self, context: ToolExecutionContext, arguments: Mapping[str, object]) ) from None retrieval_fingerprint = binding.retrieval_fingerprint or binding.index_fingerprint - - try: - declared = self.retrieval.store.load_retrieval_settings( - binding.standard_id, binding.revision).get("mode") - except StandardStoreError as exc: - raise StandardConfigurationError(str(exc)) from None - - mode = _configured_mode(declared) - key = ("standard.search", retrieval_fingerprint, mode, query, section, limit) + modes = [self._search_mode(item) for item in searched] + key = ("standard.search", + tuple((item.retrieval_fingerprint or item.index_fingerprint, mode) + for item, mode in zip(searched, modes)), + query, section, limit) if key in context.cache: return context.cache[key] - try: - response = self.retrieval.search_response( - binding.standard_id, binding.revision, query, - section=(str(section) if section is not None else None), - limit=limit, mode=mode, - ) - except ValueError as exc: - raise StandardToolRefusal( - INVALID_QUERY, str(exc), - {"how": "reword the query, or omit limit to take the default"} - ) from None + responses = [] - results = response.results + for item, mode in zip(searched, modes): + try: + responses.append(self.retrieval.search_response( + item.standard_id, item.revision, query, + section=(str(section) if section is not None else None), + limit=limit, mode=mode, + )) + except ValueError as exc: + raise StandardToolRefusal( + INVALID_QUERY, str(exc), + {"how": "reword the query, or omit limit to take the default"} + ) from None + + response = responses[0] + + results = _interleave([item.results for item in responses], limit) payload = { "binding": {"standard_id": binding.standard_id, "revision": binding.revision, @@ -540,6 +616,11 @@ def search(self, context: ToolExecutionContext, arguments: Mapping[str, object]) "completion_budget": response.completion_budget, "results": [item.to_dict() for item in results], } + + if len(searched) > 1: + payload["standards_searched"] = [ + f"{item.standard_id} {item.revision}" for item in searched] + result = ToolHandlerResult( json.dumps(payload, ensure_ascii=False, sort_keys=True), metadata={ @@ -553,19 +634,31 @@ def search(self, context: ToolExecutionContext, arguments: Mapping[str, object]) "evidence_completion": response.evidence_completion, "completion_budget": response.completion_budget, "retrieval_fingerprint": retrieval_fingerprint, - "lexical_candidate_count": response.lexical_candidate_count, - "vector_candidate_count": response.vector_candidate_count, - "expanded_cross_reference_ids": list( - response.expanded_cross_reference_ids), + "lexical_candidate_count": sum( + item.lexical_candidate_count or 0 for item in responses), + "vector_candidate_count": sum( + item.vector_candidate_count or 0 for item in responses), + "expanded_cross_reference_ids": [ + ref for item in responses + for ref in item.expanded_cross_reference_ids], }, ) context.cache[key] = result return result + def _search_mode(self, binding: StandardBinding): + try: + declared = self.retrieval.store.load_retrieval_settings( + binding.standard_id, binding.revision).get("mode") + except StandardStoreError as exc: + raise StandardConfigurationError(str(exc)) from None + + return _configured_mode(declared) + def fetch(self, context: ToolExecutionContext, arguments: Mapping[str, object]): - binding = self._active_binding(context, arguments) source_id = _source_id(arguments) + binding = self._owner(context, arguments, source_id) _require_owned(context, source_id) offset = arguments.get("text_offset", 0) @@ -629,8 +722,8 @@ def fetch(self, context: ToolExecutionContext, arguments: Mapping[str, object]): ) def cite(self, context: ToolExecutionContext, arguments: Mapping[str, object]): - binding = self._active_binding(context, arguments) source_id = _source_id(arguments) + binding = self._owner(context, arguments, source_id) # A citation dereferences a handle too. It returns no words, but it # returns the section and the page -- which is exactly what it takes diff --git a/client/tests/test_standard_companions.py b/client/tests/test_standard_companions.py new file mode 100644 index 0000000..023d822 --- /dev/null +++ b/client/tests/test_standard_companions.py @@ -0,0 +1,176 @@ +"""Standards bound beside the active one. + +A question can need two documents: an architecture manual and the interrupt +controller specification it defers to, say. The active standard keeps the +verdict; a companion is searched, read and cited like it. +""" + +import json +import tempfile +import unittest +from pathlib import Path + +from evidence import conformance_guard +from harness.tool_registry import ToolRegistry +from harness.tool_router import ToolExecutionContext, ToolRouter +from runtime.result_store import ResultStore +from runtime.tracing import NullTraceRecorder, TraceEmitter +from standard.standard_commands import ( + StandardCommandError, StandardOperator, handle_standard_command, +) +from standard.standard_ingest import ingest_pdf +from standard.standard_retrieval import rebuild_lexical_index +from standard.standard_store import StandardStore +from standard.standard_tools import StandardToolService +from tests.standard_fixture import synthetic_pdf_bytes + +COMPANION_PAGES = ( + ((760, "Synthetic Controller Specification"), + (738, "Revision C-1 - TEST_FIXTURE / SYNTHETIC"), + (700, "4 Doorbells"), + (670, "4.1 Doorbell Register"), + (640, "Software shall write the doorbell register to raise a doorbell."), + (600, "doorbell means a message sent from one core to another.")), +) + + +class _Store(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + root = Path(self.temp.name) + self.store = StandardStore(root / "standards") + + for standard_id, revision, pdf_bytes in ( + ("TEST-STD", "TEST-1", synthetic_pdf_bytes()), + ("CTRL-STD", "C-1", synthetic_pdf_bytes(pages=COMPANION_PAGES))): + pdf = root / f"{standard_id}.pdf" + pdf.write_bytes(pdf_bytes) + ingest_pdf(self.store, pdf, standard_id=standard_id, + revision=revision, source_origin="TEST_FIXTURE") + rebuild_lexical_index(self.store, standard_id, revision) + + self.operator = StandardOperator(self.store) + self.root = root + + def tearDown(self): + self.temp.cleanup() + + def command(self, text): + return handle_standard_command(text, self.operator) + + +class Binding(_Store): + def test_a_companion_needs_an_active_standard(self): + with self.assertRaises(StandardCommandError): + self.command("/standard add CTRL-STD C-1") + + def test_add_keeps_the_active_standard_and_records_the_companion(self): + self.command("/standard use TEST-STD TEST-1") + self.command("/standard add CTRL-STD C-1") + + self.assertEqual(self.operator.active_binding().standard_id, "TEST-STD") + self.assertEqual([item.standard_id for item in self.operator.companion_bindings()], + ["CTRL-STD"]) + session = self.operator.session_binding() + self.assertEqual(session["standard_id"], "TEST-STD") + self.assertEqual([item["standard_id"] for item in session["companions"]], + ["CTRL-STD"]) + self.assertIn("Companion: CTRL-STD C-1", self.command("/standard status")) + self.assertIn("<- companion", self.command("/standard list")) + + def test_the_active_standard_cannot_be_its_own_companion(self): + self.command("/standard use TEST-STD TEST-1") + + with self.assertRaises(StandardCommandError): + self.command("/standard add TEST-STD TEST-1") + + def test_rebinding_keeps_companions_except_the_new_active_one(self): + self.command("/standard use TEST-STD TEST-1") + self.command("/standard add CTRL-STD C-1") + self.command("/standard use TEST-STD TEST-1") + self.assertEqual(len(self.operator.companion_bindings()), 1) + + self.command("/standard use CTRL-STD C-1") + self.assertEqual(self.operator.companion_bindings(), []) + + def test_drop_and_unbind_clear_companions(self): + self.command("/standard use TEST-STD TEST-1") + self.command("/standard add CTRL-STD C-1") + self.command("/standard drop CTRL-STD") + self.assertEqual(self.operator.companion_bindings(), []) + + with self.assertRaises(StandardCommandError): + self.command("/standard drop CTRL-STD") + + self.command("/standard add CTRL-STD C-1") + self.command("/standard unbind") + self.assertIsNone(self.operator.session_binding()) + self.assertEqual(self.operator.companion_bindings(), []) + + +class Tools(_Store): + def setUp(self): + super().setUp() + self.command("/standard use TEST-STD TEST-1") + self.command("/standard add CTRL-STD C-1") + registry = ToolRegistry() + StandardToolService(self.store).register(registry) + self.router = ToolRouter(registry) + self.context = ToolExecutionContext( + "task_12345678", TraceEmitter(NullTraceRecorder()), {}, + result_store=ResultStore(self.root / "results"), + metadata={"standard_binding": self.operator.session_binding()}) + + def execute(self, name, arguments): + return self.router.execute(self.context, "call_1", name, arguments) + + def search(self, **arguments): + result = self.execute("standard.search", arguments) + self.assertTrue(result.success, result.text) + + return json.loads(result.text) + + def test_search_covers_every_bound_standard(self): + payload = self.search(query="reserved value doorbell register") + + self.assertEqual({item["standard_id"] for item in payload["results"]}, + {"TEST-STD", "CTRL-STD"}) + self.assertEqual(payload["standards_searched"], ["TEST-STD TEST-1", "CTRL-STD C-1"]) + + def test_standard_id_narrows_the_search_to_one(self): + payload = self.search(query="doorbell register", standard_id="CTRL-STD") + + self.assertTrue(payload["results"]) + self.assertEqual({item["standard_id"] for item in payload["results"]}, {"CTRL-STD"}) + + def test_fetch_and_cite_find_the_standard_that_holds_the_source(self): + found = self.search(query="doorbell register", standard_id="CTRL-STD") + source_id = found["results"][0]["source_id"] + + fetched = self.execute("standard.fetch", {"source_id": source_id}) + self.assertTrue(fetched.success, fetched.text) + self.assertEqual(json.loads(fetched.text)["unit"]["standard_id"], "CTRL-STD") + cited = self.execute("standard.cite", {"source_id": source_id}) + self.assertTrue(cited.success, cited.text) + + def test_a_standard_that_is_not_bound_is_denied(self): + denied = self.execute("standard.search", {"query": "doorbell", + "standard_id": "NOT-BOUND"}) + + self.assertFalse(denied.success) + self.assertIn("active StandardBinding", denied.text) + + +class Names(unittest.TestCase): + def test_a_companion_is_a_standard_the_guards_recognise(self): + binding = {"standard_id": "ARM-DDI0487", "revision": "M.c", + "companions": [{"standard_id": "ARM-IHI0069", "revision": "H.b"}]} + + names = conformance_guard.standard_names(binding) + + self.assertIn("ddi0487", names) + self.assertIn("ihi0069", names) + + +if __name__ == "__main__": + unittest.main() diff --git a/doc/source/reasoning/standards.rst b/doc/source/reasoning/standards.rst index b547b3d..a6d95b5 100644 --- a/doc/source/reasoning/standards.rst +++ b/doc/source/reasoning/standards.rst @@ -316,6 +316,30 @@ looks authoritative and is not. Use the normative store when you want claims about the document to be **citable and checked**. Use a corpus when you want to find things in it. +Companion standards +=================== + +One document rarely says everything a question needs. The Arm Architecture +Reference Manual lists the GIC system registers but defers their fields to +the GIC architecture specification; an answer about raising an SGI needs +both. ``/standard add`` binds a second document beside the active one: + +.. code-block:: text + + /standard use ARM-DDI0487 M.c + /standard add ARM-IHI0069 H.b + +``standard.search`` then covers both and says which standard each result +comes from; ``standard.fetch`` and ``standard.cite`` find the document that +holds a source on their own, and the model is told which companions are +bound. The guards accept a clause from either, and a sentence naming either +document speaks for a bound standard. + +The active standard keeps one role a companion does not take: a conformance +verdict is still judged against it alone. A companion's corpus is held to +the same rule as the active one -- if it changed underneath its binding, the +binding is refused rather than silently renewed. + The rest of the operator commands ================================= @@ -331,8 +355,12 @@ The rest of the operator commands - what is bound right now * - ``/standard use `` - bind one + * - ``/standard add `` + - bind another one beside it, as a companion + * - ``/standard drop `` + - remove a companion * - ``/standard unbind`` - - bind nothing + - bind nothing, companions included * - ``/standard verify [ ]`` - check the corpus and every index in full, then the contents table * - ``/standard rebuild [ ] [--allow-offload]`` diff --git a/scripts/docker/stage-standards.py b/scripts/docker/stage-standards.py index cf8b7dd..85426f0 100755 --- a/scripts/docker/stage-standards.py +++ b/scripts/docker/stage-standards.py @@ -107,15 +107,38 @@ def main() -> int: if binding.is_file(): try: - active = json.loads(binding.read_text()).get("active", {}) + document = json.loads(binding.read_text()) except (OSError, json.JSONDecodeError): - active = {} + document = {} + active = document.get("active") or {} bound = f"{active.get('standard_id')} {active.get('revision')}" if any(bound == name for name, _ in taken): - shutil.copy2(binding, out / ".active-binding.json") - print(f" standards bound on open: {bound}") + # Companions follow the same rule as the binding: one whose + # document stayed behind is dropped, not carried as a dangling + # reference. + + names = {name for name, _ in taken} + companions = [item for item in document.get("companions") or () + if f"{item.get('standard_id')} {item.get('revision')}" in names] + + for item in document.get("companions") or (): + if item not in companions: + print(f" standards companion dropped ({item.get('standard_id')} " + f"{item.get('revision')} is not in this image)") + + document = {key: value for key, value in document.items() + if key != "companions"} + + if companions: + document["companions"] = companions + + (out / ".active-binding.json").write_text( + json.dumps(document, sort_keys=True, separators=(",", ":"))) + print(f" standards bound on open: {bound}" + + "".join(f" + {item['standard_id']} {item['revision']}" + for item in companions)) elif active: print(f" standards binding dropped ({bound} is not in this image) —" f" the container opens unbound") From e3c18bd949787d38106fc5e7a23ea380618f4a6f Mon Sep 17 00:00:00 2001 From: Daniel Rossier Date: Thu, 26 Nov 2026 18:37:57 +0100 Subject: [PATCH 3/3] Check field positions and line references against what was read Two kinds of number slipped through every guard in real answers: a register field copied at the wrong bit ("IRM, bit [40]" answered as bit [4]) and file:line references counted by hand off sed output (ipi_setup_sgi cited at smp.c:1230, defined at 1231). The normative claims guard now collects the positions register descriptions state ("FIELD, bit [n]", "FIELD, bits [h:l]") and reports MISPOSITIONED_FIELD when an answer gives a field a position none of them states. Only fields the evidence positions are checked, and any stated position satisfies a claim, since one field name recurs across registers. The finding is repairable, as wording. The final answer's file:line references are checked against the files the turn touched: when the line does not hold the symbol named beside the reference but exactly one line within three does, the reference is corrected and the answer says so; anything else is left as written. --- client/normative/normative_claims.py | 75 +++++++++++++- client/runtime/agent_finalization.py | 9 +- client/runtime/answer_repair.py | 9 ++ client/runtime/line_references.py | 148 +++++++++++++++++++++++++++ client/tests/test_answer_repair.py | 3 +- client/tests/test_field_positions.py | 63 ++++++++++++ client/tests/test_line_references.py | 67 ++++++++++++ 7 files changed, 371 insertions(+), 3 deletions(-) create mode 100644 client/runtime/line_references.py create mode 100644 client/tests/test_field_positions.py create mode 100644 client/tests/test_line_references.py diff --git a/client/normative/normative_claims.py b/client/normative/normative_claims.py index 180802f..52b987b 100644 --- a/client/normative/normative_claims.py +++ b/client/normative/normative_claims.py @@ -51,6 +51,7 @@ AMBIGUOUS_CITATION = "AMBIGUOUS_CITATION" #: A named provision credited with a force its role cannot carry. MISATTRIBUTED_FORCE = "MISATTRIBUTED_FORCE" +MISPOSITIONED_FIELD = "MISPOSITIONED_FIELD" #: Where a name that is not the document's own came from: the operator's #: request or the repository the turn read. Either may say which @@ -752,6 +753,73 @@ def ambiguity_findings(answer, evidence): for problem in ambiguous] +#: How a register description states a field's place: "IRM, bit [40]", +#: "INTID, bits [27:24]". + +_STATED_POSITION = re.compile( + r"\b([A-Z][A-Za-z0-9_]{1,31}),\s*bits?\s*\[(\d{1,3})(?::(\d{1,3}))?\]") + +#: How an answer gives one: the same form, a parenthesised gloss between the +#: name and the bits, or a table row with the field and its bits in cells. + +_CLAIMED_POSITION = re.compile( + r"\b([A-Z][A-Za-z0-9_]{1,31})[`*]*(?:\s*\([^)\n]{0,60}\))?\s*[,:]?\s*" + r"(?:[—–-]\s*)?bits?\s*\[(\d{1,3})(?::(\d{1,3}))?\]") +_CLAIMED_ROW = re.compile( + r"^\s*\|\s*[`*]*([A-Z][A-Za-z0-9_]{1,31})[`*]*[^|\n]*\|\s*[`*]*" + r"(?:bits?\s*)?\[(\d{1,3})(?::(\d{1,3}))?\]", re.M) + + +def _position(high, low): + return (int(high), int(low if low is not None else high)) + + +def _render_position(position): + high, low = position + + return f"[{high}]" if high == low else f"[{high}:{low}]" + + +def position_findings(answer, evidence): + """A field placed where no retrieved description puts it. + + Copying a register description is where a number slips: "IRM, bit [40]" + came back as bit [4]. Only fields the evidence itself positions are + checked, and a claim stands if it matches ANY position stated for that + name -- the same field name recurs across registers at different places. + """ + + stated = {} + + for unit in evidence.units: + for match in _STATED_POSITION.finditer(unit.text): + stated.setdefault(match.group(1), set()).add( + _position(match.group(2), match.group(3))) + + if not stated: + return [] + + problems, seen = [], set() + + for pattern in (_CLAIMED_POSITION, _CLAIMED_ROW): + for match in pattern.finditer(answer or ""): + name = match.group(1) + claimed = _position(match.group(2), match.group(3)) + + if name not in stated or claimed in stated[name] or (name, claimed) in seen: + continue + + seen.add((name, claimed)) + problems.append({ + "kind": MISPOSITIONED_FIELD, "identifier": name, + "claimed": _render_position(claimed), + "stated": ", ".join(_render_position(item) + for item in sorted(stated[name], reverse=True)), + }) + + return problems + + def findings(answer, evidence, *, question="", permitted=(), binding=None, requested=()): return (ambiguity_findings(answer, evidence) + identifier_findings(answer, evidence, permitted=permitted, @@ -759,7 +827,8 @@ def findings(answer, evidence, *, question="", permitted=(), binding=None, reque + modality_findings(answer, evidence, question=question) + coherence_findings(answer, evidence, question=question) + cardinality_findings(answer, evidence, question=question) - + attribution_findings(answer, evidence)) + + attribution_findings(answer, evidence) + + position_findings(answer, evidence)) def _note(problems, evidence): @@ -786,6 +855,10 @@ def _note(problems, evidence): lines.append(f" - a bound of {problem['asserted']} is asserted; " "no retrieved clause states one. Counting flags, " "types or examples does not establish a limit.") + elif kind == MISPOSITIONED_FIELD: + lines.append(f" - {problem['identifier']} is placed at bit " + f"{problem['claimed']}; the retrieved description " + f"places it at {problem['stated']}.") elif kind == MISATTRIBUTED_FORCE: lines.append(f" - {problem['reference']} is credited with " f"{problem['claimed']} force; its role is " diff --git a/client/runtime/agent_finalization.py b/client/runtime/agent_finalization.py index 0e3ef42..6d57a05 100644 --- a/client/runtime/agent_finalization.py +++ b/client/runtime/agent_finalization.py @@ -12,7 +12,7 @@ ) from runtime.tracing import EventStatus, EventType from evidence import project_build -from runtime import work_order +from runtime import line_references, work_order from standard.standard_answer_policy import STOPPED_BY_BUDGET from runtime.agent_context import AgentContext, AgentResult, RuntimeTerminalReason from runtime.agent_notes import unsupported_change_claim @@ -320,6 +320,13 @@ def _result( if claim_note: response = (response or "") + claim_note + # File:line references are checked against the files this turn + # touched; a counted number that drifted by a line or two is corrected + # in the answer, which says so. + + response, _ = line_references.check( + response or "", getattr(context, "project_root", ""), tool_log) + # The last word on a turn that wrote. Deterministic, from the tool log, # and on every exit path -- the budget's included, which is the one # that handed back four edited files and a tree that did not compile. diff --git a/client/runtime/answer_repair.py b/client/runtime/answer_repair.py index 43f57d4..99930bb 100644 --- a/client/runtime/answer_repair.py +++ b/client/runtime/answer_repair.py @@ -51,6 +51,8 @@ # A provision credited with the wrong force is a wording problem: the # evidence in hand already says which provision imposes what. normative_claims.MISATTRIBUTED_FORCE, + # A position copied wrong: the description in hand states the right one. + normative_claims.MISPOSITIONED_FIELD, }) #: And ones it cannot. A bound nothing states is not a wording problem. @@ -72,6 +74,7 @@ PRESENTATION_ONLY = frozenset({ normative_claims.UNGROUNDED_IDENTIFIER, normative_claims.AMBIGUOUS_CITATION, + normative_claims.MISPOSITIONED_FIELD, }) #: How a turn says it is not answering. Matched against the opening of a @@ -243,6 +246,12 @@ def _finding_lines(problems): f"{problem['supported']}. If another provision above " "imposes the obligation, attribute it to that one.") + elif kind == normative_claims.MISPOSITIONED_FIELD: + lines.append(f" - You placed {problem['identifier']} at bit " + f"{problem['claimed']}; the description above places " + f"it at {problem['stated']}. Copy the position from " + "the description.") + return lines diff --git a/client/runtime/line_references.py b/client/runtime/line_references.py new file mode 100644 index 0000000..79fa0e4 --- /dev/null +++ b/client/runtime/line_references.py @@ -0,0 +1,148 @@ +"""File:line references in an answer, checked against the files they name. + +A model that reads code through `sed -n 'a,bp'` sees no line numbers and +counts them itself, and one-off slips follow: `ipi_setup_sgi` cited at +smp.c:1230 when it is defined at 1231. Nothing downstream checked a +reference against the file. + +The check is narrow on purpose. A reference is examined only when the +answer names the symbol it points at, beside it, and only files this turn +touched are opened. If the line holds the symbol, the reference stands; if +exactly one line within a few of it does, the reference is corrected and the +answer says so; anything else is left as written. A wrong correction would +be worse than none. +""" + +from __future__ import annotations + +import os +import re + +#: How far a counted line number is allowed to have drifted. + +_WINDOW = 3 + +#: `path/to/file.c:123`, or `:123` continuing the file named last -- the +#: bare form only after a space or a bracket, so that a bit range such as +#: [47:44] is never read as one. + +_REFERENCE = re.compile( + r"(?:(?P(?:[\w.+-]+/)*[\w.+-]+\.[A-Za-z]{1,4})|(?<=[\s(]))" + r":(?P\d{1,6})(?![\d:\]])") + +#: The symbol a reference is about: the identifier closest before it. + +_SYMBOL = re.compile(r"`?([A-Za-z_][A-Za-z0-9_]{2,})`?(?:\(\))?") + +_PATH_TOKEN = re.compile(r"(?:[\w.+-]+/)+[\w.+-]+\.[A-Za-z]{1,4}") + +_KEYWORDS = {"the", "and", "for", "case", "line", "lines", "file", "at", "in", + "see", "from", "with", "via", "then", "which", "calls", "call", + "defined", "registered", "static", "void", "int", "return", + "struct", "const", "unsigned"} + + +def _candidates(root, tool_log): + """Files this turn touched, as absolute paths that exist.""" + + found = set() + + for entry in tool_log or (): + for token in _PATH_TOKEN.findall(str(entry)): + path = token if os.path.isabs(token) else os.path.join(root or ".", token) + + if os.path.isfile(path): + found.add(os.path.normpath(path)) + + return found + + +def _resolve(cited, candidates): + """The one touched file a cited path designates, or None.""" + + cited = cited.lstrip("./") + matches = [path for path in candidates + if path.endswith("/" + cited) or os.path.basename(path) == cited] + + return matches[0] if len(matches) == 1 else None + + +def _symbol_before(text, start): + """The identifier the reference at `start` is about, if one is beside it.""" + + window = text[max(0, start - 80):start] + names = [name for name in _SYMBOL.findall(window) + if name.lower() not in _KEYWORDS and not name.isdigit()] + + return names[-1] if names else None + + +class _Lines: + def __init__(self): + self.files = {} + + def get(self, path): + if path not in self.files: + try: + with open(path, encoding="utf-8", errors="replace") as handle: + self.files[path] = handle.read().splitlines() + except OSError: + self.files[path] = [] + + return self.files[path] + + +def check(answer, root, tool_log): + """The answer with drifted references corrected, and what was corrected.""" + + candidates = _candidates(root, tool_log) + + if not answer or not candidates: + return answer, [] + + lines, corrections, out = _Lines(), [], [] + position, current = 0, None + + for match in _REFERENCE.finditer(answer): + cited = match.group("path") + path = _resolve(cited, candidates) if cited else current + + if cited: + current = path + + if path is None: + continue + + number = int(match.group("line")) + symbol = _symbol_before(answer, match.start()) + content = lines.get(path) + + if not symbol or not content or not 0 < number <= len(content) + _WINDOW: + continue + + def holds(n): + return 0 < n <= len(content) and re.search( + rf"\b{re.escape(symbol)}\b", content[n - 1]) + + if holds(number): + continue + + near = [n for n in range(number - _WINDOW, number + _WINDOW + 1) if holds(n)] + + if len(near) != 1: + continue + + out.append(answer[position:match.start("line")]) + out.append(str(near[0])) + position = match.end("line") + corrections.append((cited or os.path.basename(path), number, near[0], symbol)) + + if not corrections: + return answer, [] + + out.append(answer[position:]) + note = ("\n\nLine references corrected against the files: " + + ", ".join(f"{name}:{old} → {new} ({symbol})" + for name, old, new, symbol in corrections) + ".") + + return "".join(out) + note, corrections diff --git a/client/tests/test_answer_repair.py b/client/tests/test_answer_repair.py index e45a615..0908800 100644 --- a/client/tests/test_answer_repair.py +++ b/client/tests/test_answer_repair.py @@ -338,7 +338,8 @@ class FindingsAreSortedByWhatTheyBearOn(unittest.TestCase): def test_wording_findings_leave_the_conclusion_alone(self): self.assertEqual( ar.PRESENTATION_ONLY, - {nc.UNGROUNDED_IDENTIFIER, nc.AMBIGUOUS_CITATION}) + {nc.UNGROUNDED_IDENTIFIER, nc.AMBIGUOUS_CITATION, + nc.MISPOSITIONED_FIELD}) def test_conclusion_findings_may_change_it(self): self.assertEqual( diff --git a/client/tests/test_field_positions.py b/client/tests/test_field_positions.py new file mode 100644 index 0000000..c2417bc --- /dev/null +++ b/client/tests/test_field_positions.py @@ -0,0 +1,63 @@ +"""A field placed where no retrieved description puts it. + +Seen in use: the GIC specification says "IRM, bit [40]" and the answer said +bit [4]. The guards checked names and force, never the numbers copied +beside them. +""" + +import unittest + +from normative import normative_claims as nc +from runtime import answer_repair as ar + + +def evidence(*texts): + found = nc.NormativeEvidence() + + for index, text in enumerate(texts): + found.observe({"text": text, "section": "12.2.22", + "source_id": f"std-{index:032d}"}) + + return found + + +SGI1R = evidence("IRM, bit [40] Interrupt Routing Mode.", + "INTID, bits [27:24] The INTID of the SGI.", + "INTID, bits [23:0] The INTID of the pending interrupt.") + + +class Positions(unittest.TestCase): + def kinds(self, answer, found=SGI1R): + return [(item["identifier"], item["claimed"]) + for item in nc.position_findings(answer, found)] + + def test_a_miscopied_bit_is_found(self): + self.assertEqual(self.kinds("IRM (Interrupt Routing Mode), bit [4] — routing."), + [("IRM", "[4]")]) + + def test_the_stated_position_passes(self): + self.assertEqual(self.kinds("IRM, bit [40] selects the routing mode."), []) + + def test_a_name_reused_across_registers_matches_any_of_its_positions(self): + self.assertEqual(self.kinds("INTID, bits [27:24] carries the SGI number."), []) + self.assertEqual(self.kinds("INTID, bits [3:0] carries it."), [("INTID", "[3:0]")]) + + def test_table_rows_are_checked(self): + self.assertEqual(self.kinds("| Field | Bits |\n|---|---|\n| **IRM** | [4] | routing |"), + [("IRM", "[4]")]) + + def test_a_field_the_evidence_does_not_position_is_left_alone(self): + self.assertEqual(self.kinds("TargetList, bits [15:0] selects the PEs."), []) + self.assertEqual(self.kinds("IRM, bit [4]", evidence("No positions here.")), []) + + def test_it_reaches_the_guard_and_is_repairable(self): + problems = nc.findings("IRM, bit [4] selects the routing mode.", SGI1R) + + self.assertIn(nc.MISPOSITIONED_FIELD, [item["kind"] for item in problems]) + position = [item for item in problems if item["kind"] == nc.MISPOSITIONED_FIELD] + self.assertTrue(ar.is_repairable(position)) + self.assertIn("[40]", "\n".join(ar._finding_lines(position))) + + +if __name__ == "__main__": + unittest.main() diff --git a/client/tests/test_line_references.py b/client/tests/test_line_references.py new file mode 100644 index 0000000..0b8ff0e --- /dev/null +++ b/client/tests/test_line_references.py @@ -0,0 +1,67 @@ +"""File:line references checked against the files a turn touched.""" + +import tempfile +import unittest +from pathlib import Path + +from runtime import line_references as lr + +SOURCE = "\n".join([ + "#include ", # 1 + "", # 2 + "static void ipi_setup_sgi(int ipi)", # 3 + "{", # 4 + "\terr = request_percpu_irq(irq, ipi_handler);", # 5 + "}", # 6 + "", # 7 + "static void other(void)", # 8 +]) + "\n" + + +class References(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = self.temp.name + path = Path(self.root, "arch/kernel/smp.c") + path.parent.mkdir(parents=True) + path.write_text(SOURCE) + self.log = ["terminal {\"command\": \"sed -n '1,8p' arch/kernel/smp.c\"}"] + + def tearDown(self): + self.temp.cleanup() + + def check(self, answer): + return lr.check(answer, self.root, self.log) + + def test_a_drifted_line_is_corrected_and_said(self): + text, fixes = self.check("registered by ipi_setup_sgi() (smp.c:2).") + + self.assertEqual(fixes, [("smp.c", 2, 3, "ipi_setup_sgi")]) + self.assertIn("(smp.c:3)", text) + self.assertIn("smp.c:2 → 3 (ipi_setup_sgi)", text) + + def test_a_right_reference_and_a_continuation_stand(self): + answer = "ipi_setup_sgi() (arch/kernel/smp.c:3, request_percpu_irq at :5)." + + self.assertEqual(self.check(answer), (answer, [])) + + def test_a_continuation_is_corrected_against_the_file_named_last(self): + text, fixes = self.check("ipi_setup_sgi (smp.c:3), request_percpu_irq at :6.") + + self.assertEqual(fixes, [("smp.c", 6, 5, "request_percpu_irq")]) + + def test_nothing_is_guessed(self): + for answer in ("smp.c:2 is where it starts.", # no symbol + "ipi_setup_sgi() (smp.c:40)", # too far + "ipi_setup_sgi() (unknown.c:2)", # untouched file + "RS, bits [47:44] and ipi_setup_sgi [7:2]"): # a bit range + self.assertEqual(self.check(answer), (answer, []), answer) + + def test_files_the_turn_did_not_touch_are_not_opened(self): + answer = "ipi_setup_sgi() (smp.c:2)" + + self.assertEqual(lr.check(answer, self.root, []), (answer, [])) + + +if __name__ == "__main__": + unittest.main()