src/lightspeed@ops@protocol_contract_harness.erl

-module(lightspeed@ops@protocol_contract_harness).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/lightspeed/ops/protocol_contract_harness.gleam").
-export([run_scenario/1, run_matrix/0, scenario_label/1, pass_fail_label/1, signature/1, scenario/1, deterministic/1, outcomes/1, failed_scenarios/1, nondeterministic_failures/1, report_signature/1, snapshot_signature/0, snapshot_report_markdown/0]).
-export_type([scenario/0, scenario_outcome/0, report/0, envelope_track/0, corpus_case/0]).

-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.

?MODULEDOC(" Deterministic protocol contract verification and fuzz harness for M43.\n").

-type scenario() :: protocol_conformance_matrix_expansion |
    envelope_fuzz_corpus_expansion |
    fuzz_regression_replay_certification |
    unified_protocol_evidence_surface.

-type scenario_outcome() :: {scenario_outcome,
        scenario(),
        boolean(),
        boolean(),
        binary()}.

-type report() :: {report, list(scenario_outcome()), integer(), integer()}.

-type envelope_track() :: transport_envelope |
    event_envelope |
    diff_envelope |
    pipeline_envelope.

-type corpus_case() :: {corpus_case,
        binary(),
        envelope_track(),
        binary(),
        binary()}.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 910).
-spec count_nondeterministic(list(scenario_outcome())) -> integer().
count_nondeterministic(Outcomes) ->
    case Outcomes of
        [] ->
            0;

        [Outcome | Rest] ->
            case erlang:element(4, Outcome) of
                true ->
                    count_nondeterministic(Rest);

                false ->
                    1 + count_nondeterministic(Rest)
            end
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 899).
-spec count_failed(list(scenario_outcome())) -> integer().
count_failed(Outcomes) ->
    case Outcomes of
        [] ->
            0;

        [Outcome | Rest] ->
            case erlang:element(3, Outcome) of
                true ->
                    count_failed(Rest);

                false ->
                    1 + count_failed(Rest)
            end
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 921).
-spec join_with(binary(), list(binary())) -> binary().
join_with(Separator, Values) ->
    case Values of
        [] ->
            <<""/utf8>>;

        [Value] ->
            Value;

        [Value@1 | Rest] ->
            <<<<Value@1/binary, Separator/binary>>/binary,
                (join_with(Separator, Rest))/binary>>
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 929).
-spec bool_label(boolean()) -> binary().
bool_label(Value) ->
    case Value of
        true ->
            <<"true"/utf8>>;

        false ->
            <<"false"/utf8>>
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 366).
-spec expanded_corpus() -> list(corpus_case()).
expanded_corpus() ->
    [{corpus_case,
            <<"transport_hello_rejected"/utf8>>,
            transport_envelope,
            lightspeed@protocol:encode(lightspeed@protocol:hello()),
            <<"error:unsupported_client_frame:hello"/utf8>>},
        {corpus_case,
            <<"transport_diff_rejected"/utf8>>,
            transport_envelope,
            lightspeed@protocol:encode(
                {diff, <<"d-1"/utf8>>, <<"<p>x</p>"/utf8>>}
            ),
            <<"error:unsupported_client_frame:diff"/utf8>>},
        {corpus_case,
            <<"transport_decode_error"/utf8>>,
            transport_envelope,
            <<"event|e-1|increment|bad\\"/utf8>>,
            <<"error:protocol_decode_failed:invalid_escape_sequence"/utf8>>},
        {corpus_case,
            <<"transport_payload_too_large"/utf8>>,
            transport_envelope,
            lightspeed@protocol:encode(
                {event,
                    <<"e-oversize"/utf8>>,
                    <<"increment"/utf8>>,
                    <<"{\"blob\":\"1234567890123456789012345678901234567890\"}"/utf8>>}
            ),
            <<"error:unsupported_client_frame:payload_too_large"/utf8>>},
        {corpus_case,
            <<"transport_unknown_event"/utf8>>,
            transport_envelope,
            lightspeed@protocol:encode(
                {event, <<"e-unknown"/utf8>>, <<"unknown"/utf8>>, <<"{}"/utf8>>}
            ),
            <<"error:unsupported_client_event:unknown"/utf8>>},
        {corpus_case,
            <<"event_increment_ok"/utf8>>,
            event_envelope,
            lightspeed@protocol:encode(
                {event, <<"evt-1"/utf8>>, <<"increment"/utf8>>, <<"{}"/utf8>>}
            ),
            <<"ok:event:increment"/utf8>>},
        {corpus_case,
            <<"event_decrement_ok"/utf8>>,
            event_envelope,
            lightspeed@protocol:encode(
                {event, <<"evt-2"/utf8>>, <<"decrement"/utf8>>, <<"{}"/utf8>>}
            ),
            <<"ok:event:decrement"/utf8>>},
        {corpus_case,
            <<"event_unknown_name"/utf8>>,
            event_envelope,
            lightspeed@protocol:encode(
                {event, <<"evt-3"/utf8>>, <<"unknown"/utf8>>, <<"{}"/utf8>>}
            ),
            <<"error:unsupported_event:unknown"/utf8>>},
        {corpus_case,
            <<"event_bad_payload_shape"/utf8>>,
            event_envelope,
            lightspeed@protocol:encode(
                {event,
                    <<"evt-4"/utf8>>,
                    <<"increment"/utf8>>,
                    <<"not-json"/utf8>>}
            ),
            <<"error:malformed_event_payload"/utf8>>},
        {corpus_case,
            <<"event_missing_ref"/utf8>>,
            event_envelope,
            lightspeed@protocol:encode(
                {event, <<""/utf8>>, <<"increment"/utf8>>, <<"{}"/utf8>>}
            ),
            <<"error:missing_event_ref"/utf8>>},
        {corpus_case,
            <<"event_wrong_frame_kind"/utf8>>,
            event_envelope,
            lightspeed@protocol:encode({ack, <<"ack-1"/utf8>>}),
            <<"error:unsupported_event_envelope:ack"/utf8>>},
        {corpus_case,
            <<"event_decode_error"/utf8>>,
            event_envelope,
            <<"event|evt-5|increment|bad\\"/utf8>>,
            <<"error:protocol_decode_failed:invalid_escape_sequence"/utf8>>},
        {corpus_case,
            <<"diff_replace_ok"/utf8>>,
            diff_envelope,
            lightspeed@diff:encode_stream(
                [{replace, <<"#app"/utf8>>, <<"<div>ok</div>"/utf8>>}]
            ),
            <<"ok_ops:1:replace"/utf8>>},
        {corpus_case,
            <<"diff_reorder_ok"/utf8>>,
            diff_envelope,
            lightspeed@diff:encode_stream(
                [{reorder_keyed,
                        <<"#items"/utf8>>,
                        [<<"k1"/utf8>>, <<"k2"/utf8>>]}]
            ),
            <<"ok_ops:1:reorder_keyed"/utf8>>},
        {corpus_case,
            <<"diff_unsupported_version"/utf8>>,
            diff_envelope,
            <<"ps|2|0|0"/utf8>>,
            <<"error:unsupported_version:2"/utf8>>},
        {corpus_case,
            <<"diff_missing_dictionary_entry"/utf8>>,
            diff_envelope,
            <<"ps|1|0|1|r,0,1"/utf8>>,
            <<"error:missing_dictionary_entry:0"/utf8>>},
        {corpus_case,
            <<"diff_malformed_operation"/utf8>>,
            diff_envelope,
            <<"ps|1|1|#app|1|z,0"/utf8>>,
            <<"error:malformed_operation:z,0"/utf8>>},
        {corpus_case,
            <<"diff_bad_dynamic_slots"/utf8>>,
            diff_envelope,
            <<"ps|1|3|#app|fp|slot|1|u,0,1,1,2"/utf8>>,
            <<"error:bad_field_count:dynamic_slots:2:1"/utf8>>},
        {corpus_case,
            <<"pipeline_checkpoint_ok"/utf8>>,
            pipeline_envelope,
            <<"checkpoint|run-1|extract_orders|1|10|100|source-a|101"/utf8>>,
            <<"ok:run=run-1|stage=extract_orders|sequence=1"/utf8>>},
        {corpus_case,
            <<"pipeline_bad_field_count"/utf8>>,
            pipeline_envelope,
            <<"checkpoint|run-1|extract_orders|1|10|100|source-a"/utf8>>,
            <<"error:bad_field_count:pipeline_checkpoint:8:7"/utf8>>},
        {corpus_case,
            <<"pipeline_invalid_integer"/utf8>>,
            pipeline_envelope,
            <<"checkpoint|run-1|extract_orders|a|10|100|source-a|101"/utf8>>,
            <<"error:invalid_integer:sequence:a"/utf8>>},
        {corpus_case,
            <<"pipeline_invalid_checkpoint"/utf8>>,
            pipeline_envelope,
            <<"checkpoint|run-1|extract_orders|1|-1|100|source-a|101"/utf8>>,
            <<"error:invalid_checkpoint"/utf8>>},
        {corpus_case,
            <<"pipeline_empty_stage"/utf8>>,
            pipeline_envelope,
            <<"checkpoint|run-1||1|10|100|source-a|101"/utf8>>,
            <<"error:invalid_checkpoint"/utf8>>}].

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 843).
-spec error_cases(list(corpus_case()), list(corpus_case())) -> list(corpus_case()).
error_cases(Cases, Acc_rev) ->
    case Cases of
        [] ->
            lists:reverse(Acc_rev);

        [Entry | Rest] ->
            case gleam_stdlib:string_starts_with(
                erlang:element(5, Entry),
                <<"error:"/utf8>>
            ) of
                true ->
                    error_cases(Rest, [Entry | Acc_rev]);

                false ->
                    error_cases(Rest, Acc_rev)
            end
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 888).
-spec contains(list(binary()), binary()) -> boolean().
contains(Values, Target) ->
    case Values of
        [] ->
            false;

        [Value | Rest] ->
            case Value =:= Target of
                true ->
                    true;

                false ->
                    contains(Rest, Target)
            end
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 874).
-spec drift_class(binary()) -> binary().
drift_class(Expected) ->
    case gleam@string:split(Expected, <<":"/utf8>>) of
        [<<"error"/utf8>>, Class | _] ->
            Class;

        _ ->
            <<"unknown"/utf8>>
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 857).
-spec drift_classes_from_cases(list(corpus_case()), list(binary())) -> list(binary()).
drift_classes_from_cases(Cases, Classes_rev) ->
    case Cases of
        [] ->
            lists:reverse(Classes_rev);

        [Entry | Rest] ->
            Next = drift_class(erlang:element(5, Entry)),
            Next_classes = case contains(Classes_rev, Next) of
                true ->
                    Classes_rev;

                false ->
                    [Next | Classes_rev]
            end,
            drift_classes_from_cases(Rest, Next_classes)
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 747).
-spec parse_int_field(binary(), binary()) -> {ok, integer()} | {error, binary()}.
parse_int_field(Field, Value) ->
    case gleam_stdlib:parse_int(Value) of
        {ok, Parsed} ->
            {ok, Parsed};

        {error, _} ->
            {error,
                <<<<<<"error:invalid_integer:"/utf8, Field/binary>>/binary,
                        ":"/utf8>>/binary,
                    Value/binary>>}
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 693).
-spec pipeline_envelope_case_label(binary()) -> binary().
pipeline_envelope_case_label(Payload) ->
    case gleam@string:split(Payload, <<"|"/utf8>>) of
        [<<"checkpoint"/utf8>>,
            Run_id,
            Stage,
            Sequence_text,
            Offset_text,
            Event_time_text,
            Idempotency_key,
            At_ms_text] ->
            case parse_int_field(<<"sequence"/utf8>>, Sequence_text) of
                {error, Reason} ->
                    Reason;

                {ok, Sequence} ->
                    case parse_int_field(<<"offset"/utf8>>, Offset_text) of
                        {error, Reason@1} ->
                            Reason@1;

                        {ok, Offset} ->
                            case parse_int_field(
                                <<"event_time_ms"/utf8>>,
                                Event_time_text
                            ) of
                                {error, Reason@2} ->
                                    Reason@2;

                                {ok, Event_time_ms} ->
                                    case parse_int_field(
                                        <<"at_ms"/utf8>>,
                                        At_ms_text
                                    ) of
                                        {error, Reason@3} ->
                                            Reason@3;

                                        {ok, At_ms} ->
                                            Entry = lightspeed@pipeline@checkpoint:checkpoint(
                                                Run_id,
                                                Stage,
                                                Sequence,
                                                lightspeed@pipeline@checkpoint:watermark(
                                                    Offset,
                                                    Event_time_ms
                                                ),
                                                Idempotency_key,
                                                At_ms
                                            ),
                                            case lightspeed@pipeline@checkpoint:valid(
                                                Entry
                                            ) of
                                                true ->
                                                    <<<<<<<<<<"ok:run="/utf8,
                                                                        (erlang:element(
                                                                            2,
                                                                            Entry
                                                                        ))/binary>>/binary,
                                                                    "|stage="/utf8>>/binary,
                                                                (erlang:element(
                                                                    3,
                                                                    Entry
                                                                ))/binary>>/binary,
                                                            "|sequence="/utf8>>/binary,
                                                        (erlang:integer_to_binary(
                                                            erlang:element(
                                                                4,
                                                                Entry
                                                            )
                                                        ))/binary>>;

                                                false ->
                                                    <<"error:invalid_checkpoint"/utf8>>
                                            end
                                    end
                            end
                    end
            end;

        Tokens ->
            <<"error:bad_field_count:pipeline_checkpoint:8:"/utf8,
                (erlang:integer_to_binary(erlang:length(Tokens)))/binary>>
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 682).
-spec diff_envelope_case_label(binary()) -> binary().
diff_envelope_case_label(Payload) ->
    case lightspeed@diff:decode_stream(Payload) of
        {ok, Patches} ->
            <<<<<<"ok_ops:"/utf8,
                        (erlang:integer_to_binary(erlang:length(Patches)))/binary>>/binary,
                    ":"/utf8>>/binary,
                (join_with(
                    <<","/utf8>>,
                    gleam@list:map(Patches, fun lightspeed@diff:operation/1)
                ))/binary>>;

        {error, Error} ->
            <<"error:"/utf8,
                (lightspeed@diff:decode_error_to_string(Error))/binary>>
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 810).
-spec frame_tag(lightspeed@protocol:frame()) -> binary().
frame_tag(Frame) ->
    case Frame of
        {hello, _, _} ->
            <<"hello"/utf8>>;

        {event, _, _, _} ->
            <<"event"/utf8>>;

        {diff, _, _} ->
            <<"diff"/utf8>>;

        {ack, _} ->
            <<"ack"/utf8>>;

        {failure, _, _} ->
            <<"failure"/utf8>>
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 824).
-spec is_structured_payload(binary()) -> boolean().
is_structured_payload(Payload) ->
    gleam_stdlib:string_starts_with(Payload, <<"{"/utf8>>) andalso gleam_stdlib:string_ends_with(
        Payload,
        <<"}"/utf8>>
    ).

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 820).
-spec is_supported_event(binary()) -> boolean().
is_supported_event(Name) ->
    (Name =:= <<"increment"/utf8>>) orelse (Name =:= <<"decrement"/utf8>>).

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 661).
-spec event_envelope_case_label(binary()) -> binary().
event_envelope_case_label(Payload) ->
    case lightspeed@protocol:decode(Payload) of
        {ok, {event, Ref, Name, Event_payload}} ->
            case Ref =:= <<""/utf8>> of
                true ->
                    <<"error:missing_event_ref"/utf8>>;

                false ->
                    case is_supported_event(Name) of
                        false ->
                            <<"error:unsupported_event:"/utf8, Name/binary>>;

                        true ->
                            case is_structured_payload(Event_payload) of
                                true ->
                                    <<"ok:event:"/utf8, Name/binary>>;

                                false ->
                                    <<"error:malformed_event_payload"/utf8>>
                            end
                    end
            end;

        {ok, Frame} ->
            <<"error:unsupported_event_envelope:"/utf8,
                (frame_tag(Frame))/binary>>;

        {error, Error} ->
            <<"error:protocol_decode_failed:"/utf8,
                (lightspeed@protocol:decode_error_to_string(Error))/binary>>
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 797).
-spec frame_labels(list(binary())) -> binary().
frame_labels(Frames) ->
    join_with(
        <<","/utf8>>,
        gleam@list:map(
            Frames,
            fun(Frame) -> case lightspeed@protocol:decode(Frame) of
                    {ok, Decoded} ->
                        frame_tag(Decoded);

                    {error, Error} ->
                        <<"decode_error:"/utf8,
                            (lightspeed@protocol:decode_error_to_string(Error))/binary>>
                end end
        )
    ).

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 786).
-spec first_failure_reason(list(binary())) -> binary().
first_failure_reason(Frames) ->
    case Frames of
        [] ->
            <<""/utf8>>;

        [Frame | Rest] ->
            case lightspeed@protocol:decode(Frame) of
                {ok, {failure, _, Reason}} ->
                    Reason;

                _ ->
                    first_failure_reason(Rest)
            end
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 754).
-spec connect_transport(integer()) -> {ok,
        lightspeed@transport@matrix:adapter_state()} |
    {error, binary()}.
connect_transport(Max_payload_bytes) ->
    case lightspeed@transport@matrix:connect_with_policies(
        lightspeed@agent@session:start(
            <<"m43-transport"/utf8>>,
            <<"proc-a"/utf8>>,
            rehydrate,
            0,
            100
        ),
        {connect_request,
            <<"/counter"/utf8>>,
            <<"csrf"/utf8>>,
            <<"https://example.test"/utf8>>,
            0,
            false},
        web_socket_only,
        lightspeed@transport@contract:allow_all(<<"proc-a"/utf8>>),
        lightspeed@transport@contract:allow_protection(),
        {security_policy, true, true, Max_payload_bytes},
        {timeout_policy, 30000, 60000}
    ) of
        {connected, State, _} ->
            {ok, State};

        {rejected, Error} ->
            {error, lightspeed@transport@contract:error_to_string(Error)}
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 643).
-spec transport_envelope_case_label(binary()) -> binary().
transport_envelope_case_label(Payload) ->
    Payload_limit = case gleam_stdlib:contains_string(
        Payload,
        <<"e-oversize"/utf8>>
    ) of
        true ->
            16;

        false ->
            64
    end,
    case connect_transport(Payload_limit) of
        {error, Reason} ->
            <<"error:connect_failed:"/utf8, Reason/binary>>;

        {ok, State} ->
            Result = lightspeed@transport@matrix:'receive'(State, Payload, 1, 1),
            case first_failure_reason(erlang:element(3, Result)) of
                <<""/utf8>> ->
                    <<"ok:"/utf8,
                        (frame_labels(erlang:element(3, Result)))/binary>>;

                Reason@1 ->
                    <<"error:"/utf8, Reason@1/binary>>
            end
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 634).
-spec corpus_case_label(corpus_case()) -> binary().
corpus_case_label(Entry) ->
    case erlang:element(3, Entry) of
        transport_envelope ->
            transport_envelope_case_label(erlang:element(4, Entry));

        event_envelope ->
            event_envelope_case_label(erlang:element(4, Entry));

        diff_envelope ->
            diff_envelope_case_label(erlang:element(4, Entry));

        pipeline_envelope ->
            pipeline_envelope_case_label(erlang:element(4, Entry))
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 588).
-spec replay_regression_cases(
    list(corpus_case()),
    integer(),
    integer(),
    list(binary())
) -> {integer(), list(binary())}.
replay_regression_cases(Cases, Index, Mismatches, Outcomes_rev) ->
    case Cases of
        [] ->
            {Mismatches, lists:reverse(Outcomes_rev)};

        [Entry | Rest] ->
            First = corpus_case_label(Entry),
            Replayed = corpus_case_label(Entry),
            Next_mismatches = case ((First =:= erlang:element(5, Entry)) andalso (Replayed
            =:= erlang:element(5, Entry)))
            andalso (First =:= Replayed) of
                true ->
                    Mismatches;

                false ->
                    Mismatches + 1
            end,
            replay_regression_cases(
                Rest,
                Index + 1,
                Next_mismatches,
                [<<<<<<<<<<<<(erlang:integer_to_binary(Index))/binary,
                                            ":"/utf8>>/binary,
                                        (erlang:element(2, Entry))/binary>>/binary,
                                    ":"/utf8>>/binary,
                                First/binary>>/binary,
                            ":replay="/utf8>>/binary,
                        Replayed/binary>> |
                    Outcomes_rev]
            )
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 289).
-spec evaluate_fuzz_regression_replay_certification() -> {boolean(), binary()}.
evaluate_fuzz_regression_replay_certification() ->
    Regressions = error_cases(expanded_corpus(), []),
    {Replay_mismatches, Replay_outcomes} = replay_regression_cases(
        Regressions,
        1,
        0,
        []
    ),
    Passed = ((Replay_mismatches =:= 0) andalso (erlang:length(Regressions) >= 10))
    andalso (Replay_outcomes /= []),
    {Passed,
        <<<<<<<<<<"replay_mismatches="/utf8,
                            (erlang:integer_to_binary(Replay_mismatches))/binary>>/binary,
                        "|regressions="/utf8>>/binary,
                    (erlang:integer_to_binary(erlang:length(Regressions)))/binary>>/binary,
                "|replay="/utf8>>/binary,
            (join_with(<<","/utf8>>, Replay_outcomes))/binary>>}.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 881).
-spec append_labels(list(binary()), list(binary())) -> list(binary()).
append_labels(Left, Right) ->
    case Left of
        [] ->
            Right;

        [Value | Rest] ->
            [Value | append_labels(Rest, Right)]
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 565).
-spec evaluate_corpus_cases(
    list(corpus_case()),
    integer(),
    integer(),
    list(binary())
) -> {integer(), list(binary())}.
evaluate_corpus_cases(Cases, Index, Mismatches, Outcomes_rev) ->
    case Cases of
        [] ->
            {Mismatches, lists:reverse(Outcomes_rev)};

        [Entry | Rest] ->
            Actual = corpus_case_label(Entry),
            Next_mismatches = case Actual =:= erlang:element(5, Entry) of
                true ->
                    Mismatches;

                false ->
                    Mismatches + 1
            end,
            evaluate_corpus_cases(
                Rest,
                Index + 1,
                Next_mismatches,
                [<<<<<<<<(erlang:integer_to_binary(Index))/binary, ":"/utf8>>/binary,
                                (erlang:element(2, Entry))/binary>>/binary,
                            ":"/utf8>>/binary,
                        Actual/binary>> |
                    Outcomes_rev]
            )
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 828).
-spec cases_for_track(
    list(corpus_case()),
    envelope_track(),
    list(corpus_case())
) -> list(corpus_case()).
cases_for_track(Cases, Target, Acc_rev) ->
    case Cases of
        [] ->
            lists:reverse(Acc_rev);

        [Entry | Rest] ->
            case erlang:element(3, Entry) =:= Target of
                true ->
                    cases_for_track(Rest, Target, [Entry | Acc_rev]);

                false ->
                    cases_for_track(Rest, Target, Acc_rev)
            end
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 230).
-spec evaluate_envelope_fuzz_corpus_expansion() -> {boolean(), binary()}.
evaluate_envelope_fuzz_corpus_expansion() ->
    Transport_cases = cases_for_track(expanded_corpus(), transport_envelope, []),
    Event_cases = cases_for_track(expanded_corpus(), event_envelope, []),
    Diff_cases = cases_for_track(expanded_corpus(), diff_envelope, []),
    Pipeline_cases = cases_for_track(expanded_corpus(), pipeline_envelope, []),
    {Transport_mismatches, Transport_outcomes} = evaluate_corpus_cases(
        Transport_cases,
        1,
        0,
        []
    ),
    {Event_mismatches, Event_outcomes} = evaluate_corpus_cases(
        Event_cases,
        1,
        0,
        []
    ),
    {Diff_mismatches, Diff_outcomes} = evaluate_corpus_cases(
        Diff_cases,
        1,
        0,
        []
    ),
    {Pipeline_mismatches, Pipeline_outcomes} = evaluate_corpus_cases(
        Pipeline_cases,
        1,
        0,
        []
    ),
    Total_mismatches = ((Transport_mismatches + Event_mismatches) + Diff_mismatches)
    + Pipeline_mismatches,
    All_outcomes = append_labels(
        append_labels(Transport_outcomes, Event_outcomes),
        append_labels(Diff_outcomes, Pipeline_outcomes)
    ),
    Passed = ((((Total_mismatches =:= 0) andalso (erlang:length(Transport_cases)
    =:= 5))
    andalso (erlang:length(Event_cases) =:= 7))
    andalso (erlang:length(Diff_cases) =:= 6))
    andalso (erlang:length(Pipeline_cases) =:= 5),
    {Passed,
        <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"mismatches="/utf8,
                                                                                    (erlang:integer_to_binary(
                                                                                        Total_mismatches
                                                                                    ))/binary>>/binary,
                                                                                "|transport="/utf8>>/binary,
                                                                            (erlang:integer_to_binary(
                                                                                erlang:length(
                                                                                    Transport_cases
                                                                                )
                                                                            ))/binary>>/binary,
                                                                        "/"/utf8>>/binary,
                                                                    (erlang:integer_to_binary(
                                                                        Transport_mismatches
                                                                    ))/binary>>/binary,
                                                                "|event="/utf8>>/binary,
                                                            (erlang:integer_to_binary(
                                                                erlang:length(
                                                                    Event_cases
                                                                )
                                                            ))/binary>>/binary,
                                                        "/"/utf8>>/binary,
                                                    (erlang:integer_to_binary(
                                                        Event_mismatches
                                                    ))/binary>>/binary,
                                                "|diff="/utf8>>/binary,
                                            (erlang:integer_to_binary(
                                                erlang:length(Diff_cases)
                                            ))/binary>>/binary,
                                        "/"/utf8>>/binary,
                                    (erlang:integer_to_binary(Diff_mismatches))/binary>>/binary,
                                "|pipeline="/utf8>>/binary,
                            (erlang:integer_to_binary(
                                erlang:length(Pipeline_cases)
                            ))/binary>>/binary,
                        "/"/utf8>>/binary,
                    (erlang:integer_to_binary(Pipeline_mismatches))/binary>>/binary,
                "|cases="/utf8>>/binary,
            (join_with(<<","/utf8>>, All_outcomes))/binary>>}.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 345).
-spec protocol_matrix_cases() -> list({binary(), binary()}).
protocol_matrix_cases() ->
    Escaped_event_payload = lightspeed@protocol:encode(
        {event, <<"r|1"/utf8>>, <<"save"/utf8>>, <<"{\"path\":\"a|b\"}"/utf8>>}
    ),
    [{<<"hello|lightspeed|1"/utf8>>, <<"ok:hello:lightspeed:1"/utf8>>},
        {<<"hello|lightspeed|0"/utf8>>, <<"error:unsupported_version:0"/utf8>>},
        {<<"hello|lightspeed|2"/utf8>>, <<"error:unsupported_version:2"/utf8>>},
        {<<"hello|lightspeed|abc"/utf8>>, <<"error:invalid_version:abc"/utf8>>},
        {<<"hello|other|1"/utf8>>, <<"error:unsupported_protocol:other"/utf8>>},
        {Escaped_event_payload, <<"ok:event:r|1:save"/utf8>>},
        {<<"ack|r-1"/utf8>>, <<"ok:ack:r-1"/utf8>>},
        {<<"failure|f-1|fault"/utf8>>, <<"ok:failure:f-1"/utf8>>},
        {<<"noop|x"/utf8>>, <<"error:unknown_frame_tag:noop"/utf8>>}].

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 622).
-spec protocol_matrix_case_label(binary()) -> binary().
protocol_matrix_case_label(Payload) ->
    case lightspeed@protocol:decode(Payload) of
        {ok, {hello, Protocol_name, Version}} ->
            <<<<<<"ok:hello:"/utf8, Protocol_name/binary>>/binary, ":"/utf8>>/binary,
                (erlang:integer_to_binary(Version))/binary>>;

        {ok, {event, Ref, Name, _}} ->
            <<<<<<"ok:event:"/utf8, Ref/binary>>/binary, ":"/utf8>>/binary,
                Name/binary>>;

        {ok, {diff, Ref@1, _}} ->
            <<"ok:diff:"/utf8, Ref@1/binary>>;

        {ok, {ack, Ref@2}} ->
            <<"ok:ack:"/utf8, Ref@2/binary>>;

        {ok, {failure, Ref@3, _}} ->
            <<"ok:failure:"/utf8, Ref@3/binary>>;

        {error, Error} ->
            <<"error:"/utf8,
                (lightspeed@protocol:decode_error_to_string(Error))/binary>>
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 541).
-spec evaluate_protocol_cases(
    list({binary(), binary()}),
    integer(),
    integer(),
    list(binary())
) -> {integer(), list(binary())}.
evaluate_protocol_cases(Cases, Index, Mismatches, Outcomes_rev) ->
    case Cases of
        [] ->
            {Mismatches, lists:reverse(Outcomes_rev)};

        [Entry | Rest] ->
            {Payload, Expected} = Entry,
            Actual = protocol_matrix_case_label(Payload),
            Next_mismatches = case Actual =:= Expected of
                true ->
                    Mismatches;

                false ->
                    Mismatches + 1
            end,
            evaluate_protocol_cases(
                Rest,
                Index + 1,
                Next_mismatches,
                [<<<<(erlang:integer_to_binary(Index))/binary, ":"/utf8>>/binary,
                        Actual/binary>> |
                    Outcomes_rev]
            )
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 208).
-spec evaluate_protocol_conformance_matrix_expansion() -> {boolean(), binary()}.
evaluate_protocol_conformance_matrix_expansion() ->
    {Mismatches, Outcomes} = evaluate_protocol_cases(
        protocol_matrix_cases(),
        1,
        0,
        []
    ),
    Passed = ((Mismatches =:= 0) andalso (1 =:= 1)) andalso (1 =:= 1),
    {Passed,
        <<<<<<<<<<<<<<"mismatches="/utf8,
                                    (erlang:integer_to_binary(Mismatches))/binary>>/binary,
                                "|protocol_version="/utf8>>/binary,
                            (erlang:integer_to_binary(1))/binary>>/binary,
                        "|patch_stream_version="/utf8>>/binary,
                    (erlang:integer_to_binary(1))/binary>>/binary,
                "|cases="/utf8>>/binary,
            (join_with(<<","/utf8>>, Outcomes))/binary>>}.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 309).
-spec evaluate_unified_protocol_evidence_surface() -> {boolean(), binary()}.
evaluate_unified_protocol_evidence_surface() ->
    {Protocol_passed, Protocol_signature} = evaluate_protocol_conformance_matrix_expansion(
        
    ),
    {Envelope_passed, Envelope_signature} = evaluate_envelope_fuzz_corpus_expansion(
        
    ),
    {Replay_passed, Replay_signature} = evaluate_fuzz_regression_replay_certification(
        
    ),
    Drift_classes = drift_classes_from_cases(
        error_cases(expanded_corpus(), []),
        []
    ),
    Passed = ((Protocol_passed andalso Envelope_passed) andalso Replay_passed)
    andalso (erlang:length(Drift_classes) >= 6),
    {Passed,
        <<<<<<<<<<<<<<<<<<<<<<<<<<"protocol="/utf8,
                                                            (bool_label(
                                                                Protocol_passed
                                                            ))/binary>>/binary,
                                                        "|envelopes="/utf8>>/binary,
                                                    (bool_label(Envelope_passed))/binary>>/binary,
                                                "|replay="/utf8>>/binary,
                                            (bool_label(Replay_passed))/binary>>/binary,
                                        "|drift_classes="/utf8>>/binary,
                                    (join_with(<<","/utf8>>, Drift_classes))/binary>>/binary,
                                "|protocol_signature="/utf8>>/binary,
                            Protocol_signature/binary>>/binary,
                        "|envelope_signature="/utf8>>/binary,
                    Envelope_signature/binary>>/binary,
                "|replay_signature="/utf8>>/binary,
            Replay_signature/binary>>}.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 196).
-spec evaluate(scenario()) -> {boolean(), binary()}.
evaluate(Scenario) ->
    case Scenario of
        protocol_conformance_matrix_expansion ->
            evaluate_protocol_conformance_matrix_expansion();

        envelope_fuzz_corpus_expansion ->
            evaluate_envelope_fuzz_corpus_expansion();

        fuzz_regression_replay_certification ->
            evaluate_fuzz_regression_replay_certification();

        unified_protocol_evidence_surface ->
            evaluate_unified_protocol_evidence_surface()
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 77).
?DOC(" Run one M43 scenario twice and require deterministic parity.\n").
-spec run_scenario(scenario()) -> scenario_outcome().
run_scenario(Scenario) ->
    {First_passed, First_signature} = evaluate(Scenario),
    {Second_passed, Second_signature} = evaluate(Scenario),
    Deterministic = (First_passed =:= Second_passed) andalso (First_signature
    =:= Second_signature),
    Passed = (First_passed andalso Second_passed) andalso Deterministic,
    {scenario_outcome, Scenario, Passed, Deterministic, First_signature}.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 59).
?DOC(" Run all M43 scenarios.\n").
-spec run_matrix() -> report().
run_matrix() ->
    Outcomes = begin
        _pipe = [protocol_conformance_matrix_expansion,
            envelope_fuzz_corpus_expansion,
            fuzz_regression_replay_certification,
            unified_protocol_evidence_surface],
        gleam@list:map(_pipe, fun run_scenario/1)
    end,
    {report, Outcomes, count_failed(Outcomes), count_nondeterministic(Outcomes)}.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 93).
?DOC(" Scenario label.\n").
-spec scenario_label(scenario()) -> binary().
scenario_label(Scenario) ->
    case Scenario of
        protocol_conformance_matrix_expansion ->
            <<"protocol_conformance_matrix_expansion"/utf8>>;

        envelope_fuzz_corpus_expansion ->
            <<"envelope_fuzz_corpus_expansion"/utf8>>;

        fuzz_regression_replay_certification ->
            <<"fuzz_regression_replay_certification"/utf8>>;

        unified_protocol_evidence_surface ->
            <<"unified_protocol_evidence_surface"/utf8>>
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 104).
?DOC(" Stable pass/fail label.\n").
-spec pass_fail_label(scenario_outcome()) -> binary().
pass_fail_label(Outcome) ->
    case erlang:element(3, Outcome) of
        true ->
            <<"pass"/utf8>>;

        false ->
            <<"fail"/utf8>>
    end.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 112).
?DOC(" Scenario signature accessor.\n").
-spec signature(scenario_outcome()) -> binary().
signature(Outcome) ->
    erlang:element(5, Outcome).

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 117).
?DOC(" Scenario accessor.\n").
-spec scenario(scenario_outcome()) -> scenario().
scenario(Outcome) ->
    erlang:element(2, Outcome).

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 122).
?DOC(" Determinism accessor.\n").
-spec deterministic(scenario_outcome()) -> boolean().
deterministic(Outcome) ->
    erlang:element(4, Outcome).

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 127).
?DOC(" Report outcomes accessor.\n").
-spec outcomes(report()) -> list(scenario_outcome()).
outcomes(Report) ->
    erlang:element(2, Report).

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 132).
?DOC(" Failed scenario count.\n").
-spec failed_scenarios(report()) -> integer().
failed_scenarios(Report) ->
    erlang:element(3, Report).

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 137).
?DOC(" Nondeterministic scenario count.\n").
-spec nondeterministic_failures(report()) -> integer().
nondeterministic_failures(Report) ->
    erlang:element(4, Report).

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 142).
?DOC(" Stable report signature.\n").
-spec report_signature(report()) -> binary().
report_signature(Report) ->
    Entries = gleam@list:map(
        erlang:element(2, Report),
        fun(Outcome) ->
            <<<<<<<<<<<<(scenario_label(erlang:element(2, Outcome)))/binary,
                                    "="/utf8>>/binary,
                                (pass_fail_label(Outcome))/binary>>/binary,
                            ":deterministic="/utf8>>/binary,
                        (bool_label(erlang:element(4, Outcome)))/binary>>/binary,
                    ":"/utf8>>/binary,
                (erlang:element(5, Outcome))/binary>>
        end
    ),
    join_with(<<";"/utf8>>, Entries).

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 158).
?DOC(" Deterministic snapshot signature for M43 fixture drift gates.\n").
-spec snapshot_signature() -> binary().
snapshot_signature() ->
    <<<<<<"m43.snapshot.v"/utf8, (erlang:integer_to_binary(1))/binary>>/binary,
            "|"/utf8>>/binary,
        (report_signature(run_matrix()))/binary>>.

-file("src/lightspeed/ops/protocol_contract_harness.gleam", 166).
?DOC(" Deterministic markdown report for M43 fixture scripts.\n").
-spec snapshot_report_markdown() -> binary().
snapshot_report_markdown() ->
    Report = run_matrix(),
    Failed = failed_scenarios(Report),
    Nondeterministic = nondeterministic_failures(Report),
    Status = case (Failed =:= 0) andalso (Nondeterministic =:= 0) of
        true ->
            <<"OK"/utf8>>;

        false ->
            <<"FAIL"/utf8>>
    end,
    <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"# Protocol Contract Fixture Report\n\n"/utf8,
                                                                            "snapshot_version: "/utf8>>/binary,
                                                                        (erlang:integer_to_binary(
                                                                            1
                                                                        ))/binary>>/binary,
                                                                    "\n"/utf8>>/binary,
                                                                "status: "/utf8>>/binary,
                                                            Status/binary>>/binary,
                                                        "\n"/utf8>>/binary,
                                                    "failed_scenarios: "/utf8>>/binary,
                                                (erlang:integer_to_binary(
                                                    Failed
                                                ))/binary>>/binary,
                                            "\n"/utf8>>/binary,
                                        "nondeterministic_failures: "/utf8>>/binary,
                                    (erlang:integer_to_binary(Nondeterministic))/binary>>/binary,
                                "\n\n"/utf8>>/binary,
                            "snapshot_signature: "/utf8>>/binary,
                        (snapshot_signature())/binary>>/binary,
                    "\n\n"/utf8>>/binary,
                "report_signature: "/utf8>>/binary,
            (report_signature(Report))/binary>>/binary,
        "\n"/utf8>>.