feat: add the Deliverable dependency graph and Ledger
Increment 3 of .scratch/solution-architect-agent/spec.md, test-first. - app/execution/deliverables.py: four Phases, nine Deliverables and their Dependencies declared once, plus per-kind contracts (required headings, attachments) checked by check_submission. - app/execution/ledger.py: pure Ledger enforcing both acceptance thresholds, Phase Approvals (including pre-approved mode and change requests), Revision cascade with withdrawn Approvals, the revision cap with escalation and user override, attempt numbers that reject stale submissions, an ordered event log, and dict round-tripping. - 37 new tests; full suite 102 passed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1
app/execution/__init__.py
Normal file
1
app/execution/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""Execution of the solution-architecture workflow: Deliverables, the Ledger and the graph."""
|
||||
174
app/execution/deliverables.py
Normal file
174
app/execution/deliverables.py
Normal file
@@ -0,0 +1,174 @@
|
||||
"""The dependency graph of Deliverables, grouped into Phases.
|
||||
|
||||
This is the only place Phases, Deliverables and Dependencies are declared. Section
|
||||
names are provider-neutral; they match the numbered headings of a Cloud provider's
|
||||
solution-guide template by suffix (e.g. "Products and features mapping" matches
|
||||
"4.1. Google Cloud products and features mapping").
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
|
||||
|
||||
class PhaseId(StrEnum):
|
||||
REQUIREMENTS_DISCOVERY = "requirements_discovery"
|
||||
SOLUTION_ARCHITECTURE = "solution_architecture"
|
||||
SOLUTION_VALIDATION = "solution_validation"
|
||||
PACKAGING = "packaging"
|
||||
|
||||
|
||||
PHASE_ORDER: tuple[PhaseId, ...] = tuple(PhaseId)
|
||||
|
||||
|
||||
class DeliverableKind(StrEnum):
|
||||
REQUIREMENTS = "requirements"
|
||||
TECHNICAL_DECOMPOSITION = "technical_decomposition"
|
||||
PRODUCT_SELECTION = "product_selection"
|
||||
ARCHITECTURE_DIAGRAM = "architecture_diagram"
|
||||
ARCHITECTURE_DESCRIPTION = "architecture_description"
|
||||
DESIGN_RECOMMENDATIONS = "design_recommendations"
|
||||
DEPLOYMENT_GUIDANCE = "deployment_guidance"
|
||||
VALIDATION_RESULTS = "validation_results"
|
||||
SOLUTION_GUIDE = "solution_guide"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DeliverableSpec:
|
||||
kind: DeliverableKind
|
||||
phase: PhaseId
|
||||
specialist: str
|
||||
depends_on: tuple[DeliverableKind, ...] = ()
|
||||
sections: tuple[str, ...] = ()
|
||||
attachments: tuple[str, ...] = ()
|
||||
|
||||
|
||||
_K = DeliverableKind
|
||||
|
||||
DEPENDENCY_GRAPH: Mapping[DeliverableKind, DeliverableSpec] = {
|
||||
spec.kind: spec
|
||||
for spec in (
|
||||
DeliverableSpec(
|
||||
_K.REQUIREMENTS,
|
||||
PhaseId.REQUIREMENTS_DISCOVERY,
|
||||
"requirements-analyst",
|
||||
sections=(
|
||||
"Functional requirements",
|
||||
"Non-functional requirements",
|
||||
"Current state",
|
||||
"Dependencies",
|
||||
),
|
||||
),
|
||||
DeliverableSpec(
|
||||
_K.TECHNICAL_DECOMPOSITION,
|
||||
PhaseId.REQUIREMENTS_DISCOVERY,
|
||||
"decomposer",
|
||||
depends_on=(_K.REQUIREMENTS,),
|
||||
),
|
||||
DeliverableSpec(
|
||||
_K.PRODUCT_SELECTION,
|
||||
PhaseId.SOLUTION_ARCHITECTURE,
|
||||
"product-selector",
|
||||
depends_on=(_K.TECHNICAL_DECOMPOSITION,),
|
||||
sections=("Products and features mapping",),
|
||||
),
|
||||
DeliverableSpec(
|
||||
_K.ARCHITECTURE_DIAGRAM,
|
||||
PhaseId.SOLUTION_ARCHITECTURE,
|
||||
"diagrammer",
|
||||
depends_on=(_K.PRODUCT_SELECTION,),
|
||||
attachments=("architecture.mmd",),
|
||||
),
|
||||
DeliverableSpec(
|
||||
_K.ARCHITECTURE_DESCRIPTION,
|
||||
PhaseId.SOLUTION_ARCHITECTURE,
|
||||
"describer",
|
||||
depends_on=(_K.ARCHITECTURE_DIAGRAM, _K.PRODUCT_SELECTION),
|
||||
),
|
||||
DeliverableSpec(
|
||||
_K.DESIGN_RECOMMENDATIONS,
|
||||
PhaseId.SOLUTION_ARCHITECTURE,
|
||||
"design-advisor",
|
||||
depends_on=(_K.PRODUCT_SELECTION, _K.REQUIREMENTS),
|
||||
sections=(
|
||||
"Security, privacy, and compliance",
|
||||
"Reliability",
|
||||
"Operational excellence",
|
||||
"Cost optimization",
|
||||
"Performance efficiency",
|
||||
"Sustainability",
|
||||
),
|
||||
),
|
||||
DeliverableSpec(
|
||||
_K.DEPLOYMENT_GUIDANCE,
|
||||
PhaseId.SOLUTION_ARCHITECTURE,
|
||||
"iac-author",
|
||||
depends_on=(_K.PRODUCT_SELECTION, _K.DESIGN_RECOMMENDATIONS),
|
||||
sections=(
|
||||
"Deployment prerequisites",
|
||||
"Step-by-step deployment instructions",
|
||||
),
|
||||
attachments=("terraform/main.tf", "terraform/variables.tf"),
|
||||
),
|
||||
DeliverableSpec(
|
||||
_K.VALIDATION_RESULTS,
|
||||
PhaseId.SOLUTION_VALIDATION,
|
||||
"validator",
|
||||
depends_on=(_K.DEPLOYMENT_GUIDANCE,),
|
||||
sections=("Deployment dry-run", "Architecture and policy analysis"),
|
||||
),
|
||||
DeliverableSpec(
|
||||
_K.SOLUTION_GUIDE,
|
||||
PhaseId.PACKAGING,
|
||||
"packager",
|
||||
depends_on=(_K.VALIDATION_RESULTS,),
|
||||
sections=(
|
||||
"Executive summary and workload overview",
|
||||
"Requirements and current state",
|
||||
"Technical decomposition of the workload",
|
||||
"Proposed solution architecture",
|
||||
"Design and configuration recommendations",
|
||||
"Deployment guidance",
|
||||
"Validation plan",
|
||||
"References",
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
def deliverables_in(phase: PhaseId) -> tuple[DeliverableKind, ...]:
|
||||
return tuple(kind for kind, spec in DEPENDENCY_GRAPH.items() if spec.phase is phase)
|
||||
|
||||
|
||||
_HEADING = re.compile(r"^ {0,3}#{1,6}\s+(.+?)\s*#*\s*$", re.MULTILINE)
|
||||
_NUMBERING = re.compile(r"^\d+(?:\.\d+)*\.?\s+")
|
||||
_TRAILING = re.compile(r"[\s:.\-–—]+$")
|
||||
|
||||
|
||||
def _normalise(text: str) -> str:
|
||||
text = _NUMBERING.sub("", text.strip().lower())
|
||||
return " ".join(_TRAILING.sub("", text).split())
|
||||
|
||||
|
||||
def check_submission(
|
||||
kind: DeliverableKind, content: str, attachments: Mapping[str, str]
|
||||
) -> tuple[str, ...]:
|
||||
"""Return what a submission lacks against its contract; empty means it's complete."""
|
||||
if not content.strip():
|
||||
return ("content: must not be empty",)
|
||||
|
||||
spec = DEPENDENCY_GRAPH[kind]
|
||||
headings = [_normalise(match) for match in _HEADING.findall(content)]
|
||||
missing = []
|
||||
for section in spec.sections:
|
||||
required = _normalise(section)
|
||||
if not any(h == required or h.endswith(" " + required) for h in headings):
|
||||
missing.append(f"section: {section}")
|
||||
for name in spec.attachments:
|
||||
if name not in attachments:
|
||||
missing.append(f"attachment: {name}")
|
||||
return tuple(missing)
|
||||
317
app/execution/ledger.py
Normal file
317
app/execution/ledger.py
Normal file
@@ -0,0 +1,317 @@
|
||||
"""The Ledger: every rule code owns about Deliverable progress, Approvals and Revisions.
|
||||
|
||||
Pure and synchronous: no I/O, no framework types. Invalid requests raise
|
||||
LedgerRefusal and leave the Ledger unchanged; tools turn refusals into messages
|
||||
the agent can act on.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
from app.execution.deliverables import (
|
||||
DEPENDENCY_GRAPH,
|
||||
PHASE_ORDER,
|
||||
DeliverableKind,
|
||||
PhaseId,
|
||||
deliverables_in,
|
||||
)
|
||||
|
||||
PRE_APPROVED_ACTOR = "pre-approved"
|
||||
|
||||
|
||||
class DeliverableStatus(StrEnum):
|
||||
PENDING = "pending"
|
||||
IN_PROGRESS = "in_progress"
|
||||
SUBMITTED = "submitted"
|
||||
|
||||
|
||||
class PhaseStatus(StrEnum):
|
||||
OPEN = "open"
|
||||
AWAITING_APPROVAL = "awaiting_approval"
|
||||
APPROVED = "approved"
|
||||
|
||||
|
||||
class LedgerRefusal(Exception):
|
||||
"""A request the Ledger's rules don't allow. Nothing was changed."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LedgerEvent:
|
||||
sequence: int
|
||||
type: str # started | released | submitted | approval_requested | approved |
|
||||
# changes_requested | reopened | reset | approval_withdrawn | escalated
|
||||
subject: str # a DeliverableKind or PhaseId value
|
||||
actor: str
|
||||
detail: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReopenResult:
|
||||
reset: tuple[DeliverableKind, ...]
|
||||
withdrawn_approvals: tuple[PhaseId, ...]
|
||||
escalation: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class _DeliverableRecord:
|
||||
status: DeliverableStatus = DeliverableStatus.PENDING
|
||||
attempt: int = 0
|
||||
revisions: int = 0
|
||||
feedback: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
class Ledger:
|
||||
def __init__(self, pre_approved: bool = False, max_revisions: int = 3) -> None:
|
||||
self.pre_approved = pre_approved
|
||||
self.max_revisions = max_revisions
|
||||
self._deliverables = {kind: _DeliverableRecord() for kind in DEPENDENCY_GRAPH}
|
||||
self._phases = {phase: PhaseStatus.OPEN for phase in PHASE_ORDER}
|
||||
self._events: list[LedgerEvent] = []
|
||||
|
||||
# --- queries -----------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def events(self) -> tuple[LedgerEvent, ...]:
|
||||
return tuple(self._events)
|
||||
|
||||
def status(self, kind: DeliverableKind) -> DeliverableStatus:
|
||||
return self._deliverables[kind].status
|
||||
|
||||
def phase_status(self, phase: PhaseId) -> PhaseStatus:
|
||||
return self._phases[phase]
|
||||
|
||||
def revisions(self, kind: DeliverableKind) -> int:
|
||||
return self._deliverables[kind].revisions
|
||||
|
||||
def feedback(self, kind: DeliverableKind) -> tuple[str, ...]:
|
||||
return tuple(self._deliverables[kind].feedback)
|
||||
|
||||
def dependencies_met(self, kind: DeliverableKind) -> bool:
|
||||
spec = DEPENDENCY_GRAPH[kind]
|
||||
for dependency in spec.depends_on:
|
||||
dependency_phase = DEPENDENCY_GRAPH[dependency].phase
|
||||
if dependency_phase is spec.phase:
|
||||
if self.status(dependency) is not DeliverableStatus.SUBMITTED:
|
||||
return False
|
||||
elif self._phases[dependency_phase] is not PhaseStatus.APPROVED:
|
||||
return False
|
||||
return True
|
||||
|
||||
def ready_work(self) -> tuple[DeliverableKind, ...]:
|
||||
return tuple(
|
||||
kind
|
||||
for kind in DEPENDENCY_GRAPH
|
||||
if self.status(kind) is DeliverableStatus.PENDING
|
||||
and self.dependencies_met(kind)
|
||||
)
|
||||
|
||||
def phases_ready_for_approval(self) -> tuple[PhaseId, ...]:
|
||||
return tuple(
|
||||
phase
|
||||
for phase in PHASE_ORDER
|
||||
if self._phases[phase] is PhaseStatus.OPEN and not self._unsubmitted(phase)
|
||||
)
|
||||
|
||||
def can_finish(self) -> bool:
|
||||
return self._phases[PHASE_ORDER[-1]] is PhaseStatus.APPROVED
|
||||
|
||||
# --- delegation and submission -----------------------------------------------
|
||||
|
||||
def start(
|
||||
self, kinds: Iterable[DeliverableKind], actor: str
|
||||
) -> dict[DeliverableKind, int]:
|
||||
"""Move ready Deliverables in progress; returns the attempt number for each."""
|
||||
kinds = list(dict.fromkeys(kinds))
|
||||
ready = set(self.ready_work())
|
||||
not_ready = [kind for kind in kinds if kind not in ready]
|
||||
if not_ready:
|
||||
raise LedgerRefusal(
|
||||
"Not ready to start: "
|
||||
+ ", ".join(self._describe_unready(k) for k in not_ready)
|
||||
)
|
||||
attempts = {}
|
||||
for kind in kinds:
|
||||
record = self._deliverables[kind]
|
||||
record.status = DeliverableStatus.IN_PROGRESS
|
||||
record.attempt += 1
|
||||
attempts[kind] = record.attempt
|
||||
self._record("started", kind, actor, f"attempt {record.attempt}")
|
||||
return attempts
|
||||
|
||||
def submit(self, kind: DeliverableKind, attempt: int, actor: str) -> None:
|
||||
"""Accept the current attempt. Any later start, release or reopen supersedes it."""
|
||||
self._require_current_attempt(kind, attempt)
|
||||
self._deliverables[kind].status = DeliverableStatus.SUBMITTED
|
||||
self._record("submitted", kind, actor, f"attempt {attempt}")
|
||||
|
||||
def release(self, kind: DeliverableKind, attempt: int, reason: str) -> None:
|
||||
"""Return in-progress work to pending (e.g. the Specialist needs input)."""
|
||||
self._require_current_attempt(kind, attempt)
|
||||
record = self._deliverables[kind]
|
||||
record.status = DeliverableStatus.PENDING
|
||||
self._record("released", kind, DEPENDENCY_GRAPH[kind].specialist, reason)
|
||||
|
||||
# --- approvals ---------------------------------------------------------------
|
||||
|
||||
def request_approval(self, phase: PhaseId, actor: str) -> None:
|
||||
if self._phases[phase] is not PhaseStatus.OPEN:
|
||||
raise LedgerRefusal(f"Phase {phase} is {self._phases[phase]}, not open")
|
||||
unsubmitted = self._unsubmitted(phase)
|
||||
if unsubmitted:
|
||||
raise LedgerRefusal(
|
||||
f"Phase {phase} has unsubmitted Deliverables: {', '.join(unsubmitted)}"
|
||||
)
|
||||
self._phases[phase] = PhaseStatus.AWAITING_APPROVAL
|
||||
self._record("approval_requested", phase, actor)
|
||||
if self.pre_approved:
|
||||
self.approve(phase, actor=PRE_APPROVED_ACTOR)
|
||||
|
||||
def approve(self, phase: PhaseId, actor: str) -> None:
|
||||
self._require_awaiting(phase)
|
||||
self._phases[phase] = PhaseStatus.APPROVED
|
||||
self._record("approved", phase, actor)
|
||||
|
||||
def request_changes(self, phase: PhaseId, feedback: str, actor: str) -> None:
|
||||
self._require_awaiting(phase)
|
||||
self._phases[phase] = PhaseStatus.OPEN
|
||||
self._record("changes_requested", phase, actor, feedback)
|
||||
|
||||
# --- revisions ---------------------------------------------------------------
|
||||
|
||||
def reopen(
|
||||
self,
|
||||
kind: DeliverableKind,
|
||||
reason: str,
|
||||
actor: str,
|
||||
override_cap: bool = False,
|
||||
) -> ReopenResult:
|
||||
record = self._deliverables[kind]
|
||||
if record.status is not DeliverableStatus.SUBMITTED:
|
||||
raise LedgerRefusal(
|
||||
f"Only submitted Deliverables can be reopened; {kind} is {record.status}"
|
||||
)
|
||||
if record.revisions >= self.max_revisions and not override_cap:
|
||||
escalation = (
|
||||
f"{kind} has reached its revision limit ({self.max_revisions}). "
|
||||
f"Requested change: {reason}. Ask the user whether to revise it again "
|
||||
"or accept it as it stands."
|
||||
)
|
||||
self._record("escalated", kind, actor, reason)
|
||||
return ReopenResult(reset=(), withdrawn_approvals=(), escalation=escalation)
|
||||
|
||||
record.status = DeliverableStatus.PENDING
|
||||
record.revisions += 1
|
||||
record.feedback.append(reason)
|
||||
self._record("reopened", kind, actor, reason)
|
||||
reset = [kind]
|
||||
|
||||
for dependent in self._dependents_of(kind):
|
||||
dependent_record = self._deliverables[dependent]
|
||||
if dependent_record.status is DeliverableStatus.PENDING:
|
||||
continue
|
||||
dependent_record.status = DeliverableStatus.PENDING
|
||||
dependent_record.feedback.append(f"Dependency {kind} was revised: {reason}")
|
||||
self._record("reset", dependent, actor, f"dependency {kind} reopened")
|
||||
reset.append(dependent)
|
||||
|
||||
withdrawn = []
|
||||
for phase in PHASE_ORDER:
|
||||
affected = any(DEPENDENCY_GRAPH[k].phase is phase for k in reset)
|
||||
if affected and self._phases[phase] is not PhaseStatus.OPEN:
|
||||
self._phases[phase] = PhaseStatus.OPEN
|
||||
self._record("approval_withdrawn", phase, actor, f"{kind} reopened")
|
||||
withdrawn.append(phase)
|
||||
|
||||
return ReopenResult(reset=tuple(reset), withdrawn_approvals=tuple(withdrawn))
|
||||
|
||||
# --- persistence -------------------------------------------------------------
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"pre_approved": self.pre_approved,
|
||||
"max_revisions": self.max_revisions,
|
||||
"deliverables": {
|
||||
kind.value: {
|
||||
"status": record.status.value,
|
||||
"attempt": record.attempt,
|
||||
"revisions": record.revisions,
|
||||
"feedback": list(record.feedback),
|
||||
}
|
||||
for kind, record in self._deliverables.items()
|
||||
},
|
||||
"phases": {
|
||||
phase.value: status.value for phase, status in self._phases.items()
|
||||
},
|
||||
"events": [asdict(event) for event in self._events],
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict[str, Any]) -> Ledger:
|
||||
ledger = cls(
|
||||
pre_approved=data["pre_approved"], max_revisions=data["max_revisions"]
|
||||
)
|
||||
for kind_value, record in data["deliverables"].items():
|
||||
ledger._deliverables[DeliverableKind(kind_value)] = _DeliverableRecord(
|
||||
status=DeliverableStatus(record["status"]),
|
||||
attempt=record["attempt"],
|
||||
revisions=record["revisions"],
|
||||
feedback=list(record["feedback"]),
|
||||
)
|
||||
for phase_value, status in data["phases"].items():
|
||||
ledger._phases[PhaseId(phase_value)] = PhaseStatus(status)
|
||||
ledger._events = [LedgerEvent(**event) for event in data["events"]]
|
||||
return ledger
|
||||
|
||||
# --- internals ---------------------------------------------------------------
|
||||
|
||||
def _record(self, type_: str, subject: str, actor: str, detail: str = "") -> None:
|
||||
self._events.append(
|
||||
LedgerEvent(len(self._events) + 1, type_, str(subject), actor, detail)
|
||||
)
|
||||
|
||||
def _unsubmitted(self, phase: PhaseId) -> list[DeliverableKind]:
|
||||
return [
|
||||
kind
|
||||
for kind in deliverables_in(phase)
|
||||
if self.status(kind) is not DeliverableStatus.SUBMITTED
|
||||
]
|
||||
|
||||
def _dependents_of(self, kind: DeliverableKind) -> list[DeliverableKind]:
|
||||
"""Every Deliverable that depends on `kind`, directly or not, in graph order."""
|
||||
dependents: set[DeliverableKind] = set()
|
||||
frontier = {kind}
|
||||
while frontier:
|
||||
frontier = {
|
||||
candidate
|
||||
for candidate, spec in DEPENDENCY_GRAPH.items()
|
||||
if candidate not in dependents and frontier & set(spec.depends_on)
|
||||
}
|
||||
dependents |= frontier
|
||||
return [candidate for candidate in DEPENDENCY_GRAPH if candidate in dependents]
|
||||
|
||||
def _describe_unready(self, kind: DeliverableKind) -> str:
|
||||
status = self.status(kind)
|
||||
if status is not DeliverableStatus.PENDING:
|
||||
return f"{kind} ({status})"
|
||||
return f"{kind} (dependencies not met)"
|
||||
|
||||
def _require_current_attempt(self, kind: DeliverableKind, attempt: int) -> None:
|
||||
record = self._deliverables[kind]
|
||||
if (
|
||||
record.status is not DeliverableStatus.IN_PROGRESS
|
||||
or attempt != record.attempt
|
||||
):
|
||||
raise LedgerRefusal(
|
||||
f"{kind} is {record.status}, not in_progress with attempt {attempt}; "
|
||||
"this attempt is not current"
|
||||
)
|
||||
|
||||
def _require_awaiting(self, phase: PhaseId) -> None:
|
||||
if self._phases[phase] is not PhaseStatus.AWAITING_APPROVAL:
|
||||
raise LedgerRefusal(
|
||||
f"Phase {phase} is {self._phases[phase]}, not awaiting_approval"
|
||||
)
|
||||
Reference in New Issue
Block a user