Some checks failed
check agents / check (push) Failing after 13s
The cp1-solution-architecture-agent and the sa-aws/azure/gcp-cloud MCP servers, a separate stream from the individual and sub-agent patterns. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
198 lines
7.7 KiB
Python
198 lines
7.7 KiB
Python
"""Presenting an Execution to callers: prompt text and the /generate response shape."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
from collections.abc import Mapping, Sequence
|
|
from typing import Any
|
|
|
|
from app.engine.runtime import RoleSpec
|
|
from app.engine.agent import Interaction
|
|
from app.core.deliverables import DEPENDENCY_GRAPH, DeliverableKind
|
|
|
|
|
|
def describe_prompt(prompt: Mapping[str, Any]) -> str:
|
|
"""Plain-text rendering of what the user is asked, including how to answer."""
|
|
if "approval" in prompt:
|
|
approval = prompt["approval"]
|
|
reply = {"approval": {"phase": approval["phase"], "decision": "approve"}}
|
|
changes = {
|
|
"approval": {
|
|
"phase": approval["phase"],
|
|
"decision": "changes",
|
|
"feedback": "<what to change>",
|
|
}
|
|
}
|
|
return (
|
|
f"Please review the {approval['phase']} Phase: {approval['summary']}\n\n"
|
|
f"Deliverables: {', '.join(approval['deliverables'])}.\n\n"
|
|
f"{_describe_changes(approval)}"
|
|
f"{_describe_target_architecture(approval.get('target_architecture'))}"
|
|
f"To approve, reply with the data {json.dumps(reply)}. "
|
|
f"To request changes, reply with {json.dumps(changes)}. "
|
|
"A text reply is recorded as conversation and never approves."
|
|
)
|
|
if "permission" in prompt:
|
|
permission = prompt["permission"]
|
|
grant = {"permission": {permission["tier"]: True}}
|
|
return (
|
|
"May I read live resources in your cloud environment to discover the current "
|
|
f"state? Requested by: {', '.join(permission['requested_by'])}.\n\n"
|
|
f"To allow, reply with the data {json.dumps(grant)}; to refuse, use false."
|
|
)
|
|
lines = [
|
|
f"{index}. ({item['from']}) {item['question']}"
|
|
for index, item in enumerate(prompt.get("questions", []), start=1)
|
|
]
|
|
return "\n".join(lines) + "\n\nReply in text; answer every question you can."
|
|
|
|
|
|
_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."""
|
|
state = interaction.state
|
|
deliverables: Mapping[str, Mapping[str, Any]] = state.get("deliverables", {})
|
|
ledger = state.get("ledger", {})
|
|
|
|
def content(kind: DeliverableKind) -> str | None:
|
|
item = deliverables.get(kind.value)
|
|
return item["content"] if item else None
|
|
|
|
def attachment(kind: DeliverableKind, name: str) -> str | None:
|
|
item = deliverables.get(kind.value)
|
|
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.value 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[DeliverableKind], roles: Mapping[str, RoleSpec]
|
|
) -> list[str]:
|
|
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
|