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
16 changes: 14 additions & 2 deletions client/normative/normative_precedence.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,11 @@
# A question, a quotation of the user, or a statement about what is unknown.
_INTERROGATIVE = re.compile(r"\?\s*$")

# A heading names what follows ("## What the standard says about SGIs"), and
# an indirect question asks it; neither states anything the guard could back.
_HEADING = re.compile(r"^\s*#{1,6}\s")
_INDIRECT = re.compile(r"\b(?:what|how|whether|where|which|when)\s+$", re.I)

# How far back a citation still carries. Three sentences reaches the bullet
# that stated the rule from the conclusion drawn two sentences later, which is
# the shape the model actually writes; it does not reach across a section of
Expand Down Expand Up @@ -196,10 +201,17 @@ def states_a_requirement(sentence, binding=None):
document or merely described -- cannot come to a different answer than
this module does.
"""
if _INTERROGATIVE.search(sentence) or _NEGATED.search(sentence):
if (_INTERROGATIVE.search(sentence) or _NEGATED.search(sentence)
or _HEADING.match(sentence)):
return False

return bool(_subject(binding).search(sentence) or _clause_voiced(sentence))
spoken = _subject(binding).search(sentence)

if (spoken and _INDIRECT.search(sentence[:spoken.start()])
and ":" not in sentence[spoken.end():]):
spoken = None

return bool(spoken or _clause_voiced(sentence))


def stated_content(sentence, binding=None):
Expand Down
2 changes: 1 addition & 1 deletion client/runtime/agent_finalization.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def _inject_evidence_call(self, context: AgentContext, policy,
return False

policy.observe_tool_result(injected.tool, envelope.model_content,
origin=injected.origin)
origin=injected.origin, structured=envelope.text)
context.conversation.append(ConversationMessage(
"assistant", (ToolUseBlock(call_id, injected.tool,
dict(injected.arguments)),),
Expand Down
3 changes: 2 additions & 1 deletion client/runtime/agent_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -930,7 +930,8 @@ def run(self, context: AgentContext, *, defer_completion: bool = False) -> Agent

if policy is not None and call.name in policy.STANDARD_TOOLS:
policy.observe_tool_result(call.name,
envelope.model_content)
envelope.model_content,
structured=envelope.text)

# Every call, for the record of which source files the
# turn read. A conformance answer that read none says so.
Expand Down
20 changes: 19 additions & 1 deletion client/runtime/answer_repair.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,24 @@ def _provision_lines(evidence):
lines.append(f" [{cited}] modality: {record.modality}\n"
f" {record.text[:400]}")

return lines or _unit_lines(evidence)


def _unit_lines(evidence, limit=40):
"""The retrieved units themselves, for a document that declares no
provisions: a register description is evidence too, and an empty list
told the model that the fields it had quoted came from nowhere."""
lines, seen = [], set()

for unit in evidence.units:
if unit.source_id in seen or len(lines) >= limit:
continue

seen.add(unit.source_id)
text = " ".join(unit.text.split())
lines.append(f" [§{unit.section or '?'}, source {unit.source_id}]\n"
f" {text[:400]}")

return lines


Expand All @@ -222,7 +240,7 @@ def _finding_lines(problems):
if kind == normative_claims.UNGROUNDED_IDENTIFIER:
lines.append(
f" - `{problem['identifier']}` is named in your answer and "
"appears in no provision below. Do not use it again, and do "
"appears in no evidence below. Do not use it again, and do "
"not substitute a variant spelling, an expansion or a "
"synonym for it. If it was not needed to answer the "
"question, leave it out and keep the rest of the answer as "
Expand Down
90 changes: 58 additions & 32 deletions client/standard/standard_answer_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
from evidence import conformance_guard
from evidence import conformance_mode
from standard import diagram_geometry
from standard import standard_tools
from evidence import evidence_bootstrap
from evidence import evidence_progress
from evidence import evidence_recovery
Expand Down Expand Up @@ -174,12 +175,16 @@ class StandardAnswerPolicy:

# -- observation ------------------------------------------------------

def observe_tool_result(self, name, text, *, origin=MODEL):
def observe_tool_result(self, name, text, *, origin=MODEL, structured=None):
"""One tool result, exactly as the model was shown it.

Every ledger reads from here and none of them writes anywhere: the
payload is parsed, never modified, and a result that is not JSON or is
a refusal contributes nothing but its provenance.

A fetch is shown as rendered text, so its payload is the structured
result (`structured`, the envelope's whole text) cut back to that
rendering.
"""
self.provenance.observe(text)

Expand All @@ -188,6 +193,15 @@ def observe_tool_result(self, name, text, *, origin=MODEL):
except ValueError:
payload = None

if payload is None and structured and name == "standard.fetch":
try:
whole = json.loads(structured)
except ValueError:
whole = None

if isinstance(whole, dict) and not whole.get("error"):
payload = standard_tools.shown_fetch(whole, text)

empty = False

# Which clauses the model was actually shown. A refusal carries none.
Expand Down Expand Up @@ -321,6 +335,39 @@ def should_stop_for_exhaustion(self, answer=""):

# -- the boundary -----------------------------------------------------

def _rule_guards(self, text):
"""The conformance and precedence guards, recorded on the policy."""

# A compliance verdict the turn is not entitled to. Between the two
# guards on purpose: it reads the evidence-guarded text, and what it
# writes in place of a verdict is built from the clause ledger, so
# the provenance guard behind it has nothing to find there.

guarded, findings, replaced, conformance_fired = conformance_guard.guard(
text, self.clauses, standard_id=self.standard_id,
revision=self.revision, binding=self.binding)
self.conformance_fired = conformance_fired
self.conformance_findings = list(findings)
self.replaced_verdicts = list(replaced)

# ...and the same question on the other subject: a statement of what
# the STANDARD requires, backed by a clause this turn retrieved.
# Beside the conformance guard because they are one idea seen from
# two sides -- what the code does about a rule, and what the rule
# says -- and before the provenance guard for its reason: what it
# writes is built from the ledger, so nothing downstream finds a
# source in it.

guarded, requirements, replaced_requirements, precedence_fired = (
normative_precedence.guard(
guarded, self.clauses, standard_id=self.standard_id,
revision=self.revision, binding=self.binding))
self.precedence_fired = precedence_fired
self.precedence_findings = list(requirements)
self.replaced_requirements = list(replaced_requirements)

return guarded

def finalize(self, answer, *, rounds=None, stopped_by=None):
"""The user-visible answer, and only what the evidence supports of it."""
self.raw_answer = answer or ""
Expand Down Expand Up @@ -349,33 +396,8 @@ def finalize(self, answer, *, rounds=None, stopped_by=None):
self.guard_fired = replaced
self.guard_violations = list(violations)

# A compliance verdict the turn is not entitled to. Between the two
# guards on purpose: it reads the evidence-guarded text, and what it
# writes in place of a verdict is built from the clause ledger, so
# the provenance guard behind it has nothing to find there.

guarded, findings, replaced, conformance_fired = conformance_guard.guard(
guarded, self.clauses, standard_id=self.standard_id,
revision=self.revision, binding=self.binding)
self.conformance_fired = conformance_fired
self.conformance_findings = list(findings)
self.replaced_verdicts = list(replaced)

# ...and the same question on the other subject: a statement of what
# the STANDARD requires, backed by a clause this turn retrieved.
# Beside the conformance guard because they are one idea seen from
# two sides -- what the code does about a rule, and what the rule
# says -- and before the provenance guard for its reason: what it
# writes is built from the ledger, so nothing downstream finds a
# source in it.

guarded, requirements, replaced_requirements, precedence_fired = (
normative_precedence.guard(
guarded, self.clauses, standard_id=self.standard_id,
revision=self.revision, binding=self.binding))
self.precedence_fired = precedence_fired
self.precedence_findings = list(requirements)
self.replaced_requirements = list(replaced_requirements)
evidence_guarded = guarded
guarded = self._rule_guards(guarded)

# What the answer CLAIMS, against what the evidence SAYS. The guards
# above establish that a supporting clause was retrieved; none of them
Expand All @@ -397,15 +419,18 @@ def finalize(self, answer, *, rounds=None, stopped_by=None):

requested = normative_claims.identifiers_in(self.question)

before_repair = guarded
guarded, claim_problems, claims_fired = normative_claims.guard(
guarded, self.claim_evidence, question=self.question,
permitted=permitted, binding=self.binding, requested=requested)

# One constrained rewrite, when the evidence in hand can settle what
# was wrong with the prose. No new retrieval, no loop, and the same
# guard again on what comes back -- a repair that fails is withheld
# exactly as the original was.
# guards again on what comes back -- a repair that fails is withheld
# exactly as the original was. It rewrites the answer as the model
# wrote it: handed the rule guards' notes in place of its sentences,
# it kept the notes as prose of its own.

before_repair = evidence_guarded

if (claims_fired and self.repair_ask is not None
and answer_repair.is_repairable(claim_problems)):
Expand All @@ -428,7 +453,8 @@ def finalize(self, answer, *, rounds=None, stopped_by=None):
permitted=permitted, binding=self.binding, requested=requested)

if not retry_fired:
guarded, claim_problems, claims_fired = checked, [], False
guarded = self._rule_guards(checked)
claim_problems, claims_fired = [], False
self.repair_accepted = True
else:
claim_problems = list(retry_problems)
Expand Down
47 changes: 47 additions & 0 deletions client/standard/standard_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,53 @@ def fits(*candidate: str) -> bool:

return "\n".join([core] + extras) if extras else core

_INCOMPLETE = re.compile(r"\[INCOMPLETE: characters (\d+)-(\d+) of \d+")
_CONTINUED = re.compile(r"continued from character (\d+) of \d+")


def shown_fetch(fetched: Mapping[str, object], rendered: str) -> dict:
"""The part of a fetch result the model was actually shown.

The guards read evidence as structured units, and what reaches the model
is `render_fetch_for_model`'s text, which is not JSON: read as JSON it was
nothing, and a field the model quoted from a fetched unit or from its
neighbours was then judged to come from nowhere. This is the structured
result cut back to that rendering -- the unit's text as far as it was
shown, and the parent, rows, neighbours and cross-references the
rendering kept, each with the preview it was given.
"""
shown = dict(fetched)
unit = dict(fetched.get("unit") or {})
full = str(unit.get("text") or "")
cut = _INCOMPLETE.search(rendered)
continued = _CONTINUED.search(rendered)

if cut:
unit["text"] = full[int(cut.group(1)):int(cut.group(2))]
elif continued:
unit["text"] = full[int(continued.group(1)):]

shown["unit"] = unit

def kept(item):
if not isinstance(item, Mapping) or str(item.get("source_id") or "") not in rendered:
return None

item = dict(item)
text = " ".join(str(item.get("text") or "").split())
item["text"] = text[:_CONTEXT_PREVIEW_CHARS].rstrip()

return item

parent = kept(fetched.get("parent"))
shown["parent"] = parent

for key in ("table_rows", "neighbors", "resolved_cross_references"):
shown[key] = [item for item in map(kept, fetched.get(key) or []) if item]

return shown


# How a caller comes by a source id at all. There is no listing of the corpus,
# so pointing at one would be inventing a path that does not exist.

Expand Down
109 changes: 109 additions & 0 deletions client/tests/test_fetch_evidence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
"""What a fetch showed the model is what the guards read.

Seen in use: `standard.fetch` is shown as rendered text, not JSON, and the
policy parsed it as JSON. Every fetch then counted for nothing: a field the
model quoted from the fetched register's neighbours ("RS, bits [47:44]
RangeSelector") was judged to come from nowhere and removed by the repair,
and a miscopied position beside it went unchecked.
"""

import json
import sys
import unittest
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

import synthetic_standard
from standard import standard_answer_policy as sap
from standard.standard_tools import render_fetch_for_model, shown_fetch

MODE = "WidgetMode, bits [7:4] Widget Mode. Selects how the reply is encoded."
LATE = "WidgetTail, bits [31:28] Widget Tail. Never shown to the model."


def fetched():
found = synthetic_standard.fetch(neighbours=())
found["unit"]["source_id"] = "std-" + "1" * 32
found["neighbors"] = [
{"section": synthetic_standard.SECTION, "source_id": "std-" + "2" * 32,
"text": MODE},
{"section": synthetic_standard.SECTION, "source_id": "std-" + "3" * 32,
"text": LATE},
]

return found


def rendered(found, budget=None):
if budget is None:
budget = len(render_fetch_for_model(found, budget=100000)) - len(LATE)

return render_fetch_for_model(found, budget=budget)


class Shown(unittest.TestCase):
def test_only_the_neighbours_the_rendering_kept_are_evidence(self):
found = fetched()
text = rendered(found)

self.assertIn("WidgetMode", text)
self.assertNotIn("WidgetTail", text)
self.assertEqual([item["text"] for item in shown_fetch(found, text)["neighbors"]],
[MODE])

def test_a_unit_cut_short_counts_as_far_as_it_was_shown(self):
found = fetched()
found["unit"]["text"] = "A" * 400 + " WidgetLate appears only past the cut."
text = render_fetch_for_model(found, budget=600)

self.assertIn("[INCOMPLETE", text)
self.assertNotIn("WidgetLate", shown_fetch(found, text)["unit"]["text"])


class Policy(unittest.TestCase):
"""A register description: a document that declares no provisions."""

def policy(self, **options):
policy = sap.policy_for(synthetic_standard.BINDING, "Which fields?", **options)
found = fetched()
found["unit"]["text"] = "Purpose Generates widgets for the current state."
policy.observe_tool_result("standard.fetch", rendered(found),
structured=json.dumps(found))

return policy

def test_a_rendered_fetch_reaches_every_ledger(self):
policy = self.policy()

self.assertIn("widgetmode", policy.claim_evidence.identifiers())
self.assertNotIn("widgettail", policy.claim_evidence.identifiers())
self.assertIn(synthetic_standard.SECTION, policy.clauses.sections)

def test_the_repair_rewrites_the_answer_not_the_guards_notes(self):
seen = []

def ask(text):
seen.append(text)

return ("WidgetMode, bits [7:4] selects the encoding.\n"
"The standard requires a barrier after the write, as §9.9 says.")

policy = self.policy(repair_ask=ask)
answer = ("WidgetMode, bits [7:4] selects the encoding, and WidgetBogus "
"picks the target.\n"
"The standard requires a barrier after the write, as §9.9 says.")

shown = policy.finalize(answer, stopped_by=sap.STOPPED_BY_MODEL)

self.assertTrue(seen, "the repair was never attempted")
self.assertNotIn("No requirement of", seen[0])
self.assertIn("requires a barrier", seen[0])
self.assertIn(MODE[:40], seen[0])
self.assertNotIn("WidgetBogus", shown)
self.assertIn("No requirement of", shown)
self.assertTrue(policy.precedence_fired)


if __name__ == "__main__":
unittest.main()
Loading
Loading