"""A live run's CMDB reconciliation: uploaded exports normalised by the model and judged and reconciled in code (ADR 0018). The sample estate keeps the agent loop and the alz-cmdb tools.""" import asyncio import json import os from pathlib import Path from typing import Any, Dict, Optional import jsonschema import structlog from kyndryl_agent_runtime import ask_sub_agent from kyndryl_agent_runtime.request_cycle import Reply from kyndryl_agent_runtime.tools import call_tool from app import live logger = structlog.get_logger(__name__) OUTPUT_SCHEMA = json.loads((Path(__file__).resolve().parents[1] / "schemas" / "output.json").read_text()) def _setting(name: str, default: int) -> int: try: return max(1, int(os.getenv(name, default))) except ValueError: return default async def pre_process(payload: dict) -> Optional[Any]: if payload.get("provider", "sample") not in ("azure", "gcp"): return None # the Meridian sample estate: prompt.md and the alz-cmdb tools, unchanged async def ask(prompt: str) -> str: return await ask_sub_agent("normalise_cmdb_batch", prompt) async def ask_relationships(prompt: str) -> str: return await ask_sub_agent("normalise_cmdb_relationship_batch", prompt) async def listing(provider: str): return await asyncio.to_thread(live.list_scope, provider, call_tool) result: Dict[str, Any] = await live.build( payload, ask, listing, batch_size=_setting("CMDB_BATCH_SIZE", 25), max_tries=_setting("CMDB_MAX_TRIES", 3), log=lambda event, **fields: logger.info(event, **fields), ask_relationships=ask_relationships, ) errors = sorted(jsonschema.Draft202012Validator(OUTPUT_SCHEMA).iter_errors(result), key=lambda e: list(e.path)) if errors: # a Reply can't be repaired by the output contract, so a broken one fails the step here raise live.cmdb.CmdbFailed(f"the reconciliation broke its output schema: {errors[0].message}") return Reply(json.dumps(result, ensure_ascii=False))