from __future__ import annotations import argparse import hashlib import json import shutil import subprocess 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" CLAIM_LIMIT = ( "This proof is static/source-oracle parity plus executable modern-service replay. " "It is not live COBOL/CICS all-path runtime equivalence." ) OUTPUT_FILES = [ "FINAL_PROOF_README.md", "FINAL_RECEIPT_SUMMARY.json", "REPRO_COMMANDS.txt", "STATIC_ORACLE_REPLAY_REPORT.json", "KNOWN_LIMITS.md", "ARTIFACT_MANIFEST.json", ] OPTIONAL_OUTPUT_FILES = [ "A_GRADE_PROMOTION_REPORT.json", "A_GRADE_PROMOTION_README.md", "NO_COST_CONFIDENCE_REPORT.json", "NO_COST_CONFIDENCE_README.md", ] 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.rstrip() + "\n", encoding="utf-8") 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 stable_hash(payload: Any) -> str: return hashlib.sha256(json.dumps(payload, sort_keys=True, default=str).encode("utf-8")).hexdigest() def file_record(path: Path, *, base: Path | None = None, role: str = "artifact") -> dict[str, Any]: label = str(path.resolve()) if base is not None: try: label = str(path.resolve().relative_to(base.resolve())) except ValueError: label = str(path.resolve()) return { "path": label.replace("\\", "/"), "absolute_path": str(path.resolve()), "role": role, "exists": path.exists(), "size_bytes": path.stat().st_size if path.exists() else None, "sha256": sha256_path(path) if path.exists() and path.is_file() else None, } def git_value(source_root: Path, *args: str) -> str: safe_dir = source_root.resolve().as_posix() result = subprocess.run( ["git", "-c", f"safe.directory={safe_dir}", "-C", str(source_root), *args], check=False, capture_output=True, text=True, ) return result.stdout.strip() if result.returncode == 0 else "" def git_identity(source_root: Path) -> dict[str, Any]: return { "remote_url": git_value(source_root, "remote", "get-url", "origin") or SOURCE_REMOTE, "head": git_value(source_root, "rev-parse", "HEAD") or SOURCE_HEAD, "status_short": git_value(source_root, "status", "--short"), } def command_lines(source_head: str) -> dict[str, str]: return { "setup": r"python -m carddemo.cli init-db --source-root ..\source --db-path .\carddemo.sqlite", "run": r"python -m carddemo.cli serve --source-root ..\source --db-path .\carddemo.sqlite --port 8087", "test": r"python -m unittest discover -s tests", "receipt": r"python tools\generate_receipts.py --source-root ..\source --db-path .\carddemo.sqlite --out-dir .\reports", "static_oracle_replay": rf"python tools\replay_static_oracles.py --source-root ..\source --out-dir .\reports --source-head {source_head}", "a_grade_promotion": r"python tools\evaluate_a_grade_promotion.py --source-root ..\source --out-dir .\final_proof", "no_cost_confidence": r"python tools\build_no_cost_confidence.py --source-root ..\source --out-dir .\final_proof", "package_final_proof": r"python tools\package_final_proof.py --source-root ..\source", "all_local_proof_no_server": ( f'powershell -NoProfile -Command "python -m carddemo.cli init-db --source-root ..\\source ' f'--db-path .\\carddemo.sqlite; python -m unittest discover -s tests; ' f'python tools\\generate_receipts.py --source-root ..\\source --db-path .\\carddemo.sqlite ' f'--out-dir .\\reports; python tools\\replay_static_oracles.py --source-root ..\\source ' f'--out-dir .\\reports --source-head {source_head}; ' f'python tools\\evaluate_a_grade_promotion.py --source-root ..\\source --out-dir .\\final_proof; ' f'python tools\\build_no_cost_confidence.py --source-root ..\\source --out-dir .\\final_proof; ' f'python tools\\package_final_proof.py --source-root ..\\source"' ), } def validate_current_rubric(receipt: dict[str, Any], replay: dict[str, Any], next_gaps: list[Any]) -> None: parity = receipt["capability_parity"] grade_counts = parity["grade_counts"] failures = [] if parity["capability_count"] != 50: failures.append(f"capability_count={parity['capability_count']}") if grade_counts.get("B") != 50: failures.append(f"B={grade_counts.get('B')}") if grade_counts.get("F") != 0: failures.append(f"F={grade_counts.get('F')}") if parity["gap_count"] != 0: failures.append(f"gap_count={parity['gap_count']}") if next_gaps: failures.append("next_gap_ranking_not_empty") if not replay.get("passed"): failures.append("static_oracle_replay_failed") if failures: raise SystemExit("Cannot package final proof; rubric checks failed: " + ", ".join(failures)) def load_verification(out_dir: Path) -> dict[str, Any] | None: path = out_dir / "CLEAN_REPRO_VERIFICATION.json" return read_json(path) if path.exists() else None def load_a_grade_report(out_dir: Path) -> dict[str, Any] | None: path = out_dir / "A_GRADE_PROMOTION_REPORT.json" return read_json(path) if path.exists() else None def load_no_cost_report(out_dir: Path) -> dict[str, Any] | None: path = out_dir / "NO_COST_CONFIDENCE_REPORT.json" return read_json(path) if path.exists() else None def summarize_a_grade_report(out_dir: Path, report: dict[str, Any] | None) -> dict[str, Any] | None: if report is None: return None gate = report["a_grade_gate"] parity = report["current_static_source_oracle_status"] return { "path": str((out_dir / "A_GRADE_PROMOTION_REPORT.json").resolve()), "readme_path": str((out_dir / "A_GRADE_PROMOTION_README.md").resolve()), "report_version": report["report_version"], "report_hash": report["report_hash"], "generated_utc": report["generated_utc"], "decision_action": report["decision"]["action"], "promotable_to_A": gate["promotable_to_A"], "required_live_matches": gate["required_live_matches"], "accepted_live_matches": gate["accepted_live_matches"], "missing_live_matches": gate["missing_live_matches"], "current_A": gate["current_A"], "target_A": gate["target_A"], "current_grade_counts": parity["grade_counts"], "current_gap_count": parity["gap_count"], "blocker_codes": [blocker["code"] for blocker in report.get("blockers", [])], "trace_contract": report["legacy_runtime_trace_contract"], } def summarize_no_cost_report(out_dir: Path, report: dict[str, Any] | None) -> dict[str, Any] | None: if report is None: return None summary = report["no_cost_confidence_summary"] coverage = report["capability_coverage"] replay = report["static_oracle_replay"] a_gate = report["a_grade_gate"] return { "path": str((out_dir / "NO_COST_CONFIDENCE_REPORT.json").resolve()), "readme_path": str((out_dir / "NO_COST_CONFIDENCE_README.md").resolve()), "report_version": report["report_version"], "report_hash": report["report_hash"], "generated_utc": report["generated_utc"], "reviewer_posture": summary["reviewer_posture"], "ready_for_pre_runtime_review": summary["ready_for_pre_runtime_review"], "remaining_gap": summary["remaining_gap"], "capability_count": coverage["capability_count"], "static_oracle_ready_count": coverage["static_oracle_ready_count"], "source_ref_total": coverage["source_ref_total"], "static_replay_passed": replay["passed"], "edge_case_count": report["fixture_corpus"]["edge_case_count"], "golden_trace_count": report["fixture_corpus"]["golden_trace_count"], "paid_runtime_used": report["no_cost_scope"]["paid_runtime_used"], "legacy_runtime_claim_made": report["no_cost_scope"]["legacy_runtime_claim_made"], "a_promotable": a_gate["promotable_to_A"], "a_missing_live_matches": a_gate["missing_live_matches"], } def build_summary( modern_root: Path, source_root: Path, out_dir: Path, receipt: dict[str, Any], parity_report: dict[str, Any], replay: dict[str, Any], next_gaps: list[Any], verification: dict[str, Any] | None, a_grade_report: dict[str, Any] | None, no_cost_report: dict[str, Any] | None, ) -> dict[str, Any]: source_git = git_identity(source_root) commands = command_lines(source_git["head"]) screenshot = modern_root / "reports" / "ui_batch_reports_smoke.png" smoke_evidence = [] if screenshot.exists(): smoke_evidence.append(file_record(screenshot, base=modern_root, role="existing_screenshot")) if verification and verification.get("api_smoke"): smoke_evidence.append( { "role": "clean_copy_api_smoke", "passed": verification.get("api_smoke_passed"), "port": verification.get("server_port"), "endpoints": list(verification["api_smoke"].keys()), } ) parity = receipt["capability_parity"] return { "summary_version": "carddemo_final_proof_summary_v0", "generated_utc": datetime.now(timezone.utc).replace(microsecond=0).isoformat(), "source": { "repo_url": source_git["remote_url"], "head": source_git["head"], "local_path": str(source_root.resolve()), "status_short": source_git["status_short"], "source_hash_count": receipt["source_hash_count"], "source_hashes_digest": stable_hash(receipt["source_hashes"]), }, "modern_code": { "local_path": str(modern_root.resolve()), "modern_hash_count": receipt["modern_hash_count"], "modern_hashes_digest": stable_hash(receipt["modern_hashes"]), }, "commands": commands, "receipt": { "path": str((modern_root / "reports" / "modernization_receipt.json").resolve()), "receipt_hash": receipt["receipt_hash"], "generated_utc": receipt["generated_utc"], "seed_counts": receipt["seed_counts"], "source_head": receipt["source_head"], }, "parity": { "rubric": "current static/source-oracle rubric", "capability_count": parity["capability_count"], "grade_counts": parity["grade_counts"], "B": parity["grade_counts"].get("B", 0), "F": parity["grade_counts"].get("F", 0), "gap_count": parity["gap_count"], "next_gap_ranking_count": len(next_gaps), "one_for_one_parity_ready": parity["one_for_one_parity_ready"], "static_oracle_or_better_count": parity["static_oracle_or_better_count"], "strict_runtime_parity_count": parity["strict_runtime_parity_count"], "proof_grade_meanings": receipt["proof_grade_meanings"], "parity_report_passed": parity_report["passed"], "parity_hash": parity_report["parity_hash"], }, "static_oracle_replay": { "path": str((out_dir / "STATIC_ORACLE_REPLAY_REPORT.json").resolve()), "source_report_path": str((modern_root / "reports" / "static_oracle_replay.json").resolve()), "passed": replay["passed"], "replay_hash": replay["replay_hash"], "evidence_hash": replay["evidence_hash"], "runtime_probe_count": replay["runtime_probe_count"], "failed_checks": replay["failed_checks"], "claim_limit": replay["claim_limit"], }, "smoke_evidence": smoke_evidence, "clean_repro_verification": verification, "a_grade_promotion": summarize_a_grade_report(out_dir, a_grade_report), "no_cost_confidence": summarize_no_cost_report(out_dir, no_cost_report), "known_limits": [ CLAIM_LIMIT, "A-grade live legacy runtime trace matching remains 0 under the current proof-grade rubric.", "A-grade promotion is gated by A_GRADE_PROMOTION_REPORT.json and requires accepted live legacy runtime traces.", "NO_COST_CONFIDENCE_REPORT.json records maximum unpaid/pre-runtime evidence and the remaining paid/runtime validation boundary.", "The static replay exercises selected trace expectations; it is not exhaustive path coverage.", "The modern app is a local Python/SQLite target and not a production deployment package.", ], "public_actions_allowed": False, "bundle_path": str(out_dir.resolve()), } def final_readme(summary: dict[str, Any]) -> str: commands = summary["commands"] verification = summary.get("clean_repro_verification") or {} a_grade = summary.get("a_grade_promotion") no_cost = summary.get("no_cost_confidence") clean_status = "not run" if verification: clean_status = "passed" if verification.get("passed") else "failed" smoke_lines = [] for item in summary["smoke_evidence"]: if item["role"] == "existing_screenshot": smoke_lines.append(f"- Screenshot: `{item['path']}` SHA-256 `{item['sha256']}`.") elif item["role"] == "clean_copy_api_smoke": smoke_lines.append( f"- Clean-copy API smoke: passed={item['passed']} port={item['port']} endpoints={', '.join(item['endpoints'])}." ) if not smoke_lines: smoke_lines.append("- No screenshot or API smoke artifact is bundled.") if a_grade: a_grade_lines = [ f"- A-grade gate decision: `{a_grade['decision_action']}`", f"- Promotable to A: `{a_grade['promotable_to_A']}`", f"- Required live legacy runtime matches: `{a_grade['required_live_matches']}`", f"- Accepted live legacy runtime matches: `{a_grade['accepted_live_matches']}`", f"- Missing live legacy runtime matches: `{a_grade['missing_live_matches']}`", f"- A-grade report hash: `{a_grade['report_hash']}`", ] else: a_grade_lines = ["- A-grade promotion gate was not run before packaging."] if no_cost: no_cost_lines = [ f"- Reviewer posture: `{no_cost['reviewer_posture']}`", f"- Ready for pre-runtime review: `{no_cost['ready_for_pre_runtime_review']}`", f"- Paid runtime used: `{no_cost['paid_runtime_used']}`", f"- Legacy runtime claim made: `{no_cost['legacy_runtime_claim_made']}`", f"- Source-backed static capabilities: `{no_cost['static_oracle_ready_count']}`", f"- Source refs in capability ledger: `{no_cost['source_ref_total']}`", f"- Golden traces / edge cases: `{no_cost['golden_trace_count']}` / `{no_cost['edge_case_count']}`", f"- Remaining gap: `{no_cost['remaining_gap']}`", f"- No-cost confidence report hash: `{no_cost['report_hash']}`", ] else: no_cost_lines = ["- No-cost confidence proof was not run before packaging."] return f""" # AWS CardDemo Modernization Final Proof This bundle packages the local AWS CardDemo modernization run as a reproducible technical-review artifact. It does not add application features; it records the source identity, modern code location, commands, receipts, static-oracle replay, no-cost confidence proof, A-grade promotion gate, known limits, and clean-copy verification status. ## Source Identity - Source repo: `{summary['source']['repo_url']}` - Source version: `{summary['source']['head']}` - Source local path used for this run: `{summary['source']['local_path']}` - Source file hash count in receipt: `{summary['source']['source_hash_count']}` - Source hash digest over receipt map: `{summary['source']['source_hashes_digest']}` ## Modern Code - Modern code path: `{summary['modern_code']['local_path']}` - Modern file hash count in receipt: `{summary['modern_code']['modern_hash_count']}` - Modern hash digest over receipt map: `{summary['modern_code']['modern_hashes_digest']}` ## One-Command Setup And Run Run these from the modern code root with the AWS CardDemo source clone/copy at `..\\source`. Setup database: ```powershell {commands['setup']} ``` Run web/API server: ```powershell {commands['run']} ``` Open `http://127.0.0.1:8087`. ## One-Command Tests ```powershell {commands['test']} ``` ## One-Command Static-Oracle Replay ```powershell {commands['static_oracle_replay']} ``` ## One-Command A-Grade Promotion Gate ```powershell {commands['a_grade_promotion']} ``` ## One-Command No-Cost Confidence Proof ```powershell {commands['no_cost_confidence']} ``` ## Full Local Proof Refresh ```powershell {commands['all_local_proof_no_server']} ``` ## Final Receipt Summary - Receipt hash: `{summary['receipt']['receipt_hash']}` - Receipt generated: `{summary['receipt']['generated_utc']}` - Static replay hash: `{summary['static_oracle_replay']['replay_hash']}` - Static replay passed: `{summary['static_oracle_replay']['passed']}` - Runtime probe count: `{summary['static_oracle_replay']['runtime_probe_count']}` - Failed replay checks: `{summary['static_oracle_replay']['failed_checks']}` ## Parity Summary Under the current static/source-oracle rubric: - Capability count: `{summary['parity']['capability_count']}` - B-grade static/source-oracle capabilities: `{summary['parity']['B']}` - F-grade gaps: `{summary['parity']['F']}` - Gap count: `{summary['parity']['gap_count']}` - Next-gap ranking count: `{summary['parity']['next_gap_ranking_count']}` - Static-oracle-or-better count: `{summary['parity']['static_oracle_or_better_count']}` - A-grade live legacy runtime trace count: `{summary['parity']['strict_runtime_parity_count']}` Proof grade meanings are recorded in `FINAL_RECEIPT_SUMMARY.json`. ## No-Cost Confidence Proof {chr(10).join(no_cost_lines)} This is the maximum unpaid/pre-runtime evidence layer. It is meant to convince a technical reviewer that the modernization is probably functional under the extracted legacy-derived behavior, while preserving the live runtime validation gap. ## A-Grade Promotion Gate {chr(10).join(a_grade_lines)} The A-grade gate is intentionally stricter than the B-grade static/source-oracle proof. It requires accepted live legacy COBOL/CICS runtime trace matches for each capability before any capability can be promoted to A. ## Smoke Evidence {chr(10).join(smoke_lines)} ## Clean-Copy Verification - Clean-copy verification status: `{clean_status}` - Verification report included in `FINAL_RECEIPT_SUMMARY.json` when present. ## Caveat {CLAIM_LIMIT} See `KNOWN_LIMITS.md` for the full claim boundary. """ def known_limits() -> str: return f""" # Known Limits {CLAIM_LIMIT} - Proof grade `B` means static legacy data/copybook/source-oracle match. It does not mean the original COBOL/CICS system was executed and compared for every path. - Proof grade `A` is reserved for actual legacy runtime trace match; this bundle records `A=0`. - `A_GRADE_PROMOTION_REPORT.json` is the executable promotion gate. It fails closed unless accepted live legacy runtime trace records exist for every capability. - `NO_COST_CONFIDENCE_REPORT.json` records maximum unpaid/pre-runtime evidence. It is designed to support review confidence, not to replace live legacy validation. - The replay report executes the modern Python service against extracted static/source-oracle expectations. It is useful evidence, but not exhaustive path coverage. - The source data and copybooks are from AWS CardDemo at the pinned source version in `FINAL_RECEIPT_SUMMARY.json`. - The app is a local Python/SQLite modernization target. Production concerns such as deployment topology, operations, security hardening, and load testing are outside this proof bundle. - Public release, upload, or promotion is intentionally not performed by this bundle. """ def repro_commands(summary: dict[str, Any]) -> str: commands = summary["commands"] return f""" Run from the modern code root. The source clone/copy must be at ..\\source. SOURCE REPO: {summary['source']['repo_url']} SOURCE HEAD: {summary['source']['head']} MODERN CODE: {summary['modern_code']['local_path']} SETUP: {commands['setup']} RUN SERVER: {commands['run']} TEST: {commands['test']} STATIC ORACLE REPLAY: {commands['static_oracle_replay']} A-GRADE PROMOTION GATE: {commands['a_grade_promotion']} NO-COST CONFIDENCE PROOF: {commands['no_cost_confidence']} REGENERATE RECEIPTS: {commands['receipt']} PACKAGE FINAL PROOF: {commands['package_final_proof']} FULL LOCAL PROOF REFRESH WITHOUT SERVER: {commands['all_local_proof_no_server']} CAVEAT: {CLAIM_LIMIT} """ def build_manifest(out_dir: Path, modern_root: Path) -> dict[str, Any]: bundle_names = [name for name in OUTPUT_FILES if name != "ARTIFACT_MANIFEST.json"] bundle_names.extend(name for name in OPTIONAL_OUTPUT_FILES if (out_dir / name).exists()) bundle_files = [file_record(out_dir / name, base=out_dir, role="final_bundle_output") for name in bundle_names] existing = [ modern_root / "reports" / "modernization_receipt.json", modern_root / "reports" / "parity_gap_report.json", modern_root / "reports" / "capability_ledger.json", modern_root / "reports" / "golden_traces.json", modern_root / "reports" / "edge_cases.json", modern_root / "reports" / "next_gap_ranking.json", modern_root / "reports" / "static_oracle_replay.json", modern_root / "reports" / "ui_batch_reports_smoke.png", ] verification = out_dir / "CLEAN_REPRO_VERIFICATION.json" if verification.exists(): existing.append(verification) payload = { "manifest_version": "carddemo_final_proof_manifest_v0", "generated_utc": datetime.now(timezone.utc).replace(microsecond=0).isoformat(), "bundle_path": str(out_dir.resolve()), "bundle_files": bundle_files, "referenced_existing_artifacts": [file_record(path, base=modern_root, role="referenced_evidence") for path in existing if path.exists()], "public_actions_allowed": False, } payload["manifest_payload_hash"] = stable_hash(payload) return payload def main() -> None: parser = argparse.ArgumentParser(description="Package the final CardDemo proof bundle") 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) 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() reports = modern_root / "reports" receipt = read_json(reports / "modernization_receipt.json") parity_report = read_json(reports / "parity_gap_report.json") replay = read_json(reports / "static_oracle_replay.json") next_gaps = read_json(reports / "next_gap_ranking.json") validate_current_rubric(receipt, replay, next_gaps) out_dir.mkdir(parents=True, exist_ok=True) verification = load_verification(out_dir) a_grade_report = load_a_grade_report(out_dir) no_cost_report = load_no_cost_report(out_dir) summary = build_summary( modern_root, source_root, out_dir, receipt, parity_report, replay, next_gaps, verification, a_grade_report, no_cost_report, ) shutil.copy2(reports / "static_oracle_replay.json", out_dir / "STATIC_ORACLE_REPLAY_REPORT.json") write_json(out_dir / "FINAL_RECEIPT_SUMMARY.json", summary) write_text(out_dir / "FINAL_PROOF_README.md", final_readme(summary)) write_text(out_dir / "REPRO_COMMANDS.txt", repro_commands(summary)) write_text(out_dir / "KNOWN_LIMITS.md", known_limits()) write_json(out_dir / "ARTIFACT_MANIFEST.json", build_manifest(out_dir, modern_root)) print( json.dumps( { "out_dir": str(out_dir), "files": OUTPUT_FILES, "parity": summary["parity"], "static_oracle_replay": summary["static_oracle_replay"], "a_grade_promotion": summary["a_grade_promotion"], "no_cost_confidence": summary["no_cost_confidence"], "clean_repro_verification_present": verification is not None, }, indent=2, sort_keys=True, ) ) if __name__ == "__main__": main()