Files
cp1-agents/sub-agents/ALZ-F01: Discovery Workflow Agent/scripts/build_workflow.py
Jonathan Boniface 8bb62a4a42 ALZ-F01 Discovery sub-agent pattern: report phase and fetch in code
Orchestrator report phase (ADR 0013) and fetching in code (ADR 0014), with the report renderer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 22:13:25 +00:00

154 lines
8.0 KiB
Python

#!/usr/bin/env python3
"""Write workflows/cp1-alz-discovery.json: the KAB workflow export for ALZ-F01 Discovery.
The same export format as cp4-agents' workflow (export_version 2.0.0). Four steps call the one orchestrator agent,
one per phase. The report step stops for approval. A step can pass only workflow inputs and earlier steps' outputs, so step 1 sends no phase (the agent
plans a new run) and each later step sends the previous step's next_phase. The critique step stops for the
Engagement Lead's approval. The step schemas are the agent's own contract, read from its schemas/ folder, so run
this again after changing them. Standard library only.
Front steps (ADR 0012, the repository's scripts/kab_front_steps.py), feeding the plan step only -- the orchestrator imports them into
its workspace and its sub-agents see only records:
u1 Parse Assessment Files: the run form's upload field `file` -> plan step's `source_documents`
a1 Artifacts: project artifacts fixed by id -> plan step's `artifacts`
Usage (from the Feature folder): python3 scripts/build_workflow.py [--no-upload] [--artifact-id ID ...] [--out FILE]
(the committed export is the default: with the upload step, no artifacts)
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
# kab_front_steps is shared by every Feature, in the repository's scripts/ folder.
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "scripts"))
from kab_front_steps import AGENT_STEP_TIMEOUT_MINUTES, ARTIFACTS_ID, UPLOAD_ID, front_steps, shift # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
AGENT = "cp1-alz-discovery-orchestrator-agent"
AGENT_ID = AGENT.replace("-", "_")
DISPLAY = "CP1 - ALZ Discovery Orchestrator Agent"
URL = f"http://{AGENT}.agents.svc.cluster.local:8080"
NAME = "CP1 - Agentic Landing Zone - Discovery"
STAMP = "2026-10-29T12:00:00"
PHASES = [
("plan", "Turn the scope, sources and budgets into a task graph that accounts for every scope entry."),
("collect", "Ingest CMDB / ITSM records and scan the planned targets into one finding per scope entry."),
("analyse", "Build the canonical inventory, CMDB drift, data classification, network map and dependency graph."),
("critique", "Validate coverage, injection handling, evidence and tool-call integrity; the verdict is enforced in code."),
("report", "Write the customer's report as Markdown and HTML, in code, from the run's records. No model is called."),
]
def build(with_upload: bool = True, artifact_ids=()) -> dict:
schemas = ROOT / AGENT / "schemas"
input_schema = json.loads((schemas / "input.json").read_text())
output_schema = json.loads((schemas / "output.json").read_text())
front = front_steps(
with_upload, list(artifact_ids), upload_label="Discovery source files",
upload_description="Optional client files for discovery: a CMDB or asset export, a scope list, network "
"documentation. They are imported into the run's workspace and given to the planner "
"and the inventory and CMDB steps as evidence, never as instructions.",
artifacts_description="Project artifacts for discovery, e.g. an earlier run's outputs. Imported into the "
"run's workspace with their id, type and hash as provenance.")
lead = 1 if front else 0
steps, connections = list(front), []
for index, (phase, description) in enumerate(PHASES):
step_id = f"s{index + 1}"
inputs = {"from_workflow": ["engagement_id", "run_id"] + ([] if index else ["include_cmdb", "include_itsm"])}
depends = [f"s{index}"] if index else []
if index:
inputs["from_steps"] = {"phase": f"s{index}.next_phase"}
connections.append({"source": f"s{index}", "target": step_id})
else:
# Only the plan step takes files: the orchestrator imports them; its sub-agents get records.
wired = {}
if any(f["id"] == UPLOAD_ID for f in front):
wired["source_documents"] = f"{UPLOAD_ID}.parsed_content"
if any(f["id"] == ARTIFACTS_ID for f in front):
wired["artifacts"] = f"{ARTIFACTS_ID}.artifacts"
if wired:
inputs["from_steps"] = wired
for f in front:
depends.append(f["id"])
connections.append({"source": f["id"], "target": step_id})
hitl = {"enabled": False}
if phase == "report":
hitl = {
"enabled": True,
"checkpoint_type": "approval",
"review_focus": "The Engagement Lead reads the report, with the verdict, declared gaps and SME queues, before "
"Assessment starts. A fail verdict is never auto-approved.",
"timeout_hours": 24,
"allowed_actions": ["continue", "rerun", "abort"],
"max_reruns": 2,
}
step_name = f"{DISPLAY} - {phase} Step"
steps.append(shift({
"id": step_id,
"agent": AGENT_ID,
"agent_type": AGENT_ID,
"name": step_name,
"timeout_minutes": AGENT_STEP_TIMEOUT_MINUTES,
"type": "sequential",
"executionLevel": index,
"parallelGroup": index,
"depends_on": depends,
"position": {"x": 320 * index, "y": 0},
"inputs": inputs,
"hitl": hitl,
"data": {
"agentType": AGENT_ID,
"name": step_name,
"description": f"Phase {phase}: {description}",
"category": "agent",
"temporalActivityName": "generic_agent_call",
"endpoint": {"url": URL, "method": "POST", "timeout": AGENT_STEP_TIMEOUT_MINUTES * 60, "protocol": "JSONRPC",
"protocol_version": "0.3.0"},
"agent_metadata": {"agent_name": AGENT_ID},
"inputSchema": input_schema,
"outputSchema": output_schema,
},
}, lead))
description = f"{NAME}: {DISPLAY} runs plan; then collect; then analyse; then critique (Engagement Lead approval)."
return {
"export_version": "2.0.0",
"export_timestamp": STAMP,
"source_environment": "unknown",
"workflow": {"name": NAME, "description": description, "version": "0.2.0",
"category": "cross-industry-catalog", "sub_category": "Public Cloud",
"tags": ["cp1", "public-cloud", "agentic-landing-zone"]},
"dependencies": {"activities": [],
"agents": [{"name": AGENT_ID, "display_name": DISPLAY, "source_url": URL, "category": "agent"}]},
"template": {
"name": NAME, "version": "0.2.0", "description": description,
"metadata": {"name": NAME, "description": description,
"category": {"main": "cross-industry-catalog", "sub": "Public Cloud"},
"sub_category": "Public Cloud", "status": "draft",
"tags": ["cp1", "public-cloud", "agentic-landing-zone"],
"created": f"{STAMP}.000Z", "modified": f"{STAMP}.000Z",
"display_order": 1, "is_public": False, "edge_visuals": []},
"connections": connections,
"steps": steps,
},
}
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--no-upload", action="store_true", help="leave out the Parse Assessment Files step")
parser.add_argument("--artifact-id", action="append", default=[], help="add an Artifacts step with this id")
parser.add_argument("--out", type=Path, default=ROOT / "workflows" / "cp1-alz-discovery.json")
args = parser.parse_args(argv)
export = build(not args.no_upload, args.artifact_id)
args.out.write_text(json.dumps(export, indent=2) + "\n")
print(f"wrote {args.out}: {len(export['template']['steps'])} steps")
return 0
if __name__ == "__main__":
raise SystemExit(main())