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
33 changes: 27 additions & 6 deletions client/cli/standard_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
7 changes: 7 additions & 0 deletions client/cli/startup_banner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
19 changes: 16 additions & 3 deletions client/evidence/conformance_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
75 changes: 74 additions & 1 deletion client/normative/normative_claims.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -752,14 +753,82 @@ 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,
binding=binding, requested=requested)
+ 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):
Expand All @@ -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 "
Expand Down
28 changes: 23 additions & 5 deletions client/runtime/agent_finalization.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@

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
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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -309,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.
Expand Down
4 changes: 3 additions & 1 deletion client/runtime/agent_model_turn.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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
Expand Down
35 changes: 33 additions & 2 deletions client/runtime/answer_repair.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -137,6 +140,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"(?<![\w.-])[^\W\d_]+$|[,(\[{]$")

#: Lines that end without punctuation by nature.

_UNPUNCTUATED = re.compile(r"^\s*(?:[-*+•]|\d+[.)]|#|\||```|>)")


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.

Expand All @@ -145,7 +170,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):
Expand Down Expand Up @@ -221,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


Expand All @@ -232,7 +263,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),
Expand Down
Loading
Loading