use super::*;

#[test]
fn projects_executable_packed_records_into_runtime_and_services_follow_on() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: Some(save_cargo_catalog(&[
            (1, crate::event::targets::RuntimeCargoClass::Factory),
            (5, crate::event::targets::RuntimeCargoClass::FarmMine),
            (9, crate::event::targets::RuntimeCargoClass::Other),
        ])),
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 7,
            live_record_count: 1,
            live_entry_ids: vec![7],
            decoded_record_count: 1,
            imported_runtime_record_count: 1,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 7,
                payload_offset: Some(0x7202),
                payload_len: Some(64),
                decode_status: "executable".to_string(),
                payload_family: "synthetic_harness".to_string(),
                trigger_kind: Some(7),
                active: Some(true),
                marks_collection_dirty: Some(true),
                one_shot: Some(false),
                compact_control: None,
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 1,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![0, 1, 0, 0],
                grouped_effect_rows: vec![],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![
                    RuntimeEffect::SetWorldFlag {
                        key: "from_packed_root".to_string(),
                        value: true,
                    },
                    RuntimeEffect::AppendEventRecord {
                        record: Box::new(RuntimeEventRecordTemplate {
                            record_id: 99,
                            trigger_kind: 0x0a,
                            active: true,
                            marks_collection_dirty: false,
                            one_shot: false,
                            conditions: Vec::new(),
                            effects: vec![RuntimeEffect::SetSpecialCondition {
                                label: "Imported Follow-On".to_string(),
                                value: 1,
                            }],
                        }),
                    },
                ],
                executable_import_ready: true,
                notes: vec!["decoded test record".to_string()],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "packed-events-exec",
        Some("test packed event input".to_string()),
    )
    .expect("save slice should project");

    assert_eq!(input.state.event_runtime_records.len(), 1);
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .map(|summary| summary.imported_runtime_record_count),
        Some(1)
    );

    let result = execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("trigger service should succeed");

    assert_eq!(result.final_summary.event_runtime_record_count, 2);
    assert_eq!(result.final_summary.total_event_record_service_count, 2);
    assert_eq!(result.final_summary.total_trigger_dispatch_count, 2);
    assert_eq!(result.final_summary.dirty_rerun_count, 1);
    assert_eq!(input.state.world_flags.get("from_packed_root"), Some(&true));
    assert_eq!(
        input.state.special_conditions.get("Imported Follow-On"),
        Some(&1)
    );
    assert_eq!(input.state.event_runtime_records[0].service_count, 1);
    assert_eq!(input.state.event_runtime_records[1].record_id, 99);
    assert_eq!(input.state.event_runtime_records[1].service_count, 1);
}

#[test]
fn leaves_parity_only_packed_records_out_of_runtime_event_records() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: Some(save_cargo_catalog(&[
            (1, crate::event::targets::RuntimeCargoClass::Factory),
            (5, crate::event::targets::RuntimeCargoClass::FarmMine),
            (9, crate::event::targets::RuntimeCargoClass::Other),
        ])),
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 7,
            live_record_count: 1,
            live_entry_ids: vec![7],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 7,
                payload_offset: Some(0x7202),
                payload_len: Some(48),
                decode_status: "parity_only".to_string(),
                payload_family: "synthetic_harness".to_string(),
                trigger_kind: Some(7),
                active: Some(true),
                marks_collection_dirty: Some(false),
                one_shot: Some(false),
                compact_control: None,
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![0, 0, 0, 0],
                grouped_effect_rows: vec![],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::AdjustCompanyCash {
                    target: crate::event::targets::RuntimeCompanyTarget::Ids { ids: vec![42] },
                    delta: 50,
                }],
                executable_import_ready: false,
                notes: vec!["decoded but not importable".to_string()],
            }],
        }),
        notes: vec![],
    };

    let input =
        build_runtime_state_input_from_save_slice(&save_slice, "packed-events-parity-only", None)
            .expect("save slice should project");

    assert!(input.state.event_runtime_records.is_empty());
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .map(|summary| summary.decoded_record_count),
        Some(1)
    );
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .map(|summary| summary.imported_runtime_record_count),
        Some(0)
    );
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_missing_company_context")
    );
}

#[test]
fn classifies_symbolic_company_target_blockers_for_standalone_import() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: Some(save_cargo_catalog(&[
            (1, crate::event::targets::RuntimeCargoClass::Factory),
            (5, crate::event::targets::RuntimeCargoClass::FarmMine),
            (9, crate::event::targets::RuntimeCargoClass::Other),
        ])),
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 12,
            live_record_count: 3,
            live_entry_ids: vec![10, 11, 12],
            decoded_record_count: 3,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![
                synthetic_packed_record(
                    0,
                    10,
                    RuntimeEffect::AdjustCompanyCash {
                        target: RuntimeCompanyTarget::SelectedCompany,
                        delta: 1,
                    },
                ),
                synthetic_packed_record(
                    1,
                    11,
                    RuntimeEffect::AdjustCompanyDebt {
                        target: RuntimeCompanyTarget::HumanCompanies,
                        delta: 2,
                    },
                ),
                synthetic_packed_record(
                    2,
                    12,
                    RuntimeEffect::AdjustCompanyDebt {
                        target: RuntimeCompanyTarget::ConditionTrueCompany,
                        delta: 3,
                    },
                ),
            ],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_save_slice(&save_slice, "symbolic-blockers", None)
        .expect("standalone projection should succeed");

    assert!(input.state.event_runtime_records.is_empty());
    let outcomes = input
        .state
        .packed_event_collection
        .as_ref()
        .expect("packed event collection should be present")
        .records
        .iter()
        .map(|record| record.import_outcome.clone())
        .collect::<Vec<_>>();
    assert_eq!(
        outcomes,
        vec![
            Some("blocked_missing_selection_context".to_string()),
            Some("blocked_missing_company_role_context".to_string()),
            Some("blocked_missing_condition_context".to_string()),
        ]
    );
}

#[test]
fn overlays_symbolic_company_targets_into_executable_runtime_records() {
    let base_state = RuntimeState {
        companies: vec![
            crate::state::RuntimeCompany {
                company_id: 1,
                controller_kind: RuntimeCompanyControllerKind::Human,
                current_cash: 100,
                debt: 10,
                credit_rating_score: None,
                prime_rate: None,
                track_piece_counts: RuntimeTrackPieceCounts::default(),
                active: true,
                available_track_laying_capacity: None,
                linked_chairman_profile_id: None,
                book_value_per_share: 0,
                investor_confidence: 0,
                management_attitude: 0,
                takeover_cooldown_year: None,
                merger_cooldown_year: None,
            },
            crate::state::RuntimeCompany {
                company_id: 2,
                controller_kind: RuntimeCompanyControllerKind::Ai,
                current_cash: 50,
                debt: 20,
                credit_rating_score: None,
                prime_rate: None,
                track_piece_counts: RuntimeTrackPieceCounts::default(),
                active: true,
                available_track_laying_capacity: None,
                linked_chairman_profile_id: None,
                book_value_per_share: 0,
                investor_confidence: 0,
                management_attitude: 0,
                takeover_cooldown_year: None,
                merger_cooldown_year: None,
            },
        ],
        selected_company_id: Some(1),
        ..state()
    };
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 22,
            live_record_count: 2,
            live_entry_ids: vec![21, 22],
            decoded_record_count: 2,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![
                synthetic_packed_record(
                    0,
                    21,
                    RuntimeEffect::AdjustCompanyCash {
                        target: RuntimeCompanyTarget::SelectedCompany,
                        delta: 15,
                    },
                ),
                synthetic_packed_record(
                    1,
                    22,
                    RuntimeEffect::AdjustCompanyDebt {
                        target: RuntimeCompanyTarget::AiCompanies,
                        delta: 4,
                    },
                ),
            ],
        }),
        notes: vec![],
    };

    let mut input =
        build_runtime_state_input_from_overlay(&base_state, &save_slice, "symbolic-overlay", None)
            .expect("overlay projection should succeed");

    assert_eq!(input.state.event_runtime_records.len(), 2);
    let outcomes = input
        .state
        .packed_event_collection
        .as_ref()
        .expect("packed event collection should be present")
        .records
        .iter()
        .map(|record| record.import_outcome.clone())
        .collect::<Vec<_>>();
    assert_eq!(
        outcomes,
        vec![Some("imported".to_string()), Some("imported".to_string())]
    );

    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("symbolic overlay dispatch should succeed");

    assert_eq!(input.state.companies[0].current_cash, 115);
    assert_eq!(input.state.companies[1].debt, 24);
}

#[test]
fn leaves_real_records_without_compact_control_blocked_missing_compact_control() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 7,
            live_record_count: 1,
            live_entry_ids: vec![7],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 7,
                payload_offset: Some(0x7202),
                payload_len: Some(96),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: None,
                active: None,
                marks_collection_dirty: None,
                one_shot: None,
                compact_control: None,
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 1,
                standalone_condition_rows: real_condition_rows(),
                negative_sentinel_scope: Some(company_negative_sentinel_scope(
                    RuntimeCompanyConditionTestScope::AllCompanies,
                )),
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: real_grouped_rows(),
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::SetCompanyCash {
                    target: RuntimeCompanyTarget::ConditionTrueCompany,
                    value: 7,
                }],
                executable_import_ready: true,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "packed-events-structural-only",
        None,
    )
    .expect("save slice should project");

    assert!(input.state.event_runtime_records.is_empty());
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_missing_compact_control")
    );
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .map(|summary| summary.records[0].standalone_condition_rows.len()),
        Some(1)
    );
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .map(|summary| summary.records[0].grouped_effect_rows.len()),
        Some(1)
    );
}

#[test]
fn lowers_negative_sentinel_company_scopes_into_runtime_company_targets() {
    let base_state = RuntimeState {
        companies: vec![
            crate::state::RuntimeCompany {
                company_id: 1,
                controller_kind: RuntimeCompanyControllerKind::Human,
                current_cash: 100,
                debt: 10,
                credit_rating_score: None,
                prime_rate: None,
                track_piece_counts: RuntimeTrackPieceCounts::default(),
                active: true,
                available_track_laying_capacity: None,
                linked_chairman_profile_id: None,
                book_value_per_share: 0,
                investor_confidence: 0,
                management_attitude: 0,
                takeover_cooldown_year: None,
                merger_cooldown_year: None,
            },
            crate::state::RuntimeCompany {
                company_id: 2,
                controller_kind: RuntimeCompanyControllerKind::Ai,
                current_cash: 50,
                debt: 20,
                credit_rating_score: None,
                prime_rate: None,
                track_piece_counts: RuntimeTrackPieceCounts::default(),
                active: true,
                available_track_laying_capacity: None,
                linked_chairman_profile_id: None,
                book_value_per_share: 0,
                investor_confidence: 0,
                management_attitude: 0,
                takeover_cooldown_year: None,
                merger_cooldown_year: None,
            },
            crate::state::RuntimeCompany {
                company_id: 3,
                controller_kind: RuntimeCompanyControllerKind::Human,
                current_cash: 70,
                debt: 30,
                credit_rating_score: None,
                prime_rate: None,
                track_piece_counts: RuntimeTrackPieceCounts::default(),
                active: true,
                available_track_laying_capacity: None,
                linked_chairman_profile_id: None,
                book_value_per_share: 0,
                investor_confidence: 0,
                management_attitude: 0,
                takeover_cooldown_year: None,
                merger_cooldown_year: None,
            },
        ],
        selected_company_id: Some(3),
        ..state()
    };
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 11,
            live_record_count: 5,
            live_entry_ids: vec![7, 8, 9, 10, 11],
            decoded_record_count: 5,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![
                SmpLoadedPackedEventRecordSummary {
                    record_index: 0,
                    live_entry_id: 7,
                    payload_offset: Some(0x7202),
                    payload_len: Some(133),
                    decode_status: "parity_only".to_string(),
                    payload_family: "real_packed_v1".to_string(),
                    trigger_kind: Some(6),
                    active: None,
                    marks_collection_dirty: None,
                    one_shot: Some(true),
                    compact_control: Some(real_compact_control()),
                    text_bands: packed_text_bands(),
                    standalone_condition_row_count: 1,
                    standalone_condition_rows: real_condition_rows(),
                    negative_sentinel_scope: Some(company_negative_sentinel_scope(
                        RuntimeCompanyConditionTestScope::AllCompanies,
                    )),
                    grouped_effect_row_counts: vec![1, 0, 0, 0],
                    grouped_effect_rows: real_grouped_rows(),
                    decoded_conditions: Vec::new(),
                    decoded_actions: vec![RuntimeEffect::SetCompanyCash {
                        target: RuntimeCompanyTarget::ConditionTrueCompany,
                        value: 7,
                    }],
                    executable_import_ready: true,
                    notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
                },
                SmpLoadedPackedEventRecordSummary {
                    record_index: 1,
                    live_entry_id: 8,
                    payload_offset: Some(0x7282),
                    payload_len: Some(133),
                    decode_status: "parity_only".to_string(),
                    payload_family: "real_packed_v1".to_string(),
                    trigger_kind: Some(6),
                    active: None,
                    marks_collection_dirty: None,
                    one_shot: Some(true),
                    compact_control: Some(real_compact_control()),
                    text_bands: packed_text_bands(),
                    standalone_condition_row_count: 1,
                    standalone_condition_rows: real_condition_rows(),
                    negative_sentinel_scope: Some(company_negative_sentinel_scope(
                        RuntimeCompanyConditionTestScope::SelectedCompanyOnly,
                    )),
                    grouped_effect_row_counts: vec![1, 0, 0, 0],
                    grouped_effect_rows: real_grouped_rows(),
                    decoded_conditions: Vec::new(),
                    decoded_actions: vec![RuntimeEffect::SetCompanyCash {
                        target: RuntimeCompanyTarget::ConditionTrueCompany,
                        value: 8,
                    }],
                    executable_import_ready: true,
                    notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
                },
                SmpLoadedPackedEventRecordSummary {
                    record_index: 2,
                    live_entry_id: 9,
                    payload_offset: Some(0x7302),
                    payload_len: Some(133),
                    decode_status: "parity_only".to_string(),
                    payload_family: "real_packed_v1".to_string(),
                    trigger_kind: Some(6),
                    active: None,
                    marks_collection_dirty: None,
                    one_shot: Some(true),
                    compact_control: Some(real_compact_control()),
                    text_bands: packed_text_bands(),
                    standalone_condition_row_count: 1,
                    standalone_condition_rows: real_condition_rows(),
                    negative_sentinel_scope: Some(company_negative_sentinel_scope(
                        RuntimeCompanyConditionTestScope::AiCompaniesOnly,
                    )),
                    grouped_effect_row_counts: vec![1, 0, 0, 0],
                    grouped_effect_rows: real_grouped_rows(),
                    decoded_conditions: Vec::new(),
                    decoded_actions: vec![RuntimeEffect::SetCompanyCash {
                        target: RuntimeCompanyTarget::ConditionTrueCompany,
                        value: 9,
                    }],
                    executable_import_ready: true,
                    notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
                },
                SmpLoadedPackedEventRecordSummary {
                    record_index: 3,
                    live_entry_id: 10,
                    payload_offset: Some(0x7382),
                    payload_len: Some(133),
                    decode_status: "parity_only".to_string(),
                    payload_family: "real_packed_v1".to_string(),
                    trigger_kind: Some(6),
                    active: None,
                    marks_collection_dirty: None,
                    one_shot: Some(true),
                    compact_control: Some(real_compact_control()),
                    text_bands: packed_text_bands(),
                    standalone_condition_row_count: 1,
                    standalone_condition_rows: real_condition_rows(),
                    negative_sentinel_scope: Some(company_negative_sentinel_scope(
                        RuntimeCompanyConditionTestScope::HumanCompaniesOnly,
                    )),
                    grouped_effect_row_counts: vec![1, 0, 0, 0],
                    grouped_effect_rows: real_grouped_rows(),
                    decoded_conditions: Vec::new(),
                    decoded_actions: vec![RuntimeEffect::SetCompanyCash {
                        target: RuntimeCompanyTarget::ConditionTrueCompany,
                        value: 10,
                    }],
                    executable_import_ready: true,
                    notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
                },
                SmpLoadedPackedEventRecordSummary {
                    record_index: 4,
                    live_entry_id: 11,
                    payload_offset: Some(0x7402),
                    payload_len: Some(133),
                    decode_status: "parity_only".to_string(),
                    payload_family: "real_packed_v1".to_string(),
                    trigger_kind: Some(6),
                    active: None,
                    marks_collection_dirty: None,
                    one_shot: Some(true),
                    compact_control: Some(real_compact_control()),
                    text_bands: packed_text_bands(),
                    standalone_condition_row_count: 1,
                    standalone_condition_rows: real_condition_rows(),
                    negative_sentinel_scope: Some(company_negative_sentinel_scope(
                        RuntimeCompanyConditionTestScope::Disabled,
                    )),
                    grouped_effect_row_counts: vec![1, 0, 0, 0],
                    grouped_effect_rows: real_grouped_rows(),
                    decoded_conditions: Vec::new(),
                    decoded_actions: vec![RuntimeEffect::SetCompanyCash {
                        target: RuntimeCompanyTarget::ConditionTrueCompany,
                        value: 11,
                    }],
                    executable_import_ready: true,
                    notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
                },
            ],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "packed-events-real-descriptor-frontier",
        None,
    )
    .expect("save slice should project");

    assert_eq!(input.state.event_runtime_records.len(), 4);
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].compact_control.as_ref())
            .map(|control| control.mode_byte_0x7ef),
        Some(6)
    );
    let effects = input
        .state
        .event_runtime_records
        .iter()
        .map(|record| record.effects[0].clone())
        .collect::<Vec<_>>();
    assert_eq!(
        effects,
        vec![
            RuntimeEffect::SetCompanyCash {
                target: RuntimeCompanyTarget::AllActive,
                value: 7,
            },
            RuntimeEffect::SetCompanyCash {
                target: RuntimeCompanyTarget::SelectedCompany,
                value: 8,
            },
            RuntimeEffect::SetCompanyCash {
                target: RuntimeCompanyTarget::AiCompanies,
                value: 9,
            },
            RuntimeEffect::SetCompanyCash {
                target: RuntimeCompanyTarget::HumanCompanies,
                value: 10,
            },
        ]
    );
    assert_eq!(
        input.state.packed_event_collection.as_ref().map(|summary| {
            summary
                .records
                .iter()
                .map(|record| record.import_outcome.clone())
                .collect::<Vec<_>>()
        }),
        Some(vec![
            Some("imported".to_string()),
            Some("imported".to_string()),
            Some("imported".to_string()),
            Some("imported".to_string()),
            Some("blocked_company_condition_scope_disabled".to_string()),
        ])
    );
}

#[test]
fn blocks_player_scoped_effects_without_player_runtime_context() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 7,
            live_record_count: 1,
            live_entry_ids: vec![7],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 7,
                payload_offset: Some(0x7202),
                payload_len: Some(133),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(6),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(true),
                compact_control: Some(real_compact_control()),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 1,
                standalone_condition_rows: real_condition_rows(),
                negative_sentinel_scope: Some(player_negative_sentinel_scope()),
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: real_grouped_rows(),
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::SetPlayerCash {
                    target: RuntimePlayerTarget::ConditionTruePlayer,
                    value: 7,
                }],
                executable_import_ready: true,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "negative-sentinel-player-scope",
        None,
    )
    .expect("save slice should project");

    assert!(input.state.event_runtime_records.is_empty());
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_missing_player_context")
    );
}

#[test]
fn blocks_named_or_aggregate_territory_conditions_without_territory_context() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 7,
            live_record_count: 1,
            live_entry_ids: vec![7],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 7,
                payload_offset: Some(0x7202),
                payload_len: Some(133),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(6),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(true),
                compact_control: Some(real_compact_control()),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 1,
                standalone_condition_rows: vec![SmpLoadedPackedEventConditionRowSummary {
                    row_index: 0,
                    raw_condition_id: 2313,
                    subtype: 0,
                    flag_bytes: vec![
                        10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    ],
                    candidate_name: None,
                    comparator: Some("ge".to_string()),
                    metric: Some("Territory Track Pieces".to_string()),
                    semantic_family: Some("numeric_threshold".to_string()),
                    semantic_preview: Some("Test Territory Track Pieces >= 10".to_string()),
                    recovered_cargo_slot: None,
                    recovered_cargo_class: None,
                    requires_candidate_name_binding: false,
                    notes: Vec::new(),
                }],
                negative_sentinel_scope: Some(territory_negative_sentinel_scope()),
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: real_grouped_rows(),
                decoded_conditions: vec![RuntimeCondition::TerritoryNumericThreshold {
                    target: RuntimeTerritoryTarget::AllTerritories,
                    metric: crate::event::metrics::RuntimeTerritoryMetric::TrackPiecesTotal,
                    comparator: crate::event::conditions::RuntimeConditionComparator::Ge,
                    value: 10,
                }],
                decoded_actions: vec![RuntimeEffect::SetCompanyCash {
                    target: RuntimeCompanyTarget::ConditionTrueCompany,
                    value: 7,
                }],
                executable_import_ready: true,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "negative-sentinel-territory-scope",
        None,
    )
    .expect("save slice should project");

    assert!(input.state.event_runtime_records.is_empty());
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_missing_territory_context")
    );
}

#[test]
fn leaves_real_records_with_unclassified_scope_blocked_unmapped_real_descriptor() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 7,
            live_record_count: 1,
            live_entry_ids: vec![7],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 7,
                payload_offset: Some(0x7202),
                payload_len: Some(133),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(6),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(true),
                compact_control: Some(real_compact_control_without_symbolic_company_scope()),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 1,
                standalone_condition_rows: real_condition_rows(),
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: real_grouped_rows(),
                decoded_conditions: Vec::new(),
                decoded_actions: vec![],
                executable_import_ready: false,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "packed-events-real-descriptor-frontier",
        None,
    )
    .expect("save slice should project");

    assert!(input.state.event_runtime_records.is_empty());
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_unmapped_real_descriptor")
    );
}

#[test]
fn leaves_recovered_shell_owned_descriptor_rows_on_explicit_shell_owned_frontier() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: Some(save_company_roster()),
        chairman_profile_table: Some(save_chairman_profile_table()),
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 8,
            live_record_count: 1,
            live_entry_ids: vec![8],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 8,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(true),
                compact_control: Some(real_compact_control_without_symbolic_company_scope()),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: Vec::new(),
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![2, 0, 0, 0],
                grouped_effect_rows: vec![
                    real_stock_prices_shell_row(120),
                    real_merger_premium_shell_row(25),
                ],
                decoded_conditions: Vec::new(),
                decoded_actions: Vec::new(),
                executable_import_ready: false,
                notes: vec!["synthetic shell-owned descriptor test record".to_string()],
            }],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "packed-events-shell-owned-descriptor-frontier",
        None,
    )
    .expect("save slice should project");

    assert!(input.state.event_runtime_records.is_empty());
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_shell_owned_descriptor")
    );
}

#[test]
fn imports_credit_rating_descriptor_from_save_slice_company_context() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: Some(save_company_roster()),
        chairman_profile_table: Some(save_chairman_profile_table()),
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 9,
            live_record_count: 1,
            live_entry_ids: vec![9],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 9,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "executable".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(true),
                compact_control: Some(real_compact_control_without_symbolic_company_scope()),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: Vec::new(),
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_credit_rating_row(640)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::SetCompanyGovernanceScalar {
                    target: RuntimeCompanyTarget::SelectedCompany,
                    metric: crate::event::metrics::RuntimeCompanyMetric::CreditRating,
                    value: 640,
                }],
                executable_import_ready: true,
                notes: vec!["synthetic governance descriptor test record".to_string()],
            }],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "packed-events-credit-rating-descriptor",
        None,
    )
    .expect("save slice should project");

    assert_eq!(input.state.event_runtime_records.len(), 1);
    assert_eq!(
        input
            .state
            .event_runtime_records
            .first()
            .map(|record| record.effects.clone()),
        Some(vec![RuntimeEffect::SetCompanyGovernanceScalar {
            target: RuntimeCompanyTarget::SelectedCompany,
            metric: crate::event::metrics::RuntimeCompanyMetric::CreditRating,
            value: 640,
        }])
    );
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("imported")
    );
}

#[test]
fn blocks_scalar_locomotive_availability_rows_without_catalog_context() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 31,
            live_record_count: 1,
            live_entry_ids: vec![31],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 31,
                payload_offset: Some(0x7202),
                payload_len: Some(96),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(6),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: vec![],
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![SmpLoadedPackedEventGroupedEffectRowSummary {
                    group_index: 0,
                    row_index: 0,
                    descriptor_id: 250,
                    descriptor_label: Some("Big Boy 4-8-8-4 Availability".to_string()),
                    target_mask_bits: Some(0x08),
                    parameter_family: Some("locomotive_availability_scalar".to_string()),
                    grouped_target_subject: None,
                    grouped_target_scope: None,
                    opcode: 3,
                    raw_scalar_value: 42,
                    value_byte_0x09: 0,
                    value_dword_0x0d: 0,
                    value_byte_0x11: 0,
                    value_byte_0x12: 0,
                    value_word_0x14: 0,
                    value_word_0x16: 0,
                    row_shape: "scalar_assignment".to_string(),
                    semantic_family: Some("scalar_assignment".to_string()),
                    semantic_preview: Some("Set Big Boy 4-8-8-4 Availability to 42".to_string()),
                    recovered_cargo_slot: None,
                    recovered_cargo_class: None,
                    recovered_cargo_label: None,
                    recovered_locomotive_id: Some(10),
                    locomotive_name: None,
                    notes: vec![],
                }],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![],
                executable_import_ready: false,
                notes: vec![
                    "decoded from grounded real 0x4e9a row framing".to_string(),
                    "scalar locomotive availability rows still need catalog context".to_string(),
                ],
            }],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "packed-events-recovered-locomotive-availability-frontier",
        None,
    )
    .expect("save slice should project");

    assert!(input.state.event_runtime_records.is_empty());
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_missing_locomotive_catalog_context")
    );
}

#[test]
fn blocks_boolean_locomotive_availability_rows_without_catalog_context() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 32,
            live_record_count: 1,
            live_entry_ids: vec![32],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 32,
                payload_offset: Some(0x7202),
                payload_len: Some(96),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: vec![],
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_locomotive_availability_row(250, 1)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![],
                executable_import_ready: false,
                notes: vec![
                    "boolean locomotive availability row still needs catalog context".to_string(),
                ],
            }],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "packed-events-locomotive-availability-missing-catalog",
        None,
    )
    .expect("save slice should project");

    assert!(input.state.event_runtime_records.is_empty());
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_missing_locomotive_catalog_context")
    );
}

#[test]
fn imports_scalar_locomotive_availability_rows_with_save_derived_catalog_context() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: Some(save_named_locomotive_table(61)),
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 33,
            live_record_count: 1,
            live_entry_ids: vec![33],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 33,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: vec![],
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![2, 0, 0, 0],
                grouped_effect_rows: vec![
                    real_locomotive_availability_row(250, 42),
                    real_locomotive_availability_row(301, 7),
                ],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![],
                executable_import_ready: false,
                notes: vec![
                    "scalar locomotive availability rows use save-derived catalog context"
                        .to_string(),
                ],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "save-derived-locomotive-availability",
        None,
    )
    .expect("save slice should project");

    assert_eq!(input.state.locomotive_catalog.len(), 61);
    assert_eq!(input.state.event_runtime_records.len(), 1);
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("imported")
    );

    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("save-derived locomotive availability record should run");

    assert_eq!(
        input
            .state
            .named_locomotive_availability
            .get("Big Boy 4-8-8-4"),
        Some(&42)
    );
    assert_eq!(
        input.state.named_locomotive_availability.get("Zephyr"),
        Some(&7)
    );
}

#[test]
fn overlays_scalar_locomotive_availability_rows_into_named_availability_effects() {
    let base_state = RuntimeState {
        calendar: CalendarPoint {
            year: 1845,
            month_slot: 2,
            phase_slot: 1,
            tick_slot: 3,
        },
        world_flags: BTreeMap::new(),
        save_profile: RuntimeSaveProfileState::default(),
        world_restore: RuntimeWorldRestoreState::default(),
        metadata: BTreeMap::new(),
        companies: Vec::new(),
        selected_company_id: None,
        players: Vec::new(),
        selected_player_id: None,
        chairman_profiles: Vec::new(),
        selected_chairman_profile_id: None,
        trains: Vec::new(),
        locomotive_catalog: vec![
            crate::state::RuntimeLocomotiveCatalogEntry {
                locomotive_id: 10,
                name: "Big Boy 4-8-8-4".to_string(),
            },
            crate::state::RuntimeLocomotiveCatalogEntry {
                locomotive_id: 61,
                name: "Zephyr".to_string(),
            },
        ],
        cargo_catalog: Vec::new(),
        territories: Vec::new(),
        company_territory_track_piece_counts: Vec::new(),
        company_territory_access: Vec::new(),
        packed_event_collection: None,
        event_runtime_records: Vec::new(),
        candidate_availability: BTreeMap::new(),
        named_locomotive_availability: BTreeMap::from([
            ("Big Boy 4-8-8-4".to_string(), 0),
            ("Zephyr".to_string(), 1),
        ]),
        named_locomotive_cost: BTreeMap::new(),
        all_cargo_price_override: None,
        named_cargo_price_overrides: BTreeMap::new(),
        all_cargo_production_override: None,
        factory_cargo_production_override: None,
        farm_mine_cargo_production_override: None,
        named_cargo_production_overrides: BTreeMap::new(),
        cargo_production_overrides: BTreeMap::new(),
        world_runtime_variables: BTreeMap::new(),
        company_runtime_variables: BTreeMap::new(),
        player_runtime_variables: BTreeMap::new(),
        territory_runtime_variables: BTreeMap::new(),
        world_scalar_overrides: BTreeMap::new(),
        special_conditions: BTreeMap::new(),
        service_state: RuntimeServiceState::default(),
    };
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 33,
            live_record_count: 1,
            live_entry_ids: vec![33],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 33,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: vec![],
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![2, 0, 0, 0],
                grouped_effect_rows: vec![
                    real_locomotive_availability_row(250, 42),
                    real_locomotive_availability_row(301, 7),
                ],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![],
                executable_import_ready: false,
                notes: vec![
                    "scalar locomotive availability rows use overlay catalog context".to_string(),
                ],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "overlay-locomotive-availability",
        None,
    )
    .expect("overlay input should project");

    assert_eq!(input.state.event_runtime_records.len(), 1);
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("imported")
    );

    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("overlay-imported locomotive availability record should run");

    assert_eq!(
        input
            .state
            .named_locomotive_availability
            .get("Big Boy 4-8-8-4"),
        Some(&42)
    );
    assert_eq!(
        input.state.named_locomotive_availability.get("Zephyr"),
        Some(&7)
    );
}

#[test]
fn blocks_recovered_locomotive_cost_rows_without_catalog_context_lower_band() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 34,
            live_record_count: 1,
            live_entry_ids: vec![34],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 34,
                payload_offset: Some(0x7202),
                payload_len: Some(96),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: vec![],
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_locomotive_cost_row(352, 250000)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![],
                executable_import_ready: false,
                notes: vec!["scalar locomotive cost row still needs catalog context".to_string()],
            }],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "packed-events-locomotive-cost-frontier-lower-band",
        None,
    )
    .expect("save slice should project");

    assert!(input.state.event_runtime_records.is_empty());
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_missing_locomotive_catalog_context")
    );
}

#[test]
fn blocks_recovered_locomotive_cost_rows_without_catalog_context() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 35,
            live_record_count: 1,
            live_entry_ids: vec![35],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 35,
                payload_offset: Some(0x7202),
                payload_len: Some(96),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: vec![],
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_locomotive_cost_row(352, 250000)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![],
                executable_import_ready: false,
                notes: vec!["scalar locomotive cost row still needs catalog context".to_string()],
            }],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "packed-events-locomotive-cost-missing-catalog",
        None,
    )
    .expect("save slice should project");

    assert!(input.state.event_runtime_records.is_empty());
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_missing_locomotive_catalog_context")
    );
}

#[test]
fn imports_scalar_locomotive_cost_rows_with_save_derived_catalog_context() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: Some(save_named_locomotive_table(61)),
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 41,
            live_record_count: 1,
            live_entry_ids: vec![41],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 41,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: vec![],
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![2, 0, 0, 0],
                grouped_effect_rows: vec![
                    real_locomotive_cost_row(352, 250000),
                    real_locomotive_cost_row(412, 325000),
                ],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![],
                executable_import_ready: false,
                notes: vec![
                    "scalar locomotive cost rows use save-derived catalog context".to_string(),
                ],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "save-derived-locomotive-cost",
        None,
    )
    .expect("save slice should project");

    assert_eq!(input.state.locomotive_catalog.len(), 61);
    assert_eq!(input.state.event_runtime_records.len(), 1);
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("imported")
    );

    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("save-derived locomotive cost record should run");

    assert_eq!(
        input.state.named_locomotive_cost.get("2-D-2"),
        Some(&250000)
    );
    assert_eq!(
        input.state.named_locomotive_cost.get("Zephyr"),
        Some(&325000)
    );
}

#[test]
fn overlays_scalar_locomotive_cost_rows_into_named_cost_effects() {
    let base_state = RuntimeState {
        calendar: CalendarPoint {
            year: 1845,
            month_slot: 2,
            phase_slot: 1,
            tick_slot: 3,
        },
        world_flags: BTreeMap::new(),
        save_profile: RuntimeSaveProfileState::default(),
        world_restore: RuntimeWorldRestoreState::default(),
        metadata: BTreeMap::new(),
        companies: Vec::new(),
        selected_company_id: None,
        players: Vec::new(),
        selected_player_id: None,
        chairman_profiles: Vec::new(),
        selected_chairman_profile_id: None,
        trains: Vec::new(),
        locomotive_catalog: vec![
            crate::state::RuntimeLocomotiveCatalogEntry {
                locomotive_id: 1,
                name: "2-D-2".to_string(),
            },
            crate::state::RuntimeLocomotiveCatalogEntry {
                locomotive_id: 61,
                name: "Zephyr".to_string(),
            },
        ],
        cargo_catalog: Vec::new(),
        territories: Vec::new(),
        company_territory_track_piece_counts: Vec::new(),
        company_territory_access: Vec::new(),
        packed_event_collection: None,
        event_runtime_records: Vec::new(),
        candidate_availability: BTreeMap::new(),
        named_locomotive_availability: BTreeMap::new(),
        named_locomotive_cost: BTreeMap::from([
            ("2-D-2".to_string(), 100000),
            ("Zephyr".to_string(), 200000),
        ]),
        all_cargo_price_override: None,
        named_cargo_price_overrides: BTreeMap::new(),
        all_cargo_production_override: None,
        factory_cargo_production_override: None,
        farm_mine_cargo_production_override: None,
        named_cargo_production_overrides: BTreeMap::new(),
        cargo_production_overrides: BTreeMap::new(),
        world_runtime_variables: BTreeMap::new(),
        company_runtime_variables: BTreeMap::new(),
        player_runtime_variables: BTreeMap::new(),
        territory_runtime_variables: BTreeMap::new(),
        world_scalar_overrides: BTreeMap::new(),
        special_conditions: BTreeMap::new(),
        service_state: RuntimeServiceState::default(),
    };
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 36,
            live_record_count: 1,
            live_entry_ids: vec![36],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 36,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: vec![],
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![2, 0, 0, 0],
                grouped_effect_rows: vec![
                    real_locomotive_cost_row(352, 250000),
                    real_locomotive_cost_row(412, 325000),
                ],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![],
                executable_import_ready: false,
                notes: vec!["scalar locomotive cost rows use overlay catalog context".to_string()],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "overlay-locomotive-cost",
        None,
    )
    .expect("overlay input should project");

    assert_eq!(input.state.event_runtime_records.len(), 1);
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("imported")
    );

    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("overlay-imported locomotive cost record should run");

    assert_eq!(
        input.state.named_locomotive_cost.get("2-D-2"),
        Some(&250000)
    );
    assert_eq!(
        input.state.named_locomotive_cost.get("Zephyr"),
        Some(&325000)
    );
}

#[test]
fn keeps_negative_locomotive_cost_rows_parity_only() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 37,
            live_record_count: 1,
            live_entry_ids: vec![37],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 37,
                payload_offset: Some(0x7202),
                payload_len: Some(96),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: vec![],
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_locomotive_cost_row(352, -1)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![],
                executable_import_ready: false,
                notes: vec!["negative locomotive cost rows remain parity-only".to_string()],
            }],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "packed-events-negative-locomotive-cost-frontier",
        None,
    )
    .expect("save slice should project");

    assert!(input.state.event_runtime_records.is_empty());
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_variant_or_scope_blocked_descriptor")
    );
}

#[test]
fn imports_recovered_cargo_production_rows_into_runtime_records() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 35,
            live_record_count: 1,
            live_entry_ids: vec![35],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 35,
                payload_offset: Some(0x7202),
                payload_len: Some(96),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: vec![],
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_cargo_production_row(230, 125)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![],
                executable_import_ready: false,
                notes: vec!["cargo production rows now input through world overrides".to_string()],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "packed-events-cargo-production-frontier",
        None,
    )
    .expect("save slice should project");

    assert_eq!(input.state.event_runtime_records.len(), 1);
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("imported")
    );

    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("cargo production runtime record should run");

    assert_eq!(input.state.cargo_production_overrides.get(&1), Some(&125));
}

#[test]
fn imports_aggregate_cargo_economics_rows_into_runtime_records() {
    let save_slice = SmpLoadedSaveSlice {
            file_extension_hint: Some("gms".to_string()),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            trailer_family: None,
            bridge_family: None,
            profile: None,
            candidate_availability_table: None,
            named_locomotive_availability_table: None,
            locomotive_catalog: None,
            cargo_catalog: None,
            world_issue_37_state: None,
            world_economic_tuning_state: None,
            world_finance_neighborhood_state: None,
            world_locomotive_policy_state: None,
            company_roster: None,
            chairman_profile_table: None,
            region_collection: None,
            region_fixed_row_run_summary: None,
            placed_structure_collection: None,
            placed_structure_dynamic_side_buffer_summary: None,
            special_conditions_table: None,
            event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
                source_kind: "packed-event-runtime-collection".to_string(),
                mechanism_family: "classic-save-rehydrate-v1".to_string(),
                mechanism_confidence: "grounded".to_string(),
                container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
                metadata_tag_offset: 0x7100,
                records_tag_offset: 0x7200,
                close_tag_offset: 0x7600,
                packed_state_version: 0x3e9,
                packed_state_version_hex: "0x000003e9".to_string(),
                live_id_bound: 38,
                live_record_count: 1,
                live_entry_ids: vec![38],
                decoded_record_count: 1,
                imported_runtime_record_count: 0,
                records_with_trigger_kind: 0,
                records_missing_trigger_kind: 0,
                nondirect_compact_record_count: 0,
                nondirect_compact_records_missing_trigger_kind: 0,
                trigger_kinds_present: vec![],
                control_lane_notes: vec![],
                add_building_dispatch_strip_record_indexes: vec![],
                add_building_dispatch_strip_descriptor_labels: vec![],
                add_building_dispatch_strip_records_with_trigger_kind: 0,
                add_building_dispatch_strip_records_missing_trigger_kind: 0,
                add_building_dispatch_strip_row_shape_families: vec![],
                add_building_dispatch_strip_signature_families: vec![],
                add_building_dispatch_strip_condition_tuple_families: vec![],
                add_building_dispatch_strip_signature_condition_clusters: vec![],
                records: vec![SmpLoadedPackedEventRecordSummary {
                    record_index: 0,
                    live_entry_id: 38,
                    payload_offset: Some(0x7202),
                    payload_len: Some(144),
                    decode_status: "parity_only".to_string(),
                    payload_family: "real_packed_v1".to_string(),
                    trigger_kind: Some(7),
                    active: None,
                    marks_collection_dirty: None,
                    one_shot: Some(false),
                    compact_control: Some(real_compact_control()),
                    text_bands: vec![],
                    standalone_condition_row_count: 0,
                    standalone_condition_rows: vec![],
                    negative_sentinel_scope: None,
                    grouped_effect_row_counts: vec![4, 0, 0, 0],
                    grouped_effect_rows: vec![
                        real_all_cargo_price_row(180),
                        real_aggregate_cargo_production_row(177, 210),
                        real_aggregate_cargo_production_row(178, 225),
                        real_aggregate_cargo_production_row(179, 175),
                    ],
                    decoded_conditions: Vec::new(),
                    decoded_actions: vec![],
                    executable_import_ready: false,
                    notes: vec![
                        "grounded aggregate cargo economics descriptors input through bounded override surfaces"
                            .to_string(),
                    ],
                }],
            }),
            notes: vec![],
        };

    let mut input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "packed-events-aggregate-cargo-economics",
        None,
    )
    .expect("save slice should project");

    assert_eq!(input.state.event_runtime_records.len(), 1);
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("imported")
    );

    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("aggregate cargo economics runtime record should run");

    assert_eq!(input.state.all_cargo_price_override, Some(180));
    assert_eq!(input.state.all_cargo_production_override, Some(210));
    assert_eq!(input.state.factory_cargo_production_override, Some(225));
    assert_eq!(input.state.farm_mine_cargo_production_override, Some(175));
}

#[test]
fn imports_named_cargo_price_rows_when_binding_is_grounded() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 39,
            live_record_count: 1,
            live_entry_ids: vec![39],
            decoded_record_count: 1,
            imported_runtime_record_count: 1,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 39,
                payload_offset: Some(0x7202),
                payload_len: Some(96),
                decode_status: "executable".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: vec![],
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_named_cargo_price_row(106, 140)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::SetCargoPriceOverride {
                    target: RuntimeCargoPriceTarget::Named {
                        name: "Alcohol".to_string(),
                    },
                    value: 140,
                }],
                executable_import_ready: true,
                notes: vec![
                    "named cargo price descriptors now input through named cargo overrides"
                        .to_string(),
                ],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "packed-events-named-cargo-price-input",
        None,
    )
    .expect("save slice should project");

    assert_eq!(input.state.event_runtime_records.len(), 1);
    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("named cargo price runtime record should run");

    assert_eq!(
        input.state.named_cargo_price_overrides.get("Alcohol"),
        Some(&140)
    );
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("imported")
    );
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].grouped_effect_rows.first())
            .and_then(|row| row.descriptor_label.as_deref()),
        Some("Alcohol Price")
    );
}

#[test]
fn imports_named_cargo_production_rows_when_binding_is_grounded() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 40,
            live_record_count: 1,
            live_entry_ids: vec![40],
            decoded_record_count: 1,
            imported_runtime_record_count: 1,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 40,
                payload_offset: Some(0x7202),
                payload_len: Some(96),
                decode_status: "executable".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: vec![],
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_named_cargo_production_row(180, 160)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::SetCargoProductionOverride {
                    target: RuntimeCargoProductionTarget::Named {
                        name: "Alcohol".to_string(),
                    },
                    value: 160,
                }],
                executable_import_ready: true,
                notes: vec![
                    "named cargo production descriptors now input through named cargo overrides"
                        .to_string(),
                ],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "packed-events-named-cargo-production-parity",
        None,
    )
    .expect("save slice should project");

    assert_eq!(input.state.event_runtime_records.len(), 1);
    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("named cargo production runtime record should run");

    assert_eq!(
        input.state.named_cargo_production_overrides.get("Alcohol"),
        Some(&160)
    );
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("imported")
    );
}

#[test]
fn keeps_negative_all_cargo_price_rows_variant_blocked() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 41,
            live_record_count: 1,
            live_entry_ids: vec![41],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 41,
                payload_offset: Some(0x7202),
                payload_len: Some(96),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: vec![],
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_all_cargo_price_row(-1)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![],
                executable_import_ready: false,
                notes: vec![
                    "negative aggregate cargo price variants remain parity-only".to_string(),
                ],
            }],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "packed-events-negative-all-cargo-price",
        None,
    )
    .expect("save slice should project");

    assert!(input.state.event_runtime_records.is_empty());
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_variant_or_scope_blocked_descriptor")
    );
}

#[test]
fn imports_recovered_territory_access_cost_rows_into_runtime_records() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 36,
            live_record_count: 1,
            live_entry_ids: vec![36],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 36,
                payload_offset: Some(0x7202),
                payload_len: Some(96),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: vec![],
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_territory_access_cost_row(750000)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![],
                executable_import_ready: false,
                notes: vec![
                    "territory access cost rows now input through world restore".to_string(),
                ],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "packed-events-territory-access-cost-frontier",
        None,
    )
    .expect("save slice should project");

    assert_eq!(input.state.event_runtime_records.len(), 1);
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("imported")
    );

    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("territory access cost runtime record should run");

    assert_eq!(
        input.state.world_restore.territory_access_cost,
        Some(750000)
    );
}

#[test]
fn overlays_real_company_cash_descriptor_into_executable_runtime_record() {
    let base_state = RuntimeState {
        calendar: CalendarPoint {
            year: 1845,
            month_slot: 2,
            phase_slot: 1,
            tick_slot: 3,
        },
        world_flags: BTreeMap::new(),
        save_profile: RuntimeSaveProfileState::default(),
        world_restore: RuntimeWorldRestoreState::default(),
        metadata: BTreeMap::new(),
        companies: vec![crate::state::RuntimeCompany {
            company_id: 42,
            controller_kind: RuntimeCompanyControllerKind::Human,
            current_cash: 500,
            debt: 20,
            credit_rating_score: None,
            prime_rate: None,
            track_piece_counts: RuntimeTrackPieceCounts::default(),
            active: true,
            available_track_laying_capacity: None,
            linked_chairman_profile_id: None,
            book_value_per_share: 0,
            investor_confidence: 0,
            management_attitude: 0,
            takeover_cooldown_year: None,
            merger_cooldown_year: None,
        }],
        selected_company_id: Some(42),
        players: Vec::new(),
        selected_player_id: None,
        chairman_profiles: Vec::new(),
        selected_chairman_profile_id: None,
        trains: Vec::new(),
        locomotive_catalog: Vec::new(),
        cargo_catalog: Vec::new(),
        territories: Vec::new(),
        company_territory_track_piece_counts: Vec::new(),
        company_territory_access: Vec::new(),
        packed_event_collection: None,
        event_runtime_records: Vec::new(),
        candidate_availability: BTreeMap::new(),
        named_locomotive_availability: BTreeMap::new(),
        named_locomotive_cost: BTreeMap::new(),
        all_cargo_price_override: None,
        named_cargo_price_overrides: BTreeMap::new(),
        all_cargo_production_override: None,
        factory_cargo_production_override: None,
        farm_mine_cargo_production_override: None,
        named_cargo_production_overrides: BTreeMap::new(),
        cargo_production_overrides: BTreeMap::new(),
        world_runtime_variables: BTreeMap::new(),
        company_runtime_variables: BTreeMap::new(),
        player_runtime_variables: BTreeMap::new(),
        territory_runtime_variables: BTreeMap::new(),
        world_scalar_overrides: BTreeMap::new(),
        special_conditions: BTreeMap::new(),
        service_state: RuntimeServiceState::default(),
    };
    let save_slice = SmpLoadedSaveSlice {
            file_extension_hint: Some("gms".to_string()),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            trailer_family: None,
            bridge_family: None,
            profile: None,
            candidate_availability_table: None,
            named_locomotive_availability_table: None,
                locomotive_catalog: None,
            cargo_catalog: None,
            world_issue_37_state: None,
            world_economic_tuning_state: None,
            world_finance_neighborhood_state: None,
                world_locomotive_policy_state: None,
                company_roster: None,
                chairman_profile_table: None,
            region_collection: None,
            region_fixed_row_run_summary: None,
            placed_structure_collection: None,
            placed_structure_dynamic_side_buffer_summary: None,
            special_conditions_table: None,
            event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
                source_kind: "packed-event-runtime-collection".to_string(),
                mechanism_family: "classic-save-rehydrate-v1".to_string(),
                mechanism_confidence: "grounded".to_string(),
                container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
                metadata_tag_offset: 0x7100,
                records_tag_offset: 0x7200,
                close_tag_offset: 0x7600,
                packed_state_version: 0x3e9,
                packed_state_version_hex: "0x000003e9".to_string(),
                live_id_bound: 9,
                live_record_count: 1,
                live_entry_ids: vec![9],
                decoded_record_count: 1,
                imported_runtime_record_count: 0,
                records_with_trigger_kind: 0,
                records_missing_trigger_kind: 0,
                nondirect_compact_record_count: 0,
                nondirect_compact_records_missing_trigger_kind: 0,
                trigger_kinds_present: vec![],
                control_lane_notes: vec![],
                add_building_dispatch_strip_record_indexes: vec![],
                add_building_dispatch_strip_descriptor_labels: vec![],
                add_building_dispatch_strip_records_with_trigger_kind: 0,
                add_building_dispatch_strip_records_missing_trigger_kind: 0,
                add_building_dispatch_strip_row_shape_families: vec![],
                add_building_dispatch_strip_signature_families: vec![],
                add_building_dispatch_strip_condition_tuple_families: vec![],
                add_building_dispatch_strip_signature_condition_clusters: vec![],
                records: vec![SmpLoadedPackedEventRecordSummary {
                    record_index: 0,
                    live_entry_id: 9,
                    payload_offset: Some(0x7202),
                    payload_len: Some(133),
                    decode_status: "parity_only".to_string(),
                    payload_family: "real_packed_v1".to_string(),
                    trigger_kind: Some(7),
                    active: None,
                    marks_collection_dirty: None,
                    one_shot: Some(false),
                    compact_control: Some(SmpLoadedPackedEventCompactControlSummary {
                        mode_byte_0x7ef: 7,
                        primary_selector_0x7f0: 0x63,
                        grouped_mode_0x7f4: 2,
                        one_shot_header_0x7f5: 0,
                        modifier_flag_0x7f9: 1,
                        modifier_flag_0x7fa: 0,
                        grouped_target_scope_ordinals_0x7fb: vec![1, 1, 1, 1],
                        grouped_scope_checkboxes_0x7ff: vec![1, 0, 0, 0],
                        summary_toggle_0x800: 1,
                        grouped_territory_selectors_0x80f: vec![-1, -1, -1, -1],
                    }),
                    text_bands: packed_text_bands(),
                    standalone_condition_row_count: 0,
                    standalone_condition_rows: vec![],
                    negative_sentinel_scope: None,
                    grouped_effect_row_counts: vec![1, 0, 0, 0],
                    grouped_effect_rows: vec![SmpLoadedPackedEventGroupedEffectRowSummary {
                        group_index: 0,
                        row_index: 0,
                        descriptor_id: 2,
                        descriptor_label: Some("Company Cash".to_string()),
                        target_mask_bits: Some(0x01),
                        parameter_family: Some("company_finance_scalar".to_string()),
                        grouped_target_subject: None,
                        grouped_target_scope: None,
                        opcode: 8,
                        raw_scalar_value: 250,
                        value_byte_0x09: 1,
                        value_dword_0x0d: 12,
                        value_byte_0x11: 2,
                        value_byte_0x12: 3,
                        value_word_0x14: 24,
                        value_word_0x16: 36,
                        row_shape: "multivalue_scalar".to_string(),
                        semantic_family: Some("multivalue_scalar".to_string()),
                        semantic_preview: Some(
                            "Set Company Cash to 250 with aux [2, 3, 24, 36]".to_string(),
                        ),
                        recovered_cargo_slot: None,
                        recovered_cargo_class: None,
                        recovered_cargo_label: None,
                        recovered_locomotive_id: None,
                        locomotive_name: Some("Mikado".to_string()),
                        notes: vec![
                            "grouped effect row carries locomotive-name side string".to_string(),
                        ],
                    }],
                    decoded_conditions: Vec::new(),
                    decoded_actions: vec![RuntimeEffect::SetCompanyCash {
                        target: RuntimeCompanyTarget::SelectedCompany,
                        value: 250,
                    }],
                    executable_import_ready: true,
                    notes: vec![
                        "decoded from grounded real 0x4e9a row framing".to_string(),
                        "grouped descriptor labels and target masks come from the checked-in effect table recovered around 0x006103a0".to_string(),
                    ],
                }],
            }),
            notes: vec![],
        };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "real-company-cash-overlay",
        None,
    )
    .expect("overlay input should project");

    assert_eq!(input.state.event_runtime_records.len(), 1);
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("imported")
    );

    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("real company-cash descriptor should execute through the normal trigger path");

    assert_eq!(input.state.companies[0].current_cash, 250);
}

#[test]
fn overlays_real_territory_access_descriptor_into_executable_runtime_record() {
    let base_state = RuntimeState {
        companies: vec![crate::state::RuntimeCompany {
            company_id: 42,
            controller_kind: RuntimeCompanyControllerKind::Human,
            current_cash: 500,
            debt: 20,
            credit_rating_score: None,
            prime_rate: None,
            track_piece_counts: RuntimeTrackPieceCounts::default(),
            active: true,
            available_track_laying_capacity: None,
            linked_chairman_profile_id: None,
            book_value_per_share: 0,
            investor_confidence: 0,
            management_attitude: 0,
            takeover_cooldown_year: None,
            merger_cooldown_year: None,
        }],
        selected_company_id: Some(42),
        territories: vec![crate::state::RuntimeTerritory {
            territory_id: 7,
            name: Some("Appalachia".to_string()),
            track_piece_counts: RuntimeTrackPieceCounts::default(),
        }],
        ..state()
    };
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 11,
            live_record_count: 1,
            live_entry_ids: vec![11],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 11,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(6),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(SmpLoadedPackedEventCompactControlSummary {
                    mode_byte_0x7ef: 6,
                    primary_selector_0x7f0: 12,
                    grouped_mode_0x7f4: 2,
                    one_shot_header_0x7f5: 0,
                    modifier_flag_0x7f9: 0,
                    modifier_flag_0x7fa: 0,
                    grouped_target_scope_ordinals_0x7fb: vec![1, 1, 1, 1],
                    grouped_scope_checkboxes_0x7ff: vec![1, 0, 0, 0],
                    summary_toggle_0x800: 1,
                    grouped_territory_selectors_0x80f: vec![7, -1, -1, -1],
                }),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_territory_access_row(true, vec![])],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::SetCompanyTerritoryAccess {
                    target: RuntimeCompanyTarget::SelectedCompany,
                    territory: RuntimeTerritoryTarget::Ids { ids: vec![7] },
                    value: true,
                }],
                executable_import_ready: true,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "real-territory-access-overlay",
        None,
    )
    .expect("overlay input should project");

    assert_eq!(input.state.event_runtime_records.len(), 1);
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("imported")
    );

    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 6 },
    )
    .expect("real territory-access descriptor should execute");

    assert_eq!(
        input.state.company_territory_access,
        vec![crate::state::RuntimeCompanyTerritoryAccess {
            company_id: 42,
            territory_id: 7,
        }]
    );
}

#[test]
fn keeps_real_territory_access_false_row_parity_only() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 12,
            live_record_count: 1,
            live_entry_ids: vec![12],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 12,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(6),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(SmpLoadedPackedEventCompactControlSummary {
                    mode_byte_0x7ef: 6,
                    primary_selector_0x7f0: 12,
                    grouped_mode_0x7f4: 2,
                    one_shot_header_0x7f5: 0,
                    modifier_flag_0x7f9: 0,
                    modifier_flag_0x7fa: 0,
                    grouped_target_scope_ordinals_0x7fb: vec![1, 1, 1, 1],
                    grouped_scope_checkboxes_0x7ff: vec![1, 0, 0, 0],
                    summary_toggle_0x800: 1,
                    grouped_territory_selectors_0x80f: vec![7, -1, -1, -1],
                }),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_territory_access_row(false, vec![])],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![],
                executable_import_ready: false,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let input =
        build_runtime_state_input_from_save_slice(&save_slice, "real-territory-access-false", None)
            .expect("save slice should project");

    assert!(input.state.event_runtime_records.is_empty());
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_territory_access_variant")
    );
}

#[test]
fn keeps_real_territory_access_missing_scope_row_parity_only() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 13,
            live_record_count: 1,
            live_entry_ids: vec![13],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 13,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(6),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(SmpLoadedPackedEventCompactControlSummary {
                    mode_byte_0x7ef: 6,
                    primary_selector_0x7f0: 12,
                    grouped_mode_0x7f4: 2,
                    one_shot_header_0x7f5: 0,
                    modifier_flag_0x7f9: 0,
                    modifier_flag_0x7fa: 0,
                    grouped_target_scope_ordinals_0x7fb: vec![9, 1, 1, 1],
                    grouped_scope_checkboxes_0x7ff: vec![1, 0, 0, 0],
                    summary_toggle_0x800: 1,
                    grouped_territory_selectors_0x80f: vec![-1, -1, -1, -1],
                }),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_territory_access_row(
                    true,
                    vec!["territory access row is missing company or territory scope".to_string()],
                )],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![],
                executable_import_ready: false,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "real-territory-access-missing-scope",
        None,
    )
    .expect("save slice should project");

    assert!(input.state.event_runtime_records.is_empty());
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_territory_access_scope")
    );
}

#[test]
fn overlays_real_deactivate_company_descriptor_into_executable_runtime_record() {
    let base_state = RuntimeState {
        companies: vec![crate::state::RuntimeCompany {
            company_id: 42,
            controller_kind: RuntimeCompanyControllerKind::Human,
            current_cash: 500,
            debt: 20,
            credit_rating_score: None,
            prime_rate: None,
            track_piece_counts: RuntimeTrackPieceCounts::default(),
            active: true,
            available_track_laying_capacity: None,
            linked_chairman_profile_id: None,
            book_value_per_share: 0,
            investor_confidence: 0,
            management_attitude: 0,
            takeover_cooldown_year: None,
            merger_cooldown_year: None,
        }],
        selected_company_id: Some(42),
        ..state()
    };
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 13,
            live_record_count: 1,
            live_entry_ids: vec![13],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 13,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(SmpLoadedPackedEventCompactControlSummary {
                    mode_byte_0x7ef: 7,
                    primary_selector_0x7f0: 0x63,
                    grouped_mode_0x7f4: 2,
                    one_shot_header_0x7f5: 0,
                    modifier_flag_0x7f9: 1,
                    modifier_flag_0x7fa: 0,
                    grouped_target_scope_ordinals_0x7fb: vec![1, 1, 1, 1],
                    grouped_scope_checkboxes_0x7ff: vec![1, 0, 0, 0],
                    summary_toggle_0x800: 1,
                    grouped_territory_selectors_0x80f: vec![-1, -1, -1, -1],
                }),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_deactivate_company_row(true)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::DeactivateCompany {
                    target: RuntimeCompanyTarget::SelectedCompany,
                }],
                executable_import_ready: true,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "real-deactivate-company-overlay",
        None,
    )
    .expect("overlay input should project");

    assert_eq!(input.state.event_runtime_records.len(), 1);
    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("real deactivate-company descriptor should execute");

    assert!(!input.state.companies[0].active);
    assert_eq!(input.state.selected_company_id, None);
}

#[test]
fn overlays_real_deactivate_player_descriptor_into_executable_runtime_record() {
    let base_state = RuntimeState {
        players: vec![
            crate::state::RuntimePlayer {
                player_id: 7,
                current_cash: 500,
                active: true,
                controller_kind: RuntimeCompanyControllerKind::Human,
            },
            crate::state::RuntimePlayer {
                player_id: 8,
                current_cash: 250,
                active: true,
                controller_kind: RuntimeCompanyControllerKind::Ai,
            },
        ],
        selected_player_id: Some(7),
        ..state()
    };
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 18,
            live_record_count: 1,
            live_entry_ids: vec![18],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 18,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(SmpLoadedPackedEventCompactControlSummary {
                    mode_byte_0x7ef: 7,
                    primary_selector_0x7f0: 0x63,
                    grouped_mode_0x7f4: 2,
                    one_shot_header_0x7f5: 0,
                    modifier_flag_0x7f9: 0,
                    modifier_flag_0x7fa: 2,
                    grouped_target_scope_ordinals_0x7fb: vec![0, 0, 0, 0],
                    grouped_scope_checkboxes_0x7ff: vec![1, 0, 0, 0],
                    summary_toggle_0x800: 1,
                    grouped_territory_selectors_0x80f: vec![-1, -1, -1, -1],
                }),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 1,
                standalone_condition_rows: real_condition_rows(),
                negative_sentinel_scope: Some(SmpLoadedPackedEventNegativeSentinelScopeSummary {
                    company_test_scope: RuntimeCompanyConditionTestScope::Disabled,
                    player_test_scope: RuntimePlayerConditionTestScope::SelectedPlayerOnly,
                    territory_scope_selector_is_0x63: false,
                    source_row_indexes: vec![0],
                }),
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_deactivate_player_row(true)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::DeactivatePlayer {
                    target: RuntimePlayerTarget::ConditionTruePlayer,
                }],
                executable_import_ready: true,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "real-deactivate-player-overlay",
        None,
    )
    .expect("overlay input should project");

    assert_eq!(input.state.event_runtime_records.len(), 1);
    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("real deactivate-player descriptor should execute");

    assert!(!input.state.players[0].active);
    assert!(input.state.players[1].active);
    assert_eq!(input.state.selected_player_id, None);
}

#[test]
fn keeps_real_deactivate_player_false_row_parity_only() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 19,
            live_record_count: 1,
            live_entry_ids: vec![19],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 19,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(SmpLoadedPackedEventCompactControlSummary {
                    mode_byte_0x7ef: 7,
                    primary_selector_0x7f0: 0x63,
                    grouped_mode_0x7f4: 2,
                    one_shot_header_0x7f5: 0,
                    modifier_flag_0x7f9: 0,
                    modifier_flag_0x7fa: 2,
                    grouped_target_scope_ordinals_0x7fb: vec![0, 0, 0, 0],
                    grouped_scope_checkboxes_0x7ff: vec![1, 0, 0, 0],
                    summary_toggle_0x800: 1,
                    grouped_territory_selectors_0x80f: vec![-1, -1, -1, -1],
                }),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 1,
                standalone_condition_rows: real_condition_rows(),
                negative_sentinel_scope: Some(SmpLoadedPackedEventNegativeSentinelScopeSummary {
                    company_test_scope: RuntimeCompanyConditionTestScope::Disabled,
                    player_test_scope: RuntimePlayerConditionTestScope::SelectedPlayerOnly,
                    territory_scope_selector_is_0x63: false,
                    source_row_indexes: vec![0],
                }),
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_deactivate_player_row(false)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![],
                executable_import_ready: false,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "real-deactivate-player-false",
        None,
    )
    .expect("save slice should project");

    assert!(input.state.event_runtime_records.is_empty());
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_variant_or_scope_blocked_descriptor")
    );
}

#[test]
fn keeps_real_deactivate_company_false_row_parity_only() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 14,
            live_record_count: 1,
            live_entry_ids: vec![14],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 14,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(SmpLoadedPackedEventCompactControlSummary {
                    mode_byte_0x7ef: 7,
                    primary_selector_0x7f0: 0x63,
                    grouped_mode_0x7f4: 2,
                    one_shot_header_0x7f5: 0,
                    modifier_flag_0x7f9: 1,
                    modifier_flag_0x7fa: 0,
                    grouped_target_scope_ordinals_0x7fb: vec![1, 1, 1, 1],
                    grouped_scope_checkboxes_0x7ff: vec![1, 0, 0, 0],
                    summary_toggle_0x800: 1,
                    grouped_territory_selectors_0x80f: vec![-1, -1, -1, -1],
                }),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_deactivate_company_row(false)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![],
                executable_import_ready: false,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "real-deactivate-company-false",
        None,
    )
    .expect("save slice should project");

    assert!(input.state.event_runtime_records.is_empty());
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_variant_or_scope_blocked_descriptor")
    );
}

#[test]
fn overlays_real_track_capacity_descriptor_into_executable_runtime_record() {
    let base_state = RuntimeState {
        companies: vec![crate::state::RuntimeCompany {
            company_id: 42,
            controller_kind: RuntimeCompanyControllerKind::Human,
            current_cash: 500,
            debt: 20,
            credit_rating_score: None,
            prime_rate: None,
            track_piece_counts: RuntimeTrackPieceCounts::default(),
            active: true,
            available_track_laying_capacity: None,
            linked_chairman_profile_id: None,
            book_value_per_share: 0,
            investor_confidence: 0,
            management_attitude: 0,
            takeover_cooldown_year: None,
            merger_cooldown_year: None,
        }],
        selected_company_id: Some(42),
        ..state()
    };
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 16,
            live_record_count: 1,
            live_entry_ids: vec![16],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 16,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(SmpLoadedPackedEventCompactControlSummary {
                    mode_byte_0x7ef: 7,
                    primary_selector_0x7f0: 0x63,
                    grouped_mode_0x7f4: 2,
                    one_shot_header_0x7f5: 0,
                    modifier_flag_0x7f9: 1,
                    modifier_flag_0x7fa: 0,
                    grouped_target_scope_ordinals_0x7fb: vec![1, 1, 1, 1],
                    grouped_scope_checkboxes_0x7ff: vec![1, 0, 0, 0],
                    summary_toggle_0x800: 1,
                    grouped_territory_selectors_0x80f: vec![-1, -1, -1, -1],
                }),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_track_capacity_row(18)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::SetCompanyTrackLayingCapacity {
                    target: RuntimeCompanyTarget::SelectedCompany,
                    value: Some(18),
                }],
                executable_import_ready: true,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "real-track-capacity-overlay",
        None,
    )
    .expect("overlay input should project");

    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("real track-capacity descriptor should execute");

    assert_eq!(
        input.state.companies[0].available_track_laying_capacity,
        Some(18)
    );
}

#[test]
fn overlays_real_economic_status_descriptor_into_executable_runtime_record() {
    let base_state = state();
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 18,
            live_record_count: 1,
            live_entry_ids: vec![18],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 18,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_economic_status_row(2)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::SetEconomicStatusCode { value: 2 }],
                executable_import_ready: true,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "real-economic-status-overlay",
        None,
    )
    .expect("overlay input should project");

    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("real economic-status descriptor should execute");

    assert_eq!(input.state.world_restore.economic_status_code, Some(2));
}

#[test]
fn imports_real_limited_track_building_amount_descriptor_into_executable_runtime_record() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 52,
            live_record_count: 1,
            live_entry_ids: vec![52],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 52,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(6),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_limited_track_building_amount_row(18)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::SetLimitedTrackBuildingAmount { value: 18 }],
                executable_import_ready: true,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "real-limited-track-building-amount-save-slice",
        None,
    )
    .expect("save-slice input should project");

    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 6 },
    )
    .expect("real limited-track-building-amount descriptor should execute");

    assert_eq!(
        input.state.world_restore.limited_track_building_amount,
        Some(18)
    );
}

#[test]
fn overlays_real_special_condition_descriptor_into_executable_runtime_record() {
    let base_state = state();
    let save_slice = SmpLoadedSaveSlice {
            file_extension_hint: Some("gms".to_string()),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            trailer_family: None,
            bridge_family: None,
            profile: None,
            candidate_availability_table: None,
            named_locomotive_availability_table: None,
                locomotive_catalog: None,
            cargo_catalog: None,
            world_issue_37_state: None,
            world_economic_tuning_state: None,
            world_finance_neighborhood_state: None,
                world_locomotive_policy_state: None,
                company_roster: None,
                chairman_profile_table: None,
            region_collection: None,
            region_fixed_row_run_summary: None,
            placed_structure_collection: None,
            placed_structure_dynamic_side_buffer_summary: None,
            special_conditions_table: None,
            event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
                source_kind: "packed-event-runtime-collection".to_string(),
                mechanism_family: "classic-save-rehydrate-v1".to_string(),
                mechanism_confidence: "grounded".to_string(),
                container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
                metadata_tag_offset: 0x7100,
                records_tag_offset: 0x7200,
                close_tag_offset: 0x7600,
                packed_state_version: 0x3e9,
                packed_state_version_hex: "0x000003e9".to_string(),
                live_id_bound: 21,
                live_record_count: 1,
                live_entry_ids: vec![21],
                decoded_record_count: 1,
                imported_runtime_record_count: 0,
                records_with_trigger_kind: 0,
                records_missing_trigger_kind: 0,
                nondirect_compact_record_count: 0,
                nondirect_compact_records_missing_trigger_kind: 0,
                trigger_kinds_present: vec![],
                control_lane_notes: vec![],
                add_building_dispatch_strip_record_indexes: vec![],
                add_building_dispatch_strip_descriptor_labels: vec![],
                add_building_dispatch_strip_records_with_trigger_kind: 0,
                add_building_dispatch_strip_records_missing_trigger_kind: 0,
                add_building_dispatch_strip_row_shape_families: vec![],
                add_building_dispatch_strip_signature_families: vec![],
                add_building_dispatch_strip_condition_tuple_families: vec![],
                add_building_dispatch_strip_signature_condition_clusters: vec![],
                records: vec![SmpLoadedPackedEventRecordSummary {
                    record_index: 0,
                    live_entry_id: 21,
                    payload_offset: Some(0x7202),
                    payload_len: Some(120),
                    decode_status: "parity_only".to_string(),
                    payload_family: "real_packed_v1".to_string(),
                    trigger_kind: Some(7),
                    active: None,
                    marks_collection_dirty: None,
                    one_shot: Some(false),
                    compact_control: Some(real_compact_control()),
                    text_bands: packed_text_bands(),
                    standalone_condition_row_count: 0,
                    standalone_condition_rows: vec![],
                    negative_sentinel_scope: None,
                    grouped_effect_row_counts: vec![1, 0, 0, 0],
                    grouped_effect_rows: vec![real_special_condition_row(1)],
                    decoded_conditions: Vec::new(),
                    decoded_actions: vec![RuntimeEffect::SetSpecialCondition {
                        label: "Use Wartime Cargos".to_string(),
                        value: 1,
                    }],
                    executable_import_ready: true,
                    notes: vec![
                        "decoded from grounded real 0x4e9a row framing".to_string(),
                        "whole-game descriptor labels and parameter families come from the checked-in effect table".to_string(),
                    ],
                }],
            }),
            notes: vec![],
        };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "real-special-condition-overlay",
        None,
    )
    .expect("overlay input should project");

    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("real special-condition descriptor should execute");

    assert_eq!(
        input.state.special_conditions.get("Use Wartime Cargos"),
        Some(&1)
    );
}

#[test]
fn overlays_real_candidate_availability_descriptor_into_executable_runtime_record() {
    let base_state = state();
    let save_slice = SmpLoadedSaveSlice {
            file_extension_hint: Some("gms".to_string()),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            trailer_family: None,
            bridge_family: None,
            profile: None,
            candidate_availability_table: None,
            named_locomotive_availability_table: None,
                locomotive_catalog: None,
            cargo_catalog: None,
            world_issue_37_state: None,
            world_economic_tuning_state: None,
            world_finance_neighborhood_state: None,
                world_locomotive_policy_state: None,
                company_roster: None,
                chairman_profile_table: None,
            region_collection: None,
            region_fixed_row_run_summary: None,
            placed_structure_collection: None,
            placed_structure_dynamic_side_buffer_summary: None,
            special_conditions_table: None,
            event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
                source_kind: "packed-event-runtime-collection".to_string(),
                mechanism_family: "classic-save-rehydrate-v1".to_string(),
                mechanism_confidence: "grounded".to_string(),
                container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
                metadata_tag_offset: 0x7100,
                records_tag_offset: 0x7200,
                close_tag_offset: 0x7600,
                packed_state_version: 0x3e9,
                packed_state_version_hex: "0x000003e9".to_string(),
                live_id_bound: 22,
                live_record_count: 1,
                live_entry_ids: vec![22],
                decoded_record_count: 1,
                imported_runtime_record_count: 0,
                records_with_trigger_kind: 0,
                records_missing_trigger_kind: 0,
                nondirect_compact_record_count: 0,
                nondirect_compact_records_missing_trigger_kind: 0,
                trigger_kinds_present: vec![],
                control_lane_notes: vec![],
                add_building_dispatch_strip_record_indexes: vec![],
                add_building_dispatch_strip_descriptor_labels: vec![],
                add_building_dispatch_strip_records_with_trigger_kind: 0,
                add_building_dispatch_strip_records_missing_trigger_kind: 0,
                add_building_dispatch_strip_row_shape_families: vec![],
                add_building_dispatch_strip_signature_families: vec![],
                add_building_dispatch_strip_condition_tuple_families: vec![],
                add_building_dispatch_strip_signature_condition_clusters: vec![],
                records: vec![SmpLoadedPackedEventRecordSummary {
                    record_index: 0,
                    live_entry_id: 22,
                    payload_offset: Some(0x7202),
                    payload_len: Some(120),
                    decode_status: "parity_only".to_string(),
                    payload_family: "real_packed_v1".to_string(),
                    trigger_kind: Some(7),
                    active: None,
                    marks_collection_dirty: None,
                    one_shot: Some(false),
                    compact_control: Some(real_compact_control()),
                    text_bands: packed_text_bands(),
                    standalone_condition_row_count: 0,
                    standalone_condition_rows: vec![],
                    negative_sentinel_scope: None,
                    grouped_effect_row_counts: vec![1, 0, 0, 0],
                    grouped_effect_rows: vec![real_candidate_availability_row(1)],
                    decoded_conditions: Vec::new(),
                    decoded_actions: vec![RuntimeEffect::SetCandidateAvailability {
                        name: "Turbo Diesel".to_string(),
                        value: 1,
                    }],
                    executable_import_ready: true,
                    notes: vec![
                        "decoded from grounded real 0x4e9a row framing".to_string(),
                        "whole-game descriptor labels and parameter families come from the checked-in effect table".to_string(),
                    ],
                }],
            }),
            notes: vec![],
        };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "real-candidate-availability-overlay",
        None,
    )
    .expect("overlay input should project");

    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("real candidate-availability descriptor should execute");

    assert_eq!(
        input.state.candidate_availability.get("Turbo Diesel"),
        Some(&1)
    );
}

#[test]
fn overlays_real_world_flag_descriptor_into_executable_runtime_record() {
    let base_state = state();
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 23,
            live_record_count: 1,
            live_entry_ids: vec![23],
            decoded_record_count: 1,
            imported_runtime_record_count: 1,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 23,
                payload_offset: Some(0x7200),
                payload_len: Some(120),
                decode_status: "executable".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_world_flag_row(
                    110,
                    "Disable Stock Buying and Selling",
                    true,
                )],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::SetWorldFlag {
                    key: "world.disable_stock_buying_and_selling".to_string(),
                    value: true,
                }],
                executable_import_ready: true,
                notes: vec![
                    "decoded from grounded real 0x4e9a row framing".to_string(),
                    "world-flag descriptor identity and keyed runtime mapping are checked in"
                        .to_string(),
                ],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "real-world-flag-overlay",
        None,
    )
    .expect("overlay input should project");

    assert_eq!(input.state.event_runtime_records.len(), 1);
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("imported")
    );
    crate::execute_step_command(
        &mut input.state,
        &crate::StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("trigger service should execute");
    assert_eq!(
        input
            .state
            .world_flags
            .get("world.disable_stock_buying_and_selling"),
        Some(&true)
    );
}

#[test]
fn overlays_real_world_flag_false_variant_into_executable_runtime_record() {
    let base_state = state();
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 24,
            live_record_count: 1,
            live_entry_ids: vec![24],
            decoded_record_count: 1,
            imported_runtime_record_count: 1,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 24,
                payload_offset: Some(0x7200),
                payload_len: Some(120),
                decode_status: "executable".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_world_flag_row(
                    110,
                    "Disable Stock Buying and Selling",
                    false,
                )],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::SetWorldFlag {
                    key: "world.disable_stock_buying_and_selling".to_string(),
                    value: false,
                }],
                executable_import_ready: true,
                notes: vec![
                    "decoded from grounded real 0x4e9a row framing".to_string(),
                    "world-flag descriptor identity and keyed runtime mapping are checked in"
                        .to_string(),
                ],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "real-world-flag-false-overlay",
        None,
    )
    .expect("overlay input should project");

    crate::execute_step_command(
        &mut input.state,
        &crate::StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("trigger service should execute");
    assert_eq!(
        input
            .state
            .world_flags
            .get("world.disable_stock_buying_and_selling"),
        Some(&false)
    );
}

#[test]
fn overlays_recovered_locomotive_policy_descriptors_into_executable_runtime_record() {
    let base_state = state();
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 29,
            live_record_count: 1,
            live_entry_ids: vec![29],
            decoded_record_count: 1,
            imported_runtime_record_count: 1,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 29,
                payload_offset: Some(0x7200),
                payload_len: Some(160),
                decode_status: "executable".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![3, 0, 0, 0],
                grouped_effect_rows: vec![
                    real_world_flag_row(454, "All Steam Locos Avail.", true),
                    real_world_flag_row(455, "All Diesel Locos Avail.", false),
                    real_world_flag_row(456, "All Electric Locos Avail.", true),
                ],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![
                    RuntimeEffect::SetWorldFlag {
                        key: "world.all_steam_locos_available".to_string(),
                        value: true,
                    },
                    RuntimeEffect::SetWorldFlag {
                        key: "world.all_diesel_locos_available".to_string(),
                        value: false,
                    },
                    RuntimeEffect::SetWorldFlag {
                        key: "world.all_electric_locos_available".to_string(),
                        value: true,
                    },
                ],
                executable_import_ready: true,
                notes: vec![
                    "recovered locomotive policy descriptor band now imports as keyed world flags"
                        .to_string(),
                ],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "real-locomotive-policy-overlay",
        None,
    )
    .expect("overlay input should project");

    crate::execute_step_command(
        &mut input.state,
        &crate::StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("trigger service should execute");
    assert_eq!(
        input
            .state
            .world_flags
            .get("world.all_steam_locos_available"),
        Some(&true)
    );
    assert_eq!(
        input
            .state
            .world_flags
            .get("world.all_diesel_locos_available"),
        Some(&false)
    );
    assert_eq!(
        input
            .state
            .world_flags
            .get("world.all_electric_locos_available"),
        Some(&true)
    );
    assert_eq!(
        input
            .state
            .world_restore
            .all_steam_locomotives_available_raw_u8,
        Some(1)
    );
    assert_eq!(
        input
            .state
            .world_restore
            .all_diesel_locomotives_available_raw_u8,
        Some(0)
    );
    assert_eq!(
        input
            .state
            .world_restore
            .all_electric_locomotives_available_raw_u8,
        Some(1)
    );
}

#[test]
fn overlays_real_world_flag_condition_into_executable_runtime_record() {
    let mut base_state = state();
    base_state
        .world_flags
        .insert("world.disable_stock_buying_and_selling".to_string(), true);
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 27,
            live_record_count: 1,
            live_entry_ids: vec![27],
            decoded_record_count: 1,
            imported_runtime_record_count: 1,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 27,
                payload_offset: Some(0x7200),
                payload_len: Some(152),
                decode_status: "executable".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 1,
                standalone_condition_rows: vec![SmpLoadedPackedEventConditionRowSummary {
                    row_index: 0,
                    raw_condition_id: 2535,
                    subtype: 0,
                    flag_bytes: vec![
                        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    ],
                    candidate_name: None,
                    comparator: Some("eq".to_string()),
                    metric: Some("World Flag: Disable Stock Buying and Selling".to_string()),
                    semantic_family: Some("world_flag_equals".to_string()),
                    semantic_preview: Some(
                        "Test Disable Stock Buying and Selling == TRUE".to_string(),
                    ),
                    recovered_cargo_slot: None,
                    recovered_cargo_class: None,
                    requires_candidate_name_binding: false,
                    notes: vec!["checked-in whole-game condition metadata sample".to_string()],
                }],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![SmpLoadedPackedEventGroupedEffectRowSummary {
                    group_index: 0,
                    row_index: 0,
                    descriptor_id: 109,
                    descriptor_label: Some("Turbo Diesel Availability".to_string()),
                    target_mask_bits: Some(0x08),
                    parameter_family: Some("candidate_availability_scalar".to_string()),
                    grouped_target_subject: None,
                    grouped_target_scope: None,
                    opcode: 3,
                    raw_scalar_value: 1,
                    value_byte_0x09: 0,
                    value_dword_0x0d: 0,
                    value_byte_0x11: 0,
                    value_byte_0x12: 0,
                    value_word_0x14: 0,
                    value_word_0x16: 0,
                    row_shape: "scalar_assignment".to_string(),
                    semantic_family: Some("scalar_assignment".to_string()),
                    semantic_preview: Some("Set Turbo Diesel Availability to 1".to_string()),
                    recovered_cargo_slot: None,
                    recovered_cargo_class: None,
                    recovered_cargo_label: None,
                    recovered_locomotive_id: None,
                    locomotive_name: None,
                    notes: vec!["checked-in whole-game grouped-effect sample".to_string()],
                }],
                decoded_conditions: vec![RuntimeCondition::WorldFlagEquals {
                    key: "world.disable_stock_buying_and_selling".to_string(),
                    value: true,
                }],
                decoded_actions: vec![RuntimeEffect::SetCandidateAvailability {
                    name: "Turbo Diesel".to_string(),
                    value: 1,
                }],
                executable_import_ready: true,
                notes: vec!["world-flag condition gates a world-side effect".to_string()],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "real-world-flag-condition-overlay",
        None,
    )
    .expect("overlay input should project");

    crate::execute_step_command(
        &mut input.state,
        &crate::StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("trigger service should execute");
    assert_eq!(
        input.state.candidate_availability.get("Turbo Diesel"),
        Some(&1)
    );
}

#[test]
fn imports_and_executes_world_scalar_conditions_through_runtime_state() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: Some(save_cargo_catalog(&[
            (1, crate::event::targets::RuntimeCargoClass::Factory),
            (5, crate::event::targets::RuntimeCargoClass::FarmMine),
            (9, crate::event::targets::RuntimeCargoClass::Other),
        ])),
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7800,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 45,
            live_record_count: 2,
            live_entry_ids: vec![41, 45],
            decoded_record_count: 2,
            imported_runtime_record_count: 2,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![
                SmpLoadedPackedEventRecordSummary {
                    record_index: 0,
                    live_entry_id: 41,
                    payload_offset: Some(0x7200),
                    payload_len: Some(192),
                    decode_status: "executable".to_string(),
                    payload_family: "real_packed_v1".to_string(),
                    trigger_kind: Some(6),
                    active: None,
                    marks_collection_dirty: None,
                    one_shot: Some(false),
                    compact_control: Some(real_compact_control()),
                    text_bands: packed_text_bands(),
                    standalone_condition_row_count: 0,
                    standalone_condition_rows: vec![],
                    negative_sentinel_scope: None,
                    grouped_effect_row_counts: vec![7, 0, 0, 0],
                    grouped_effect_rows: vec![
                        real_locomotive_availability_row(250, 42),
                        real_locomotive_cost_row(352, 250000),
                        real_cargo_production_row(230, 125),
                        real_cargo_production_row(234, 75),
                        real_cargo_production_row(238, 30),
                        real_limited_track_building_amount_row(18),
                        real_territory_access_cost_row(750000),
                    ],
                    decoded_conditions: vec![],
                    decoded_actions: vec![
                        RuntimeEffect::SetNamedLocomotiveAvailabilityValue {
                            name: "Big Boy".to_string(),
                            value: 42,
                        },
                        RuntimeEffect::SetNamedLocomotiveCost {
                            name: "Locomotive 1".to_string(),
                            value: 250000,
                        },
                        RuntimeEffect::SetCargoProductionSlot {
                            slot: 1,
                            value: 125,
                        },
                        RuntimeEffect::SetCargoProductionSlot { slot: 5, value: 75 },
                        RuntimeEffect::SetCargoProductionSlot { slot: 9, value: 30 },
                        RuntimeEffect::SetLimitedTrackBuildingAmount { value: 18 },
                        RuntimeEffect::SetTerritoryAccessCost { value: 750000 },
                    ],
                    executable_import_ready: true,
                    notes: vec!["world-scalar setup record".to_string()],
                },
                SmpLoadedPackedEventRecordSummary {
                    record_index: 1,
                    live_entry_id: 45,
                    payload_offset: Some(0x7300),
                    payload_len: Some(184),
                    decode_status: "executable".to_string(),
                    payload_family: "real_packed_v1".to_string(),
                    trigger_kind: Some(7),
                    active: None,
                    marks_collection_dirty: None,
                    one_shot: Some(false),
                    compact_control: Some(real_compact_control()),
                    text_bands: packed_text_bands(),
                    standalone_condition_row_count: 9,
                    standalone_condition_rows: vec![
                        SmpLoadedPackedEventConditionRowSummary {
                            row_index: 0,
                            raw_condition_id: 2422,
                            subtype: 4,
                            flag_bytes: {
                                let mut bytes = vec![0; 25];
                                bytes[0..4].copy_from_slice(&42_i32.to_le_bytes());
                                bytes
                            },
                            candidate_name: Some("Big Boy".to_string()),
                            comparator: Some("eq".to_string()),
                            metric: Some("Named Locomotive Availability: Big Boy".to_string()),
                            semantic_family: Some("world_scalar_threshold".to_string()),
                            semantic_preview: Some(
                                "Test Named Locomotive Availability: Big Boy == 42".to_string(),
                            ),
                            recovered_cargo_slot: None,
                            recovered_cargo_class: None,
                            requires_candidate_name_binding: false,
                            notes: vec![],
                        },
                        SmpLoadedPackedEventConditionRowSummary {
                            row_index: 1,
                            raw_condition_id: 2423,
                            subtype: 4,
                            flag_bytes: {
                                let mut bytes = vec![0; 25];
                                bytes[0..4].copy_from_slice(&250000_i32.to_le_bytes());
                                bytes
                            },
                            candidate_name: Some("Locomotive 1".to_string()),
                            comparator: Some("eq".to_string()),
                            metric: Some("Named Locomotive Cost: Locomotive 1".to_string()),
                            semantic_family: Some("world_scalar_threshold".to_string()),
                            semantic_preview: Some(
                                "Test Named Locomotive Cost: Locomotive 1 == 250000".to_string(),
                            ),
                            recovered_cargo_slot: None,
                            recovered_cargo_class: None,
                            requires_candidate_name_binding: false,
                            notes: vec![],
                        },
                        SmpLoadedPackedEventConditionRowSummary {
                            row_index: 2,
                            raw_condition_id: 200,
                            subtype: 4,
                            flag_bytes: {
                                let mut bytes = vec![0; 25];
                                bytes[0..4].copy_from_slice(&125_i32.to_le_bytes());
                                bytes
                            },
                            candidate_name: Some("Cargo Production Slot 1".to_string()),
                            comparator: Some("eq".to_string()),
                            metric: Some("Cargo Production: Cargo Production Slot 1".to_string()),
                            semantic_family: Some("world_scalar_threshold".to_string()),
                            semantic_preview: Some(
                                "Test Cargo Production: Cargo Production Slot 1 == 125".to_string(),
                            ),
                            recovered_cargo_slot: Some(1),
                            recovered_cargo_class: Some("factory".to_string()),
                            requires_candidate_name_binding: false,
                            notes: vec![],
                        },
                        SmpLoadedPackedEventConditionRowSummary {
                            row_index: 3,
                            raw_condition_id: 2418,
                            subtype: 4,
                            flag_bytes: {
                                let mut bytes = vec![0; 25];
                                bytes[0..4].copy_from_slice(&125_i32.to_le_bytes());
                                bytes
                            },
                            candidate_name: None,
                            comparator: Some("eq".to_string()),
                            metric: Some("Cargo Production Total".to_string()),
                            semantic_family: Some("world_scalar_threshold".to_string()),
                            semantic_preview: Some(
                                "Test Cargo Production Total == 230".to_string(),
                            ),
                            recovered_cargo_slot: None,
                            recovered_cargo_class: None,
                            requires_candidate_name_binding: false,
                            notes: vec![],
                        },
                        SmpLoadedPackedEventConditionRowSummary {
                            row_index: 4,
                            raw_condition_id: 2419,
                            subtype: 4,
                            flag_bytes: {
                                let mut bytes = vec![0; 25];
                                bytes[0..4].copy_from_slice(&125_i32.to_le_bytes());
                                bytes
                            },
                            candidate_name: None,
                            comparator: Some("eq".to_string()),
                            metric: Some("Factory Production Total".to_string()),
                            semantic_family: Some("world_scalar_threshold".to_string()),
                            semantic_preview: Some(
                                "Test Factory Production Total == 125".to_string(),
                            ),
                            recovered_cargo_slot: None,
                            recovered_cargo_class: Some("factory".to_string()),
                            requires_candidate_name_binding: false,
                            notes: vec![],
                        },
                        SmpLoadedPackedEventConditionRowSummary {
                            row_index: 5,
                            raw_condition_id: 2420,
                            subtype: 4,
                            flag_bytes: {
                                let mut bytes = vec![0; 25];
                                bytes[0..4].copy_from_slice(&75_i32.to_le_bytes());
                                bytes
                            },
                            candidate_name: None,
                            comparator: Some("eq".to_string()),
                            metric: Some("Farm/Mine Production Total".to_string()),
                            semantic_family: Some("world_scalar_threshold".to_string()),
                            semantic_preview: Some(
                                "Test Farm/Mine Production Total == 75".to_string(),
                            ),
                            recovered_cargo_slot: None,
                            recovered_cargo_class: Some("farm_mine".to_string()),
                            requires_candidate_name_binding: false,
                            notes: vec![],
                        },
                        SmpLoadedPackedEventConditionRowSummary {
                            row_index: 6,
                            raw_condition_id: 2421,
                            subtype: 4,
                            flag_bytes: {
                                let mut bytes = vec![0; 25];
                                bytes[0..4].copy_from_slice(&30_i32.to_le_bytes());
                                bytes
                            },
                            candidate_name: None,
                            comparator: Some("eq".to_string()),
                            metric: Some("Other Cargo Production Total".to_string()),
                            semantic_family: Some("world_scalar_threshold".to_string()),
                            semantic_preview: Some(
                                "Test Other Cargo Production Total == 30".to_string(),
                            ),
                            recovered_cargo_slot: None,
                            recovered_cargo_class: Some("other".to_string()),
                            requires_candidate_name_binding: false,
                            notes: vec![],
                        },
                        SmpLoadedPackedEventConditionRowSummary {
                            row_index: 7,
                            raw_condition_id: 2547,
                            subtype: 4,
                            flag_bytes: {
                                let mut bytes = vec![0; 25];
                                bytes[0..4].copy_from_slice(&18_i32.to_le_bytes());
                                bytes
                            },
                            candidate_name: None,
                            comparator: Some("eq".to_string()),
                            metric: Some("Limited Track Building Amount".to_string()),
                            semantic_family: Some("world_scalar_threshold".to_string()),
                            semantic_preview: Some(
                                "Test Limited Track Building Amount == 18".to_string(),
                            ),
                            recovered_cargo_slot: None,
                            recovered_cargo_class: None,
                            requires_candidate_name_binding: false,
                            notes: vec![],
                        },
                        SmpLoadedPackedEventConditionRowSummary {
                            row_index: 8,
                            raw_condition_id: 1516,
                            subtype: 4,
                            flag_bytes: {
                                let mut bytes = vec![0; 25];
                                bytes[0..4].copy_from_slice(&750000_i32.to_le_bytes());
                                bytes
                            },
                            candidate_name: None,
                            comparator: Some("eq".to_string()),
                            metric: Some("Territory Access Cost".to_string()),
                            semantic_family: Some("world_scalar_threshold".to_string()),
                            semantic_preview: Some(
                                "Test Territory Access Cost == 750000".to_string(),
                            ),
                            recovered_cargo_slot: None,
                            recovered_cargo_class: None,
                            requires_candidate_name_binding: false,
                            notes: vec![],
                        },
                    ],
                    negative_sentinel_scope: None,
                    grouped_effect_row_counts: vec![1, 0, 0, 0],
                    grouped_effect_rows: vec![real_world_flag_row(
                        110,
                        "Disable Stock Buying and Selling",
                        true,
                    )],
                    decoded_conditions: vec![
                        RuntimeCondition::NamedLocomotiveAvailabilityThreshold {
                            name: "Big Boy".to_string(),
                            comparator: RuntimeConditionComparator::Eq,
                            value: 42,
                        },
                        RuntimeCondition::NamedLocomotiveCostThreshold {
                            name: "Locomotive 1".to_string(),
                            comparator: RuntimeConditionComparator::Eq,
                            value: 250000,
                        },
                        RuntimeCondition::CargoProductionSlotThreshold {
                            slot: 1,
                            label: "Cargo Production Slot 1".to_string(),
                            comparator: RuntimeConditionComparator::Eq,
                            value: 125,
                        },
                        RuntimeCondition::CargoProductionTotalThreshold {
                            comparator: RuntimeConditionComparator::Eq,
                            value: 230,
                        },
                        RuntimeCondition::FactoryProductionTotalThreshold {
                            comparator: RuntimeConditionComparator::Eq,
                            value: 125,
                        },
                        RuntimeCondition::FarmMineProductionTotalThreshold {
                            comparator: RuntimeConditionComparator::Eq,
                            value: 75,
                        },
                        RuntimeCondition::OtherCargoProductionTotalThreshold {
                            comparator: RuntimeConditionComparator::Eq,
                            value: 30,
                        },
                        RuntimeCondition::LimitedTrackBuildingAmountThreshold {
                            comparator: RuntimeConditionComparator::Eq,
                            value: 18,
                        },
                        RuntimeCondition::TerritoryAccessCostThreshold {
                            comparator: RuntimeConditionComparator::Eq,
                            value: 750000,
                        },
                    ],
                    decoded_actions: vec![RuntimeEffect::SetWorldFlag {
                        key: "world.world_scalar_conditions_passed".to_string(),
                        value: true,
                    }],
                    executable_import_ready: true,
                    notes: vec!["world-scalar conditions gate a world-side effect".to_string()],
                },
            ],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "world-scalar-condition-save-slice",
        None,
    )
    .expect("save-slice input should project");

    crate::execute_step_command(
        &mut input.state,
        &crate::StepCommand::ServiceTriggerKind { trigger_kind: 6 },
    )
    .expect("setup trigger should execute");
    assert_eq!(
        input.state.named_locomotive_availability.get("Big Boy"),
        Some(&42)
    );
    assert_eq!(
        input.state.named_locomotive_cost.get("Locomotive 1"),
        Some(&250000)
    );
    assert_eq!(input.state.cargo_production_overrides.get(&1), Some(&125));
    assert_eq!(input.state.cargo_production_overrides.get(&5), Some(&75));
    assert_eq!(input.state.cargo_production_overrides.get(&9), Some(&30));
    assert_eq!(input.state.cargo_catalog.len(), 3);
    assert_eq!(
        input.state.cargo_catalog[0].cargo_class,
        crate::event::targets::RuntimeCargoClass::Factory
    );
    assert_eq!(
        input.state.cargo_catalog[1].cargo_class,
        crate::event::targets::RuntimeCargoClass::FarmMine
    );
    assert_eq!(
        input.state.cargo_catalog[2].cargo_class,
        crate::event::targets::RuntimeCargoClass::Other
    );
    assert_eq!(input.state.event_runtime_records.len(), 2);
    assert_eq!(
        input.state.event_runtime_records[1].conditions,
        vec![
            RuntimeCondition::NamedLocomotiveAvailabilityThreshold {
                name: "Big Boy".to_string(),
                comparator: RuntimeConditionComparator::Eq,
                value: 42,
            },
            RuntimeCondition::NamedLocomotiveCostThreshold {
                name: "Locomotive 1".to_string(),
                comparator: RuntimeConditionComparator::Eq,
                value: 250000,
            },
            RuntimeCondition::CargoProductionSlotThreshold {
                slot: 1,
                label: "Cargo Production Slot 1".to_string(),
                comparator: RuntimeConditionComparator::Eq,
                value: 125,
            },
            RuntimeCondition::CargoProductionTotalThreshold {
                comparator: RuntimeConditionComparator::Eq,
                value: 230,
            },
            RuntimeCondition::FactoryProductionTotalThreshold {
                comparator: RuntimeConditionComparator::Eq,
                value: 125,
            },
            RuntimeCondition::FarmMineProductionTotalThreshold {
                comparator: RuntimeConditionComparator::Eq,
                value: 75,
            },
            RuntimeCondition::OtherCargoProductionTotalThreshold {
                comparator: RuntimeConditionComparator::Eq,
                value: 30,
            },
            RuntimeCondition::LimitedTrackBuildingAmountThreshold {
                comparator: RuntimeConditionComparator::Eq,
                value: 18,
            },
            RuntimeCondition::TerritoryAccessCostThreshold {
                comparator: RuntimeConditionComparator::Eq,
                value: 750000,
            },
        ]
    );
    crate::execute_step_command(
        &mut input.state,
        &crate::StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("gated trigger should execute");

    assert_eq!(
        input
            .state
            .world_flags
            .get("world.world_scalar_conditions_passed"),
        Some(&true)
    );
}

#[test]
fn overlays_selected_chairman_conditions_into_imported_runtime_records() {
    let base_state = RuntimeState {
        calendar: CalendarPoint {
            year: 1840,
            month_slot: 1,
            phase_slot: 2,
            tick_slot: 3,
        },
        world_flags: BTreeMap::new(),
        save_profile: RuntimeSaveProfileState::default(),
        world_restore: RuntimeWorldRestoreState::default(),
        metadata: BTreeMap::new(),
        companies: vec![crate::state::RuntimeCompany {
            company_id: 1,
            controller_kind: RuntimeCompanyControllerKind::Human,
            current_cash: 100,
            debt: 0,
            credit_rating_score: None,
            prime_rate: None,
            track_piece_counts: RuntimeTrackPieceCounts::default(),
            active: true,
            available_track_laying_capacity: None,
            linked_chairman_profile_id: Some(1),
            book_value_per_share: 2620,
            investor_confidence: 37,
            management_attitude: 58,
            takeover_cooldown_year: Some(1839),
            merger_cooldown_year: Some(1838),
        }],
        selected_company_id: Some(1),
        players: Vec::new(),
        selected_player_id: None,
        chairman_profiles: vec![
            crate::state::RuntimeChairmanProfile {
                profile_id: 1,
                name: "Chairman One".to_string(),
                active: true,
                current_cash: 500,
                linked_company_id: Some(1),
                company_holdings: BTreeMap::new(),
                holdings_value_total: 700,
                net_worth_total: 1200,
                purchasing_power_total: 1500,
            },
            crate::state::RuntimeChairmanProfile {
                profile_id: 2,
                name: "Chairman Two".to_string(),
                active: true,
                current_cash: 200,
                linked_company_id: None,
                company_holdings: BTreeMap::new(),
                holdings_value_total: 400,
                net_worth_total: 600,
                purchasing_power_total: 800,
            },
        ],
        selected_chairman_profile_id: Some(1),
        trains: Vec::new(),
        locomotive_catalog: Vec::new(),
        cargo_catalog: Vec::new(),
        territories: Vec::new(),
        company_territory_track_piece_counts: Vec::new(),
        company_territory_access: Vec::new(),
        packed_event_collection: None,
        event_runtime_records: Vec::new(),
        candidate_availability: BTreeMap::new(),
        named_locomotive_availability: BTreeMap::new(),
        named_locomotive_cost: BTreeMap::new(),
        all_cargo_price_override: None,
        named_cargo_price_overrides: BTreeMap::new(),
        all_cargo_production_override: None,
        factory_cargo_production_override: None,
        farm_mine_cargo_production_override: None,
        named_cargo_production_overrides: BTreeMap::new(),
        cargo_production_overrides: BTreeMap::new(),
        world_runtime_variables: BTreeMap::new(),
        company_runtime_variables: BTreeMap::new(),
        player_runtime_variables: BTreeMap::new(),
        territory_runtime_variables: BTreeMap::new(),
        world_scalar_overrides: BTreeMap::new(),
        special_conditions: BTreeMap::new(),
        service_state: RuntimeServiceState::default(),
    };
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 71,
            live_record_count: 1,
            live_entry_ids: vec![71],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 71,
                payload_offset: Some(0x7202),
                payload_len: Some(136),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(6),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: vec![],
                standalone_condition_row_count: 1,
                standalone_condition_rows: vec![SmpLoadedPackedEventConditionRowSummary {
                    row_index: 0,
                    raw_condition_id: 2218,
                    subtype: 4,
                    flag_bytes: {
                        let mut bytes = vec![0; 25];
                        bytes[0..4].copy_from_slice(&500_i32.to_le_bytes());
                        bytes
                    },
                    candidate_name: None,
                    comparator: Some("eq".to_string()),
                    metric: Some("Player Cash".to_string()),
                    semantic_family: Some("numeric_threshold".to_string()),
                    semantic_preview: Some("Test Player Cash == 500".to_string()),
                    recovered_cargo_slot: None,
                    recovered_cargo_class: None,
                    requires_candidate_name_binding: false,
                    notes: vec![],
                }],
                negative_sentinel_scope: Some(selected_chairman_negative_sentinel_scope()),
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_world_flag_row(
                    110,
                    "Disable Stock Buying and Selling",
                    true,
                )],
                decoded_conditions: vec![RuntimeCondition::ChairmanNumericThreshold {
                    target: RuntimeChairmanTarget::SelectedChairman,
                    metric: crate::event::metrics::RuntimeChairmanMetric::CurrentCash,
                    comparator: RuntimeConditionComparator::Eq,
                    value: 500,
                }],
                decoded_actions: vec![RuntimeEffect::SetWorldFlag {
                    key: "world.chairman_condition_imported".to_string(),
                    value: true,
                }],
                executable_import_ready: true,
                notes: vec!["chairman metric condition gates a world-side effect".to_string()],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "chairman-condition-overlay",
        None,
    )
    .expect("overlay input should project");

    assert_eq!(input.state.event_runtime_records.len(), 1);
    assert_eq!(
        input.state.event_runtime_records[0].conditions,
        vec![RuntimeCondition::ChairmanNumericThreshold {
            target: RuntimeChairmanTarget::SelectedChairman,
            metric: crate::event::metrics::RuntimeChairmanMetric::CurrentCash,
            comparator: RuntimeConditionComparator::Eq,
            value: 500,
        }]
    );

    crate::execute_step_command(
        &mut input.state,
        &crate::StepCommand::ServiceTriggerKind { trigger_kind: 6 },
    )
    .expect("chairman-gated trigger should execute");

    assert_eq!(
        input
            .state
            .world_flags
            .get("world.chairman_condition_imported"),
        Some(&true)
    );
}

#[test]
fn overlays_book_value_conditions_into_imported_runtime_records() {
    let base_state = RuntimeState {
        calendar: CalendarPoint {
            year: 1840,
            month_slot: 1,
            phase_slot: 2,
            tick_slot: 3,
        },
        world_flags: BTreeMap::new(),
        save_profile: RuntimeSaveProfileState::default(),
        world_restore: RuntimeWorldRestoreState::default(),
        metadata: BTreeMap::new(),
        companies: vec![crate::state::RuntimeCompany {
            company_id: 1,
            controller_kind: RuntimeCompanyControllerKind::Human,
            current_cash: 100,
            debt: 0,
            credit_rating_score: None,
            prime_rate: None,
            track_piece_counts: RuntimeTrackPieceCounts::default(),
            active: true,
            available_track_laying_capacity: None,
            linked_chairman_profile_id: None,
            book_value_per_share: 2620,
            investor_confidence: 37,
            management_attitude: 58,
            takeover_cooldown_year: Some(1839),
            merger_cooldown_year: Some(1838),
        }],
        selected_company_id: Some(1),
        players: Vec::new(),
        selected_player_id: None,
        chairman_profiles: Vec::new(),
        selected_chairman_profile_id: None,
        trains: Vec::new(),
        locomotive_catalog: Vec::new(),
        cargo_catalog: Vec::new(),
        territories: Vec::new(),
        company_territory_track_piece_counts: Vec::new(),
        company_territory_access: Vec::new(),
        packed_event_collection: None,
        event_runtime_records: Vec::new(),
        candidate_availability: BTreeMap::new(),
        named_locomotive_availability: BTreeMap::new(),
        named_locomotive_cost: BTreeMap::new(),
        all_cargo_price_override: None,
        named_cargo_price_overrides: BTreeMap::new(),
        all_cargo_production_override: None,
        factory_cargo_production_override: None,
        farm_mine_cargo_production_override: None,
        named_cargo_production_overrides: BTreeMap::new(),
        cargo_production_overrides: BTreeMap::new(),
        world_runtime_variables: BTreeMap::new(),
        company_runtime_variables: BTreeMap::new(),
        player_runtime_variables: BTreeMap::new(),
        territory_runtime_variables: BTreeMap::new(),
        world_scalar_overrides: BTreeMap::new(),
        special_conditions: BTreeMap::new(),
        service_state: RuntimeServiceState::default(),
    };
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 72,
            live_record_count: 1,
            live_entry_ids: vec![72],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 72,
                payload_offset: Some(0x7202),
                payload_len: Some(136),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: vec![],
                standalone_condition_row_count: 1,
                standalone_condition_rows: vec![SmpLoadedPackedEventConditionRowSummary {
                    row_index: 0,
                    raw_condition_id: 2620,
                    subtype: 4,
                    flag_bytes: {
                        let mut bytes = vec![0; 25];
                        bytes[0..4].copy_from_slice(&2620_i32.to_le_bytes());
                        bytes
                    },
                    candidate_name: None,
                    comparator: Some("eq".to_string()),
                    metric: Some("Book Value Per Share".to_string()),
                    semantic_family: Some("numeric_threshold".to_string()),
                    semantic_preview: Some("Test Book Value Per Share == 2620".to_string()),
                    recovered_cargo_slot: None,
                    recovered_cargo_class: None,
                    requires_candidate_name_binding: false,
                    notes: vec![],
                }],
                negative_sentinel_scope: Some(company_negative_sentinel_scope(
                    RuntimeCompanyConditionTestScope::SelectedCompanyOnly,
                )),
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_world_flag_row(
                    110,
                    "Disable Stock Buying and Selling",
                    true,
                )],
                decoded_conditions: vec![RuntimeCondition::CompanyNumericThreshold {
                    target: RuntimeCompanyTarget::ConditionTrueCompany,
                    metric: crate::event::metrics::RuntimeCompanyMetric::BookValuePerShare,
                    comparator: RuntimeConditionComparator::Eq,
                    value: 2620,
                }],
                decoded_actions: vec![RuntimeEffect::SetWorldFlag {
                    key: "world.book_value_condition_imported".to_string(),
                    value: true,
                }],
                executable_import_ready: true,
                notes: vec!["book value per share condition gates a world-side effect".to_string()],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "company-book-value-condition-overlay",
        None,
    )
    .expect("overlay input should project");

    assert_eq!(input.state.event_runtime_records.len(), 1);
    assert_eq!(
        input.state.event_runtime_records[0].conditions,
        vec![RuntimeCondition::CompanyNumericThreshold {
            target: RuntimeCompanyTarget::SelectedCompany,
            metric: crate::event::metrics::RuntimeCompanyMetric::BookValuePerShare,
            comparator: RuntimeConditionComparator::Eq,
            value: 2620,
        }]
    );

    crate::execute_step_command(
        &mut input.state,
        &crate::StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("company-governance trigger should execute");

    assert_eq!(
        input
            .state
            .world_flags
            .get("world.book_value_condition_imported"),
        Some(&true)
    );
}

#[test]
fn imports_investor_confidence_condition_from_save_slice_company_context() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: Some(save_company_roster()),
        chairman_profile_table: Some(save_chairman_profile_table()),
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 73,
            live_record_count: 1,
            live_entry_ids: vec![73],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 73,
                payload_offset: Some(0x7202),
                payload_len: Some(136),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: vec![],
                standalone_condition_row_count: 1,
                standalone_condition_rows: vec![SmpLoadedPackedEventConditionRowSummary {
                    row_index: 0,
                    raw_condition_id: 2366,
                    subtype: 4,
                    flag_bytes: {
                        let mut bytes = vec![0; 25];
                        bytes[0..4].copy_from_slice(&37_i32.to_le_bytes());
                        bytes
                    },
                    candidate_name: None,
                    comparator: Some("eq".to_string()),
                    metric: Some("Investor Confidence".to_string()),
                    semantic_family: Some("numeric_threshold".to_string()),
                    semantic_preview: Some("Test Investor Confidence == 37".to_string()),
                    recovered_cargo_slot: None,
                    recovered_cargo_class: None,
                    requires_candidate_name_binding: false,
                    notes: vec![],
                }],
                negative_sentinel_scope: Some(company_negative_sentinel_scope(
                    RuntimeCompanyConditionTestScope::SelectedCompanyOnly,
                )),
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_world_flag_row(
                    110,
                    "Disable Stock Buying and Selling",
                    true,
                )],
                decoded_conditions: vec![RuntimeCondition::CompanyNumericThreshold {
                    target: RuntimeCompanyTarget::ConditionTrueCompany,
                    metric: crate::event::metrics::RuntimeCompanyMetric::InvestorConfidence,
                    comparator: RuntimeConditionComparator::Eq,
                    value: 37,
                }],
                decoded_actions: vec![RuntimeEffect::SetWorldFlag {
                    key: "world.investor_confidence_condition_imported".to_string(),
                    value: true,
                }],
                executable_import_ready: true,
                notes: vec!["investor confidence condition gates a world-side effect".to_string()],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "company-investor-confidence-condition",
        None,
    )
    .expect("save-slice input should project");

    assert_eq!(input.state.event_runtime_records.len(), 1);
    assert_eq!(
        input.state.event_runtime_records[0].conditions,
        vec![RuntimeCondition::CompanyNumericThreshold {
            target: RuntimeCompanyTarget::SelectedCompany,
            metric: crate::event::metrics::RuntimeCompanyMetric::InvestorConfidence,
            comparator: RuntimeConditionComparator::Eq,
            value: 37,
        }]
    );

    crate::execute_step_command(
        &mut input.state,
        &crate::StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("investor-confidence trigger should execute");

    assert_eq!(
        input
            .state
            .world_flags
            .get("world.investor_confidence_condition_imported"),
        Some(&true)
    );
}

#[test]
fn imports_management_attitude_condition_from_save_slice_company_context() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: Some(save_company_roster()),
        chairman_profile_table: Some(save_chairman_profile_table()),
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 74,
            live_record_count: 1,
            live_entry_ids: vec![74],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 74,
                payload_offset: Some(0x7202),
                payload_len: Some(136),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: vec![],
                standalone_condition_row_count: 1,
                standalone_condition_rows: vec![SmpLoadedPackedEventConditionRowSummary {
                    row_index: 0,
                    raw_condition_id: 2369,
                    subtype: 4,
                    flag_bytes: {
                        let mut bytes = vec![0; 25];
                        bytes[0..4].copy_from_slice(&58_i32.to_le_bytes());
                        bytes
                    },
                    candidate_name: None,
                    comparator: Some("eq".to_string()),
                    metric: Some("Management Attitude".to_string()),
                    semantic_family: Some("numeric_threshold".to_string()),
                    semantic_preview: Some("Test Management Attitude == 58".to_string()),
                    recovered_cargo_slot: None,
                    recovered_cargo_class: None,
                    requires_candidate_name_binding: false,
                    notes: vec![],
                }],
                negative_sentinel_scope: Some(company_negative_sentinel_scope(
                    RuntimeCompanyConditionTestScope::SelectedCompanyOnly,
                )),
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_world_flag_row(
                    110,
                    "Disable Stock Buying and Selling",
                    true,
                )],
                decoded_conditions: vec![RuntimeCondition::CompanyNumericThreshold {
                    target: RuntimeCompanyTarget::ConditionTrueCompany,
                    metric: crate::event::metrics::RuntimeCompanyMetric::ManagementAttitude,
                    comparator: RuntimeConditionComparator::Eq,
                    value: 58,
                }],
                decoded_actions: vec![RuntimeEffect::SetWorldFlag {
                    key: "world.management_attitude_condition_imported".to_string(),
                    value: true,
                }],
                executable_import_ready: true,
                notes: vec!["management attitude condition gates a world-side effect".to_string()],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "company-management-attitude-condition",
        None,
    )
    .expect("save-slice input should project");

    assert_eq!(input.state.event_runtime_records.len(), 1);
    assert_eq!(
        input.state.event_runtime_records[0].conditions,
        vec![RuntimeCondition::CompanyNumericThreshold {
            target: RuntimeCompanyTarget::SelectedCompany,
            metric: crate::event::metrics::RuntimeCompanyMetric::ManagementAttitude,
            comparator: RuntimeConditionComparator::Eq,
            value: 58,
        }]
    );

    crate::execute_step_command(
        &mut input.state,
        &crate::StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("management-attitude trigger should execute");

    assert_eq!(
        input
            .state
            .world_flags
            .get("world.management_attitude_condition_imported"),
        Some(&true)
    );
}

#[test]
fn overlays_recovered_world_toggle_batch_into_executable_runtime_record() {
    let base_state = state();
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 25,
            live_record_count: 1,
            live_entry_ids: vec![25],
            decoded_record_count: 1,
            imported_runtime_record_count: 1,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 25,
                payload_offset: Some(0x7200),
                payload_len: Some(168),
                decode_status: "executable".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![3, 0, 0, 0],
                grouped_effect_rows: vec![
                    real_world_flag_row(111, "Disable Margin Buying/Short Selling Stock", true),
                    real_world_flag_row(120, "Disable All Track Building", true),
                    real_world_flag_row(131, "Disable Starting Any Companies", false),
                ],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![
                    RuntimeEffect::SetWorldFlag {
                        key: "world.disable_margin_buying_short_selling_stock".to_string(),
                        value: true,
                    },
                    RuntimeEffect::SetWorldFlag {
                        key: "world.disable_all_track_building".to_string(),
                        value: true,
                    },
                    RuntimeEffect::SetWorldFlag {
                        key: "world.disable_starting_any_companies".to_string(),
                        value: false,
                    },
                ],
                executable_import_ready: true,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "real-world-toggle-batch-overlay",
        None,
    )
    .expect("overlay input should project");

    crate::execute_step_command(
        &mut input.state,
        &crate::StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("trigger service should execute");
    assert_eq!(
        input
            .state
            .world_flags
            .get("world.disable_margin_buying_short_selling_stock"),
        Some(&true)
    );
    assert_eq!(
        input
            .state
            .world_flags
            .get("world.disable_all_track_building"),
        Some(&true)
    );
    assert_eq!(
        input
            .state
            .world_flags
            .get("world.disable_starting_any_companies"),
        Some(&false)
    );
}

#[test]
fn overlays_recovered_late_world_toggle_batch_into_executable_runtime_record() {
    let base_state = state();
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 26,
            live_record_count: 1,
            live_entry_ids: vec![26],
            decoded_record_count: 1,
            imported_runtime_record_count: 1,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 26,
                payload_offset: Some(0x7200),
                payload_len: Some(184),
                decode_status: "executable".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![5, 0, 0, 0],
                grouped_effect_rows: vec![
                    real_world_flag_row(139, "Use Bio-Accelerator Cars", true),
                    real_world_flag_row(140, "Disable Cargo Economy", true),
                    real_world_flag_row(142, "Disable Train Crashes", false),
                    real_world_flag_row(143, "Disable Train Crashes AND Breakdowns", true),
                    real_world_flag_row(144, "AI Ignore Territories At Startup", true),
                ],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![
                    RuntimeEffect::SetWorldFlag {
                        key: "world.use_bio_accelerator_cars".to_string(),
                        value: true,
                    },
                    RuntimeEffect::SetWorldFlag {
                        key: "world.disable_cargo_economy".to_string(),
                        value: true,
                    },
                    RuntimeEffect::SetWorldFlag {
                        key: "world.disable_train_crashes".to_string(),
                        value: false,
                    },
                    RuntimeEffect::SetWorldFlag {
                        key: "world.disable_train_crashes_and_breakdowns".to_string(),
                        value: true,
                    },
                    RuntimeEffect::SetWorldFlag {
                        key: "world.ai_ignore_territories_at_startup".to_string(),
                        value: true,
                    },
                ],
                executable_import_ready: true,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "real-late-world-toggle-batch-overlay",
        None,
    )
    .expect("overlay input should project");

    crate::execute_step_command(
        &mut input.state,
        &crate::StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("trigger service should execute");
    assert_eq!(
        input
            .state
            .world_flags
            .get("world.use_bio_accelerator_cars"),
        Some(&true)
    );
    assert_eq!(
        input.state.world_flags.get("world.disable_cargo_economy"),
        Some(&true)
    );
    assert_eq!(
        input.state.world_flags.get("world.disable_train_crashes"),
        Some(&false)
    );
    assert_eq!(
        input
            .state
            .world_flags
            .get("world.disable_train_crashes_and_breakdowns"),
        Some(&true)
    );
    assert_eq!(
        input
            .state
            .world_flags
            .get("world.ai_ignore_territories_at_startup"),
        Some(&true)
    );
}

#[test]
fn overlays_real_confiscate_all_descriptor_into_executable_runtime_record() {
    let base_state = RuntimeState {
        companies: vec![
            crate::state::RuntimeCompany {
                company_id: 42,
                controller_kind: RuntimeCompanyControllerKind::Human,
                current_cash: 500,
                debt: 20,
                credit_rating_score: None,
                prime_rate: None,
                track_piece_counts: RuntimeTrackPieceCounts::default(),
                active: true,
                available_track_laying_capacity: None,
                linked_chairman_profile_id: None,
                book_value_per_share: 0,
                investor_confidence: 0,
                management_attitude: 0,
                takeover_cooldown_year: None,
                merger_cooldown_year: None,
            },
            crate::state::RuntimeCompany {
                company_id: 7,
                controller_kind: RuntimeCompanyControllerKind::Ai,
                current_cash: 90,
                debt: 10,
                credit_rating_score: None,
                prime_rate: None,
                track_piece_counts: RuntimeTrackPieceCounts::default(),
                active: true,
                available_track_laying_capacity: None,
                linked_chairman_profile_id: None,
                book_value_per_share: 0,
                investor_confidence: 0,
                management_attitude: 0,
                takeover_cooldown_year: None,
                merger_cooldown_year: None,
            },
        ],
        selected_company_id: Some(42),
        trains: vec![
            RuntimeTrain {
                train_id: 1,
                owner_company_id: 42,
                territory_id: None,
                locomotive_name: Some("Mikado".to_string()),
                active: true,
                retired: false,
            },
            RuntimeTrain {
                train_id: 2,
                owner_company_id: 7,
                territory_id: None,
                locomotive_name: Some("Orca".to_string()),
                active: true,
                retired: false,
            },
        ],
        ..state()
    };
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 19,
            live_record_count: 1,
            live_entry_ids: vec![19],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 19,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(SmpLoadedPackedEventCompactControlSummary {
                    mode_byte_0x7ef: 7,
                    primary_selector_0x7f0: 0x63,
                    grouped_mode_0x7f4: 2,
                    one_shot_header_0x7f5: 0,
                    modifier_flag_0x7f9: 1,
                    modifier_flag_0x7fa: 0,
                    grouped_target_scope_ordinals_0x7fb: vec![1, 1, 1, 1],
                    grouped_scope_checkboxes_0x7ff: vec![1, 0, 0, 0],
                    summary_toggle_0x800: 1,
                    grouped_territory_selectors_0x80f: vec![-1, -1, -1, -1],
                }),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_confiscate_all_row(true)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::ConfiscateCompanyAssets {
                    target: RuntimeCompanyTarget::SelectedCompany,
                }],
                executable_import_ready: true,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "real-confiscate-all-overlay",
        None,
    )
    .expect("overlay input should project");

    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("real confiscate-all descriptor should execute");

    assert_eq!(input.state.companies[0].current_cash, 0);
    assert_eq!(input.state.companies[0].debt, 0);
    assert!(!input.state.companies[0].active);
    assert_eq!(input.state.selected_company_id, None);
    assert!(!input.state.trains[0].active);
    assert!(input.state.trains[0].retired);
    assert!(input.state.trains[1].active);
    assert!(!input.state.trains[1].retired);
}

#[test]
fn keeps_real_confiscate_all_false_row_parity_only() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 20,
            live_record_count: 1,
            live_entry_ids: vec![20],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 20,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(real_compact_control()),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_confiscate_all_row(false)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![],
                executable_import_ready: false,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let input =
        build_runtime_state_input_from_save_slice(&save_slice, "real-confiscate-all-false", None)
            .expect("save slice should project");

    assert!(input.state.event_runtime_records.is_empty());
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_confiscation_variant")
    );
}

#[test]
fn blocks_confiscate_all_without_train_context() {
    let base_state = RuntimeState {
        companies: vec![crate::state::RuntimeCompany {
            company_id: 42,
            controller_kind: RuntimeCompanyControllerKind::Human,
            current_cash: 500,
            debt: 20,
            credit_rating_score: None,
            prime_rate: None,
            track_piece_counts: RuntimeTrackPieceCounts::default(),
            active: true,
            available_track_laying_capacity: None,
            linked_chairman_profile_id: None,
            book_value_per_share: 0,
            investor_confidence: 0,
            management_attitude: 0,
            takeover_cooldown_year: None,
            merger_cooldown_year: None,
        }],
        selected_company_id: Some(42),
        ..state()
    };
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 24,
            live_record_count: 1,
            live_entry_ids: vec![24],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 24,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(SmpLoadedPackedEventCompactControlSummary {
                    mode_byte_0x7ef: 7,
                    primary_selector_0x7f0: 0x63,
                    grouped_mode_0x7f4: 2,
                    one_shot_header_0x7f5: 0,
                    modifier_flag_0x7f9: 1,
                    modifier_flag_0x7fa: 0,
                    grouped_target_scope_ordinals_0x7fb: vec![1, 1, 1, 1],
                    grouped_scope_checkboxes_0x7ff: vec![1, 0, 0, 0],
                    summary_toggle_0x800: 1,
                    grouped_territory_selectors_0x80f: vec![-1, -1, -1, -1],
                }),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_confiscate_all_row(true)],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::ConfiscateCompanyAssets {
                    target: RuntimeCompanyTarget::SelectedCompany,
                }],
                executable_import_ready: true,
                notes: vec![],
            }],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "real-confiscate-all-missing-trains",
        None,
    )
    .expect("overlay input should project");

    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_missing_train_context")
    );
    assert!(input.state.event_runtime_records.is_empty());
}

#[test]
fn overlays_real_retire_train_descriptor_by_company_scope() {
    let base_state = RuntimeState {
        companies: vec![
            crate::state::RuntimeCompany {
                company_id: 42,
                controller_kind: RuntimeCompanyControllerKind::Human,
                current_cash: 500,
                debt: 20,
                credit_rating_score: None,
                prime_rate: None,
                track_piece_counts: RuntimeTrackPieceCounts::default(),
                active: true,
                available_track_laying_capacity: None,
                linked_chairman_profile_id: None,
                book_value_per_share: 0,
                investor_confidence: 0,
                management_attitude: 0,
                takeover_cooldown_year: None,
                merger_cooldown_year: None,
            },
            crate::state::RuntimeCompany {
                company_id: 7,
                controller_kind: RuntimeCompanyControllerKind::Ai,
                current_cash: 90,
                debt: 10,
                credit_rating_score: None,
                prime_rate: None,
                track_piece_counts: RuntimeTrackPieceCounts::default(),
                active: true,
                available_track_laying_capacity: None,
                linked_chairman_profile_id: None,
                book_value_per_share: 0,
                investor_confidence: 0,
                management_attitude: 0,
                takeover_cooldown_year: None,
                merger_cooldown_year: None,
            },
        ],
        selected_company_id: Some(42),
        trains: vec![
            RuntimeTrain {
                train_id: 1,
                owner_company_id: 42,
                territory_id: Some(7),
                locomotive_name: Some("Mikado".to_string()),
                active: true,
                retired: false,
            },
            RuntimeTrain {
                train_id: 2,
                owner_company_id: 42,
                territory_id: Some(8),
                locomotive_name: Some("Orca".to_string()),
                active: true,
                retired: false,
            },
            RuntimeTrain {
                train_id: 3,
                owner_company_id: 7,
                territory_id: Some(7),
                locomotive_name: Some("Mikado".to_string()),
                active: true,
                retired: false,
            },
        ],
        territories: vec![
            crate::state::RuntimeTerritory {
                territory_id: 7,
                name: Some("Appalachia".to_string()),
                track_piece_counts: RuntimeTrackPieceCounts::default(),
            },
            crate::state::RuntimeTerritory {
                territory_id: 8,
                name: Some("Great Plains".to_string()),
                track_piece_counts: RuntimeTrackPieceCounts::default(),
            },
        ],
        ..state()
    };
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 21,
            live_record_count: 1,
            live_entry_ids: vec![21],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 21,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(SmpLoadedPackedEventCompactControlSummary {
                    mode_byte_0x7ef: 7,
                    primary_selector_0x7f0: 0x63,
                    grouped_mode_0x7f4: 2,
                    one_shot_header_0x7f5: 0,
                    modifier_flag_0x7f9: 1,
                    modifier_flag_0x7fa: 0,
                    grouped_target_scope_ordinals_0x7fb: vec![1, 1, 1, 1],
                    grouped_scope_checkboxes_0x7ff: vec![1, 0, 0, 0],
                    summary_toggle_0x800: 1,
                    grouped_territory_selectors_0x80f: vec![-1, -1, -1, -1],
                }),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_retire_train_row(true, None, vec![])],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::RetireTrains {
                    company_target: Some(RuntimeCompanyTarget::SelectedCompany),
                    territory_target: None,
                    locomotive_name: None,
                }],
                executable_import_ready: true,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "real-retire-train-company-overlay",
        None,
    )
    .expect("overlay input should project");

    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("real retire-train descriptor should execute");

    assert!(input.state.trains[0].retired);
    assert!(input.state.trains[1].retired);
    assert!(!input.state.trains[2].retired);
}

#[test]
fn overlays_real_retire_train_descriptor_by_territory_and_locomotive_scope() {
    let base_state = RuntimeState {
        companies: vec![crate::state::RuntimeCompany {
            company_id: 42,
            controller_kind: RuntimeCompanyControllerKind::Human,
            current_cash: 500,
            debt: 20,
            credit_rating_score: None,
            prime_rate: None,
            track_piece_counts: RuntimeTrackPieceCounts::default(),
            active: true,
            available_track_laying_capacity: None,
            linked_chairman_profile_id: None,
            book_value_per_share: 0,
            investor_confidence: 0,
            management_attitude: 0,
            takeover_cooldown_year: None,
            merger_cooldown_year: None,
        }],
        selected_company_id: Some(42),
        trains: vec![
            RuntimeTrain {
                train_id: 1,
                owner_company_id: 42,
                territory_id: Some(7),
                locomotive_name: Some("Mikado".to_string()),
                active: true,
                retired: false,
            },
            RuntimeTrain {
                train_id: 2,
                owner_company_id: 42,
                territory_id: Some(7),
                locomotive_name: Some("Orca".to_string()),
                active: true,
                retired: false,
            },
            RuntimeTrain {
                train_id: 3,
                owner_company_id: 42,
                territory_id: Some(8),
                locomotive_name: Some("Mikado".to_string()),
                active: true,
                retired: false,
            },
        ],
        territories: vec![
            crate::state::RuntimeTerritory {
                territory_id: 7,
                name: Some("Appalachia".to_string()),
                track_piece_counts: RuntimeTrackPieceCounts::default(),
            },
            crate::state::RuntimeTerritory {
                territory_id: 8,
                name: Some("Great Plains".to_string()),
                track_piece_counts: RuntimeTrackPieceCounts::default(),
            },
        ],
        ..state()
    };
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 22,
            live_record_count: 1,
            live_entry_ids: vec![22],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 22,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(SmpLoadedPackedEventCompactControlSummary {
                    mode_byte_0x7ef: 7,
                    primary_selector_0x7f0: 0x63,
                    grouped_mode_0x7f4: 2,
                    one_shot_header_0x7f5: 0,
                    modifier_flag_0x7f9: 1,
                    modifier_flag_0x7fa: 0,
                    grouped_target_scope_ordinals_0x7fb: vec![8, 1, 1, 1],
                    grouped_scope_checkboxes_0x7ff: vec![1, 0, 0, 0],
                    summary_toggle_0x800: 1,
                    grouped_territory_selectors_0x80f: vec![7, -1, -1, -1],
                }),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_retire_train_row(true, Some("Mikado"), vec![])],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::RetireTrains {
                    company_target: None,
                    territory_target: Some(RuntimeTerritoryTarget::Ids { ids: vec![7] }),
                    locomotive_name: Some("Mikado".to_string()),
                }],
                executable_import_ready: true,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let mut input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "real-retire-train-territory-overlay",
        None,
    )
    .expect("overlay input should project");

    execute_step_command(
        &mut input.state,
        &StepCommand::ServiceTriggerKind { trigger_kind: 7 },
    )
    .expect("territory-scoped retire-train descriptor should execute");

    assert!(input.state.trains[0].retired);
    assert!(!input.state.trains[1].retired);
    assert!(!input.state.trains[2].retired);
}

#[test]
fn keeps_real_retire_train_missing_scope_parity_only() {
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 23,
            live_record_count: 1,
            live_entry_ids: vec![23],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 23,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(SmpLoadedPackedEventCompactControlSummary {
                    mode_byte_0x7ef: 7,
                    primary_selector_0x7f0: 0x63,
                    grouped_mode_0x7f4: 2,
                    one_shot_header_0x7f5: 0,
                    modifier_flag_0x7f9: 1,
                    modifier_flag_0x7fa: 0,
                    grouped_target_scope_ordinals_0x7fb: vec![8, 1, 1, 1],
                    grouped_scope_checkboxes_0x7ff: vec![1, 0, 0, 0],
                    summary_toggle_0x800: 1,
                    grouped_territory_selectors_0x80f: vec![-1, -1, -1, -1],
                }),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_retire_train_row(
                    true,
                    Some("Mikado"),
                    vec!["retire train row is missing company and territory scope".to_string()],
                )],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![],
                executable_import_ready: false,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_save_slice(
        &save_slice,
        "real-retire-train-missing-scope",
        None,
    )
    .expect("save slice should project");

    assert!(input.state.event_runtime_records.is_empty());
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_retire_train_scope")
    );
}

#[test]
fn blocks_retire_train_without_train_territory_context() {
    let base_state = RuntimeState {
        companies: vec![crate::state::RuntimeCompany {
            company_id: 42,
            controller_kind: RuntimeCompanyControllerKind::Human,
            current_cash: 500,
            debt: 20,
            credit_rating_score: None,
            prime_rate: None,
            track_piece_counts: RuntimeTrackPieceCounts::default(),
            active: true,
            available_track_laying_capacity: None,
            linked_chairman_profile_id: None,
            book_value_per_share: 0,
            investor_confidence: 0,
            management_attitude: 0,
            takeover_cooldown_year: None,
            merger_cooldown_year: None,
        }],
        selected_company_id: Some(42),
        trains: vec![RuntimeTrain {
            train_id: 1,
            owner_company_id: 42,
            territory_id: None,
            locomotive_name: Some("Mikado".to_string()),
            active: true,
            retired: false,
        }],
        territories: vec![crate::state::RuntimeTerritory {
            territory_id: 7,
            name: Some("Appalachia".to_string()),
            track_piece_counts: RuntimeTrackPieceCounts::default(),
        }],
        ..state()
    };
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 25,
            live_record_count: 1,
            live_entry_ids: vec![25],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 25,
                payload_offset: Some(0x7202),
                payload_len: Some(120),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(SmpLoadedPackedEventCompactControlSummary {
                    mode_byte_0x7ef: 7,
                    primary_selector_0x7f0: 0x63,
                    grouped_mode_0x7f4: 2,
                    one_shot_header_0x7f5: 0,
                    modifier_flag_0x7f9: 1,
                    modifier_flag_0x7fa: 0,
                    grouped_target_scope_ordinals_0x7fb: vec![8, 1, 1, 1],
                    grouped_scope_checkboxes_0x7ff: vec![1, 0, 0, 0],
                    summary_toggle_0x800: 1,
                    grouped_territory_selectors_0x80f: vec![7, -1, -1, -1],
                }),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 0, 0, 0],
                grouped_effect_rows: vec![real_retire_train_row(true, Some("Mikado"), vec![])],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::RetireTrains {
                    company_target: None,
                    territory_target: Some(RuntimeTerritoryTarget::Ids { ids: vec![7] }),
                    locomotive_name: Some("Mikado".to_string()),
                }],
                executable_import_ready: true,
                notes: vec![],
            }],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "real-retire-train-missing-train-territory",
        None,
    )
    .expect("overlay input should project");

    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_missing_train_territory_context")
    );
    assert!(input.state.event_runtime_records.is_empty());
}

#[test]
fn keeps_mixed_real_records_out_of_event_runtime_records() {
    let base_state = RuntimeState {
        companies: vec![crate::state::RuntimeCompany {
            company_id: 42,
            controller_kind: RuntimeCompanyControllerKind::Human,
            current_cash: 500,
            debt: 20,
            credit_rating_score: None,
            prime_rate: None,
            track_piece_counts: RuntimeTrackPieceCounts::default(),
            active: true,
            available_track_laying_capacity: None,
            linked_chairman_profile_id: None,
            book_value_per_share: 0,
            investor_confidence: 0,
            management_attitude: 0,
            takeover_cooldown_year: None,
            merger_cooldown_year: None,
        }],
        selected_company_id: Some(42),
        ..state()
    };
    let save_slice = SmpLoadedSaveSlice {
        file_extension_hint: Some("gms".to_string()),
        container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
        mechanism_family: "classic-save-rehydrate-v1".to_string(),
        mechanism_confidence: "grounded".to_string(),
        trailer_family: None,
        bridge_family: None,
        profile: None,
        candidate_availability_table: None,
        named_locomotive_availability_table: None,
        locomotive_catalog: None,
        cargo_catalog: None,
        world_issue_37_state: None,
        world_economic_tuning_state: None,
        world_finance_neighborhood_state: None,
        world_locomotive_policy_state: None,
        company_roster: None,
        chairman_profile_table: None,
        region_collection: None,
        region_fixed_row_run_summary: None,
        placed_structure_collection: None,
        placed_structure_dynamic_side_buffer_summary: None,
        special_conditions_table: None,
        event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
            source_kind: "packed-event-runtime-collection".to_string(),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            metadata_tag_offset: 0x7100,
            records_tag_offset: 0x7200,
            close_tag_offset: 0x7600,
            packed_state_version: 0x3e9,
            packed_state_version_hex: "0x000003e9".to_string(),
            live_id_bound: 17,
            live_record_count: 1,
            live_entry_ids: vec![17],
            decoded_record_count: 1,
            imported_runtime_record_count: 0,
            records_with_trigger_kind: 0,
            records_missing_trigger_kind: 0,
            nondirect_compact_record_count: 0,
            nondirect_compact_records_missing_trigger_kind: 0,
            trigger_kinds_present: vec![],
            control_lane_notes: vec![],
            add_building_dispatch_strip_record_indexes: vec![],
            add_building_dispatch_strip_descriptor_labels: vec![],
            add_building_dispatch_strip_records_with_trigger_kind: 0,
            add_building_dispatch_strip_records_missing_trigger_kind: 0,
            add_building_dispatch_strip_row_shape_families: vec![],
            add_building_dispatch_strip_signature_families: vec![],
            add_building_dispatch_strip_condition_tuple_families: vec![],
            add_building_dispatch_strip_signature_condition_clusters: vec![],
            records: vec![SmpLoadedPackedEventRecordSummary {
                record_index: 0,
                live_entry_id: 17,
                payload_offset: Some(0x7202),
                payload_len: Some(160),
                decode_status: "parity_only".to_string(),
                payload_family: "real_packed_v1".to_string(),
                trigger_kind: Some(7),
                active: None,
                marks_collection_dirty: None,
                one_shot: Some(false),
                compact_control: Some(SmpLoadedPackedEventCompactControlSummary {
                    mode_byte_0x7ef: 7,
                    primary_selector_0x7f0: 0x63,
                    grouped_mode_0x7f4: 2,
                    one_shot_header_0x7f5: 0,
                    modifier_flag_0x7f9: 1,
                    modifier_flag_0x7fa: 0,
                    grouped_target_scope_ordinals_0x7fb: vec![1, 1, 1, 1],
                    grouped_scope_checkboxes_0x7ff: vec![1, 1, 0, 0],
                    summary_toggle_0x800: 1,
                    grouped_territory_selectors_0x80f: vec![-1, -1, -1, -1],
                }),
                text_bands: packed_text_bands(),
                standalone_condition_row_count: 0,
                standalone_condition_rows: vec![],
                negative_sentinel_scope: None,
                grouped_effect_row_counts: vec![1, 1, 0, 0],
                grouped_effect_rows: vec![
                    real_track_capacity_row(18),
                    unsupported_real_grouped_row(),
                ],
                decoded_conditions: Vec::new(),
                decoded_actions: vec![RuntimeEffect::SetCompanyTrackLayingCapacity {
                    target: RuntimeCompanyTarget::SelectedCompany,
                    value: Some(18),
                }],
                executable_import_ready: false,
                notes: vec!["decoded from grounded real 0x4e9a row framing".to_string()],
            }],
        }),
        notes: vec![],
    };

    let input = build_runtime_state_input_from_overlay(
        &base_state,
        &save_slice,
        "mixed-real-record-overlay",
        None,
    )
    .expect("overlay input should project");

    assert!(input.state.event_runtime_records.is_empty());
    assert_eq!(
        input
            .state
            .packed_event_collection
            .as_ref()
            .and_then(|summary| summary.records[0].import_outcome.as_deref()),
        Some("blocked_confiscation_variant")
    );
}
