"""What each application is, from the Discovery package (F02 ADR 0015, addendum of 2026-11-08), worked out in code. The Assessment steps' outputs name an application's assets by id only, so a report written from them can say what was decided but not what the application is. This reads the Discovery package the intake verified (`discovery_documents`) and gives, per application: how Discovery identified it, its owner and business service, each asset (name, type, environment, location, criticality, CMDB record, data class, support and cost facts), its data stores, and its dependencies (a `represents` edge, a CMDB record matched to its own asset, is not one: ADR 0012). The package is found as the intake finds it (`cp1-assessment-intake-agent/app/intake.py`); the intake has already verified it, so it is read here, not checked again. Standard library only. """ from __future__ import annotations import json from typing import Any, Dict, Iterator, List, Optional FILE_SEPARATOR = "\n\n---\n\n" # the platform's join between parsed files, as in the intake def _decode(value: Any, depth: int = 0) -> Any: while isinstance(value, str) and depth < 3: try: value, depth = json.loads(value), depth + 1 except ValueError: return value return value def _packages(value: Any, depth: int = 0) -> Iterator[Dict[str, Any]]: value = _decode(value) if depth > 6: return if isinstance(value, dict): if "package_version" in value and isinstance(value.get("manifest"), dict): yield value return for item in value.values(): yield from _packages(item, depth + 1) elif isinstance(value, list): for item in value: yield from _packages(item, depth + 1) def package(documents: Optional[str]) -> Optional[Dict[str, Any]]: found = [p for doc in (documents or "").split(FILE_SEPARATOR) for p in _packages(doc.strip())] return found[0] if len(found) == 1 else None def _part(pkg: dict, part: str, field: str) -> List[dict]: return [x for x in ((pkg.get(part) or {}).get(field) or []) if isinstance(x, dict)] def _asset(record: dict, ci: dict, node: dict, store: dict) -> dict: attrs = record.get("provider_attributes") or {} facts = record.get("facts") or {} sku = attrs.get("sku") if isinstance(attrs.get("sku"), dict) else {} return { "canonical_id": record.get("canonical_id"), "name": record.get("hostname") or ci.get("name") or node.get("name"), "resource_type": attrs.get("type"), "asset_class": record.get("asset_class"), "environment": record.get("environment"), "location": attrs.get("location") or facts.get("site"), "criticality": facts.get("criticality"), "services": record.get("services") or [], "os": (record.get("os") or {}).get("family") or None, "size": attrs.get("machineSize") or attrs.get("vmSize") or sku.get("name"), "tier": sku.get("tier"), "state": attrs.get("state") or attrs.get("provisioningState"), "public_address": attrs.get("publicAddress"), "support_status": facts.get("support_status"), "end_of_support": facts.get("end_of_support"), "annual_cost": facts.get("annual_cost"), "compliance_scope": facts.get("compliance_scope"), "inventory_confidence": record.get("confidence"), "conflicts": len(record.get("conflicts") or []), "cmdb": {"ci_ref": ci.get("ci_ref"), "ci_class": ci.get("ci_class"), "lifecycle": ci.get("lifecycle"), "support_group": ci.get("support_group"), "owner": ci.get("owner")} if ci else None, "retire_constraint": node.get("retire_constraint"), "data_class": store.get("highest_class") if store else None, "data_class_reason": store.get("reason") if store else None, } def applications(documents: Optional[str]) -> Dict[str, Any]: """Per application id, what Discovery recorded about it; `found` says whether the package was read.""" pkg = package(documents) if pkg is None: return {"found": False, "note": "The Discovery package was not among discovery_documents, so the application's " "make-up isn't known to this report.", "applications": {}} records = {r.get("canonical_id"): r for r in _part(pkg, "inventory", "records")} cis = {c.get("matched_canonical_id"): c for c in _part(pkg, "cmdb", "cis") if c.get("matched_canonical_id")} nodes = {n.get("id"): n for n in _part(pkg, "dependencies", "nodes")} stores = {s.get("canonical_id"): s for s in _part(pkg, "classification", "stores")} edges = [e for e in _part(pkg, "dependencies", "edges") if e.get("type") != "represents"] queue = set((pkg.get("dependencies") or {}).get("validation_queue") or []) out: Dict[str, Any] = {} for app in _part(pkg, "applications", "applications"): members = list(app.get("members") or []) own = set(members) name = lambda ref: (nodes.get(ref) or {}).get("name") or (records.get(ref) or {}).get("hostname") or ref links = [] for e in edges: src, dst = e.get("source"), e.get("target") if src not in own and dst not in own: continue links.append({"edge_id": e.get("edge_id"), "type": e.get("type"), "direction": "internal" if src in own and dst in own else "outbound" if src in own else "inbound", "from": name(src), "to": name(dst), "confidence": e.get("confidence"), "validation": "awaiting validation" if e.get("edge_id") in queue else e.get("validation")}) out[app.get("application_id")] = { "application_id": app.get("application_id"), "name": app.get("name"), "identified_by": app.get("basis"), "business_service": app.get("business_service"), "owner": app.get("owner"), "owners_disagree": app.get("owners_disagree"), "review_required": app.get("review_required"), "review_reasons": app.get("review_reasons") or [], "assets": [_asset(records.get(m) or {"canonical_id": m}, cis.get(m) or {}, nodes.get(m) or {}, stores.get(m) or {}) for m in members], "data_stores": [{"canonical_id": s.get("canonical_id"), "name": s.get("store_name"), "highest_class": s.get("highest_class"), "reason": s.get("reason")} for m, s in stores.items() if m in own], "dependencies": links, } return {"found": True, "discovery_run_id": pkg.get("run_id"), "applications": out}