feat: working orhcestration engine
This commit is contained in:
1
execution_engine/nodes/__init__.py
Normal file
1
execution_engine/nodes/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""The nodes of the Execution graph."""
|
||||
1481
execution_engine/nodes/execution_nodes.py
Normal file
1481
execution_engine/nodes/execution_nodes.py
Normal file
File diff suppressed because it is too large
Load Diff
254
execution_engine/nodes/intake.py
Normal file
254
execution_engine/nodes/intake.py
Normal file
@@ -0,0 +1,254 @@
|
||||
"""Intake: what a message that starts something is asking for (ADR-0007).
|
||||
|
||||
Inside an Execution the router reads the user's replies. This is the same reading
|
||||
one step earlier, for a message that arrives with no Execution in progress:
|
||||
|
||||
new request design this workload start an Execution
|
||||
change request change what was delivered name the Baseline to change (ADR-0006)
|
||||
question what can you do, how long... answer; start nothing
|
||||
why did you choose X? answer from what was delivered
|
||||
|
||||
A change is never started from earlier work on a guess: the caller chooses the
|
||||
Baseline. So a message read as a change is answered with the Execution it would
|
||||
change and how to name it, and starts nothing.
|
||||
|
||||
Without a decision, and whenever the reading is not confident, the message is taken
|
||||
as a new request: that is what every message was before, and starting work nobody
|
||||
asked for is cheaper to put right than refusing work somebody did.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from execution_engine.adk.runtime import (
|
||||
AgentRuntime,
|
||||
AgentTask,
|
||||
Decider,
|
||||
Question,
|
||||
RoleSpec,
|
||||
Submitted,
|
||||
ToolResult,
|
||||
ToolSpec,
|
||||
)
|
||||
from execution_engine.baseline import BaselineError, load_baseline
|
||||
from execution_engine.customer_case import IN_PROGRESS, read_history
|
||||
from execution_engine.states.execution_state import UNASSIGNED_CASE
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
NEW_REQUEST = "new_request"
|
||||
CHANGE_REQUEST = "change_request"
|
||||
QUESTION = "question"
|
||||
|
||||
|
||||
def change_note(baseline: str) -> str:
|
||||
"""What a caller is told when their message reads as a change to delivered work."""
|
||||
return (
|
||||
"This reads as a change to the work already delivered for this "
|
||||
f"Customer case, in Execution {baseline}. Nothing was started. To change "
|
||||
f'that work from where it stood, send this again with "baseline" '
|
||||
f'set to "{baseline}". To start it as new work instead, send it again '
|
||||
'with "new_request" set to true.'
|
||||
)
|
||||
|
||||
|
||||
def no_answer_note(execution_id: str) -> str:
|
||||
"""What a caller is told when a question about delivered work went unanswered."""
|
||||
return (
|
||||
"I could not answer that from the documents delivered in Execution "
|
||||
f"{execution_id}. Its final document and Deliverables hold what was "
|
||||
"decided and why. Nothing was started for this message."
|
||||
)
|
||||
|
||||
|
||||
_MESSAGE_LIMIT = 8_000
|
||||
# How much of the delivered guide the answer is written from.
|
||||
_GUIDE_LIMIT = 80_000
|
||||
_EARLIER_SHOWN = 5
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class IntakeReading:
|
||||
kind: str # new_request | change_request | question
|
||||
confidence: float = 0.0
|
||||
judged: bool = False # False when no decision was available
|
||||
earlier: int = 0 # finished Executions of the same Customer case
|
||||
latest: str | None = None # the most recent of them: what a change would change
|
||||
# A question about what was delivered, as opposed to about the service.
|
||||
about_delivered: bool = False
|
||||
|
||||
|
||||
def finished_intents(output_root: Path, customer_case: str) -> list[Mapping[str, Any]]:
|
||||
"""The case's earlier statements of intent whose Executions delivered something."""
|
||||
if not customer_case or customer_case == UNASSIGNED_CASE:
|
||||
return []
|
||||
return [
|
||||
item
|
||||
for item in read_history(output_root, customer_case)["intents"]
|
||||
if isinstance(item, Mapping)
|
||||
and str(item.get("status", IN_PROGRESS)).startswith("completed")
|
||||
]
|
||||
|
||||
|
||||
class Intake:
|
||||
def __init__(
|
||||
self,
|
||||
decider: Decider,
|
||||
output_root: Path,
|
||||
*,
|
||||
act: float = 0.75,
|
||||
about_delivered_at: float = 0.6,
|
||||
) -> None:
|
||||
self._decider = decider
|
||||
self._output_root = output_root
|
||||
# How sure the reading must be before anything but a new Execution is done.
|
||||
self._act = act
|
||||
# How likely a question must be about delivered work to be answered from
|
||||
# it. Measured on 2026-10-10: six such questions scored 0.37 to 0.96, five
|
||||
# of them 0.73 or more; six about the service scored 0.07 to 0.16 and one
|
||||
# ambiguous one ("is my data stored anywhere?") 0.74. A wrong yes costs an
|
||||
# answer that says the documents do not cover it.
|
||||
self._about_delivered_at = about_delivered_at
|
||||
|
||||
async def read(
|
||||
self, message: str, customer_case: str | None = None, scope: str = ""
|
||||
) -> IntakeReading:
|
||||
earlier = finished_intents(self._output_root, customer_case or "")
|
||||
text = message.strip()
|
||||
if not text:
|
||||
return IntakeReading(NEW_REQUEST, earlier=len(earlier))
|
||||
answers = await self._decider.decide(
|
||||
_state(text, earlier),
|
||||
{
|
||||
"intake": Question(
|
||||
"choice",
|
||||
"What is the user's message? new_request: they describe "
|
||||
"something they want done. change_request: they "
|
||||
"ask to change or extend work already delivered to "
|
||||
"them. question: they ask about the service or about earlier "
|
||||
"work, and want an answer, not new work.",
|
||||
(NEW_REQUEST, CHANGE_REQUEST, QUESTION),
|
||||
)
|
||||
},
|
||||
scope=scope,
|
||||
)
|
||||
answer = (answers or {}).get("intake")
|
||||
if answer is None:
|
||||
return IntakeReading(NEW_REQUEST, earlier=len(earlier))
|
||||
kind, confidence = str(answer.value), float(answer.confidence)
|
||||
if kind != NEW_REQUEST and confidence < self._act:
|
||||
kind = NEW_REQUEST # not sure enough to do anything but start
|
||||
if kind == CHANGE_REQUEST and not earlier:
|
||||
kind = NEW_REQUEST # there is nothing delivered to change
|
||||
logger.info("[%s] intake: %s (%.2f)", scope, kind, confidence)
|
||||
latest = str(earlier[-1].get("execution_id")) if earlier else None
|
||||
about = (
|
||||
await self._about_delivered(text, earlier, scope)
|
||||
if kind == QUESTION and latest
|
||||
else False
|
||||
)
|
||||
return IntakeReading(
|
||||
kind,
|
||||
confidence,
|
||||
judged=True,
|
||||
earlier=len(earlier),
|
||||
latest=latest,
|
||||
about_delivered=about,
|
||||
)
|
||||
|
||||
async def _about_delivered(
|
||||
self, text: str, earlier: Sequence[Mapping[str, Any]], scope: str
|
||||
) -> bool:
|
||||
answers = await self._decider.decide(
|
||||
_state(text, earlier),
|
||||
{
|
||||
"about_delivered": Question(
|
||||
"noul",
|
||||
"Is the user asking about work already delivered to "
|
||||
"them: what it contains, why something was chosen, or what "
|
||||
"validation found? Answer no when they ask what this service "
|
||||
"does or how it works in general.",
|
||||
)
|
||||
},
|
||||
scope=scope,
|
||||
)
|
||||
answer = (answers or {}).get("about_delivered")
|
||||
return answer is not None and float(answer.value) >= self._about_delivered_at
|
||||
|
||||
|
||||
def _state(message: str, earlier: Sequence[Mapping[str, Any]]) -> str:
|
||||
lines = [f"Architectures already delivered to this user: {len(earlier)}."]
|
||||
for item in list(earlier)[-_EARLIER_SHOWN:]:
|
||||
request = " ".join(str(item.get("workflow_request", "")).split())[:300]
|
||||
lines.append(f"- {request}")
|
||||
lines.append(f"The user's message: {message[:_MESSAGE_LIMIT]}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
class DeliveredAnswers:
|
||||
"""Answers a question about delivered work from its documents, on the reply
|
||||
writer. It reads one Execution's files and starts nothing."""
|
||||
|
||||
def __init__(
|
||||
self, runtime: AgentRuntime, role: RoleSpec, output_root: Path, final: str
|
||||
) -> None:
|
||||
self._runtime = runtime
|
||||
self._role = role
|
||||
self._output_root = output_root
|
||||
# The Workflow's final Deliverable: the document an answer is written from.
|
||||
self._final = final
|
||||
|
||||
async def answer(
|
||||
self, question: str, customer_case: str, execution_id: str
|
||||
) -> str | None:
|
||||
"""The answer, or None when the documents could not be read or the writer
|
||||
gave none."""
|
||||
try:
|
||||
delivered = load_baseline(self._output_root, customer_case, execution_id)
|
||||
except BaselineError:
|
||||
return None
|
||||
guide = str(
|
||||
(delivered["deliverables"].get(self._final) or {}).get("content", "")
|
||||
)
|
||||
if not guide.strip():
|
||||
return None
|
||||
|
||||
async def write_reply(text: str) -> ToolResult:
|
||||
if not text.strip():
|
||||
return ToolResult("Not submitted: the reply is empty.")
|
||||
return ToolResult("Written.", Submitted(text))
|
||||
|
||||
tool = ToolSpec(
|
||||
"write_reply",
|
||||
"Give the text the user will read. Ends your turn.",
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {"text": {"type": "string"}},
|
||||
"required": ["text"],
|
||||
},
|
||||
write_reply,
|
||||
tier="execution",
|
||||
)
|
||||
task = AgentTask(
|
||||
role=self._role.name,
|
||||
prompt="Answer the user's question about the work delivered to them.",
|
||||
context={
|
||||
"question": question[:_MESSAGE_LIMIT],
|
||||
"delivered": {
|
||||
"execution_id": execution_id,
|
||||
"request": delivered.get("workflow_request", ""),
|
||||
"final_document": guide[:_GUIDE_LIMIT],
|
||||
},
|
||||
},
|
||||
)
|
||||
try:
|
||||
outcome = await self._runtime.run(self._role, task, [tool])
|
||||
except Exception: # a question must still get a reply
|
||||
logger.exception("Answering from delivered work failed")
|
||||
return None
|
||||
return outcome.content if isinstance(outcome, Submitted) else None
|
||||
860
execution_engine/nodes/router.py
Normal file
860
execution_engine/nodes/router.py
Normal file
@@ -0,0 +1,860 @@
|
||||
"""The Orchestrator as a router (ADR-0007): readings, a disposition, then a playbook.
|
||||
|
||||
1. Readings facts about the turn. Most come from the Ledger; the ones that need
|
||||
judgement (what is the user asking for? does this gap matter?) are
|
||||
typed answers from the decision model.
|
||||
2. Disposition code turns a judged reading into act, queue or close, by threshold.
|
||||
3. Playbook ordered groups. The first group that applies is taken, and within
|
||||
it the strongest action whose conditions hold. When no group
|
||||
applies, escalate to the user.
|
||||
|
||||
The decision model reads and never acts: every action goes through the Orchestrator's
|
||||
tools, so the Ledger refuses anything that is not allowed, whatever was decided.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Protocol
|
||||
|
||||
from execution_engine.adk.runtime import (
|
||||
AgentRuntime,
|
||||
AgentTask,
|
||||
Decider,
|
||||
Outcome,
|
||||
Question,
|
||||
RoleSpec,
|
||||
Stopped,
|
||||
Submitted,
|
||||
ToolResult,
|
||||
ToolSpec,
|
||||
)
|
||||
from execution_engine.states.ledger import DeliverableStatus, Ledger, PhaseStatus
|
||||
from execution_engine.tools.scoping import SCOPE_DATA_FILE
|
||||
from execution_engine.workflows.workflow import ValidationPolicy, Workflow
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
ORCHESTRATOR = "orchestrator"
|
||||
REPLY_WRITER = "reply-writer"
|
||||
MAX_STEPS = 12 # actions in one turn; a turn that needs more is not making progress
|
||||
|
||||
ACT, QUEUE, CLOSE = "act", "queue", "close"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Thresholds:
|
||||
"""Where a probability becomes a disposition."""
|
||||
|
||||
act: float = 0.75 # at or above: do it
|
||||
close: float = 0.15 # at or below: there is nothing to do
|
||||
confidence: float = 0.6 # a choice below this is not relied on
|
||||
|
||||
def disposition(self, probability: float) -> str:
|
||||
if probability >= self.act:
|
||||
return ACT
|
||||
if probability <= self.close:
|
||||
return CLOSE
|
||||
return QUEUE
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TurnView:
|
||||
"""What one Orchestrator turn can see."""
|
||||
|
||||
execution_id: str
|
||||
pre_approved: bool
|
||||
ledger: Ledger
|
||||
deliverables: Mapping[str, Mapping[str, Any]]
|
||||
pending_questions: Sequence[Mapping[str, Any]]
|
||||
outcomes: Sequence[Mapping[str, Any]]
|
||||
last_reply: Mapping[str, Any] | None = None # the user's message, not yet routed
|
||||
pending_change: Mapping[str, Any] | None = None # a change we asked them to confirm
|
||||
awaiting_gap_decision: bool = False
|
||||
validation_settled: int = 0 # the validation attempt already decided on
|
||||
# The user's reply answers "this Deliverable reached its Revision limit".
|
||||
awaiting_limit_decision: bool = False
|
||||
# Deliverables at their Revision limit that the user has been told about.
|
||||
revision_limit_asked: Sequence[str] = ()
|
||||
context: Mapping[str, Any] = field(default_factory=dict) # for a model Orchestrator
|
||||
|
||||
|
||||
@dataclass
|
||||
class TurnResult:
|
||||
outcome: Outcome
|
||||
decisions: list[dict[str, Any]] = field(default_factory=list)
|
||||
updates: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
class OrchestratorPolicy(Protocol):
|
||||
async def turn(self, view: TurnView, tools: Sequence[ToolSpec]) -> TurnResult: ...
|
||||
|
||||
|
||||
class ReplyWriter(Protocol):
|
||||
async def approval_summary(
|
||||
self, phase: str, facts: Mapping[str, Any]
|
||||
) -> str | None: ...
|
||||
|
||||
|
||||
# --- readings ------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class Readings:
|
||||
"""Everything the playbook decides from."""
|
||||
|
||||
# From the Ledger and the Execution's data.
|
||||
questions_waiting: bool = False
|
||||
phases_ready: tuple[str, ...] = ()
|
||||
phases_awaiting: tuple[str, ...] = () # asked for Approval, not yet decided
|
||||
ready_work: tuple[str, ...] = ()
|
||||
can_finish: bool = False
|
||||
validation_attempt: int = 0 # 0 when no validation stands undecided
|
||||
failed: list[dict[str, Any]] = field(default_factory=list)
|
||||
repeat_failed: list[dict[str, Any]] = field(default_factory=list)
|
||||
unverifiable: list[dict[str, Any]] = field(default_factory=list)
|
||||
additions: list[dict[str, Any]] = field(default_factory=list)
|
||||
dry_run_failed: bool = False
|
||||
# Checks the code's author reported cannot be met as the Target architecture
|
||||
# words them.
|
||||
unimplementable: list[dict[str, str]] = field(default_factory=list)
|
||||
# Judged: what the user's message asks for.
|
||||
change: str = CLOSE # act | queue | close
|
||||
change_target: str | None = None
|
||||
change_reason: str = ""
|
||||
# Judged: whether a gap in the Target architecture is worth a Revision.
|
||||
gap: str = CLOSE
|
||||
judged: dict[str, Any] = field(default_factory=dict) # what the decider answered
|
||||
|
||||
|
||||
# How much of the agreed requirements is shown to the decider with a user's message.
|
||||
_AGREED_LIMIT = 24_000
|
||||
|
||||
# The actions that reopen a Deliverable, and which one.
|
||||
_REOPENS = (
|
||||
"revise_requested",
|
||||
"revise_code",
|
||||
"revise_target_architecture",
|
||||
"revise_unimplementable",
|
||||
)
|
||||
|
||||
|
||||
def _reopened_by(action: str, readings: Readings, workflow: Workflow) -> str | None:
|
||||
if action == "revise_requested":
|
||||
return readings.change_target
|
||||
validation = workflow.validation
|
||||
if validation is None:
|
||||
return None
|
||||
if action == "revise_code":
|
||||
return validation.implementation
|
||||
if action in {"revise_target_architecture", "revise_unimplementable"}:
|
||||
return validation.design
|
||||
return None
|
||||
|
||||
|
||||
def _attempt(ledger: Ledger, kind: str) -> int:
|
||||
return int(ledger.to_dict()["deliverables"][str(kind)].get("attempt", 0))
|
||||
|
||||
|
||||
def _submitted(ledger: Ledger) -> list[str]:
|
||||
return [
|
||||
kind
|
||||
for kind in ledger.workflow.deliverables
|
||||
if ledger.status(kind) is DeliverableStatus.SUBMITTED
|
||||
]
|
||||
|
||||
|
||||
def _mentioned(text: str, candidates: Sequence[str]) -> list[str]:
|
||||
"""Deliverables named outright in a message, as `deployment_guidance` or in words."""
|
||||
lowered = re.sub(r"[\s_\-]+", " ", text.lower())
|
||||
return [kind for kind in candidates if str(kind).replace("_", " ") in lowered]
|
||||
|
||||
|
||||
def _failed_before(
|
||||
outcomes: Sequence[Mapping[str, Any]], validation: ValidationPolicy
|
||||
) -> set[str]:
|
||||
"""Check ids that failed in the validation before the one that stands now."""
|
||||
validations = [
|
||||
record
|
||||
for record in outcomes
|
||||
if record.get("type") == "submitted" and record.get("kind") == validation.kind
|
||||
]
|
||||
if len(validations) < 2:
|
||||
return set()
|
||||
previous = validation.read(
|
||||
validations[-2].get("attachments", {}).get(validation.data_file, "")
|
||||
)
|
||||
return {item["check"] for item in previous["failed"]}
|
||||
|
||||
|
||||
class Router:
|
||||
"""Decides an Orchestrator turn from readings and a playbook, with no language
|
||||
model choosing the action. A model, when one is given, only writes what the user
|
||||
reads."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
decider: Decider,
|
||||
writer: ReplyWriter | None = None,
|
||||
thresholds: Thresholds | None = None,
|
||||
) -> None:
|
||||
self._decider = decider
|
||||
self._writer = writer
|
||||
self._thresholds = thresholds or Thresholds()
|
||||
|
||||
async def turn(self, view: TurnView, tools: Sequence[ToolSpec]) -> TurnResult:
|
||||
by_name = {tool.name: tool for tool in tools}
|
||||
result = TurnResult(Stopped("The router took no action."))
|
||||
# A user message is routed once; a confirmation we asked for is consumed.
|
||||
result.updates = {
|
||||
"last_reply": None,
|
||||
"pending_change": None,
|
||||
"awaiting_gap_decision": False,
|
||||
"awaiting_limit_decision": False,
|
||||
}
|
||||
readings = await self._read(view, result)
|
||||
blocked: set[str] = set()
|
||||
settled = view.validation_settled
|
||||
# Told once, the user is not asked again: a Deliverable at its limit is no
|
||||
# longer reopened, and the Execution carries on with it as it stands.
|
||||
at_limit = set(view.revision_limit_asked)
|
||||
|
||||
async def call(tool: str, **arguments: Any) -> ToolResult:
|
||||
return await by_name[tool].handler(**arguments)
|
||||
|
||||
for _ in range(MAX_STEPS):
|
||||
barred = blocked | {
|
||||
name
|
||||
for name in _REOPENS
|
||||
if (kind := _reopened_by(name, readings, view.ledger.workflow))
|
||||
and str(kind) in at_limit
|
||||
}
|
||||
group, action = self._choose(view, readings, barred, settled)
|
||||
result.decisions.append(
|
||||
{"group": group, "action": action, "judged": dict(readings.judged)}
|
||||
)
|
||||
readings.judged = {}
|
||||
reply = await self._perform(action, view, readings, call, result)
|
||||
if action == "proceed":
|
||||
settled = readings.validation_attempt
|
||||
result.updates["validation_settled"] = settled
|
||||
self._read_ledger(view, readings, settled)
|
||||
continue
|
||||
if reply is None:
|
||||
return result
|
||||
if reply.outcome is not None:
|
||||
result.outcome = reply.outcome
|
||||
return result
|
||||
if "revision limit" in reply.message and not view.pre_approved:
|
||||
# Past the Revision limit the user is told, once. Their reply is
|
||||
# read as the answer to this, never as a new request for changes.
|
||||
kind = _reopened_by(action, readings, view.ledger.workflow)
|
||||
if kind:
|
||||
at_limit.add(str(kind))
|
||||
result.updates["revision_limit_asked"] = sorted(at_limit)
|
||||
result.updates["awaiting_limit_decision"] = True
|
||||
limit = await call(
|
||||
"ask_user",
|
||||
questions=[
|
||||
reply.message.split(" Use ")[0]
|
||||
+ " It will not be revised again in this Execution; I will "
|
||||
"carry on with it as it stands. Reply to continue."
|
||||
],
|
||||
)
|
||||
if limit.outcome is not None:
|
||||
result.outcome = limit.outcome
|
||||
return result
|
||||
if reply.message.startswith("Refused") or "revision limit" in reply.message:
|
||||
# Permission is the Ledger's: take the next action that is allowed.
|
||||
blocked.add(action)
|
||||
# The action changed the Execution; read the Ledger's facts again.
|
||||
self._read_ledger(view, readings, settled)
|
||||
if action in {"revise_requested", "confirm_change"}:
|
||||
readings.change = CLOSE
|
||||
result.outcome = Stopped("The router made no progress in this turn.")
|
||||
return result
|
||||
|
||||
# --- readings ---------------------------------------------------------------------
|
||||
|
||||
async def _read(self, view: TurnView, result: TurnResult) -> Readings:
|
||||
readings = Readings()
|
||||
self._read_ledger(view, readings, view.validation_settled)
|
||||
await self._read_message(view, readings)
|
||||
await self._read_gap(view, readings)
|
||||
return readings
|
||||
|
||||
def _read_ledger(self, view: TurnView, readings: Readings, settled: int) -> None:
|
||||
ledger = view.ledger
|
||||
readings.questions_waiting = bool(view.pending_questions)
|
||||
readings.phases_ready = ledger.phases_ready_for_approval()
|
||||
readings.phases_awaiting = tuple(
|
||||
phase
|
||||
for phase in ledger.workflow.phases
|
||||
if ledger.phase_status(phase) is PhaseStatus.AWAITING_APPROVAL
|
||||
)
|
||||
readings.ready_work = ledger.ready_work()
|
||||
readings.can_finish = ledger.can_finish()
|
||||
readings.validation_attempt = 0
|
||||
readings.failed, readings.repeat_failed = [], []
|
||||
readings.unverifiable, readings.additions = [], []
|
||||
readings.dry_run_failed = False
|
||||
readings.unimplementable = []
|
||||
policy = ledger.workflow.validation
|
||||
if policy is None:
|
||||
return
|
||||
if (
|
||||
policy.unimplementable
|
||||
and ledger.status(policy.implementation) is DeliverableStatus.SUBMITTED
|
||||
):
|
||||
readings.unimplementable = policy.unimplementable(view.deliverables)
|
||||
|
||||
validation = policy.kind
|
||||
phase = ledger.workflow.deliverables[validation].phase
|
||||
attempt = _attempt(ledger, validation)
|
||||
if (
|
||||
ledger.status(validation) is not DeliverableStatus.SUBMITTED
|
||||
or ledger.phase_status(phase) is PhaseStatus.APPROVED
|
||||
or attempt == settled
|
||||
):
|
||||
return
|
||||
outcome = policy.read(
|
||||
view.deliverables.get(validation, {})
|
||||
.get("attachments", {})
|
||||
.get(policy.data_file, "")
|
||||
)
|
||||
before = _failed_before(view.outcomes, policy)
|
||||
readings.validation_attempt = attempt
|
||||
readings.failed = outcome["failed"]
|
||||
readings.repeat_failed = [f for f in outcome["failed"] if f["check"] in before]
|
||||
readings.unverifiable = outcome["not_verifiable"]
|
||||
readings.additions = outcome["proposed_additions"]
|
||||
readings.dry_run_failed = outcome["dry_run"].get("verdict") == "fail"
|
||||
|
||||
async def _read_message(self, view: TurnView, readings: Readings) -> None:
|
||||
"""Triage of the user's message: is it asking for a change, to what, and how
|
||||
clearly?"""
|
||||
reply = view.last_reply
|
||||
if not reply or view.awaiting_gap_decision or view.awaiting_limit_decision:
|
||||
return
|
||||
text = str(reply.get("text", "")).strip()
|
||||
pending = view.pending_change
|
||||
if pending:
|
||||
text = f"{pending.get('text', '')}\nThe user then said: {text}"
|
||||
candidates = _submitted(view.ledger)
|
||||
if not text or not candidates:
|
||||
return
|
||||
readings.change_reason = text
|
||||
asked = [str(question) for question in reply.get("asked") or ()]
|
||||
# A structured request for changes is known to be one, and so is the reply to
|
||||
# our own question about a change they already asked for.
|
||||
structured = reply.get("kind") == "changes" or bool(pending)
|
||||
|
||||
workflow = view.ledger.workflow
|
||||
agreed = (
|
||||
""
|
||||
if structured or not workflow.agreed
|
||||
else workflow.agreed(view.deliverables)[:_AGREED_LIMIT]
|
||||
)
|
||||
questions = {
|
||||
"change_target": Question(
|
||||
"choice",
|
||||
"Which submitted Deliverable would have to change first to do what "
|
||||
"the user asks?",
|
||||
tuple(str(kind) for kind in candidates),
|
||||
),
|
||||
"change_clarity": Question(
|
||||
"score",
|
||||
"How specific is the user about what should change?",
|
||||
("vague", "partial", "specific"),
|
||||
),
|
||||
}
|
||||
if not structured:
|
||||
questions["asks_change"] = Question(
|
||||
"noul",
|
||||
"Is the user asking for a change to work that has already been "
|
||||
"submitted, as opposed to answering a question or adding information?",
|
||||
)
|
||||
if agreed:
|
||||
# Someone who restates what is already agreed is answering, however
|
||||
# much it sounds like a requirement.
|
||||
questions["already_agreed"] = Question(
|
||||
"noul",
|
||||
"Does the user's message only confirm or repeat what the agreed "
|
||||
"requirements above already say, asking for nothing different?",
|
||||
)
|
||||
state = (
|
||||
f"Submitted Deliverables: {', '.join(str(kind) for kind in candidates)}.\n"
|
||||
+ (f"The agreed requirements:\n{agreed}\n" if agreed else "")
|
||||
+ f"Questions waiting for the user: {len(view.pending_questions)}.\n"
|
||||
# What we asked is background. Only the user's own words are their
|
||||
# message: our question echoed back is not something they said.
|
||||
+ (
|
||||
"The user was replying to these questions from the agents:\n"
|
||||
+ "\n".join(f"- {question}" for question in asked)
|
||||
+ "\n"
|
||||
if asked
|
||||
else ""
|
||||
)
|
||||
+ f"The user's message: {text}"
|
||||
)
|
||||
answers = await self._decider.decide(state, questions, scope=view.execution_id)
|
||||
|
||||
named = _mentioned(text, candidates)
|
||||
if answers is None:
|
||||
# No judgement available: act only on what is certain.
|
||||
if structured:
|
||||
target = (
|
||||
candidates[0]
|
||||
if len(candidates) == 1
|
||||
else named[0]
|
||||
if len(named) == 1
|
||||
else None
|
||||
)
|
||||
readings.change = ACT if target else QUEUE
|
||||
readings.change_target = target
|
||||
return
|
||||
|
||||
readings.judged = {
|
||||
name: {"value": answer.value, "confidence": answer.confidence}
|
||||
for name, answer in answers.items()
|
||||
}
|
||||
probability = 1.0 if structured else float(answers["asks_change"].value)
|
||||
disposition = self._thresholds.disposition(probability)
|
||||
restated = answers.get("already_agreed")
|
||||
if restated is not None and restated.is_yes(self._thresholds.act):
|
||||
# It restates what is agreed: an answer, not a change.
|
||||
disposition = CLOSE
|
||||
target_answer = answers["change_target"]
|
||||
target = view.ledger.workflow.kind(str(target_answer.value))
|
||||
readings.change_target = target
|
||||
if disposition == ACT and (
|
||||
target_answer.confidence < self._thresholds.confidence
|
||||
or float(answers["change_clarity"].value) < 0.5
|
||||
):
|
||||
# They want a change, but which, or what, is not clear enough to act on.
|
||||
disposition = QUEUE
|
||||
if disposition == QUEUE and pending:
|
||||
# Asked once already: act if they named it, otherwise let it go.
|
||||
disposition = ACT if len(named) == 1 else CLOSE
|
||||
readings.change_target = named[0] if named else target
|
||||
readings.change = disposition
|
||||
|
||||
async def _read_gap(self, view: TurnView, readings: Readings) -> None:
|
||||
"""Whether a gap in the Target architecture is worth revising it for."""
|
||||
if (
|
||||
readings.failed
|
||||
or readings.dry_run_failed
|
||||
or not readings.validation_attempt
|
||||
):
|
||||
return
|
||||
if not (readings.additions or readings.unverifiable):
|
||||
return
|
||||
items = "\n".join(
|
||||
[
|
||||
f"- proposed addition on {item.get('applies_to')}: "
|
||||
f"{item.get('statement')} (serves {item.get('reason')})"
|
||||
for item in readings.additions
|
||||
]
|
||||
+ [
|
||||
f"- Check {item.get('check')} could not be verified: "
|
||||
f"{item.get('evidence')}"
|
||||
for item in readings.unverifiable
|
||||
]
|
||||
)
|
||||
reply = view.last_reply if view.awaiting_gap_decision else None
|
||||
if reply:
|
||||
question = Question(
|
||||
"noul",
|
||||
"Is the user asking for the Target architecture to be revised to "
|
||||
"close these gaps?",
|
||||
)
|
||||
state = f"Gaps found by validation:\n{items}\nThe user's reply: {reply.get('text', '')}"
|
||||
name = "wants_revision"
|
||||
else:
|
||||
question = Question(
|
||||
"noul",
|
||||
"Would leaving these gaps open mean a stated requirement or design "
|
||||
"recommendation is not met?",
|
||||
)
|
||||
state = f"Gaps found by validation:\n{items}"
|
||||
name = "gap_material"
|
||||
answers = await self._decider.decide(
|
||||
state, {name: question}, scope=view.execution_id
|
||||
)
|
||||
if answers is None:
|
||||
readings.gap = self._gap_by_rule(view, readings) if not reply else CLOSE
|
||||
return
|
||||
readings.judged[name] = {
|
||||
"value": answers[name].value,
|
||||
"confidence": answers[name].confidence,
|
||||
}
|
||||
disposition = self._thresholds.disposition(float(answers[name].value))
|
||||
if reply and disposition == QUEUE:
|
||||
disposition = CLOSE # asked once already; an unclear answer means go on
|
||||
readings.gap = disposition
|
||||
|
||||
@staticmethod
|
||||
def _gap_by_rule(view: TurnView, readings: Readings) -> str:
|
||||
"""Without a judgement: a Check that cannot be verified must be fixed, and an
|
||||
addition counts when it names a real requirement or recommendation."""
|
||||
if readings.unverifiable:
|
||||
return ACT
|
||||
policy = view.ledger.workflow.validation
|
||||
known = (
|
||||
policy.known_ids(view.deliverables)
|
||||
if policy and policy.known_ids
|
||||
else set()
|
||||
)
|
||||
for item in readings.additions:
|
||||
words = set(re.findall(r"[A-Za-z]+-\d+", str(item.get("reason", ""))))
|
||||
if words & known:
|
||||
return ACT
|
||||
return CLOSE
|
||||
|
||||
# --- the playbook -----------------------------------------------------------------
|
||||
|
||||
def _choose(
|
||||
self, view: TurnView, r: Readings, blocked: set[str], settled: int
|
||||
) -> tuple[str, str]:
|
||||
"""The first group that applies, and within it the strongest action whose
|
||||
conditions hold. No group applies: escalate."""
|
||||
interactive = not view.pre_approved
|
||||
playbook: list[tuple[str, bool, list[tuple[str, bool]]]] = [
|
||||
(
|
||||
"the user asked for a change",
|
||||
r.change in {ACT, QUEUE},
|
||||
[
|
||||
(
|
||||
"revise_requested",
|
||||
r.change == ACT and r.change_target is not None,
|
||||
),
|
||||
("confirm_change", r.change == QUEUE and interactive),
|
||||
],
|
||||
),
|
||||
(
|
||||
"questions are waiting",
|
||||
r.questions_waiting,
|
||||
[("relay_questions", True)],
|
||||
),
|
||||
(
|
||||
# Known as soon as the code is submitted, so no validation is spent
|
||||
# on a Check that cannot pass.
|
||||
"the code cannot meet a Check",
|
||||
bool(r.unimplementable),
|
||||
[("revise_unimplementable", True)],
|
||||
),
|
||||
(
|
||||
"validation decided",
|
||||
bool(r.validation_attempt),
|
||||
[
|
||||
(
|
||||
"revise_target_architecture",
|
||||
bool(r.repeat_failed) or (not r.failed and r.gap == ACT),
|
||||
),
|
||||
("revise_code", bool(r.failed) or r.dry_run_failed),
|
||||
("ask_about_gaps", r.gap == QUEUE and interactive),
|
||||
("proceed", True),
|
||||
],
|
||||
),
|
||||
(
|
||||
"a Phase is complete",
|
||||
bool(r.phases_ready or r.phases_awaiting),
|
||||
# An Approval is granted only by a structured decision, so a Phase
|
||||
# still awaiting one is asked for again.
|
||||
[("request_approval", True)],
|
||||
),
|
||||
("work is ready", bool(r.ready_work), [("delegate", True)]),
|
||||
("packaging is approved", r.can_finish, [("finish", True)]),
|
||||
]
|
||||
for group, applies, actions in playbook:
|
||||
if not applies:
|
||||
continue
|
||||
for action, holds in actions:
|
||||
if holds and action not in blocked:
|
||||
return group, action
|
||||
return "no group applies", "escalate"
|
||||
|
||||
async def _perform(
|
||||
self,
|
||||
action: str,
|
||||
view: TurnView,
|
||||
r: Readings,
|
||||
call: Callable[..., Awaitable[ToolResult]],
|
||||
result: TurnResult,
|
||||
) -> ToolResult | None:
|
||||
workflow = view.ledger.workflow
|
||||
if action == "proceed":
|
||||
return ToolResult("Proceeding.")
|
||||
if action == "revise_requested":
|
||||
assert r.change_target is not None
|
||||
return await call(
|
||||
"reopen", kind=str(r.change_target), reason=r.change_reason
|
||||
)
|
||||
if action == "confirm_change":
|
||||
guess = str(r.change_target) if r.change_target else None
|
||||
result.updates["pending_change"] = {"text": r.change_reason, "guess": guess}
|
||||
options = ", ".join(str(kind) for kind in _submitted(view.ledger))
|
||||
question = (
|
||||
f"Do you want {guess} changed? Reply naming the Deliverable to change "
|
||||
f"and what should be different. Submitted so far: {options}."
|
||||
if guess
|
||||
else "Which Deliverable should change, and what should be different? "
|
||||
f"Submitted so far: {options}."
|
||||
)
|
||||
return await call("ask_user", questions=[question])
|
||||
if action == "relay_questions":
|
||||
return await call("ask_user", questions=[])
|
||||
if action == "revise_code":
|
||||
items = r.failed or [
|
||||
{"check": "dry-run", "evidence": "the deployment dry-run failed"}
|
||||
]
|
||||
reason = "; ".join(f"{i['check']} failed: {i['evidence']}" for i in items)
|
||||
return await call(
|
||||
"reopen", kind=str(_reopened_by(action, r, workflow)), reason=reason
|
||||
)
|
||||
if action == "revise_unimplementable":
|
||||
reason = " ".join(
|
||||
f"Check {item['check']} cannot be implemented as written "
|
||||
f"({item['reason']}). Rewrite it so it can be met, or remove it with "
|
||||
"a reason."
|
||||
for item in r.unimplementable
|
||||
)
|
||||
# In the run of 2026-10-09 a second Check with the same fault came back
|
||||
# one Revision later, for the same reason word for word.
|
||||
reason += (
|
||||
" The same fault may be in other Checks: read every Check against "
|
||||
"each reason given here and correct every one it applies to."
|
||||
)
|
||||
return await call(
|
||||
"reopen", kind=str(_reopened_by(action, r, workflow)), reason=reason
|
||||
)
|
||||
if action == "revise_target_architecture":
|
||||
return await call(
|
||||
"reopen",
|
||||
kind=str(_reopened_by(action, r, workflow)),
|
||||
reason=_graph_reason(r),
|
||||
)
|
||||
if action == "ask_about_gaps":
|
||||
result.updates["awaiting_gap_decision"] = True
|
||||
listed = "; ".join(
|
||||
[str(i.get("statement")) for i in r.additions]
|
||||
+ [
|
||||
f"Check {i.get('check')} could not be verified"
|
||||
for i in r.unverifiable
|
||||
]
|
||||
)
|
||||
question = (
|
||||
"Validation passed every Check it could, and found gaps in the "
|
||||
f"Target architecture: {listed}. Should the Target architecture "
|
||||
"be revised to close them, or shall I proceed as it stands?"
|
||||
)
|
||||
return await call("ask_user", questions=[question])
|
||||
if action == "request_approval":
|
||||
phase = (r.phases_ready or r.phases_awaiting)[0]
|
||||
return await call(
|
||||
"request_approval",
|
||||
phase=str(phase),
|
||||
summary=await self._summary(phase, view, r),
|
||||
)
|
||||
if action == "delegate":
|
||||
return await call("delegate", kinds=[str(kind) for kind in r.ready_work])
|
||||
if action == "finish":
|
||||
return await call("finish")
|
||||
# escalate: no group applies.
|
||||
if view.pre_approved:
|
||||
result.outcome = Stopped(
|
||||
"No next step applies and no user is available to decide."
|
||||
)
|
||||
return None
|
||||
return await call(
|
||||
"ask_user",
|
||||
questions=["I have no next step to take. What would you like me to do?"],
|
||||
)
|
||||
|
||||
async def _summary(self, phase: str, view: TurnView, r: Readings) -> str:
|
||||
facts = approval_facts(phase, view, r)
|
||||
if self._writer is not None:
|
||||
try:
|
||||
written = await self._writer.approval_summary(str(phase), facts)
|
||||
except Exception: # a summary must never stop an Approval
|
||||
logger.exception("The reply writer failed; using the assembled summary")
|
||||
written = None
|
||||
if written and written.strip():
|
||||
return written.strip()
|
||||
return assembled_summary(phase, facts, view.ledger.workflow)
|
||||
|
||||
|
||||
def _graph_reason(r: Readings) -> str:
|
||||
parts = [
|
||||
f"Check {item['check']} failed in two validations in a row and may not be "
|
||||
f"implementable as written ({item['evidence']}). Rewrite it so it can be met, "
|
||||
"or remove it with a reason."
|
||||
for item in r.repeat_failed
|
||||
]
|
||||
if not r.repeat_failed:
|
||||
parts += [
|
||||
f"Check {item.get('check')} could not be verified from the code "
|
||||
f"({item.get('evidence')}). Rewrite it so it can be."
|
||||
for item in r.unverifiable
|
||||
]
|
||||
parts += [
|
||||
f"Add a Check on {item.get('applies_to')}: {item.get('statement')} "
|
||||
f"(serves {item.get('reason')})."
|
||||
for item in r.additions
|
||||
]
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def approval_facts(phase: str, view: TurnView, r: Readings) -> dict[str, Any]:
|
||||
"""What an Approval summary is written from: data, never Deliverable prose."""
|
||||
workflow = view.ledger.workflow
|
||||
kinds = workflow.deliverables_in(phase)
|
||||
facts: dict[str, Any] = {
|
||||
"phase": str(phase),
|
||||
"deliverables": [str(kind) for kind in kinds],
|
||||
"revisions": {
|
||||
str(kind): view.ledger.revisions(kind)
|
||||
for kind in kinds
|
||||
if view.ledger.revisions(kind)
|
||||
},
|
||||
}
|
||||
if workflow.approval_facts:
|
||||
facts.update(workflow.approval_facts(phase, view.deliverables))
|
||||
spec = workflow.spec_deliverable
|
||||
scope = (view.deliverables.get(spec) or {}).get("attachments", {}) if spec else {}
|
||||
if (
|
||||
spec
|
||||
and phase == workflow.deliverables[spec].phase
|
||||
and scope.get(SCOPE_DATA_FILE)
|
||||
):
|
||||
# What approving the spec commits to: how much the customer stated, how
|
||||
# much was assumed for them, and what is still unknown.
|
||||
try:
|
||||
agreed = json.loads(scope[SCOPE_DATA_FILE])
|
||||
except ValueError:
|
||||
agreed = {}
|
||||
facts["scope"] = {
|
||||
"kind": agreed.get("kind"),
|
||||
"assumed": [item.get("field") for item in agreed.get("assumed", [])],
|
||||
"left_to_decide": [
|
||||
item.get("field") for item in agreed.get("to_decide", [])
|
||||
],
|
||||
"unknown": [item.get("field") for item in agreed.get("to_ask", [])],
|
||||
}
|
||||
policy = workflow.validation
|
||||
validation = view.deliverables.get(policy.kind) if policy else None
|
||||
if policy and validation and phase == workflow.deliverables[policy.kind].phase:
|
||||
outcome = policy.read(
|
||||
validation.get("attachments", {}).get(policy.data_file, "")
|
||||
)
|
||||
facts["validation"] = {
|
||||
"passed": len(outcome["passed"]),
|
||||
"failed": [item["check"] for item in outcome["failed"]],
|
||||
"not_verifiable": [item["check"] for item in outcome["not_verifiable"]],
|
||||
"open_gaps": [
|
||||
item.get("statement") for item in outcome["proposed_additions"]
|
||||
],
|
||||
}
|
||||
return facts
|
||||
|
||||
|
||||
def assembled_summary(
|
||||
phase: str, facts: Mapping[str, Any], workflow: Workflow | None = None
|
||||
) -> str:
|
||||
"""An Approval summary from the facts alone, used when no writer is available."""
|
||||
lines = [
|
||||
(f"The {phase} Phase is ready: {', '.join(facts['deliverables'])} submitted.")
|
||||
]
|
||||
if workflow and workflow.summary_lines:
|
||||
lines += list(workflow.summary_lines(phase, facts))
|
||||
scope = facts.get("scope")
|
||||
if scope:
|
||||
lines.append(
|
||||
f"Scope of a {scope.get('kind') or 'workload'}: "
|
||||
f"{len(scope['assumed'])} fields assumed, "
|
||||
f"{len(scope['unknown'])} still unknown. Requirements are derived "
|
||||
"from it once you approve."
|
||||
)
|
||||
validation = facts.get("validation")
|
||||
if validation:
|
||||
lines.append(
|
||||
f"Validation: {validation['passed']} Checks passed, "
|
||||
f"{len(validation['failed'])} failed, "
|
||||
f"{len(validation['not_verifiable'])} not verifiable."
|
||||
)
|
||||
if validation["open_gaps"]:
|
||||
lines.append(
|
||||
"Open gaps: " + "; ".join(map(str, validation["open_gaps"])) + "."
|
||||
)
|
||||
if facts.get("revisions"):
|
||||
lines.append(
|
||||
"Revised: "
|
||||
+ ", ".join(
|
||||
f"{kind} × {count}" for kind, count in facts["revisions"].items()
|
||||
)
|
||||
+ "."
|
||||
)
|
||||
return " ".join(lines)
|
||||
|
||||
|
||||
# --- the two ways an Orchestrator turn can be driven ---------------------------------
|
||||
|
||||
|
||||
class ModelOrchestrator:
|
||||
"""The Orchestrator as a reasoning agent: a language model chooses the tool calls.
|
||||
|
||||
Kept so the Ledger's rules can be driven in any order by a scripted runtime in
|
||||
tests, and so an evaluation can compare it with the router.
|
||||
"""
|
||||
|
||||
def __init__(self, runtime: AgentRuntime, role: RoleSpec) -> None:
|
||||
self._runtime = runtime
|
||||
self._role = role
|
||||
|
||||
async def turn(self, view: TurnView, tools: Sequence[ToolSpec]) -> TurnResult:
|
||||
task = AgentTask(
|
||||
role=ORCHESTRATOR,
|
||||
prompt="Decide the next step for this Execution using your tools.",
|
||||
context=view.context,
|
||||
)
|
||||
return TurnResult(await self._runtime.run(self._role, task, tools))
|
||||
|
||||
|
||||
class RuntimeReplyWriter:
|
||||
"""Writes what the user reads, on a language model. It is given a decision that
|
||||
has already been made and the facts, and it decides nothing."""
|
||||
|
||||
def __init__(self, runtime: AgentRuntime, role: RoleSpec) -> None:
|
||||
self._runtime = runtime
|
||||
self._role = role
|
||||
|
||||
async def approval_summary(
|
||||
self, phase: str, facts: Mapping[str, Any]
|
||||
) -> str | None:
|
||||
async def write_reply(text: str) -> ToolResult:
|
||||
if not text.strip():
|
||||
return ToolResult("Not submitted: the reply is empty.")
|
||||
return ToolResult("Written.", Submitted(text))
|
||||
|
||||
tool = ToolSpec(
|
||||
"write_reply",
|
||||
"Give the text the user will read. Ends your turn.",
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {"text": {"type": "string"}},
|
||||
"required": ["text"],
|
||||
},
|
||||
write_reply,
|
||||
tier="execution",
|
||||
)
|
||||
task = AgentTask(
|
||||
role=REPLY_WRITER,
|
||||
prompt=f"Write the summary the user will approve the {phase} Phase from.",
|
||||
context={"phase": phase, "facts": dict(facts)},
|
||||
)
|
||||
outcome = await self._runtime.run(self._role, task, [tool])
|
||||
return outcome.content if isinstance(outcome, Submitted) else None
|
||||
Reference in New Issue
Block a user