from __future__ import annotations import argparse import hashlib import json import shutil import subprocess import zipfile from datetime import datetime, timezone from pathlib import Path from typing import Any SOURCE_REMOTE = "https://github.com/aws-samples/aws-mainframe-modernization-carddemo.git" SOURCE_HEAD = "59cc6c2fd7ebd7ef7925cad552a01a4b8b6e4d5e" REPORT_VERSION = "carddemo_a_grade_promotion_gate_v0" README_VERSION = "carddemo_a_grade_promotion_readme_v0" ACCEPTED_TRACE_KINDS = {"live_cobol_cics_runtime", "live_mainframe_runtime"} TRACE_HASH_FIELDS = ("raw_legacy_trace_hash", "legacy_runtime_trace_hash") REQUIRED_TRACE_FIELDS = ( "capability_id", "trace_kind", "source_head", "legacy_runtime_environment", "modern_observation_hash", "comparator_version", ) RUNTIME_TOOL_PROBES = { "cobc": "GnuCOBOL compiler; useful for limited COBOL probes, not sufficient for CICS/VSAM/JCL parity.", "aws": "AWS CLI; needed for AWS-hosted M2/Mainframe runtime paths.", "java": "JVM; required by several migration/runtime toolchains.", "mvn": "Maven; useful for Java-based runtime harnesses.", "gradle": "Gradle; useful for Java-based runtime harnesses.", "hercules": "Mainframe emulator; still not a CICS/VSAM/JCL runtime by itself.", "tn3270": "3270 terminal client; useful for interactive CICS transaction capture.", "docker": "Container runtime; useful only when a licensed/runnable legacy runtime image exists.", } M2_RUNTIME_ZIPS = ( Path("samples/m2/mf/CardDemo_runtime.zip"), Path("samples/m2/unikix/UniKix_CardDemo_runtime_v1.zip"), ) def read_json(path: Path) -> Any: return json.loads(path.read_text(encoding="utf-8")) def write_json(path: Path, payload: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(payload, indent=2, sort_keys=True, default=str) + "\n", encoding="utf-8") def write_text(path: Path, text: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text.strip() + "\n", encoding="utf-8") def stable_hash(payload: Any) -> str: return hashlib.sha256(json.dumps(payload, sort_keys=True, default=str).encode("utf-8")).hexdigest() def sha256_path(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def is_sha256(value: Any) -> bool: if not isinstance(value, str) or len(value) != 64: return False return all(ch in "0123456789abcdefABCDEF" for ch in value) def load_capability_ledger(modern_root: Path) -> list[dict[str, Any]]: ledger = read_json(modern_root / "reports" / "capability_ledger.json") if not isinstance(ledger, list): raise ValueError("capability_ledger.json must be a list") return [dict(item) for item in ledger] def load_current_parity(modern_root: Path) -> dict[str, Any]: receipt = read_json(modern_root / "reports" / "modernization_receipt.json") parity = dict(receipt["capability_parity"]) parity["receipt_hash"] = receipt["receipt_hash"] parity["source_head"] = receipt["source_head"] parity["receipt_generated_utc"] = receipt["generated_utc"] return parity def command_probe(executable: str) -> dict[str, Any]: resolved = shutil.which(executable) result: dict[str, Any] = { "tool": executable, "present": resolved is not None, "path": resolved, "purpose": RUNTIME_TOOL_PROBES[executable], } if not resolved: return result version_args = [resolved, "--version"] if executable == "docker": version_args = [resolved, "version", "--format", "{{json .Server.Version}}"] try: completed = subprocess.run( version_args, check=False, capture_output=True, text=True, timeout=8, ) except Exception as exc: # pragma: no cover - environment dependent result.update({"version_probe_ok": False, "version_probe_error": str(exc)}) return result output = (completed.stdout or completed.stderr or "").strip() result.update( { "version_probe_ok": completed.returncode == 0, "version_probe_returncode": completed.returncode, "version_probe_output": output[:500], } ) return result def inspect_zip(path: Path) -> dict[str, Any]: record: dict[str, Any] = { "path": str(path.resolve()), "exists": path.exists(), "size_bytes": path.stat().st_size if path.exists() else None, "sha256": sha256_path(path) if path.exists() else None, } if not path.exists(): return record with zipfile.ZipFile(path) as archive: names = archive.namelist() lowered = [name.replace("\\", "/").lower() for name in names] record.update( { "entry_count": len(names), "sample_entries": names[:30], "has_shared_load_modules": any("/loadlib/" in name and name.endswith(".so") for name in lowered), "has_app_config": any(name.endswith("app_config.json") for name in lowered), "has_catalog_jcl": any("/catalog/jcl/" in name for name in lowered), "has_catalog_data": any("/catalog/data/" in name for name in lowered), "has_unikix_layout": any("unikix" in name or "/migrated_app/" in name for name in lowered), "runtime_conclusion": ( "Deployment/runtime asset detected. This is useful provenance, but it is not a live " "executed COBOL/CICS trace corpus by itself." ), } ) return record def inspect_runtime_assets(source_root: Path) -> list[dict[str, Any]]: return [inspect_zip(source_root / relative) for relative in M2_RUNTIME_ZIPS] def trace_candidates(payload: Any) -> list[dict[str, Any]]: if isinstance(payload, list): return [item for item in payload if isinstance(item, dict)] if not isinstance(payload, dict): return [] candidates: list[dict[str, Any]] = [] if "capability_id" in payload: candidates.append(payload) for key in ("capability_matches", "matches", "traces", "results"): value = payload.get(key) if isinstance(value, list): candidates.extend(item for item in value if isinstance(item, dict)) return candidates def validate_trace_record(record: dict[str, Any], required_ids: set[str]) -> tuple[bool, list[str]]: reasons: list[str] = [] capability_id = record.get("capability_id") if capability_id not in required_ids: reasons.append("unknown_or_missing_capability_id") for field in REQUIRED_TRACE_FIELDS: if not record.get(field): reasons.append(f"missing_{field}") if record.get("trace_kind") not in ACCEPTED_TRACE_KINDS: reasons.append("trace_kind_not_live_legacy_runtime") if record.get("source_head") != SOURCE_HEAD: reasons.append("source_head_mismatch") if record.get("matched") is not True: reasons.append("matched_not_true") legacy_hash = next((record.get(field) for field in TRACE_HASH_FIELDS if record.get(field)), None) if not legacy_hash: reasons.append("missing_legacy_runtime_trace_hash") elif not is_sha256(legacy_hash): reasons.append("legacy_runtime_trace_hash_not_sha256") if not is_sha256(record.get("modern_observation_hash")): reasons.append("modern_observation_hash_not_sha256") return not reasons, reasons def load_live_trace_matches(trace_dir: Path | None, required_ids: set[str]) -> dict[str, Any]: if trace_dir is None: return { "trace_dir": None, "trace_dir_exists": False, "accepted_matches": {}, "rejected_records": [], "files_scanned": [], } trace_dir = trace_dir.resolve() files = sorted(trace_dir.rglob("*.json")) if trace_dir.exists() else [] accepted: dict[str, dict[str, Any]] = {} rejected: list[dict[str, Any]] = [] for path in files: try: payload = read_json(path) except Exception as exc: rejected.append({"path": str(path), "reasons": [f"json_parse_error:{exc}"]}) continue for record in trace_candidates(payload): ok, reasons = validate_trace_record(record, required_ids) capability_id = record.get("capability_id") if ok and isinstance(capability_id, str): accepted[capability_id] = { "path": str(path), "trace_kind": record["trace_kind"], "legacy_runtime_environment": record["legacy_runtime_environment"], "raw_legacy_trace_hash": next(record.get(field) for field in TRACE_HASH_FIELDS if record.get(field)), "modern_observation_hash": record["modern_observation_hash"], "comparator_version": record["comparator_version"], } else: rejected.append( { "path": str(path), "capability_id": capability_id, "reasons": reasons, } ) return { "trace_dir": str(trace_dir), "trace_dir_exists": trace_dir.exists(), "accepted_matches": accepted, "rejected_records": rejected, "files_scanned": [str(path) for path in files], } def build_a_grade_report(modern_root: Path, source_root: Path, trace_dir: Path | None = None) -> dict[str, Any]: modern_root = modern_root.resolve() source_root = source_root.resolve() ledger = load_capability_ledger(modern_root) current_parity = load_current_parity(modern_root) required_ids = {item["capability_id"] for item in ledger} trace_status = load_live_trace_matches(trace_dir, required_ids) accepted_matches = trace_status["accepted_matches"] missing_ids = sorted(required_ids - set(accepted_matches)) runtime_assets = inspect_runtime_assets(source_root) tool_probe = {name: command_probe(name) for name in RUNTIME_TOOL_PROBES} blockers = [] if missing_ids: blockers.append( { "code": "missing_live_legacy_trace_corpus", "detail": ( f"A-grade requires accepted live legacy runtime matches for all {len(required_ids)} " f"capabilities; accepted={len(accepted_matches)}, missing={len(missing_ids)}." ), } ) if not any(asset.get("exists") for asset in runtime_assets): blockers.append( { "code": "missing_legacy_runtime_assets", "detail": "No AWS M2 runtime zip assets were found under the pinned source tree.", } ) else: blockers.append( { "code": "runtime_assets_not_execution_evidence", "detail": ( "AWS M2/Micro Focus/UniKix package artifacts were found, but this run did not execute " "them to produce COBOL/CICS transaction traces." ), } ) if not tool_probe["aws"]["present"] and not tool_probe["hercules"]["present"]: blockers.append( { "code": "no_local_mainframe_or_aws_runtime_path_detected", "detail": "Neither AWS CLI nor a local mainframe emulator was detected for a runtime capture path.", } ) blockers.append( { "code": "static_oracle_is_not_a_grade", "detail": "The current B=50 proof is strong static/source-oracle evidence, but A requires live runtime traces.", } ) promotable = not missing_ids current_grade_counts = dict(current_parity["grade_counts"]) proposed_grade_counts = dict(current_grade_counts) if promotable: proposed_grade_counts.update({"A": len(required_ids), "B": 0, "F": 0}) capability_status = [] ledger_by_id = {item["capability_id"]: item for item in ledger} for capability_id in sorted(required_ids): ledger_item = ledger_by_id[capability_id] capability_status.append( { "capability_id": capability_id, "surface": ledger_item.get("surface"), "transaction": ledger_item.get("transaction"), "program": ledger_item.get("program"), "function": ledger_item.get("function"), "current_proof_grade": ledger_item.get("proof_grade"), "a_grade_match_found": capability_id in accepted_matches, "accepted_trace": accepted_matches.get(capability_id), "missing_reason": None if capability_id in accepted_matches else "no_accepted_live_legacy_runtime_trace", } ) report: dict[str, Any] = { "report_version": REPORT_VERSION, "generated_utc": datetime.now(timezone.utc).replace(microsecond=0).isoformat(), "source": { "repo_url": SOURCE_REMOTE, "head": SOURCE_HEAD, "local_path": str(source_root), }, "modern_code": { "local_path": str(modern_root), }, "requested_target": { "grade": "A", "scope": "all capabilities", "capability_count": len(required_ids), }, "rubric": { "A": "actual legacy COBOL/CICS runtime trace matched to modern observed behavior for the capability", "B": "static legacy data/copybook/source-oracle match plus executable modern-service replay", "F": "known parity gap or missing capability under the current rubric", }, "current_static_source_oracle_status": { "capability_count": current_parity["capability_count"], "grade_counts": current_grade_counts, "gap_count": current_parity["gap_count"], "static_oracle_or_better_count": current_parity["static_oracle_or_better_count"], "strict_runtime_parity_count": current_parity["strict_runtime_parity_count"], "receipt_hash": current_parity["receipt_hash"], "receipt_generated_utc": current_parity["receipt_generated_utc"], }, "a_grade_gate": { "promotable_to_A": promotable, "required_live_matches": len(required_ids), "accepted_live_matches": len(accepted_matches), "missing_live_matches": len(missing_ids), "current_A": current_grade_counts.get("A", 0), "target_A": len(required_ids), "proposed_grade_counts_if_gate_passes": proposed_grade_counts, "missing_capability_ids": missing_ids, }, "legacy_runtime_trace_contract": { "accepted_trace_kinds": sorted(ACCEPTED_TRACE_KINDS), "required_fields": list(REQUIRED_TRACE_FIELDS) + ["matched", "raw_legacy_trace_hash or legacy_runtime_trace_hash"], "field_rules": { "source_head": SOURCE_HEAD, "matched": True, "hash_fields": "64-character SHA-256 hex digests", "capability_id": "must match one ID in reports/capability_ledger.json", }, }, "legacy_runtime_environment_assessment": { "source_prerequisites": [ "mainframe environment with CICS, VSAM, and JCL support", "optional DB2, IMS DB, and MQ paths for optional modules", ], "local_execution_path_found": False, "local_execution_path_reason": ( "No runnable COBOL/CICS/VSAM/JCL runtime was executed in this workspace. " "Static replay and modern API tests are not live legacy execution." ), "tooling_probe": tool_probe, "runtime_assets": runtime_assets, }, "live_trace_scan": trace_status, "capability_match_status": capability_status, "blockers": blockers if not promotable else [], "decision": { "action": "promote_to_A" if promotable else "do_not_promote", "why": ( "All required live runtime trace matches were accepted." if promotable else "The current bundle proves B=50/F=0/gaps=0 under the static/source-oracle rubric, " "but it does not contain accepted live COBOL/CICS runtime traces for all capabilities." ), "next_non_human_path": [ "Run the pinned AWS CardDemo source in an AWS M2/mainframe-compatible runtime.", "Capture transaction and batch outputs for each capability ID in reports/capability_ledger.json.", "Replay the same inputs through the modern Python/SQLite service.", "Emit JSON trace records satisfying legacy_runtime_trace_contract.", "Rerun this gate with --legacy-trace-dir pointing at that corpus.", ], }, "public_actions_allowed": False, } report["report_hash"] = stable_hash(report) return report def promotion_readme(report: dict[str, Any]) -> str: gate = report["a_grade_gate"] parity = report["current_static_source_oracle_status"] return f""" # AWS CardDemo A-Grade Promotion Gate Report version: `{README_VERSION}` This file records the attempt to promote the AWS CardDemo modernization proof from B-grade static/source-oracle parity to A-grade live runtime parity. ## Decision - Action: `{report['decision']['action']}` - Promotable to A: `{gate['promotable_to_A']}` - Current grade counts: `{parity['grade_counts']}` - Required live legacy runtime matches: `{gate['required_live_matches']}` - Accepted live legacy runtime matches: `{gate['accepted_live_matches']}` - Missing live legacy runtime matches: `{gate['missing_live_matches']}` - Current static/source-oracle status: B=`{parity['grade_counts'].get('B', 0)}`, F=`{parity['grade_counts'].get('F', 0)}`, gaps=`{parity['gap_count']}` ## Rubric Boundary A-grade is reserved for actual legacy COBOL/CICS runtime traces matched against modern observed behavior for each capability. The existing proof remains B=50/F=0/gaps=0 under the current static/source-oracle rubric. This is not live COBOL/CICS all-path runtime equivalence. ## Replay Command ```powershell python tools\\evaluate_a_grade_promotion.py --source-root ..\\source --out-dir .\\final_proof ``` To test a future live trace corpus, add: ```powershell --legacy-trace-dir ``` ## Required Trace Contract Each accepted live trace record must include the fields listed in `A_GRADE_PROMOTION_REPORT.json` under `legacy_runtime_trace_contract`. The key requirements are: pinned source head, live trace kind, matched=true, a capability ID from the ledger, and SHA-256 hashes for the raw legacy trace and modern observation. """ def main() -> None: parser = argparse.ArgumentParser(description="Evaluate whether CardDemo proof can be promoted to A-grade parity") parser.add_argument("--modern-root", type=Path, default=Path(__file__).resolve().parents[1]) parser.add_argument("--source-root", type=Path, default=Path(__file__).resolve().parents[2] / "source") parser.add_argument("--out-dir", type=Path, default=None) parser.add_argument("--legacy-trace-dir", type=Path, default=None) parser.add_argument("--fail-if-not-promotable", action="store_true") args = parser.parse_args() modern_root = args.modern_root.resolve() source_root = args.source_root.resolve() out_dir = (args.out_dir or modern_root / "final_proof").resolve() trace_dir = args.legacy_trace_dir.resolve() if args.legacy_trace_dir else None report = build_a_grade_report(modern_root, source_root, trace_dir) write_json(out_dir / "A_GRADE_PROMOTION_REPORT.json", report) write_text(out_dir / "A_GRADE_PROMOTION_README.md", promotion_readme(report)) print( json.dumps( { "out_dir": str(out_dir), "promotable_to_A": report["a_grade_gate"]["promotable_to_A"], "current_grade_counts": report["current_static_source_oracle_status"]["grade_counts"], "required_live_matches": report["a_grade_gate"]["required_live_matches"], "accepted_live_matches": report["a_grade_gate"]["accepted_live_matches"], "missing_live_matches": report["a_grade_gate"]["missing_live_matches"], "report_hash": report["report_hash"], }, indent=2, sort_keys=True, ) ) if args.fail_if_not_promotable and not report["a_grade_gate"]["promotable_to_A"]: raise SystemExit(2) if __name__ == "__main__": main()