"""Presenting an Execution to callers: prompt text and the /generate response shape.""" from __future__ import annotations import re from collections.abc import Mapping, Sequence from typing import Any from execution_engine.adk.runtime import RoleSpec from execution_engine.agent import Interaction from execution_engine.presentation import describe_prompt as _describe_prompt def describe_prompt(prompt: Mapping[str, Any]) -> str: """What the user is asked, with what this Workflow's Approvals commit to.""" return _describe_prompt( prompt, lambda approval: ( _describe_changes(approval) + _describe_target_architecture(approval.get("target_architecture")) ), ) _CHANGE_WORDS = {"added": "Added", "changed": "Changed", "removed": "Removed"} def _describe_changes(approval: Mapping[str, Any]) -> str: """In a Change request: what this Phase changes against the Baseline. It comes from the ids in the two versions, not from an agent's account.""" if "changes" not in approval: return "" changes = approval["changes"] lines = [f"This changes the architecture delivered in {approval.get('baseline')}."] if not changes: lines.append("Nothing in this Phase differs from it.") for item in changes.get("requirements", []): lines.append( f"- Requirement {item['id']} {item['change']}: {item['text']} " f"({item['reason']})" ) for part in ( "components", "recommendations", "elements", "relationships", "checks", ): for change, word in _CHANGE_WORDS.items(): ids = changes.get(part, {}).get(change) if ids: lines.append(f"- {word} {part}: {', '.join(ids)}") for part, ids in changes.get("unrequested", {}).items(): lines.append( f"- Changed without being asked for ({part}): {', '.join(ids)}. No " "changed requirement reaches these." ) return "\n".join(lines) + "\n\n" def _describe_target_architecture(summary: Mapping[str, Any] | None) -> str: """What the design Approval commits to: no code is written until it is granted.""" if not summary: return "" text = ( f"The Target architecture has {summary['elements']} Elements, " f"{summary['relationships']} Relationships and {summary['checks']} Checks. " "No infrastructure code is written until you approve it; the code is then " "validated against those Checks.\n\n" ) for item in summary.get("not_applicable", []): text += ( f"Recommendation {item['recommendation']} is treated as not applicable: " f"{item['reason']}\n" ) return text + ("\n" if summary.get("not_applicable") else "") def to_generate_response( interaction: Interaction, roles: Mapping[str, RoleSpec] ) -> dict[str, Any]: """Map an Execution onto the legacy /generate response keys.""" from app.solution_architecture.workflow import DeliverableKind state = interaction.state deliverables: Mapping[str, Mapping[str, Any]] = state.get("deliverables", {}) ledger = state.get("ledger", {}) def content(kind: str) -> str | None: item = deliverables.get(kind) return item["content"] if item else None def attachment(kind: str, name: str) -> str | None: item = deliverables.get(kind) return item.get("attachments", {}).get(name) if item else None requirements = content(DeliverableKind.REQUIREMENTS) revisions = sum( d.get("revisions", 0) for d in ledger.get("deliverables", {}).values() ) submitted = [kind for kind in DeliverableKind if kind in deliverables] skills = _skills_used(submitted, roles) status = { "completed": "success", "completed_with_warnings": "completed_with_warnings", }.get(interaction.status, interaction.status) return { "execution_id": interaction.execution_id, "session_id": state.get("session_id"), "status": status, "validation_passed": interaction.status == "completed", "total_loop_iterations": revisions + 1, "current_phase": _current_phase(ledger), "artifacts": { "source_discovery_doc": _section(requirements, "Current state"), "source_mermaid_diagram": None, "requirements_doc": requirements, "architecture_doc": content(DeliverableKind.ARCHITECTURE_DESCRIPTION), "mermaid_diagram": attachment( DeliverableKind.TARGET_ARCHITECTURE, "architecture.mmd" ), "terraform_code": attachment( DeliverableKind.DEPLOYMENT_GUIDANCE, "terraform/main.tf" ), "validation_results": content(DeliverableKind.VALIDATION_RESULTS), "solution_guide": content(DeliverableKind.SOLUTION_GUIDE), }, "active_skills": skills, "warnings": list(state.get("warnings", [])), } def _skills_used(submitted: Sequence[str], roles: Mapping[str, RoleSpec]) -> list[str]: from app.solution_architecture.workflow import DEPENDENCY_GRAPH names: list[str] = [] for kind in submitted: role = roles.get(DEPENDENCY_GRAPH[kind].specialist) for skill in role.skills if role else (): if skill not in names: names.append(skill) return names def _current_phase(ledger: Mapping[str, Any]) -> str | None: phases: Mapping[str, str] = ledger.get("phases", {}) for phase, status in phases.items(): if status != "approved": return phase return list(phases)[-1] if phases else None def _section(markdown: str | None, heading: str) -> str | None: """The body under a heading (any level, numbering ignored), up to the next heading.""" if not markdown: return None lines = markdown.splitlines() pattern = re.compile( rf"^#{{1,6}}\s+(?:\d+(?:\.\d+)*\.?\s+)?{re.escape(heading)}\s*$", re.IGNORECASE ) for index, line in enumerate(lines): if pattern.match(line.strip()): level = len(line.strip()) - len(line.strip().lstrip("#")) body = [] for following in lines[index + 1 :]: stripped = following.strip() hashes = len(stripped) - len(stripped.lstrip("#")) if stripped.startswith("#") and hashes <= level: break body.append(following) return "\n".join(body).strip() or None return None