diff --git "a/modern_code/carddemo/parity.py" "b/modern_code/carddemo/parity.py" new file mode 100644--- /dev/null +++ "b/modern_code/carddemo/parity.py" @@ -0,0 +1,2102 @@ +from __future__ import annotations + +import hashlib +import tempfile +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Any + +from .legacy_parser import ( + ACCOUNT_FIELDS, + CARD_FIELDS, + CARD_XREF_FIELDS, + CUSTOMER_FIELDS, + DISCLOSURE_GROUP_FIELDS, + TRANSACTION_CATEGORY_BALANCE_FIELDS, + TRANSACTION_CATEGORY_FIELDS, + TRANSACTION_FIELDS, + TRANSACTION_TYPE_FIELDS, + USER_FIELDS, +) +from .repository import connect, seed_from_legacy +from .service import CardDemoService + + +SOURCE_SUFFIXES = {".cbl", ".cpy", ".bms", ".jcl", ".txt", ".ps", ".PS", ".CBL", ".CPY", ".JCL"} + + +@dataclass(frozen=True) +class CapabilityDefinition: + capability_id: str + surface: str + transaction: str + job: str + bms_map: str + program: str + function: str + optional_module: str + notes: str + modern_capability: str + modern_entrypoint: str + proof_grade: str + proof_basis: str + priority: int + + +def _online( + transaction: str, + bms_map: str, + program: str, + function: str, + *, + optional_module: str = "", + notes: str = "", + modern_capability: str = "", + modern_entrypoint: str = "", + proof_grade: str = "F", + proof_basis: str = "discovered in AWS inventory; no modern parity proof yet", + priority: int = 50, +) -> CapabilityDefinition: + return CapabilityDefinition( + capability_id=f"online:{transaction}", + surface="online", + transaction=transaction, + job="", + bms_map=bms_map, + program=program, + function=function, + optional_module=optional_module, + notes=notes, + modern_capability=modern_capability, + modern_entrypoint=modern_entrypoint, + proof_grade=proof_grade, + proof_basis=proof_basis, + priority=priority, + ) + + +def _batch( + job: str, + program: str, + function: str, + *, + optional_module: str = "", + notes: str = "", + modern_capability: str = "", + modern_entrypoint: str = "", + proof_grade: str = "F", + proof_basis: str = "discovered in AWS inventory; no modern parity proof yet", + priority: int = 50, +) -> CapabilityDefinition: + return CapabilityDefinition( + capability_id=f"batch:{job}", + surface="batch", + transaction="", + job=job, + bms_map="", + program=program, + function=function, + optional_module=optional_module, + notes=notes, + modern_capability=modern_capability, + modern_entrypoint=modern_entrypoint, + proof_grade=proof_grade, + proof_basis=proof_basis, + priority=priority, + ) + + +CAPABILITIES: tuple[CapabilityDefinition, ...] = ( + _online( + "CC00", + "COSGN00", + "COSGN00C", + "Signon Screen", + modern_capability="signon", + modern_entrypoint="CardDemoService.signon", + proof_grade="B", + proof_basis="COSGN00C uppercase credential lookup and admin/user routing are implemented over decoded USRSEC seed records", + priority=95, + ), + _online( + "CM00", + "COMEN01", + "COMEN01C", + "Main Menu", + modern_capability="main_menu", + modern_entrypoint="CardDemoService.main_menu", + proof_grade="B", + proof_basis="COMEN02Y/COMEN01C regular menu option count and routes are transcribed into the modern menu surface", + priority=70, + ), + _online( + "CAVW", + "COACTVW", + "COACTVWC", + "Account View", + modern_capability="account_view", + modern_entrypoint="CardDemoService.get_account_bundle", + proof_grade="B", + proof_basis="modern output is generated from original account/customer/card/transaction seed records", + priority=100, + ), + _online( + "CAUP", + "COACTUP", + "COACTUPC", + "Account Update", + modern_capability="account_update", + modern_entrypoint="CardDemoService.update_account", + proof_grade="B", + proof_basis="COACTUPC account/customer field validation, no-change detection, account xref lookup, and rewrite flow are implemented over decoded seed records", + priority=90, + ), + _online( + "CCLI", + "COCRDLI", + "COCRDLIC", + "Credit Card List", + modern_capability="card_list", + modern_entrypoint="CardDemoService.list_cards", + proof_grade="B", + proof_basis="modern output is generated from original card and xref seed records", + priority=95, + ), + _online( + "CCDL", + "COCRDSL", + "COCRDSLC", + "Credit Card View", + modern_capability="card_view", + modern_entrypoint="CardDemoService.get_card_detail", + proof_grade="B", + proof_basis="COCRDSLC account/card search-key validation and CARDDAT lookup are implemented over decoded seed records", + priority=85, + ), + _online( + "CCUP", + "COCRDUP", + "COCRDUPC", + "Credit Card Update", + modern_capability="card_update", + modern_entrypoint="CardDemoService.update_card", + proof_grade="B", + proof_basis="COCRDUPC name/status/month/year validation, no-change detection, hidden-field preservation, and card rewrite are implemented over decoded seed records", + priority=85, + ), + _online( + "CT00", + "COTRN00", + "COTRN00C", + "Transaction List", + modern_capability="transaction_list", + modern_entrypoint="CardDemoService.list_transactions", + proof_grade="B", + proof_basis="modern output is generated from original transaction/type/category seed records", + priority=100, + ), + _online( + "CT01", + "COTRN01", + "COTRN01C", + "Transaction View", + modern_capability="transaction_view", + modern_entrypoint="CardDemoService.list_transactions", + proof_grade="B", + proof_basis="transaction detail fields are exposed from original transaction records", + priority=90, + ), + _online( + "CT02", + "COTRN02", + "COTRN02C", + "Transaction Add", + modern_capability="transaction_add", + modern_entrypoint="CardDemoService.add_transaction", + proof_grade="B", + proof_basis="COTRN02C key resolution, confirmation, field validation, transaction-id increment, and TRANSACT write are implemented over seed xref/transaction records", + priority=95, + ), + _online( + "CR00", + "CORPT00", + "CORPT00C", + "Transaction Reports", + modern_capability="transaction_report", + modern_entrypoint="CardDemoService.transaction_report", + proof_grade="B", + proof_basis="report rows and totals are generated from original transaction/type/category/card seed records using the legacy report date-filter shape", + priority=80, + ), + _online( + "CB00", + "COBIL00", + "COBIL00C", + "Bill Payment", + modern_capability="bill_payment", + modern_entrypoint="CardDemoService.bill_payment", + proof_grade="B", + proof_basis="full-balance payment transaction and account update follow COBIL00C source flow over original account/xref seed records", + priority=95, + ), + _online( + "CPVS", + "COPAU00", + "COPAUS0C", + "Pending Authorization Summary", + optional_module="IMS-DB2-MQ: Pending Authorizations", + notes="Read IMS and VSAM", + modern_capability="pending_authorization_summary", + modern_entrypoint="CardDemoService.pending_authorization_summary", + proof_grade="B", + proof_basis="DBPAUTP0 IMS unload is decoded with PAUTSUM0/PAUTDTL1 DBD segment sizes and CIPAUSMY/CIPAUDTY copybook offsets; COPAUS0C account summary and five-row authorization page are modeled over the decoded seed records", + priority=60, + ), + _online( + "CPVD", + "COPAU01", + "COPAUS1C", + "Pending Authorization Details", + optional_module="IMS-DB2-MQ: Pending Authorizations", + notes="Update IMS and Insert DB2", + modern_capability="pending_authorization_detail/fraud_mark", + modern_entrypoint="CardDemoService.pending_authorization_detail/mark_authorization_fraud", + proof_grade="B", + proof_basis="COPAUS1C PAUT9CTS detail lookup and PF5 fraud toggle are modeled over decoded PAUTDTL1 rows with AUTHFRDS shadow-table writes following COPAUS2C DCLGEN/DDL", + priority=60, + ), + _online( + "CP00", + "", + "COPAUA0C", + "Process Authorization Requests", + optional_module="IMS-DB2-MQ: Pending Authorizations", + notes="MQ trigger, request and response; Insert and Update to IMS", + modern_capability="authorization_request_processing", + modern_entrypoint="CardDemoService.process_authorization_request", + proof_grade="B", + proof_basis="COPAUA0C comma-delimited MQ request parse, card/account/customer lookup, available-credit decision, response CSV, PAUTSUM0 update/insert, and PAUTDTL1 insert are modeled over decoded legacy seed data", + priority=60, + ), + _online( + "CA00", + "COADM01", + "COADM01C", + "Admin Menu", + optional_module="Db2: Transaction Type Mgmt", + modern_capability="admin_menu", + modern_entrypoint="CardDemoService.admin_menu", + proof_grade="B", + proof_basis="COADM02Y/COADM01C admin menu option count and routes are transcribed into the modern menu surface", + priority=55, + ), + _online( + "CU00", + "COUSR00", + "COUSR00C", + "List Users", + modern_capability="user_list", + modern_entrypoint="CardDemoService.list_users", + proof_grade="B", + proof_basis="modern output is generated from original EBCDIC user security file", + priority=75, + ), + _online( + "CU01", + "COUSR01", + "COUSR01C", + "Add User", + modern_capability="user_add", + modern_entrypoint="CardDemoService.add_user", + proof_grade="B", + proof_basis="COUSR01C required-field, duplicate-user, fixed-width normalization, and USRSEC write semantics are replayed against SQLite users with source-shaped messages", + priority=70, + ), + _online( + "CU02", + "COUSR02", + "COUSR02C", + "Update User", + modern_capability="user_update", + modern_entrypoint="CardDemoService.update_user", + proof_grade="B", + proof_basis="COUSR02C lookup, required-field, not-found, no-change, and USRSEC rewrite semantics are replayed against SQLite users with source-shaped messages", + priority=70, + ), + _online( + "CU03", + "COUSR03", + "COUSR03C", + "Delete User", + modern_capability="user_delete", + modern_entrypoint="CardDemoService.delete_user", + proof_grade="B", + proof_basis="COUSR03C lookup, not-found, and USRSEC delete semantics are replayed against SQLite users with source-shaped messages", + priority=70, + ), + _online( + "CTTU", + "COTRTUP", + "COTRTUPC", + "Tran Type add/edit", + optional_module="Db2: Transaction Type Mgmt", + notes="Update and insert on Db2", + modern_capability="transaction_type_maintenance", + modern_entrypoint="CardDemoService.upsert_transaction_type/delete_transaction_type", + proof_grade="B", + proof_basis="COTRTUPC type-code/description validation, no-change detection, update-or-insert, and child-record delete guard are implemented over transaction type seed records", + priority=65, + ), + _online( + "CTLI", + "COTRTLI", + "COTRTLIC", + "Tran Type list/update/delete", + optional_module="Db2: Transaction Type Mgmt", + notes="Demonstrates cursor and delete in Db2", + modern_capability="transaction_type_lookup", + modern_entrypoint="CardDemoService.transaction_types", + proof_grade="B", + proof_basis="COTRTLIC forward/backward cursor filters, seven-row page shape, TR_TYPE/TR_DESCRIPTION predicates, and update/delete handoff semantics are modeled over transaction type seed records", + priority=65, + ), + _online( + "CDRD", + "", + "CODATE01", + "Inquire System Date via MQ", + optional_module="MQ Integration", + notes="Demonstrates MQ request/response pattern", + modern_capability="mq_system_date", + modern_entrypoint="CardDemoService.mq_system_date", + proof_grade="B", + proof_basis="CODATE01 MQ GET/PUT reply flow is modeled with source-shaped 1000-byte request/reply metadata and deterministic CICS FORMATTIME MM-DD-YYYY/time formatting", + priority=45, + ), + _online( + "CDRA", + "", + "COACCT01", + "Inquire account details via MQ", + optional_module="MQ Integration", + notes="Demonstrates MQ request/response pattern", + modern_capability="mq_account_inquiry", + modern_entrypoint="CardDemoService.mq_account_inquiry", + proof_grade="B", + proof_basis="COACCT01 REQUEST-MSG-COPY function/key validation, ACCTDAT account lookup, source labels, not-found, and invalid-function reply paths are modeled over decoded account seed records", + priority=45, + ), + _batch("DUSRSECJ", "IEBGENER", "Initial Load of User security file", modern_capability="user_security_seed_load", modern_entrypoint="seed_from_legacy", proof_grade="B", proof_basis="EBCDIC user security data is parsed and loaded", priority=75), + _batch( + "DEFGDGB", + "IDCAMS", + "Setup GDG Bases", + modern_capability="batch_resource_setup", + modern_entrypoint="CardDemoService.batch_resource_setup('DEFGDGB')", + proof_grade="B", + proof_basis="DEFGDGB IDCAMS DEFINE GENERATIONDATAGROUP names, LIMIT(5), SCRATCH, and LASTCC=12 tolerance are modeled as explicit resource metadata", + priority=35, + ), + _batch( + "DEFGDGD", + "IDCAMS", + "Setup more GDG Bases for Db2", + modern_capability="batch_resource_setup", + modern_entrypoint="CardDemoService.batch_resource_setup('DEFGDGD')", + proof_grade="B", + proof_basis="DEFGDGD Db2 reference GDG bases and first-generation IEBGENER loads for TRANTYPE, TRANCATG, and DISCGRP are modeled with source LRECLs and seed row counts", + priority=35, + ), + _batch("ACCTFILE", "IDCAMS", "Refresh Account Master", modern_capability="account_seed_load", modern_entrypoint="seed_from_legacy", proof_grade="B", proof_basis="account seed file is parsed and loaded", priority=90), + _batch("CARDFILE", "IDCAMS", "Refresh Card Master", modern_capability="card_seed_load", modern_entrypoint="seed_from_legacy", proof_grade="B", proof_basis="card seed file is parsed and loaded", priority=90), + _batch("CUSTFILE", "IDCAMS", "Refresh Customer Master", modern_capability="customer_seed_load", modern_entrypoint="seed_from_legacy", proof_grade="B", proof_basis="customer seed file is parsed and loaded", priority=90), + _batch( + "CREADB21", + "DSNTEP4", + "Creates CardDemo Db2 database and loads tables", + optional_module="Db2: Transaction Type Mgmt", + modern_capability="db2_reference_setup", + modern_entrypoint="CardDemoService.db2_reference_setup", + proof_grade="B", + proof_basis="CREADB21 DB2FREE/DB2CREAT/DB2LTTYP/DB2LTCAT step order, database/table/index/grant/foreign-key metadata, and reference row loads are modeled over SQLite transaction reference tables", + priority=50, + ), + _batch( + "TRANEXTR", + "DSNTIAUL", + "Extracts latest Db2 data for Transaction types", + optional_module="Db2: Transaction Type Mgmt", + modern_capability="transaction_type_reference_extract", + modern_entrypoint="CardDemoService.transaction_type_extract", + proof_grade="B", + proof_basis="TRANEXTR DSNTIAUL SQL, backup datasets, output datasets, 60-byte TRANTYPE/TRANCATG extract records, and ordering are modeled over transaction reference seed records", + priority=50, + ), + _batch("DISCGRP", "IDCAMS", "Load Disclosure Group File", modern_capability="disclosure_group_seed_load", modern_entrypoint="seed_from_legacy", proof_grade="B", proof_basis="disclosure group seed file is parsed and loaded, including overpunch interest-rate fields", priority=40), + _batch("TRANFILE", "IDCAMS", "Load Transaction Master file", modern_capability="transaction_seed_load", modern_entrypoint="seed_from_legacy", proof_grade="B", proof_basis="transaction seed file is parsed and loaded", priority=90), + _batch("TRANCATG", "IDCAMS", "Load Transaction category types", modern_capability="transaction_category_seed_load", modern_entrypoint="seed_from_legacy", proof_grade="B", proof_basis="transaction category seed file is parsed and loaded", priority=85), + _batch("TRANTYPE", "IDCAMS", "Load Transaction type file", modern_capability="transaction_type_seed_load", modern_entrypoint="seed_from_legacy", proof_grade="B", proof_basis="transaction type seed file is parsed and loaded", priority=85), + _batch("XREFFILE", "IDCAMS", "Account, Card and Customer cross reference", modern_capability="xref_seed_load", modern_entrypoint="seed_from_legacy", proof_grade="B", proof_basis="card/account/customer xref seed file is parsed and loaded", priority=90), + _batch( + "CLOSEFIL", + "IEFBR14", + "Close VSAM files in CICS", + modern_capability="batch_resource_setup", + modern_entrypoint="CardDemoService.batch_resource_setup('CLOSEFIL')", + proof_grade="B", + proof_basis="CLOSEFIL SDSF CEMT SET FIL close commands for TRANSACT, CCXREF, ACCTDAT, CXACAIX, and USRSEC are modeled as source command metadata", + priority=30, + ), + _batch("TCATBALF", "IDCAMS", "Refresh Transaction Category Balance", modern_capability="transaction_category_balance_seed_load", modern_entrypoint="seed_from_legacy", proof_grade="B", proof_basis="transaction category balance seed file is parsed and loaded for INTCALC input", priority=55), + _batch( + "TRANBKP", + "IDCAMS", + "Refresh Transaction Master", + modern_capability="transaction_master_backup", + modern_entrypoint="CardDemoService.transaction_master_backup", + proof_grade="B", + proof_basis="TRANBKP REPROC source backup, IDCAMS delete targets, KSDS key/record-size define metadata, and transaction-master row counts are modeled over seed transactions", + priority=55, + ), + _batch("POSTTRAN", "CBTRN02C", "Transaction processing job", modern_capability="post_transaction", modern_entrypoint="CardDemoService.post_transaction", proof_grade="B", proof_basis="card/account lookup, overlimit rejection, expiration rejection, transaction category balance update, and account cycle update follow CBTRN02C source flow over seed records", priority=95), + _batch( + "TRANIDX", + "IDCAMS", + "Define AIX for transaction file", + modern_capability="batch_resource_setup", + modern_entrypoint="CardDemoService.batch_resource_setup('TRANIDX')", + proof_grade="B", + proof_basis="TRANIDX DEFINE ALTERNATEINDEX, DEFINE PATH, and BLDINDEX source metadata are modeled, including KEYS(26 304), record size, AIX data/index, pathentry, and transaction source count", + priority=35, + ), + _batch( + "OPENFIL", + "IEFBR14", + "Open files in CICS", + modern_capability="batch_resource_setup", + modern_entrypoint="CardDemoService.batch_resource_setup('OPENFIL')", + proof_grade="B", + proof_basis="OPENFIL SDSF CEMT SET FIL open commands for TRANSACT, CCXREF, ACCTDAT, CXACAIX, and USRSEC are modeled as source command metadata", + priority=30, + ), + _batch("INTCALC", "CBACT04C", "Run interest calculations", modern_capability="interest_projection", modern_entrypoint="CardDemoService.interest_projection", proof_grade="B", proof_basis="modern output uses TCATBALF and DISCGRP seed records plus the CBACT04C interest formula", priority=85), + _batch("COMBTRAN", "SORT", "Combine transaction files", modern_capability="combined_transaction_preview", modern_entrypoint="CardDemoService.combined_transactions", proof_grade="B", proof_basis="COMBTRAN SORTIN concatenation, TRAN-ID CH(1,16) ascending sort, SORTOUT GDG creation, and IDCAMS REPRO target are modeled over seed transactions plus generated INTCALC records", priority=70), + _batch("CREASTMT", "CBSTM03A", "Produce transaction statement", modern_capability="account_statement", modern_entrypoint="CardDemoService.account_statement", proof_grade="B", proof_basis="plain statement records follow CBSTM03A fixed-width line layout, CBSTM03B keyed read shape, CREASTMT card-number/transaction-id sort order, and seed-data totals; exact mainframe spool execution is not replayed", priority=90), + _batch("TRANREPT", "CBTRN03C", "Transaction Report - Submitted from CICS", modern_capability="transaction_report", modern_entrypoint="CardDemoService.transaction_report", proof_grade="B", proof_basis="report rows and totals are generated from original transaction/type/category/card seed records using the legacy report date-filter shape", priority=80), + _batch( + "ESDSRRDS", + "IDCAMS", + "Create ESDS and RRDS VSAM files", + modern_capability="batch_resource_setup", + modern_entrypoint="CardDemoService.batch_resource_setup('ESDSRRDS')", + proof_grade="B", + proof_basis="ESDSRRDS predelete, instream 80-byte user PS file, ESDS NONINDEXED cluster, RRDS NUMBERED cluster, and REPRO copy steps are modeled with source dataset metadata", + priority=35, + ), + _batch( + "CBPAUP0J", + "CBPAUP0C", + "Purge Expired Authorizations", + optional_module="IMS-DB2-MQ: Pending Authorizations", + modern_capability="pending_authorization_expiry_purge", + modern_entrypoint="CardDemoService.purge_expired_authorizations", + proof_grade="B", + proof_basis="CBPAUP0C expiry calculation, PAUTDTL1 delete, PAUTSUM0 counter adjustment, and source duplicate-approved-count summary delete predicate are modeled over decoded IMS authorization records", + priority=55, + ), + _batch( + "MNTTRDB2", + "COBTUPDT", + "Maintain Transaction type table", + optional_module="Db2: Transaction Type Mgmt", + modern_capability="batch_transaction_type_maintenance", + modern_entrypoint="CardDemoService.maintain_transaction_types", + proof_grade="B", + proof_basis="MNTTRDB2 INPFILE fixed-record layout, COBTUPDT A/U/D/* routing, return-code 4 error path, duplicate/missing row SQL outcomes, and Db2 restrict-delete behavior are modeled over transaction type seed records", + priority=60, + ), +) + + +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 _source_index(source_root: Path) -> dict[str, list[Path]]: + index: dict[str, list[Path]] = {} + for path in source_root.rglob("*"): + if path.is_file() and path.suffix in SOURCE_SUFFIXES: + index.setdefault(path.stem.lower(), []).append(path) + return index + + +def _source_names(capability: CapabilityDefinition) -> list[str]: + names = [capability.transaction, capability.job, capability.bms_map, capability.program] + return sorted({name for name in names if name and name not in {"IDCAMS", "IEBGENER", "IEFBR14", "SORT", "DSNTEP4", "DSNTIAUL"}}) + + +def _source_refs(source_root: Path, index: dict[str, list[Path]], capability: CapabilityDefinition) -> list[dict[str, str]]: + refs: list[dict[str, str]] = [] + for name in _source_names(capability): + for path in sorted(index.get(name.lower(), [])): + refs.append( + { + "path": str(path.relative_to(source_root)).replace("\\", "/"), + "sha256": sha256_path(path), + } + ) + return refs + + +def _grade_claim(grade: str) -> str: + if grade == "A": + return "matches actual legacy runtime trace" + if grade == "B": + return "matches static legacy seed-data/copybook oracle" + if grade == "C": + return "implemented or partially implemented, but strict parity proof is missing" + return "discovered capability gap" + + +def _legacy_oracle(grade: str) -> str: + if grade == "A": + return "legacy_runtime_trace" + if grade == "B": + return "legacy_seed_data_and_copybook_contract" + if grade == "C": + return "static_contract_or_inferred_rule_only" + return "not_available_yet" + + +def build_capability_ledger(source_root: Path) -> list[dict[str, Any]]: + index = _source_index(source_root) + ledger: list[dict[str, Any]] = [] + for capability in CAPABILITIES: + row = asdict(capability) + row["legacy_oracle"] = _legacy_oracle(capability.proof_grade) + row["claim"] = _grade_claim(capability.proof_grade) + row["source_refs"] = _source_refs(source_root, index, capability) + row["source_ref_count"] = len(row["source_refs"]) + row["strict_parity_ready"] = capability.proof_grade == "A" + row["static_oracle_ready"] = capability.proof_grade in {"A", "B"} + ledger.append(row) + return ledger + + +def _row_dict(row: Any) -> dict[str, Any]: + return dict(row) if row is not None else {} + + +def mine_edge_cases(db_path: Path) -> list[dict[str, Any]]: + conn = connect(db_path) + try: + cases: list[dict[str, Any]] = [] + cases.append( + { + "edge_case_id": "account_lowest_balance", + "source": "accounts", + "sample": _row_dict( + conn.execute( + "SELECT account_id, current_balance_cents, credit_limit_cents FROM accounts ORDER BY current_balance_cents ASC LIMIT 1" + ).fetchone() + ), + "expected_behavior": "account view and payment logic preserve signed money fields", + } + ) + cases.append( + { + "edge_case_id": "account_highest_balance", + "source": "accounts", + "sample": _row_dict( + conn.execute( + "SELECT account_id, current_balance_cents, credit_limit_cents FROM accounts ORDER BY current_balance_cents DESC LIMIT 1" + ).fetchone() + ), + "expected_behavior": "account view reports large balances without truncation", + } + ) + cases.append( + { + "edge_case_id": "caup_active_status_yes_no", + "source": "COACTUPC", + "sample": {"valid": ["Y", "N"], "invalid": "anything else"}, + "expected_behavior": "CAUP accepts only Y/N account status values and rejects blank or other input", + } + ) + cases.append( + { + "edge_case_id": "caup_no_change_update", + "source": "COACTUPC", + "sample": _row_dict( + conn.execute( + "SELECT account_id, active_status, credit_limit_cents, cash_credit_limit_cents, group_id FROM accounts ORDER BY account_id LIMIT 1" + ).fetchone() + ), + "expected_behavior": "CAUP detects unchanged account/customer fields and does not rewrite records", + } + ) + cases.append( + { + "edge_case_id": "transaction_largest_debit", + "source": "transactions", + "sample": _row_dict( + conn.execute( + "SELECT transaction_id, type_code, category_code, amount_cents, card_number FROM transactions ORDER BY amount_cents DESC LIMIT 1" + ).fetchone() + ), + "expected_behavior": "transaction view preserves maximum positive amount", + } + ) + cases.append( + { + "edge_case_id": "transaction_largest_credit_or_negative", + "source": "transactions", + "sample": _row_dict( + conn.execute( + "SELECT transaction_id, type_code, category_code, amount_cents, card_number FROM transactions ORDER BY amount_cents ASC LIMIT 1" + ).fetchone() + ), + "expected_behavior": "transaction view and account totals preserve negative overpunch values", + } + ) + cases.append( + { + "edge_case_id": "ct02_signed_amount_format", + "source": "COTRN02C", + "sample": {"legacy_format": "-99999999.99", "accepted_example": "+00000012.34"}, + "expected_behavior": "CT02 accepts only a sign, eight dollar digits, decimal point, and two cent digits before writing TRANSACT", + } + ) + cases.append( + { + "edge_case_id": "ct02_confirmation_required", + "source": "COTRN02C", + "sample": {"valid_confirm": "Y", "reject_confirm": "blank/N/other"}, + "expected_behavior": "CT02 validates all fields but writes the transaction only when Confirm is Y or y", + } + ) + cases.append( + { + "edge_case_id": "inactive_card_if_present", + "source": "cards", + "sample": _row_dict( + conn.execute( + "SELECT card_number, account_id, active_status, expiration_date FROM cards WHERE active_status <> 'Y' ORDER BY card_number LIMIT 1" + ).fetchone() + ), + "expected_behavior": "card update and bill payment reject inactive card paths when present", + } + ) + cases.append( + { + "edge_case_id": "ccdl_ccup_card_key_validation", + "source": "COCRDSLC/COCRDUPC", + "sample": { + "account_id_width": 11, + "card_number_width": 16, + "invalid_cards": ["", "0000000000000000", "123", "notnumeric"], + }, + "expected_behavior": "CCDL/CCUP require nonzero numeric account and 16-digit nonzero card search keys before CARDDAT lookup", + } + ) + cases.append( + { + "edge_case_id": "ccup_card_update_validation", + "source": "COCRDUPC", + "sample": { + "editable_fields": ["embossed_name", "active_status", "expiration_month", "expiration_year"], + "valid_status": ["Y", "N"], + "valid_month": "1..12", + "valid_year": "1950..2099", + }, + "expected_behavior": "CCUP accepts alphabetic card names, Y/N status, valid expiry month/year, preserves hidden fields, and rejects no-change updates", + } + ) + cases.append( + { + "edge_case_id": "transaction_type_category_coverage", + "source": "transaction_types/transaction_categories", + "sample": { + "type_count": conn.execute("SELECT COUNT(*) FROM transaction_types").fetchone()[0], + "category_count": conn.execute("SELECT COUNT(*) FROM transaction_categories").fetchone()[0], + "observed_pairs": conn.execute( + "SELECT COUNT(*) FROM (SELECT DISTINCT type_code, category_code FROM transactions)" + ).fetchone()[0], + }, + "expected_behavior": "lookup paths preserve type/category joins and unknown combinations", + } + ) + cases.append( + { + "edge_case_id": "ctli_cursor_filters_and_page_size", + "source": "COTRTLIC", + "sample": { + "page_size": 7, + "forward_predicate": "TR_TYPE >= WS-START-KEY", + "backward_predicate": "TR_TYPE < WS-START-KEY", + "type_filter": "TR_TYPE = WS-TYPE-CD-FILTER", + "description_filter": "TR_DESCRIPTION LIKE WS-TYPE-DESC-FILTER", + "type_count": conn.execute("SELECT COUNT(*) FROM transaction_types").fetchone()[0], + }, + "expected_behavior": "CTLI pages transaction types through seven-row forward/backward cursor windows with optional type and description filters", + } + ) + cases.append( + { + "edge_case_id": "cttu_type_code_numeric_nonzero", + "source": "COTRTUPC", + "sample": {"valid": ["1", "08"], "invalid": ["", "00", "A1"]}, + "expected_behavior": "CTTU normalizes numeric type codes to two digits and rejects blank, zero, or nonnumeric values", + } + ) + cases.append( + { + "edge_case_id": "cttu_child_delete_guard", + "source": "COTRTUPC", + "sample": _row_dict( + conn.execute( + "SELECT type_code, description FROM transaction_types WHERE type_code = '01'" + ).fetchone() + ), + "expected_behavior": "CTTU rejects deletion of transaction types that still have transaction/category/disclosure/balance child rows", + } + ) + cases.append( + { + "edge_case_id": "mnttrdb2_fixed_record_actions_and_sql_errors", + "source": "MNTTRDB2.jcl/COBTUPDT.cbl/TRNTYCAT.ddl", + "sample": { + "record_layout": { + "action": "column 1", + "type_code": "columns 2-3", + "description": "columns 4-53", + }, + "valid_actions": ["A", "U", "D", "*"], + "return_code_on_error": 4, + "restrict_delete_type": "01", + }, + "expected_behavior": "MNTTRDB2 applies fixed-record add/update/delete/comment actions and records return-code 4 for invalid actions, duplicate adds, missing rows, and Db2 restrict-delete failures", + } + ) + cases.append( + { + "edge_case_id": "creastmt_fixed_width_source_sort", + "source": "CREASTMT.JCL/CBSTM03A", + "sample": { + "statement_lrecl": 80, + "html_lrecl": 100, + "sort_fields": ["card_number", "transaction_id"], + "transaction_count_account_1": conn.execute( + """ + SELECT COUNT(*) + FROM transactions t + JOIN cards c ON c.card_number = t.card_number + WHERE c.account_id = 1 + """ + ).fetchone()[0], + }, + "expected_behavior": "CREASTMT preserves 80-byte statement records, source card/transaction ordering, and a Total EXP line equal to the transaction amount sum", + } + ) + cases.append( + { + "edge_case_id": "combtran_transaction_id_sort_repro", + "source": "COMBTRAN.jcl", + "sample": { + "sortin": [ + "AWS.M2.CARDDEMO.TRANSACT.BKUP(0)", + "AWS.M2.CARDDEMO.SYSTRAN(0)", + ], + "sort_field": {"symbol": "TRAN-ID", "start": 1, "length": 16, "type": "CH", "order": "A"}, + "sortout": "AWS.M2.CARDDEMO.TRANSACT.COMBINED(+1)", + "repro_target": "AWS.M2.CARDDEMO.TRANSACT.VSAM.KSDS", + "transaction_seed_count": conn.execute("SELECT COUNT(*) FROM transactions").fetchone()[0], + }, + "expected_behavior": "COMBTRAN concatenates current backup and system-generated transaction streams, sorts by TRAN-ID bytes 1-16 ascending, writes the combined GDG, then REPROs to the transaction KSDS", + } + ) + cases.append( + { + "edge_case_id": "tranbkp_transaction_master_ksds_contract", + "source": "TRANBKP.jcl", + "sample": { + "source_dataset": "AWS.M2.CARDDEMO.TRANSACT.VSAM.KSDS", + "backup_dataset": "AWS.M2.CARDDEMO.TRANSACT.BKUP(+1)", + "key": {"length": 16, "offset": 0}, + "record_size": 350, + "transaction_seed_count": conn.execute("SELECT COUNT(*) FROM transactions").fetchone()[0], + }, + "expected_behavior": "TRANBKP backs up the current transaction KSDS to the next GDG, tolerates delete-not-found return codes, and redefines a 350-byte indexed KSDS keyed by TRAN-ID bytes 1-16", + } + ) + cases.append( + { + "edge_case_id": "tranextr_reference_extract_fixed_width", + "source": "TRANEXTR.jcl", + "sample": { + "trantype_lrecl": 60, + "trancatg_lrecl": 60, + "type_count": conn.execute("SELECT COUNT(*) FROM transaction_types").fetchone()[0], + "category_count": conn.execute("SELECT COUNT(*) FROM transaction_categories").fetchone()[0], + "type_filler": "8 zero bytes", + "category_filler": "4 zero bytes", + }, + "expected_behavior": "TRANEXTR emits ordered 60-byte DSNTIAUL records for transaction types and categories after backing up the previous flat files", + } + ) + cases.append( + { + "edge_case_id": "creadb21_db2_reference_schema_and_load_order", + "source": "CREADB21.jcl/DB2CREAT.ctl/DB2LTTYP.ctl/DB2LTCAT.ctl", + "sample": { + "db2_system": "DAZ1", + "database": "CARDDEMO", + "steps": ["FREEPLN", "CRCRDDB", "RUNTEP2", "LDTCCAT"], + "type_count": conn.execute("SELECT COUNT(*) FROM transaction_types").fetchone()[0], + "category_count": conn.execute("SELECT COUNT(*) FROM transaction_categories").fetchone()[0], + "foreign_key": "TRANSACTION_TYPE_CATEGORY.TRC_TYPE_CODE -> TRANSACTION_TYPE.TR_TYPE ON DELETE RESTRICT", + }, + "expected_behavior": "CREADB21 creates the Db2 database/tablespaces/reference tables, loads transaction types before categories, and preserves the restrict-delete parent/child contract", + } + ) + cases.append( + { + "edge_case_id": "copybook_field_boundaries", + "source": "copybooks", + "sample": { + "customers_width": 500, + "accounts_width": 300, + "cards_width": 150, + "transactions_width": 350, + "disclosure_groups_width": 50, + "transaction_category_balances_width": 50, + "max_customer_field": max(field.length for field in CUSTOMER_FIELDS), + "max_transaction_field": max(field.length for field in TRANSACTION_FIELDS), + "max_disclosure_group_field": max(field.length for field in DISCLOSURE_GROUP_FIELDS), + "max_transaction_category_balance_field": max( + field.length for field in TRANSACTION_CATEGORY_BALANCE_FIELDS + ), + }, + "expected_behavior": "modern parser and API preserve fixed-width truncation boundaries", + } + ) + cases.append( + { + "edge_case_id": "disclosure_group_default_fallback", + "source": "disclosure_groups", + "sample": _row_dict( + conn.execute( + "SELECT group_id, type_code, category_code, interest_rate_basis_points FROM disclosure_groups WHERE group_id = 'DEFAULT' ORDER BY type_code, category_code LIMIT 1" + ).fetchone() + ), + "expected_behavior": "interest projection falls back to DEFAULT group when an account-specific disclosure row is absent", + } + ) + cases.append( + { + "edge_case_id": "zero_transaction_category_balance", + "source": "transaction_category_balances", + "sample": _row_dict( + conn.execute( + "SELECT account_id, type_code, category_code, balance_cents FROM transaction_category_balances ORDER BY ABS(balance_cents), account_id LIMIT 1" + ).fetchone() + ), + "expected_behavior": "INTCALC preview still materializes account/category rows and generates zero-interest transactions when balances are zero", + } + ) + cases.append( + { + "edge_case_id": "posttran_overlimit_boundary", + "source": "accounts", + "sample": _row_dict( + conn.execute( + """ + SELECT account_id, credit_limit_cents, current_cycle_credit_cents, current_cycle_debit_cents + FROM accounts + ORDER BY credit_limit_cents ASC + LIMIT 1 + """ + ).fetchone() + ), + "expected_behavior": "POSTTRAN rejects when current_cycle_credit minus current_cycle_debit plus transaction amount exceeds credit limit", + } + ) + cases.append( + { + "edge_case_id": "posttran_expired_account_boundary", + "source": "accounts", + "sample": _row_dict( + conn.execute( + "SELECT account_id, expiration_date FROM accounts ORDER BY expiration_date ASC LIMIT 1" + ).fetchone() + ), + "expected_behavior": "POSTTRAN rejects transactions whose original date is after account expiration", + } + ) + cases.append( + { + "edge_case_id": "signon_lowercase_credentials", + "source": "users", + "sample": _row_dict( + conn.execute( + "SELECT user_id, user_type FROM users ORDER BY user_id LIMIT 1" + ).fetchone() + ), + "expected_behavior": "CC00 uppercases user id and password before USRSEC lookup", + } + ) + cases.append( + { + "edge_case_id": "user_security_duplicate_add", + "source": "users", + "sample": _row_dict( + conn.execute( + "SELECT user_id, first_name, last_name, user_type FROM users ORDER BY user_id LIMIT 1" + ).fetchone() + ), + "expected_behavior": "CU01 rejects an add when the user id already exists", + } + ) + cases.append( + { + "edge_case_id": "user_security_required_fields", + "source": "COUSR01C/COUSR02C", + "sample": _row_dict( + conn.execute( + "SELECT user_id, first_name, last_name, user_type FROM users ORDER BY user_id LIMIT 1" + ).fetchone() + ), + "expected_behavior": "CU01 and CU02 reject blank user id, first name, last name, password, and user type with source-shaped messages", + } + ) + cases.append( + { + "edge_case_id": "user_security_no_change_update", + "source": "users", + "sample": _row_dict( + conn.execute( + "SELECT user_id, first_name, last_name, user_type FROM users ORDER BY user_id DESC LIMIT 1" + ).fetchone() + ), + "expected_behavior": "CU02 rejects updates when all editable fields match the existing user record", + } + ) + cases.append( + { + "edge_case_id": "user_security_non_admin_type_regular_route", + "source": "COUSR01C/COUSR02C/COSGN00C", + "sample": _row_dict( + conn.execute( + "SELECT user_id, user_type FROM users WHERE user_type <> 'A' ORDER BY user_id LIMIT 1" + ).fetchone() + ), + "expected_behavior": "CU01/CU02 only require nonblank user type; COSGN00C routes non-admin types to the regular menu", + } + ) + cases.append( + { + "edge_case_id": "pending_authorization_ims_segment_header_offset", + "source": "DBPAUTP0/CIPAUSMY/CIPAUDTY", + "sample": { + "summary_count": conn.execute("SELECT COUNT(*) FROM pending_authorization_summaries").fetchone()[0], + "detail_count": conn.execute("SELECT COUNT(*) FROM pending_authorization_details").fetchone()[0], + "first_detail": _row_dict( + conn.execute( + """ + SELECT account_id, authorization_key, auth_orig_date, auth_orig_time, card_number + FROM pending_authorization_details + ORDER BY sequence_no + LIMIT 1 + """ + ).fetchone() + ), + }, + "expected_behavior": "CPVS/CPVD seed proof ignores DFSURGU0 control markers and decodes only valid PAUTSUM0/PAUTDTL1 segment payloads", + } + ) + cases.append( + { + "edge_case_id": "authorization_available_credit_boundary", + "source": "COPAUA0C", + "sample": _row_dict( + conn.execute( + """ + SELECT account_id, credit_limit_cents, credit_balance_cents, + credit_limit_cents - credit_balance_cents AS available_cents + FROM pending_authorization_summaries + ORDER BY available_cents ASC + LIMIT 1 + """ + ).fetchone() + ), + "expected_behavior": "CP00 approves up to available pending authorization credit and declines above it with response reason 4100", + } + ) + cases.append( + { + "edge_case_id": "authorization_purge_reverse_date_key", + "source": "CBPAUP0C", + "sample": _row_dict( + conn.execute( + """ + SELECT account_id, authorization_key, auth_date_key, auth_yyddd + FROM pending_authorization_details + ORDER BY auth_yyddd ASC + LIMIT 1 + """ + ).fetchone() + ), + "expected_behavior": "CBPAUP0J computes age using CURRENT-YYDDD - (99999 - PA-AUTH-DATE-9C), not the request date string", + } + ) + cases.append( + { + "edge_case_id": "mq_cdrd_request_payload_ignored", + "source": "CODATE01", + "sample": { + "request_layout": "WS-FUNC PIC X(04), WS-KEY PIC 9(11), filler to 1000 bytes", + "reply_queue": "CARD.DEMO.REPLY.DATE", + "reply_labels": ["SYSTEM DATE : ", "SYSTEM TIME : "], + }, + "expected_behavior": "CDRD does not branch on request payload content after MQGET; it always replies with CICS ASKTIME/FORMATTIME MM-DD-YYYY and HH:MM:SS when queue operations succeed", + } + ) + cases.append( + { + "edge_case_id": "mq_cdra_inqa_account_key_validation", + "source": "COACCT01/CVACT01Y", + "sample": { + "valid_function": "INQA", + "account_key_width": 11, + "valid_account": _row_dict( + conn.execute( + "SELECT account_id, active_status, current_balance_cents, group_id FROM accounts ORDER BY account_id LIMIT 1" + ).fetchone() + ), + "invalid_paths": ["non-INQA function", "zero account key", "ACCTDAT NOTFND"], + }, + "expected_behavior": "CDRA accepts only INQA with an 11-digit account key greater than zero, returns labeled account fields from ACCTDAT on success, and emits INVALID REQUEST PARAMETERS for bad functions, zero keys, and missing accounts", + } + ) + cases.append( + { + "edge_case_id": "batch_gdg_limit_scratch_first_generation", + "source": "DEFGDGB/DEFGDGD", + "sample": { + "base_gdg_limit": 5, + "base_gdg_count": 6, + "db2_reference_gdg_count": 3, + "first_generation_lrecls": {"TRANTYPE": 60, "TRANCATG": 60, "DISCGRP": 50}, + }, + "expected_behavior": "GDG setup preserves LIMIT(5) SCRATCH for all source bases and materializes first-generation Db2 reference backups with the same LRECLs and source row counts", + } + ) + cases.append( + { + "edge_case_id": "vsam_esds_rrds_user_security_layout", + "source": "ESDSRRDS", + "sample": { + "instream_user_count": conn.execute("SELECT COUNT(*) FROM users").fetchone()[0], + "record_size": [80, 80], + "organizations": ["NONINDEXED", "NUMBERED"], + "repro_targets": ["AWS.M2.CARDDEMO.USRSEC.VSAM.ESDS", "AWS.M2.CARDDEMO.USRSEC.VSAM.RRDS"], + }, + "expected_behavior": "ESDSRRDS creates both ESDS and RRDS user-security VSAM forms from the same 80-byte PS source and REPROs the complete instream user set into both clusters", + } + ) + cases.append( + { + "edge_case_id": "transaction_aix_processed_timestamp_key", + "source": "TRANIDX", + "sample": { + "base_cluster": "AWS.M2.CARDDEMO.TRANSACT.VSAM.KSDS", + "aix": "AWS.M2.CARDDEMO.TRANSACT.VSAM.AIX", + "keys": {"length": 26, "offset": 304}, + "transaction_count": conn.execute("SELECT COUNT(*) FROM transactions").fetchone()[0], + }, + "expected_behavior": "TRANIDX defines a nonunique upgraded alternate index over processed timestamp bytes 304-329, then exposes it through the AIX path and BLDINDEXes from the transaction KSDS", + } + ) + cases.append( + { + "edge_case_id": "cics_file_control_command_set", + "source": "CLOSEFIL/OPENFIL", + "sample": { + "region": "CICSAWSA", + "files": ["TRANSACT", "CCXREF", "ACCTDAT", "CXACAIX", "USRSEC"], + "close_code": "CLO", + "open_code": "OPE", + }, + "expected_behavior": "CICS file-control setup uses the same ordered five-file set for close and open operations, changing only the terminal CEMT action code", + } + ) + return cases + finally: + conn.close() + + +def build_golden_traces(source_root: Path, db_path: Path) -> list[dict[str, Any]]: + service = CardDemoService(db_path) + summary = service.summary() + customers = service.list_customers("Kessler", limit=5) + accounts = service.list_accounts(customer_id=1, limit=5) + bundle = service.get_account_bundle(1) or {} + cards = bundle.get("cards", []) + first_card = cards[0] if cards else {} + card_detail = service.get_card_detail(first_card.get("card_number", ""), account_id=1) if first_card else {} + transactions = service.list_transactions(account_id=1, limit=5) + transaction_report = service.transaction_report(account_id=1, limit=1000) + statement = service.account_statement(1) + interest_projection = service.interest_projection(limit=1000) + combined = service.combined_transactions(limit=1000) + transaction_backup = service.transaction_master_backup(limit=5) + transaction_type_extract = service.transaction_type_extract() + db2_reference_setup = service.db2_reference_setup() + tx_types = service.transaction_types() + tx_types_filtered = service.transaction_types(type_filter="01") + tx_types_desc_filtered = service.transaction_types(description_filter="%PAYMENT%") + tx_types_backward = service.transaction_types(start_key="07", direction="backward", page_size=3) + users = service.list_users() + signon_admin = service.signon("admin001", "password") + signon_bad_password = service.signon("ADMIN001", "BADPASS") + main_menu = service.main_menu() + admin_menu = service.admin_menu() + pending_summary = service.pending_authorization_summary(1, page_size=5) + pending_detail = service.pending_authorization_detail( + 1, authorization_key=pending_summary["authorizations"][0]["authorization_key"] + ) + mq_date = service.mq_system_date({"request_message": "IGNR00000000001"}, now="2026-05-23T11:12:13") + mq_account = service.mq_account_inquiry({"request_message": "INQA00000000001"}) + mq_account_not_found = service.mq_account_inquiry({"function": "INQA", "account_id": 99999999999}) + mq_account_bad_function = service.mq_account_inquiry({"function": "BAD", "account_id": 1}) + resource_setup = service.batch_resource_setup() + gdg_base_setup = service.batch_resource_setup("DEFGDGB") + db2_gdg_setup = service.batch_resource_setup("DEFGDGD") + esds_rrds_setup = service.batch_resource_setup("ESDSRRDS") + tranidx_setup = service.batch_resource_setup("TRANIDX") + closefil_setup = service.batch_resource_setup("CLOSEFIL") + openfil_setup = service.batch_resource_setup("OPENFIL") + + traces: list[dict[str, Any]] = [ + { + "trace_id": "summary_seed_counts", + "capability_ids": ["batch:ACCTFILE", "batch:CARDFILE", "batch:CUSTFILE", "batch:TRANFILE", "batch:DUSRSECJ"], + "oracle": "legacy_seed_files", + "input": {}, + "expected": summary, + "proof_grade": "B", + }, + { + "trace_id": "customer_search_kessler", + "capability_ids": ["online:CAVW"], + "oracle": "legacy_customer_seed_file", + "input": {"query": "Kessler"}, + "expected": {"count": len(customers), "first_customer_id": customers[0]["customer_id"] if customers else None}, + "proof_grade": "B", + }, + { + "trace_id": "account_bundle_1", + "capability_ids": ["online:CAVW", "online:CCLI", "online:CT00"], + "oracle": "legacy_account_card_xref_transaction_seed_files", + "input": {"account_id": 1}, + "expected": { + "account_id": bundle.get("account", {}).get("account_id"), + "current_balance": bundle.get("account", {}).get("current_balance"), + "customer_count": len(bundle.get("customers", [])), + "card_count": len(bundle.get("cards", [])), + "recent_transaction_count": len(bundle.get("transactions", [])), + }, + "proof_grade": "B", + }, + { + "trace_id": "mq_system_date_cdrd_reply", + "capability_ids": ["online:CDRD"], + "oracle": "legacy_codate01_mq_get_asktime_formattime_put_source_flow", + "input": {"request_message_prefix": mq_date["request_message"][:15], "now": "2026-05-23T11:12:13"}, + "expected": { + "legacy_transaction": mq_date["legacy_transaction"], + "legacy_program": mq_date["legacy_program"], + "reply_queue": mq_date["reply_queue"], + "system_date": mq_date["system_date"], + "system_time": mq_date["system_time"], + "reply_message": mq_date["reply_message"], + "request_payload_validated": False, + }, + "proof_grade": "B", + }, + { + "trace_id": "mq_account_inquiry_cdra_success_and_invalid", + "capability_ids": ["online:CDRA"], + "oracle": "legacy_coacct01_request_msg_copy_acctdat_read_and_invalid_parameter_paths", + "input": {"function": "INQA", "account_id": 1}, + "expected": { + "legacy_transaction": mq_account["legacy_transaction"], + "legacy_program": mq_account["legacy_program"], + "reply_queue": mq_account["reply_queue"], + "request_account_key": mq_account["request"]["account_id_text"], + "account_id": mq_account["account_data"]["account_id"], + "active_status": mq_account["account_data"]["active_status"], + "reply_has_account_label": "ACCOUNT ID : 00000000001" in mq_account["reply_message"], + "not_found_reply": mq_account_not_found["reply_message"], + "bad_function_reply": mq_account_bad_function["reply_message"], + }, + "proof_grade": "B", + }, + { + "trace_id": "batch_resource_setup_gdg_vsam_aix_cics", + "capability_ids": [ + "batch:DEFGDGB", + "batch:DEFGDGD", + "batch:ESDSRRDS", + "batch:TRANIDX", + "batch:CLOSEFIL", + "batch:OPENFIL", + ], + "oracle": "legacy_setup_jcl_resource_metadata", + "input": {"jobs": resource_setup["legacy_jobs"]}, + "expected": { + "resource_count": resource_setup["resource_count"], + "base_gdg_names": [row["name"] for row in gdg_base_setup["gdg_bases"]], + "db2_first_generation_counts": [ + db2_gdg_setup["steps"][1]["record_count"], + db2_gdg_setup["steps"][3]["record_count"], + db2_gdg_setup["steps"][5]["record_count"], + ], + "esds_rrds_organizations": [row["organization"] for row in esds_rrds_setup["clusters"]], + "tranidx_keys": tranidx_setup["alternate_index"]["keys"], + "tranidx_source_count": tranidx_setup["bldindex"]["source_record_count"], + "close_code": closefil_setup["cemt_code"], + "open_code": openfil_setup["cemt_code"], + "file_sets_match": closefil_setup["files"] == openfil_setup["files"], + }, + "proof_grade": "B", + }, + { + "trace_id": "pending_authorization_cpvs_summary_page", + "capability_ids": ["online:CPVS"], + "oracle": "legacy_dbpautp0_ims_unload_and_copaus0c_page_flow", + "input": {"account_id": 1, "page_size": 5}, + "expected": { + "summary_count": pending_summary["summary"]["approved_auth_count"], + "summary_amount_cents": pending_summary["summary"]["approved_auth_amount_cents"], + "returned_authorizations": len(pending_summary["authorizations"]), + "next_page": pending_summary["next_page"], + "first_transaction_id": pending_summary["authorizations"][0]["transaction_id"], + }, + "proof_grade": "B", + }, + { + "trace_id": "pending_authorization_cpvd_detail_lookup", + "capability_ids": ["online:CPVD"], + "oracle": "legacy_copaus1c_paut9cts_detail_lookup_over_decoded_ims_child_segment", + "input": { + "account_id": 1, + "authorization_key": pending_summary["authorizations"][0]["authorization_key"], + }, + "expected": { + "transaction_id": pending_detail["authorization"]["transaction_id"], + "authorization_date": pending_detail["authorization"]["authorization_date"], + "authorization_response": pending_detail["authorization"]["authorization_response"], + "merchant_name": pending_detail["authorization"]["merchant_name"], + }, + "proof_grade": "B", + }, + { + "trace_id": "card_detail_ccdl_account_1", + "capability_ids": ["online:CCDL", "online:CCLI"], + "oracle": "legacy_cocrdslc_card_lookup_source_flow_over_card_seed", + "input": {"account_id": 1, "card_number": first_card.get("card_number")}, + "expected": { + "legacy_transaction": card_detail.get("legacy_transaction"), + "legacy_program": card_detail.get("legacy_program"), + "card_number": card_detail.get("card", {}).get("card_number"), + "account_id": card_detail.get("card", {}).get("account_id"), + "editable_fields": card_detail.get("editable_fields"), + }, + "proof_grade": "B", + }, + { + "trace_id": "account_1_recent_transactions", + "capability_ids": ["online:CT00", "online:CT01"], + "oracle": "legacy_transaction_seed_file", + "input": {"account_id": 1, "limit": 5}, + "expected": { + "count": len(transactions), + "transaction_ids": [row["transaction_id"] for row in transactions], + "amounts": [row["amount"] for row in transactions], + }, + "proof_grade": "B", + }, + { + "trace_id": "transaction_type_lookup", + "capability_ids": ["online:CTLI", "batch:TRANTYPE", "batch:TRANCATG"], + "oracle": "legacy_cotrtlic_cursor_filters_over_type_category_seed_files", + "input": {}, + "expected": { + "legacy_transaction": tx_types["legacy_transaction"], + "legacy_program": tx_types["legacy_program"], + "page_size": tx_types["page"]["page_size"], + "type_count": len(tx_types["types"]), + "category_count": len(tx_types["categories"]), + "type_filter_result": [row["type_code"] for row in tx_types_filtered["types"]], + "description_filter_count": len(tx_types_desc_filtered["types"]), + "backward_page_type_codes": [row["type_code"] for row in tx_types_backward["types"]], + }, + "proof_grade": "B", + }, + { + "trace_id": "transaction_report_account_1", + "capability_ids": ["online:CR00", "batch:TRANREPT"], + "oracle": "legacy_transaction_card_type_category_seed_files", + "input": {"account_id": 1, "limit": 1000}, + "expected": { + "transaction_count": transaction_report["totals"]["transaction_count"], + "total_amount_cents": transaction_report["totals"]["total_amount_cents"], + "account_ids": sorted({row["account_id"] for row in transaction_report["rows"]}), + }, + "proof_grade": "B", + }, + { + "trace_id": "account_statement_1", + "capability_ids": ["batch:CREASTMT"], + "oracle": "legacy_statement_source_flow_and_seed_files", + "input": {"account_id": 1}, + "expected": { + "transaction_count": statement["transaction_count"], + "total_expense_cents": statement["total_expense_cents"], + "first_line": statement["plain_text_lines"][0], + "last_line": statement["plain_text_lines"][-1], + "source_sort_key": statement["source_sort_key"], + "statement_lines_lrecl": statement["statement_lines_lrecl"], + "max_statement_line_width": max(len(line) for line in statement["plain_text_lines"]), + }, + "proof_grade": "B", + }, + { + "trace_id": "interest_projection_seed_tcatbal_discgrp", + "capability_ids": ["batch:INTCALC", "batch:DISCGRP", "batch:TCATBALF"], + "oracle": "legacy_tcatbal_discgrp_seed_files_and_cbact04c_formula", + "input": {"limit": 1000}, + "expected": { + "category_balance_count": interest_projection["totals"]["category_balance_count"], + "account_count": interest_projection["totals"]["account_count"], + "total_interest_cents": interest_projection["totals"]["total_interest_cents"], + "generated_transaction_count": len(interest_projection["generated_transactions"]), + }, + "proof_grade": "B", + }, + { + "trace_id": "combined_transactions_seed_plus_interest_preview", + "capability_ids": ["batch:COMBTRAN"], + "oracle": "legacy_combtran_jcl_sortin_sortout_repro_contract", + "input": {"limit": 1000}, + "expected": { + "source_datasets": combined["source_datasets"], + "sort": combined["sort"], + "sortout_dataset": combined["sortout_dataset"], + "repro_target": combined["repro_target"], + "transaction_master_count": combined["source_counts"]["transaction_master"], + "interest_projection_count": combined["source_counts"]["interest_projection"], + "total_combined": combined["source_counts"]["total_combined"], + "returned": combined["source_counts"]["returned"], + "transaction_ids_sorted": [row["transaction_id"] for row in combined["rows"]] + == sorted(row["transaction_id"] for row in combined["rows"]), + }, + "proof_grade": "B", + }, + { + "trace_id": "transaction_master_tranbkp_backup_redefine", + "capability_ids": ["batch:TRANBKP", "batch:TRANFILE"], + "oracle": "legacy_tranbkp_jcl_reproc_idcams_contract", + "input": {"limit": 5}, + "expected": { + "source_dataset": transaction_backup["source_dataset"], + "backup_dataset": transaction_backup["backup_dataset"], + "delete_targets": transaction_backup["delete_targets"], + "define_cluster": transaction_backup["define_cluster"], + "record_count": transaction_backup["record_count"], + "preview_keys_sorted": [row["key"] for row in transaction_backup["preview_records"]] + == sorted(row["key"] for row in transaction_backup["preview_records"]), + }, + "proof_grade": "B", + }, + { + "trace_id": "transaction_type_tranextr_reference_extract", + "capability_ids": ["batch:TRANEXTR", "batch:TRANTYPE", "batch:TRANCATG"], + "oracle": "legacy_tranextr_dsntiaul_sql_and_fixed_width_extract_contract", + "input": {}, + "expected": { + "legacy_program": transaction_type_extract["legacy_program"], + "legacy_plan": transaction_type_extract["legacy_plan"], + "lrecl": transaction_type_extract["lrecl"], + "counts": transaction_type_extract["counts"], + "type_record_lengths": sorted( + {len(record) for record in transaction_type_extract["records"]["transaction_types"]} + ), + "category_record_lengths": sorted( + {len(record) for record in transaction_type_extract["records"]["transaction_categories"]} + ), + "first_type_record": transaction_type_extract["records"]["transaction_types"][0], + "first_category_record": transaction_type_extract["records"]["transaction_categories"][0], + }, + "proof_grade": "B", + }, + { + "trace_id": "db2_reference_creadb21_schema_and_load", + "capability_ids": ["batch:CREADB21", "batch:TRANTYPE", "batch:TRANCATG"], + "oracle": "legacy_creadb21_db2_control_cards_and_reference_loads", + "input": {}, + "expected": { + "legacy_jcl_job": db2_reference_setup["legacy_jcl_job"], + "db2_system": db2_reference_setup["db2_system"], + "database": db2_reference_setup["database"], + "steps": [step["step"] for step in db2_reference_setup["steps"]], + "transaction_type_load_count": db2_reference_setup["tables"]["transaction_type"]["load_count"], + "transaction_category_load_count": db2_reference_setup["tables"]["transaction_type_category"]["load_count"], + "foreign_key": db2_reference_setup["tables"]["transaction_type_category"]["foreign_key"], + }, + "proof_grade": "B", + }, + { + "trace_id": "user_security_decode", + "capability_ids": ["online:CU00", "batch:DUSRSECJ"], + "oracle": "legacy_ebcdic_user_security_file", + "input": {}, + "expected": {"user_count": len(users), "first_user_id": users[0]["user_id"] if users else None}, + "proof_grade": "B", + }, + { + "trace_id": "signon_admin_success", + "capability_ids": ["online:CC00", "batch:DUSRSECJ", "online:CA00"], + "oracle": "legacy_cosgn00c_source_flow_over_usrsec_seed", + "input": {"user_id": "admin001", "password_shape": "lowercase accepted by uppercase normalization"}, + "expected": { + "authenticated": signon_admin["authenticated"], + "route_transaction": signon_admin["route_transaction"], + "route_program": signon_admin["route_program"], + "menu_option_count": signon_admin["menu"]["option_count"], + }, + "proof_grade": "B", + }, + { + "trace_id": "signon_bad_password_message", + "capability_ids": ["online:CC00"], + "oracle": "legacy_cosgn00c_error_message_source", + "input": {"user_id": "ADMIN001", "bad_password": True}, + "expected": { + "authenticated": signon_bad_password["authenticated"], + "reason": signon_bad_password["reason"], + "message": signon_bad_password["message"], + }, + "proof_grade": "B", + }, + { + "trace_id": "regular_main_menu_options", + "capability_ids": ["online:CM00"], + "oracle": "legacy_comen02y_comen01c_menu_source", + "input": {}, + "expected": { + "option_count": main_menu["option_count"], + "first_program": main_menu["options"][0]["program"], + "last_program": main_menu["options"][-1]["program"], + }, + "proof_grade": "B", + }, + { + "trace_id": "admin_menu_options", + "capability_ids": ["online:CA00"], + "oracle": "legacy_coadm02y_coadm01c_menu_source", + "input": {}, + "expected": { + "option_count": admin_menu["option_count"], + "first_program": admin_menu["options"][0]["program"], + "last_program": admin_menu["options"][-1]["program"], + }, + "proof_grade": "B", + }, + ] + + with tempfile.TemporaryDirectory() as tmp_dir: + temp_db = Path(tmp_dir) / "carddemo.sqlite" + seed_from_legacy(source_root, temp_db, reset=True) + temp_service = CardDemoService(temp_db) + before = temp_service.get_account_bundle(1) + assert before is not None + card_number = before["cards"][0]["card_number"] + expiration_timestamp = f"{before['account']['expiration_date']} 00:00:00.000000" + ct02 = temp_service.add_transaction( + { + "account_id": 1, + "type_code": "01", + "category_code": "0001", + "source": "POS TERM", + "description": "CT02 TRACE", + "amount": "+00000012.34", + "original_timestamp": "2022-01-30", + "processed_timestamp": "2022-01-31", + "merchant_id": "123456789", + "merchant_name": "CT02 MERCHANT", + "merchant_city": "SEATTLE", + "merchant_zip": "98101", + "confirm": "Y", + } + ) + after_ct02 = temp_service.get_account_bundle(1) + assert after_ct02 is not None + confirm_rejected = False + amount_rejected = False + try: + temp_service.add_transaction( + { + "account_id": 1, + "type_code": "01", + "category_code": "0001", + "source": "POS TERM", + "description": "CT02 TRACE", + "amount": "+00000012.34", + "original_timestamp": "2022-01-30", + "processed_timestamp": "2022-01-31", + "merchant_id": "123456789", + "merchant_name": "CT02 MERCHANT", + "merchant_city": "SEATTLE", + "merchant_zip": "98101", + } + ) + except ValueError: + confirm_rejected = True + try: + temp_service.add_transaction( + { + "account_id": 1, + "type_code": "01", + "category_code": "0001", + "source": "POS TERM", + "description": "CT02 TRACE", + "amount": "12.34", + "original_timestamp": "2022-01-30", + "processed_timestamp": "2022-01-31", + "merchant_id": "123456789", + "merchant_name": "CT02 MERCHANT", + "merchant_city": "SEATTLE", + "merchant_zip": "98101", + "confirm": "Y", + } + ) + except ValueError: + amount_rejected = True + traces.append( + { + "trace_id": "transaction_add_ct02_validated_write", + "capability_ids": ["online:CT02"], + "oracle": "legacy_cotrn02c_validation_and_transact_write_source_flow", + "input": {"account_id": 1, "amount": "+00000012.34", "confirm": "Y"}, + "expected": { + "transaction_id": ct02["transaction_id"], + "card_number": ct02["card_number"], + "legacy_amount": ct02["legacy_amount"], + "balance_delta_cents": after_ct02["account"]["current_balance_cents"] + - before["account"]["current_balance_cents"], + "confirm_rejected_without_y": confirm_rejected, + "amount_format_rejected": amount_rejected, + }, + "proof_grade": "B", + } + ) + before_caup = temp_service.get_account_bundle(1) + assert before_caup is not None + account_before_caup = before_caup["account"] + caup = temp_service.update_account( + 1, + { + "active_status": "N", + "credit_limit_cents": account_before_caup["credit_limit_cents"] + 10000, + "cash_credit_limit_cents": account_before_caup["cash_credit_limit_cents"] + 5000, + "group_id": "TRACEGRP", + "customer": {"zip_code": "27514"}, + }, + ) + no_change_rejected = False + bad_status_rejected = False + try: + temp_service.update_account( + 1, + { + "active_status": "N", + "credit_limit_cents": caup["credit_limit_cents"], + "cash_credit_limit_cents": caup["cash_credit_limit_cents"], + "group_id": "TRACEGRP", + "customer": {"zip_code": "27514"}, + }, + ) + except ValueError: + no_change_rejected = True + try: + temp_service.update_account(1, {"active_status": "X"}) + except ValueError: + bad_status_rejected = True + traces.append( + { + "trace_id": "account_update_caup_validated_rewrite", + "capability_ids": ["online:CAUP"], + "oracle": "legacy_coactupc_validation_and_rewrite_source_flow_over_seed_records", + "input": {"account_id": 1, "active_status": "N", "group_id": "TRACEGRP"}, + "expected": { + "legacy_transaction": caup["legacy_transaction"], + "updated_account_fields": caup["updated_account_fields"], + "updated_customer_fields": caup["updated_customer_fields"], + "credit_limit_delta_cents": caup["credit_limit_cents"] + - account_before_caup["credit_limit_cents"], + "cash_limit_delta_cents": caup["cash_credit_limit_cents"] + - account_before_caup["cash_credit_limit_cents"], + "customer_zip": caup["customer"]["zip_code"] if caup["customer"] else None, + "no_change_rejected": no_change_rejected, + "bad_status_rejected": bad_status_rejected, + }, + "proof_grade": "B", + } + ) + ccup_before = temp_service.get_card_detail(card_number, account_id=1)["card"] + ccup = temp_service.update_card( + card_number, + { + "account_id": 1, + "embossed_name": "Trace Holder", + "active_status": "N", + "expiration_month": "12", + "expiration_year": "2030", + }, + ) + ccup_no_change_rejected = False + ccup_bad_status_rejected = False + ccup_bad_month_rejected = False + try: + temp_service.update_card( + card_number, + { + "account_id": 1, + "embossed_name": "trace holder", + "active_status": "N", + "expiration_month": "12", + "expiration_year": "2030", + }, + ) + except ValueError: + ccup_no_change_rejected = True + try: + temp_service.update_card(card_number, {"active_status": "X"}) + except ValueError: + ccup_bad_status_rejected = True + try: + temp_service.update_card(card_number, {"expiration_month": "13"}) + except ValueError: + ccup_bad_month_rejected = True + traces.append( + { + "trace_id": "card_update_ccup_validated_rewrite", + "capability_ids": ["online:CCUP", "online:CCDL"], + "oracle": "legacy_cocrdupc_validation_and_rewrite_source_flow_over_seed_records", + "input": {"account_id": 1, "card_number": card_number, "active_status": "N"}, + "expected": { + "legacy_transaction": ccup["legacy_transaction"], + "changed_fields": ccup["changed_fields"], + "old_expiration_date": ccup_before["expiration_date"], + "new_expiration_date": ccup["card"]["expiration_date"], + "cvv_preserved": ccup_before["cvv"] == ccup["card"]["cvv"], + "no_change_rejected": ccup_no_change_rejected, + "bad_status_rejected": ccup_bad_status_rejected, + "bad_month_rejected": ccup_bad_month_rejected, + }, + "proof_grade": "B", + } + ) + cttu_insert = temp_service.upsert_transaction_type( + {"type_code": "8", "description": "Manual Review"} + ) + cttu_update = temp_service.upsert_transaction_type( + {"type_code": "08", "description": "Manual Review 2"} + ) + cttu_no_change_rejected = False + cttu_child_delete_rejected = False + try: + temp_service.upsert_transaction_type({"type_code": "08", "description": "manual review 2"}) + except ValueError: + cttu_no_change_rejected = True + try: + temp_service.delete_transaction_type("01") + except ValueError: + cttu_child_delete_rejected = True + cttu_delete = temp_service.delete_transaction_type("08") + traces.append( + { + "trace_id": "transaction_type_cttu_validated_upsert_delete", + "capability_ids": ["online:CTTU", "online:CTLI"], + "oracle": "legacy_cotrtupc_validation_and_transaction_type_sql_flow", + "input": {"type_code": "8", "description": "Manual Review"}, + "expected": { + "insert_type_code": cttu_insert["type_code"], + "insert_action": cttu_insert["action"], + "update_action": cttu_update["action"], + "updated_description": cttu_update["description"], + "no_change_rejected": cttu_no_change_rejected, + "child_delete_rejected": cttu_child_delete_rejected, + "new_type_deleted": cttu_delete["deleted"], + }, + "proof_grade": "B", + } + ) + mnttrdb2 = temp_service.maintain_transaction_types( + [ + "*COMMENT".ljust(53), + "A09" + "Batch Review".ljust(50), + "U09" + "Batch Review 2".ljust(50), + "D09" + "".ljust(50), + "X09" + "Bad Action".ljust(50), + "U98" + "Missing Update".ljust(50), + "A01" + "Duplicate Purchase".ljust(50), + "D01" + "".ljust(50), + ] + ) + traces.append( + { + "trace_id": "batch_transaction_type_mnttrdb2_fixed_record_flow", + "capability_ids": ["batch:MNTTRDB2", "online:CTTU", "online:CTLI"], + "oracle": "legacy_mnttrdb2_jcl_and_cobtupdt_fixed_record_sql_flow", + "input": {"input_dd": "INPFILE", "records": len(mnttrdb2["actions"])}, + "expected": { + "legacy_program": mnttrdb2["legacy_program"], + "legacy_driver": mnttrdb2["legacy_driver"], + "record_layout": mnttrdb2["record_layout"], + "return_code": mnttrdb2["return_code"], + "comment_count": mnttrdb2["counts"]["comment_count"], + "applied_count": mnttrdb2["counts"]["applied_count"], + "error_count": mnttrdb2["counts"]["error_count"], + "statuses": [row["status"] for row in mnttrdb2["actions"]], + "messages": [row["message"] for row in mnttrdb2["actions"] if row["status"] == "error"], + }, + "proof_grade": "B", + } + ) + cp00_before = temp_service.pending_authorization_summary(1, page_size=1) + cp00 = temp_service.process_authorization_request( + { + "card_number": card_number, + "auth_date": "260523", + "auth_time": "111213", + "card_expiry_date": "1129", + "transaction_amount_cents": 100, + "merchant_category_code": "5442", + "merchant_id": "123501000675423", + "merchant_name": "Amazon.com", + "merchant_city": "Wilmington", + "merchant_state": "DE", + "merchant_zip": "19801", + "transaction_id": "AUTHREQ00000001", + "processing_datetime": "2026-05-23T11:12:13.456", + } + ) + cp00_after = temp_service.pending_authorization_summary(1, page_size=1) + cp00_invalid = temp_service.process_authorization_request( + { + "card_number": "9999999999999999", + "transaction_amount_cents": 100, + "transaction_id": "AUTHREQBAD0001", + } + ) + traces.append( + { + "trace_id": "pending_authorization_cp00_request_response_and_insert", + "capability_ids": ["online:CP00", "online:CPVS", "online:CPVD"], + "oracle": "legacy_copaua0c_mq_parse_decision_summary_update_and_detail_insert", + "input": {"card_number": card_number, "transaction_amount_cents": 100}, + "expected": { + "approved": cp00["approved"], + "response_code": cp00["response"]["auth_resp_code"], + "response_reason": cp00["response"]["auth_resp_reason"], + "written": cp00["written_to_pending_authorizations"], + "approved_count_delta": cp00_after["summary"]["approved_auth_count"] + - cp00_before["summary"]["approved_auth_count"], + "invalid_card_response_reason": cp00_invalid["response"]["auth_resp_reason"], + "invalid_card_written": cp00_invalid["written_to_pending_authorizations"], + }, + "proof_grade": "B", + } + ) + fraud = temp_service.mark_authorization_fraud( + 1, cp00["authorization"]["authorization_key"], action="report", report_date="20260523" + ) + purge = temp_service.purge_expired_authorizations(current_yyddd=23305, expiry_days=5, dry_run=True) + traces.append( + { + "trace_id": "pending_authorization_cpvd_fraud_and_cbpaup0j_purge", + "capability_ids": ["online:CPVD", "batch:CBPAUP0J"], + "oracle": "legacy_copaus1c_copaus2c_fraud_toggle_and_cbpaup0c_expiry_scan", + "input": {"account_id": 1, "authorization_key": cp00["authorization"]["authorization_key"]}, + "expected": { + "fraud_status": fraud["fraud_status"], + "db2_table": fraud["db2_table"], + "purge_job": purge["legacy_job"], + "purge_dry_run": purge["dry_run"], + "purged_count": purge["purged_count"], + "expiry_days": purge["expiry_days"], + }, + "proof_grade": "B", + } + ) + posttran = temp_service.post_transaction( + { + "card_number": card_number, + "amount_cents": 100, + "type_code": "01", + "category_code": "0001", + "source": "TRACE", + "description": "POSTTRAN TRACE", + "merchant_id": "123456789", + "merchant_name": "POSTTRAN TRACE", + "merchant_city": "BATCH", + "merchant_zip": "00000", + "original_timestamp": expiration_timestamp, + "processed_timestamp": expiration_timestamp, + } + ) + after_posttran = temp_service.get_account_bundle(1) + assert after_posttran is not None + traces.append( + { + "trace_id": "posttran_accept_updates_account_and_tcatbal", + "capability_ids": ["batch:POSTTRAN", "online:CT02"], + "oracle": "legacy_cbtrn02c_validation_and_update_flow_over_seed_records", + "input": {"account_id": 1, "card_number": card_number, "amount_cents": 100}, + "expected": { + "accepted": posttran["accepted"], + "reason_code": posttran["validation"]["reason_code"], + "before_balance_cents": before["account"]["current_balance_cents"], + "after_balance_cents": after_posttran["account"]["current_balance_cents"], + "balance_delta_cents": after_posttran["account"]["current_balance_cents"] + - before["account"]["current_balance_cents"], + "cycle_credit_delta_cents": after_posttran["account"]["current_cycle_credit_cents"] + - before["account"]["current_cycle_credit_cents"], + }, + "proof_grade": "B", + } + ) + invalid_card = temp_service.post_transaction( + {"card_number": "9999999999999999", "amount_cents": 100}, + reject_on_failure=False, + ) + overlimit = temp_service.post_transaction( + { + "card_number": card_number, + "amount_cents": before["account"]["credit_limit_cents"] + 1, + "original_timestamp": expiration_timestamp, + }, + reject_on_failure=False, + ) + expired = temp_service.post_transaction( + { + "card_number": card_number, + "amount_cents": 1, + "original_timestamp": "2099-01-01 00:00:00.000000", + }, + reject_on_failure=False, + ) + traces.append( + { + "trace_id": "posttran_reject_codes", + "capability_ids": ["batch:POSTTRAN"], + "oracle": "legacy_cbtrn02c_reject_reason_codes", + "input": {"invalid_card": True, "overlimit": True, "expired": True}, + "expected": { + "invalid_card_reason": invalid_card["validation"]["reason_code"], + "overlimit_reason": overlimit["validation"]["reason_code"], + "expired_reason": expired["validation"]["reason_code"], + }, + "proof_grade": "B", + } + ) + + before_bill = temp_service.get_account_bundle(2) + assert before_bill is not None + before_balance = before_bill["account"]["current_balance_cents"] + transaction = temp_service.bill_payment(2, before_balance) + after = temp_service.get_account_bundle(2) + assert after is not None + traces.append( + { + "trace_id": "bill_payment_full_balance", + "capability_ids": ["online:CB00"], + "oracle": "legacy_cobil00c_full_balance_payment_flow_over_seed_records", + "input": {"account_id": 2, "amount_cents": before_balance}, + "expected": { + "before_balance_cents": before_balance, + "transaction_type": transaction["type_code"], + "transaction_category": transaction["category_code"], + "transaction_source": transaction["source"], + "transaction_amount": transaction["amount"], + "after_balance_cents": after["account"]["current_balance_cents"], + "balance_delta_cents": after["account"]["current_balance_cents"] - before_balance, + }, + "proof_grade": "B", + } + ) + + required_field_messages: dict[str, str] = {} + valid_user_payload = { + "user_id": "qauser01", + "first_name": "Quality", + "last_name": "Check", + "password": "secret", + "user_type": "U", + } + for required_field in ("user_id", "first_name", "last_name", "password", "user_type"): + invalid_payload = dict(valid_user_payload) + invalid_payload[required_field] = "" + try: + temp_service.add_user(invalid_payload) + except ValueError as exc: + required_field_messages[required_field] = str(exc) + + added = temp_service.add_user(valid_user_payload) + non_admin = temp_service.add_user( + { + "user_id": "qauser02", + "first_name": "Quality", + "last_name": "Nonadmin", + "password": "secret", + "user_type": "Z", + } + ) + non_admin_signon = temp_service.signon("qauser02", "secret") + updated = temp_service.update_user( + "qauser01", + { + "first_name": "Quality", + "last_name": "Updated", + "password": "secret2", + "user_type": "A", + }, + ) + duplicate_rejected = False + duplicate_rejected_message = None + no_change_rejected = False + no_change_rejected_message = None + missing_delete_rejected_message = None + try: + temp_service.add_user( + { + "user_id": "qauser01", + "first_name": "Quality", + "last_name": "Check", + "password": "secret", + "user_type": "U", + } + ) + except ValueError as exc: + duplicate_rejected = True + duplicate_rejected_message = str(exc) + try: + temp_service.update_user("qauser01", updated["user"]) + except ValueError as exc: + no_change_rejected = True + no_change_rejected_message = str(exc) + deleted = temp_service.delete_user("qauser01") + temp_service.delete_user("qauser02") + try: + temp_service.delete_user("qauser01") + except KeyError as exc: + missing_delete_rejected_message = exc.args[0] if exc.args else str(exc) + traces.append( + { + "trace_id": "user_maintenance_add_update_delete", + "capability_ids": ["online:CU01", "online:CU02", "online:CU03"], + "oracle": "legacy_cousr01_02_03_static_source_flow_over_decoded_usrsec", + "input": {"user_id": "qauser01"}, + "expected": { + "added_user_id": added["user"]["user_id"], + "updated_user_type": updated["user"]["user_type"], + "duplicate_rejected": duplicate_rejected, + "duplicate_rejected_message": duplicate_rejected_message, + "required_field_messages": required_field_messages, + "no_change_update_rejected": no_change_rejected, + "no_change_update_rejected_message": no_change_rejected_message, + "deleted_user_id": deleted["user"]["user_id"], + "exists_after_delete": temp_service.get_user("qauser01") is not None, + "delete_missing_rejected_message": missing_delete_rejected_message, + "non_admin_user_type_accepted": non_admin["user"]["user_type"], + "non_admin_signon_route": non_admin_signon["route_transaction"], + }, + "proof_grade": "B", + } + ) + return traces + + +def summarize_ledger(ledger: list[dict[str, Any]], traces: list[dict[str, Any]], edge_cases: list[dict[str, Any]]) -> dict[str, Any]: + grade_counts = {grade: 0 for grade in ("A", "B", "C", "F")} + for row in ledger: + grade_counts[row["proof_grade"]] = grade_counts.get(row["proof_grade"], 0) + 1 + return { + "capability_count": len(ledger), + "grade_counts": grade_counts, + "strict_runtime_parity_count": grade_counts.get("A", 0), + "static_oracle_or_better_count": grade_counts.get("A", 0) + grade_counts.get("B", 0), + "partial_or_inferred_count": grade_counts.get("C", 0), + "gap_count": grade_counts.get("F", 0), + "golden_trace_count": len(traces), + "edge_case_count": len(edge_cases), + "one_for_one_parity_ready": grade_counts.get("F", 0) == 0 and grade_counts.get("C", 0) == 0, + "claim_limit": "capability ledger and static-oracle traces only; no all-path COBOL runtime proof yet", + } + + +def rank_next_gaps(ledger: list[dict[str, Any]]) -> list[dict[str, Any]]: + gaps: list[dict[str, Any]] = [] + for row in ledger: + grade = row["proof_grade"] + if grade in {"A", "B"}: + continue + score = int(row["priority"]) + (40 if grade == "F" else 15) + action = "implement capability and attach static/runtime oracle" + if grade == "C": + action = "extract COBOL validation paths and upgrade proof from inferred to static/runtime trace" + gaps.append( + { + "capability_id": row["capability_id"], + "function": row["function"], + "surface": row["surface"], + "transaction_or_job": row["transaction"] or row["job"], + "current_grade": grade, + "priority": row["priority"], + "gap_score": score, + "recommended_next_action": action, + "source_ref_count": row["source_ref_count"], + } + ) + return sorted(gaps, key=lambda item: (-item["gap_score"], item["capability_id"])) + + +def build_parity_evidence(source_root: Path, db_path: Path, *, source_head: str) -> dict[str, Any]: + ledger = build_capability_ledger(source_root) + edge_cases = mine_edge_cases(db_path) + traces = build_golden_traces(source_root, db_path) + next_gaps = rank_next_gaps(ledger) + return { + "evidence_version": "carddemo_capability_parity_evidence_v0", + "source_root": str(source_root.resolve()), + "source_head": source_head, + "summary": summarize_ledger(ledger, traces, edge_cases), + "capability_ledger": ledger, + "golden_traces": traces, + "edge_cases": edge_cases, + "next_gap_ranking": next_gaps, + "proof_grade_meanings": { + "A": "actual legacy runtime trace match", + "B": "static legacy data/copybook oracle match", + "C": "implemented or inferred without strict parity proof", + "F": "discovered capability gap", + }, + "public_actions_allowed": False, + }