///|
/// Link-driver catalog for Lockwire's run-test substrate.

///|
pub fn package_id() -> String {
  "lockwire/driver"
}

///|
pub(all) enum LinkDriverSource {
  MoonEcatHalNative
  ProfinetRawNet
  ProfinetUdpNet
  ProfinetPcapDump
} derive(Eq, Debug)

///|
pub fn LinkDriverSource::label(self : LinkDriverSource) -> String {
  match self {
    MoonEcatHalNative => "moonecat-hal-native"
    ProfinetRawNet => "profinet-rawnet"
    ProfinetUdpNet => "profinet-udpnet"
    ProfinetPcapDump => "profinet-pcapdump"
  }
}

///|
pub(all) enum LinkDriverKind {
  RawEthernetSocket
  UdpDatagramSocket
  PacketCaptureWriter
  InterfaceListing
  HighResolutionClock
  ZeroCopyFramePool
} derive(Eq, Debug)

///|
pub fn LinkDriverKind::label(self : LinkDriverKind) -> String {
  match self {
    RawEthernetSocket => "raw-ethernet-socket"
    UdpDatagramSocket => "udp-datagram-socket"
    PacketCaptureWriter => "packet-capture-writer"
    InterfaceListing => "interface-listing"
    HighResolutionClock => "high-resolution-clock"
    ZeroCopyFramePool => "zero-copy-frame-pool"
  }
}

///|
pub(all) enum LinkDriverRuntime {
  WindowsNpcap
  LinuxRawSocket
  WinsockUdp
  BsdUdpSocket
  PcapFileWriter
  MoonEcatFramePool
  NativeClock
} derive(Eq, Debug)

///|
pub fn LinkDriverRuntime::label(self : LinkDriverRuntime) -> String {
  match self {
    WindowsNpcap => "windows-npcap"
    LinuxRawSocket => "linux-raw-socket"
    WinsockUdp => "winsock-udp"
    BsdUdpSocket => "bsd-udp-socket"
    PcapFileWriter => "pcap-file-writer"
    MoonEcatFramePool => "moonecat-frame-pool"
    NativeClock => "native-clock"
  }
}

///|
pub(all) struct LinkDriverSpec {
  id : String
  source : LinkDriverSource
  kind : LinkDriverKind
  runtime : LinkDriverRuntime
  reference_path : String
  operations : Array[String]
  requires_native : Bool
  requires_runtime : Bool
  has_non_native_fallback : Bool
  zero_copy : Bool
  live_validation_locked : Bool
  protocol_import_free : Bool
} derive(Eq, Debug)

///|
pub(all) struct LinkMasterHarnessDescriptor {
  id : String
  provider_id : String
  stack_id : String
  stack_family : String
  descriptor_path : String
  protocol_stack_path : String
  master_control_path : String
  driver_ids : Array[String]
  supports_scan : Bool
  supports_cyclic_io : Bool
  supports_recording : Bool
  minimal_master_candidate : Bool
  live_validation_locked : Bool
  provider_owned_delivery : Bool
  lockwire_owns_protocol_semantics : Bool
} derive(Eq, Debug)

///|
pub fn LinkMasterHarnessDescriptor::driver_count(
  self : LinkMasterHarnessDescriptor,
) -> Int {
  self.driver_ids.length()
}

///|
pub fn LinkMasterHarnessDescriptor::uses_driver(
  self : LinkMasterHarnessDescriptor,
  driver_id : String,
) -> Bool {
  self.driver_ids.any(fn(item) { item == driver_id })
}

///|
pub fn LinkMasterHarnessDescriptor::references_catalog(
  self : LinkMasterHarnessDescriptor,
  catalog : ArrayView[LinkDriverSpec],
) -> Bool {
  self.driver_ids.all(fn(driver_id) { catalog_has_driver(catalog, driver_id) })
}

///|
pub fn LinkMasterHarnessDescriptor::passes_against(
  self : LinkMasterHarnessDescriptor,
  catalog : ArrayView[LinkDriverSpec],
) -> Bool {
  self.minimal_master_candidate &&
  self.live_validation_locked &&
  self.provider_owned_delivery &&
  !self.lockwire_owns_protocol_semantics &&
  self.supports_scan &&
  self.supports_cyclic_io &&
  self.supports_recording &&
  self.driver_count() > 0 &&
  self.references_catalog(catalog)
}

///|
pub fn LinkDriverSpec::operation_count(self : LinkDriverSpec) -> Int {
  self.operations.length()
}

///|
pub fn LinkDriverSpec::has_operation(
  self : LinkDriverSpec,
  operation : String,
) -> Bool {
  self.operations.any(fn(item) { item == operation })
}

///|
pub fn LinkDriverSpec::is_native_gate(self : LinkDriverSpec) -> Bool {
  self.requires_native && self.requires_runtime
}

///|
pub fn LinkDriverSpec::catalog_label(self : LinkDriverSpec) -> String {
  "driver.catalog." +
  self.source.label() +
  "." +
  self.kind.label() +
  "." +
  self.runtime.label()
}

///|
pub(all) struct LinkDriverMergeReport {
  catalog_count : Int
  raw_ethernet_count : Int
  udp_datagram_count : Int
  pcap_count : Int
  zero_copy_count : Int
  native_gate_count : Int
  protocol_import_free : Bool
  live_adapter_evidence : Bool
  provider_master_harness_count : Int
  lockwire_builtin_master_harness_count : Int
  lockwire_protocol_semantics_owned : Bool
  trace_event_count : Int
  replay_count : Int
  same_seed_stable : Bool
  digest : @core.SimDigest
} derive(Eq, Debug)

///|
pub fn LinkDriverMergeReport::passes(self : LinkDriverMergeReport) -> Bool {
  self.catalog_count >= 7 &&
  self.raw_ethernet_count >= 2 &&
  self.udp_datagram_count >= 2 &&
  self.pcap_count >= 1 &&
  self.zero_copy_count >= 1 &&
  self.native_gate_count == self.catalog_count &&
  self.protocol_import_free &&
  !self.live_adapter_evidence &&
  self.provider_master_harness_count == 0 &&
  self.lockwire_builtin_master_harness_count == 0 &&
  !self.lockwire_protocol_semantics_owned &&
  self.trace_event_count == self.catalog_count &&
  self.replay_count == self.trace_event_count &&
  self.same_seed_stable
}

///|
pub(all) struct LinkMasterHarnessValidationReport {
  descriptor_count : Int
  passing_descriptor_count : Int
  provider_owned_descriptor_count : Int
  lockwire_protocol_semantics_owned : Bool
  trace_event_count : Int
  replay_count : Int
  same_seed_stable : Bool
  digest : @core.SimDigest
} derive(Eq, Debug)

///|
pub(all) enum LinkReadinessTargetKind {
  LinkTargetWindowsNpcap
  LinkTargetLinuxRaw
  LinkTargetStm32Threadx
} derive(Eq, Debug)

///|
pub fn LinkReadinessTargetKind::label(self : LinkReadinessTargetKind) -> String {
  match self {
    LinkTargetWindowsNpcap => "windows-npcap"
    LinkTargetLinuxRaw => "linux-raw"
    LinkTargetStm32Threadx => "stm32-threadx"
  }
}

///|
pub(all) struct LinkReadinessTarget {
  id : String
  kind : LinkReadinessTargetKind
  profile : @os.CapabilityProfile
  reactor_id : String
  os_capability_ids : Array[String]
  hal_capability_ids : Array[String]
  driver_ids : Array[String]
  host_os : String
  board_family : String
  supports_raw_frame : Bool
  supports_udp : Bool
  supports_pcap_artifact : Bool
  supports_frame_pool : Bool
  requires_threadx : Bool
  requires_bsp : Bool
  requires_hardware : Bool
  live_validation_locked : Bool
  no_live_plan_ready : Bool
  live_evidence_present : Bool
} derive(Eq, Debug)

///|
pub fn LinkReadinessTarget::driver_count(self : LinkReadinessTarget) -> Int {
  self.driver_ids.length()
}

///|
pub fn LinkReadinessTarget::hal_count(self : LinkReadinessTarget) -> Int {
  self.hal_capability_ids.length()
}

///|
pub fn LinkReadinessTarget::is_embedded(self : LinkReadinessTarget) -> Bool {
  self.profile == @os.ProfileRealEmbedded || self.requires_threadx
}

///|
pub fn LinkReadinessTarget::references_drivers(
  self : LinkReadinessTarget,
  catalog : ArrayView[LinkDriverSpec],
) -> Bool {
  self.driver_ids.all(fn(driver_id) { catalog_has_driver(catalog, driver_id) })
}

///|
pub fn LinkReadinessTarget::references_hal(
  self : LinkReadinessTarget,
  catalog : ArrayView[@hal.HalCapabilityDescriptor],
) -> Bool {
  self.hal_capability_ids.all(fn(hal_id) { catalog_has_hal(catalog, hal_id) })
}

///|
pub fn LinkReadinessTarget::references_os(
  self : LinkReadinessTarget,
  catalog : ArrayView[@os.OsCapabilityDescriptor],
) -> Bool {
  self.os_capability_ids.all(fn(os_id) { catalog_has_os(catalog, os_id) })
}

///|
pub fn LinkReadinessTarget::references_reactor(
  self : LinkReadinessTarget,
  catalog : ArrayView[@reactor.ReactorBackendDescriptor],
) -> Bool {
  catalog.any(fn(reactor) { reactor.id == self.reactor_id })
}

///|
pub(all) struct LinkReadinessMatrixReport {
  target_count : Int
  windows_target_count : Int
  linux_target_count : Int
  stm32_threadx_target_count : Int
  host_native_target_count : Int
  embedded_target_count : Int
  raw_frame_target_count : Int
  udp_target_count : Int
  pcap_artifact_target_count : Int
  frame_pool_target_count : Int
  live_locked_count : Int
  no_live_plan_ready_count : Int
  embedded_driver_gap_count : Int
  driver_reference_failure_count : Int
  hal_reference_failure_count : Int
  os_reference_failure_count : Int
  reactor_reference_failure_count : Int
  live_evidence_present : Bool
  trace_event_count : Int
  replay_count : Int
  same_seed_stable : Bool
  digest : @core.SimDigest
} derive(Eq, Debug)

///|
pub fn LinkReadinessMatrixReport::passes(
  self : LinkReadinessMatrixReport,
) -> Bool {
  self.target_count == 3 &&
  self.windows_target_count == 1 &&
  self.linux_target_count == 1 &&
  self.stm32_threadx_target_count == 1 &&
  self.host_native_target_count == 2 &&
  self.embedded_target_count == 1 &&
  self.raw_frame_target_count >= 3 &&
  self.udp_target_count >= 2 &&
  self.pcap_artifact_target_count >= 2 &&
  self.frame_pool_target_count >= 2 &&
  self.live_locked_count == self.target_count &&
  self.no_live_plan_ready_count >= 2 &&
  self.embedded_driver_gap_count == 1 &&
  self.driver_reference_failure_count == 0 &&
  self.hal_reference_failure_count == 0 &&
  self.os_reference_failure_count == 0 &&
  self.reactor_reference_failure_count == 0 &&
  !self.live_evidence_present &&
  self.trace_event_count == self.target_count &&
  self.replay_count == self.trace_event_count &&
  self.same_seed_stable
}

///|
pub fn LinkReadinessMatrixReport::to_text(
  self : LinkReadinessMatrixReport,
) -> String {
  "link_readiness.targets=\{self.target_count}|windows=\{self.windows_target_count}|linux=\{self.linux_target_count}|stm32_threadx=\{self.stm32_threadx_target_count}|embedded_driver_gap=\{self.embedded_driver_gap_count}|live_locked=\{self.live_locked_count}|no_live_plan_ready=\{self.no_live_plan_ready_count}|live_evidence_present=\{self.live_evidence_present}|digest=\{self.digest.state_digest}"
}

///|
pub fn LinkMasterHarnessValidationReport::passes(
  self : LinkMasterHarnessValidationReport,
) -> Bool {
  self.descriptor_count > 0 &&
  self.passing_descriptor_count == self.descriptor_count &&
  self.provider_owned_descriptor_count == self.descriptor_count &&
  !self.lockwire_protocol_semantics_owned &&
  self.trace_event_count == self.descriptor_count &&
  self.replay_count == self.trace_event_count &&
  self.same_seed_stable
}

///|
pub fn link_readiness_targets() -> Array[LinkReadinessTarget] {
  [
    {
      id: "target.windows.npcap.full_link",
      kind: LinkTargetWindowsNpcap,
      profile: @os.ProfileNativeReal,
      reactor_id: "reactor.iocp",
      os_capability_ids: [
        "os.clock.native_highres", "os.native_stub.loader", "os.event_loop.iocp",
        "os.socket.udp", "os.raw_nic.windows_npcap", "os.capture.pcap_file",
      ],
      hal_capability_ids: ["hal.frame_pool.native"],
      driver_ids: [
        "moonecat.windows_npcap.raw_frame", "profinet.udpnet.winsock_udp", "profinet.pcapdump.capture_writer",
        "moonecat.native.zero_copy_frame_pool",
      ],
      host_os: "windows",
      board_family: "",
      supports_raw_frame: true,
      supports_udp: true,
      supports_pcap_artifact: true,
      supports_frame_pool: true,
      requires_threadx: false,
      requires_bsp: false,
      requires_hardware: true,
      live_validation_locked: true,
      no_live_plan_ready: true,
      live_evidence_present: false,
    },
    {
      id: "target.linux.raw_udp_pcap",
      kind: LinkTargetLinuxRaw,
      profile: @os.ProfileRealLinux,
      reactor_id: "reactor.epoll",
      os_capability_ids: [
        "os.clock.native_highres", "os.native_stub.loader", "os.event_loop.epoll_fd",
        "os.socket.udp", "os.raw_nic.linux_af_packet", "os.capture.pcap_file",
      ],
      hal_capability_ids: ["hal.frame_pool.native"],
      driver_ids: [
        "moonecat.linux_raw_socket.raw_frame", "profinet.rawnet.raw_ethernet", "profinet.rawnet.highres_clock",
        "profinet.udpnet.bsd_udp", "profinet.pcapdump.capture_writer", "moonecat.native.zero_copy_frame_pool",
      ],
      host_os: "linux",
      board_family: "",
      supports_raw_frame: true,
      supports_udp: true,
      supports_pcap_artifact: true,
      supports_frame_pool: true,
      requires_threadx: false,
      requires_bsp: false,
      requires_hardware: true,
      live_validation_locked: true,
      no_live_plan_ready: true,
      live_evidence_present: false,
    },
    {
      id: "target.stm32.threadx.mac_can_uart",
      kind: LinkTargetStm32Threadx,
      profile: @os.ProfileRealEmbedded,
      reactor_id: "reactor.threadx",
      os_capability_ids: [],
      hal_capability_ids: [
        "hal.clock.embedded", "hal.irq.embedded", "hal.dma.embedded", "hal.mac.link_port.embedded",
        "hal.canfd.link_port.embedded", "hal.uart.link_port.embedded", "hal.frame_pool.embedded",
      ],
      driver_ids: [],
      host_os: "embedded",
      board_family: "stm32-threadx",
      supports_raw_frame: true,
      supports_udp: false,
      supports_pcap_artifact: false,
      supports_frame_pool: true,
      requires_threadx: true,
      requires_bsp: true,
      requires_hardware: true,
      live_validation_locked: true,
      no_live_plan_ready: false,
      live_evidence_present: false,
    },
  ]
}

///|
pub fn link_readiness_matrix_trace_fixture(
  seed? : Int = 757,
) -> @trace.TraceLog {
  let log = @trace.TraceLog::new()
  for i, target in link_readiness_targets() {
    log.append(
      @trace.TraceEvent::make(
        event_id=i + 1,
        parent_id=None,
        vtime=@core.VTime::from_ns(Int64::from_int(i + 1) * 2_000L),
        clock_domain="driver-readiness",
        raw_ns=Int64::from_int(i + 1) * 2_000L,
        node_id="lockwire-driver",
        medium_id="multi-target-link-readiness",
        channel_id=Some(@core.ChannelId(i + 1)),
        direction=@trace.Meta,
        payload_digest=Some(target.digest_code()),
        rng_step=i + 1,
        seed~,
        backend=@core.Replay,
        label="driver.readiness." + target.kind.label() + "." + target.id,
      ),
    )
  }
  log
}

///|
pub fn link_readiness_matrix_report(
  seed? : Int = 757,
) -> LinkReadinessMatrixReport {
  let targets = link_readiness_targets()
  let driver_catalog = native_link_driver_catalog()
  let hal_catalog = @hal.hal_capability_catalog()
  let os_catalog = @os.os_capability_catalog()
  let reactor_catalog = @reactor.reactor_backend_catalog()
  let trace = link_readiness_matrix_trace_fixture(seed~)
  let digest = trace.portable_digest(seed~)
  {
    target_count: targets.length(),
    windows_target_count: count_target_kind(targets, LinkTargetWindowsNpcap),
    linux_target_count: count_target_kind(targets, LinkTargetLinuxRaw),
    stm32_threadx_target_count: count_target_kind(
      targets,
      LinkTargetStm32Threadx,
    ),
    host_native_target_count: count_targets_where(targets, fn(target) {
      !target.is_embedded()
    }),
    embedded_target_count: count_targets_where(targets, fn(target) {
      target.is_embedded()
    }),
    raw_frame_target_count: count_targets_where(targets, fn(target) {
      target.supports_raw_frame
    }),
    udp_target_count: count_targets_where(targets, fn(target) {
      target.supports_udp
    }),
    pcap_artifact_target_count: count_targets_where(targets, fn(target) {
      target.supports_pcap_artifact
    }),
    frame_pool_target_count: count_targets_where(targets, fn(target) {
      target.supports_frame_pool
    }),
    live_locked_count: count_targets_where(targets, fn(target) {
      target.live_validation_locked
    }),
    no_live_plan_ready_count: count_targets_where(targets, fn(target) {
      target.no_live_plan_ready
    }),
    embedded_driver_gap_count: count_targets_where(targets, fn(target) {
      target.is_embedded() && target.driver_count() == 0 && target.requires_bsp
    }),
    driver_reference_failure_count: count_targets_where(targets, fn(target) {
      !target.references_drivers(driver_catalog)
    }),
    hal_reference_failure_count: count_targets_where(targets, fn(target) {
      !target.references_hal(hal_catalog)
    }),
    os_reference_failure_count: count_targets_where(targets, fn(target) {
      !target.references_os(os_catalog)
    }),
    reactor_reference_failure_count: count_targets_where(targets, fn(target) {
      !target.references_reactor(reactor_catalog)
    }),
    live_evidence_present: targets.any(fn(target) {
      target.live_evidence_present
    }),
    trace_event_count: trace.len(),
    replay_count: replay_count(trace),
    same_seed_stable: digest ==
    link_readiness_matrix_trace_fixture(seed~).portable_digest(seed~),
    digest,
  }
}

///|
pub fn moonecat_link_driver_specs() -> Array[LinkDriverSpec] {
  [
    {
      id: "moonecat.windows_npcap.raw_frame",
      source: MoonEcatHalNative,
      kind: RawEthernetSocket,
      runtime: WindowsNpcap,
      reference_path: "MoonECAT/hal/native/windows_npcap_ffi.mbt",
      operations: ["open", "send", "recv", "close", "list_interfaces"],
      requires_native: true,
      requires_runtime: true,
      has_non_native_fallback: true,
      zero_copy: false,
      live_validation_locked: true,
      protocol_import_free: true,
    },
    {
      id: "moonecat.linux_raw_socket.raw_frame",
      source: MoonEcatHalNative,
      kind: RawEthernetSocket,
      runtime: LinuxRawSocket,
      reference_path: "MoonECAT/hal/native/linux_raw_socket_ffi.mbt",
      operations: ["open", "send", "recv", "close", "list_interfaces"],
      requires_native: true,
      requires_runtime: true,
      has_non_native_fallback: true,
      zero_copy: false,
      live_validation_locked: true,
      protocol_import_free: true,
    },
    {
      id: "moonecat.native.zero_copy_frame_pool",
      source: MoonEcatHalNative,
      kind: ZeroCopyFramePool,
      runtime: MoonEcatFramePool,
      reference_path: "MoonECAT/hal/native/native_zero_copy_nic.mbt",
      operations: [
        "acquire_tx", "tx_buffer", "submit", "recv", "rx_buffer", "release", "close",
      ],
      requires_native: true,
      requires_runtime: true,
      has_non_native_fallback: true,
      zero_copy: true,
      live_validation_locked: true,
      protocol_import_free: true,
    },
  ]
}

///|
pub fn profinet_link_driver_specs() -> Array[LinkDriverSpec] {
  [
    {
      id: "profinet.rawnet.raw_ethernet",
      source: ProfinetRawNet,
      kind: RawEthernetSocket,
      runtime: LinuxRawSocket,
      reference_path: "profinet_master/ffi/rawnet/rawnet.mbt",
      operations: [
        "open", "send", "receive", "local_mac", "set_nonblock", "list_interfaces",
      ],
      requires_native: true,
      requires_runtime: true,
      has_non_native_fallback: false,
      zero_copy: false,
      live_validation_locked: true,
      protocol_import_free: true,
    },
    {
      id: "profinet.rawnet.highres_clock",
      source: ProfinetRawNet,
      kind: HighResolutionClock,
      runtime: NativeClock,
      reference_path: "profinet_master/ffi/rawnet/rawnet.mbt",
      operations: [
        "monotonic_millis", "highres_micros", "sleep_until_micros", "set_realtime_process_priority",
        "set_process_affinity_mask", "set_thread_affinity_mask",
      ],
      requires_native: true,
      requires_runtime: true,
      has_non_native_fallback: false,
      zero_copy: false,
      live_validation_locked: true,
      protocol_import_free: true,
    },
    {
      id: "profinet.udpnet.winsock_udp",
      source: ProfinetUdpNet,
      kind: UdpDatagramSocket,
      runtime: WinsockUdp,
      reference_path: "profinet_master/ffi/udpnet/udpnet.mbt",
      operations: ["open", "send_to", "receive", "close"],
      requires_native: true,
      requires_runtime: true,
      has_non_native_fallback: false,
      zero_copy: false,
      live_validation_locked: true,
      protocol_import_free: true,
    },
    {
      id: "profinet.udpnet.bsd_udp",
      source: ProfinetUdpNet,
      kind: UdpDatagramSocket,
      runtime: BsdUdpSocket,
      reference_path: "profinet_master/ffi/udpnet/udpnet.mbt",
      operations: ["open", "send_to", "receive", "close"],
      requires_native: true,
      requires_runtime: true,
      has_non_native_fallback: false,
      zero_copy: false,
      live_validation_locked: true,
      protocol_import_free: true,
    },
    {
      id: "profinet.pcapdump.capture_writer",
      source: ProfinetPcapDump,
      kind: PacketCaptureWriter,
      runtime: PcapFileWriter,
      reference_path: "profinet_master/ffi/pcapdump/pcapdump.mbt",
      operations: ["open", "write_packet", "write_packet_at", "close"],
      requires_native: true,
      requires_runtime: true,
      has_non_native_fallback: false,
      zero_copy: false,
      live_validation_locked: true,
      protocol_import_free: true,
    },
  ]
}

///|
pub fn native_link_driver_catalog() -> Array[LinkDriverSpec] {
  let catalog : Array[LinkDriverSpec] = []
  for spec in moonecat_link_driver_specs() {
    catalog.push(spec)
  }
  for spec in profinet_link_driver_specs() {
    catalog.push(spec)
  }
  catalog
}

///|
pub fn native_link_driver_trace_fixture(seed? : Int = 701) -> @trace.TraceLog {
  let log = @trace.TraceLog::new()
  for i, spec in native_link_driver_catalog() {
    log.append(
      @trace.TraceEvent::make(
        event_id=i + 1,
        parent_id=None,
        vtime=@core.VTime::from_ns(Int64::from_int(i + 1) * 100L),
        clock_domain="driver-catalog",
        raw_ns=Int64::from_int(i + 1) * 100L,
        node_id="lockwire-driver",
        medium_id="link-driver-layer",
        channel_id=Some(@core.ChannelId(i + 1)),
        direction=@trace.Meta,
        payload_digest=Some(spec.digest_code()),
        rng_step=i + 1,
        seed~,
        backend=@core.Replay,
        label=spec.catalog_label(),
      ),
    )
  }
  log
}

///|
pub fn provider_master_harness_trace_fixture(
  harnesses : ArrayView[LinkMasterHarnessDescriptor],
  seed? : Int = 701,
) -> @trace.TraceLog {
  let log = @trace.TraceLog::new()
  for i, harness in harnesses {
    log.append(
      @trace.TraceEvent::make(
        event_id=i + 1,
        parent_id=None,
        vtime=@core.VTime::from_ns(Int64::from_int(i + 1) * 1_000L),
        clock_domain="driver-catalog",
        raw_ns=Int64::from_int(i + 1) * 1_000L,
        node_id="minimal-master-harness",
        medium_id="link-driver-layer",
        channel_id=Some(@core.ChannelId(i + 1)),
        direction=@trace.Meta,
        payload_digest=Some(harness.digest_code()),
        rng_step=i + 1,
        seed~,
        backend=@core.Replay,
        label="driver.master.provider." +
          harness.provider_id +
          "." +
          harness.stack_id +
          "." +
          harness.id,
      ),
    )
  }
  log
}

///|
pub fn validate_master_harness_descriptors(
  harnesses : ArrayView[LinkMasterHarnessDescriptor],
  seed? : Int = 701,
) -> LinkMasterHarnessValidationReport {
  let catalog = native_link_driver_catalog()
  let trace = provider_master_harness_trace_fixture(harnesses, seed~)
  let digest = trace.portable_digest(seed~)
  {
    descriptor_count: harnesses.length(),
    passing_descriptor_count: count_passing_master_harness_descriptors(
      harnesses, catalog,
    ),
    provider_owned_descriptor_count: count_provider_owned_harnesses(harnesses),
    lockwire_protocol_semantics_owned: harnesses.any(fn(harness) {
      harness.lockwire_owns_protocol_semantics
    }),
    trace_event_count: trace.len(),
    replay_count: replay_count(trace),
    same_seed_stable: digest ==
    provider_master_harness_trace_fixture(harnesses, seed~).portable_digest(
      seed~,
    ),
    digest,
  }
}

///|
pub fn native_link_driver_merge_report(
  seed? : Int = 701,
) -> LinkDriverMergeReport {
  let catalog = native_link_driver_catalog()
  let trace = native_link_driver_trace_fixture(seed~)
  let digest = trace.portable_digest(seed~)
  {
    catalog_count: catalog.length(),
    raw_ethernet_count: count_kind(catalog, RawEthernetSocket),
    udp_datagram_count: count_kind(catalog, UdpDatagramSocket),
    pcap_count: count_kind(catalog, PacketCaptureWriter),
    zero_copy_count: count_kind(catalog, ZeroCopyFramePool),
    native_gate_count: count_native_gates(catalog),
    protocol_import_free: catalog.all(fn(spec) { spec.protocol_import_free }),
    live_adapter_evidence: false,
    provider_master_harness_count: 0,
    lockwire_builtin_master_harness_count: 0,
    lockwire_protocol_semantics_owned: false,
    trace_event_count: trace.len(),
    replay_count: replay_count(trace),
    same_seed_stable: digest ==
    native_link_driver_trace_fixture(seed~).portable_digest(seed~),
    digest,
  }
}

///|
fn count_passing_master_harness_descriptors(
  harnesses : ArrayView[LinkMasterHarnessDescriptor],
  catalog : ArrayView[LinkDriverSpec],
) -> Int {
  let mut count = 0
  for harness in harnesses {
    if harness.passes_against(catalog) {
      count += 1
    }
  }
  count
}

///|
fn count_provider_owned_harnesses(
  harnesses : ArrayView[LinkMasterHarnessDescriptor],
) -> Int {
  let mut count = 0
  for harness in harnesses {
    if harness.provider_owned_delivery {
      count += 1
    }
  }
  count
}

///|
fn count_target_kind(
  targets : ArrayView[LinkReadinessTarget],
  kind : LinkReadinessTargetKind,
) -> Int {
  let mut count = 0
  for target in targets {
    if target.kind == kind {
      count += 1
    }
  }
  count
}

///|
fn count_targets_where(
  targets : ArrayView[LinkReadinessTarget],
  predicate : (LinkReadinessTarget) -> Bool,
) -> Int {
  let mut count = 0
  for target in targets {
    if predicate(target) {
      count += 1
    }
  }
  count
}

///|
fn catalog_has_driver(
  catalog : ArrayView[LinkDriverSpec],
  driver_id : String,
) -> Bool {
  catalog.any(fn(spec) { spec.id == driver_id })
}

///|
fn catalog_has_hal(
  catalog : ArrayView[@hal.HalCapabilityDescriptor],
  hal_id : String,
) -> Bool {
  catalog.any(fn(spec) { spec.id == hal_id })
}

///|
fn catalog_has_os(
  catalog : ArrayView[@os.OsCapabilityDescriptor],
  os_id : String,
) -> Bool {
  catalog.any(fn(spec) { spec.id == os_id })
}

///|
fn count_kind(
  catalog : ArrayView[LinkDriverSpec],
  kind : LinkDriverKind,
) -> Int {
  let mut count = 0
  for spec in catalog {
    if spec.kind == kind {
      count += 1
    }
  }
  count
}

///|
fn count_native_gates(catalog : ArrayView[LinkDriverSpec]) -> Int {
  let mut count = 0
  for spec in catalog {
    if spec.is_native_gate() && spec.live_validation_locked {
      count += 1
    }
  }
  count
}

///|
fn replay_count(log : @trace.TraceLog) -> Int {
  let replay = @trace.Replay::from_log(log)
  let mut count = 0
  while !replay.is_exhausted() {
    ignore(replay.next_event())
    count += 1
  }
  count
}

///|
fn LinkDriverSpec::digest_code(self : LinkDriverSpec) -> Int {
  string_digest(self.id) +
  self.source.code() * 1_000 +
  self.kind.code() * 10_000 +
  self.runtime.code() * 100_000
}

///|
fn LinkMasterHarnessDescriptor::digest_code(
  self : LinkMasterHarnessDescriptor,
) -> Int {
  string_digest(self.id) +
  string_digest(self.provider_id) * 3 +
  string_digest(self.stack_id) * 7 +
  self.driver_count() * 10_000
}

///|
fn LinkReadinessTarget::digest_code(self : LinkReadinessTarget) -> Int {
  string_digest(self.id) +
  self.kind.code() * 1_000 +
  self.driver_count() * 10_000 +
  self.hal_count() * 100_000
}

///|
fn string_digest(value : String) -> Int {
  let mut digest = 17
  for c in value {
    digest = digest * 31 + c.to_int()
  }
  digest
}

///|
fn LinkReadinessTargetKind::code(self : LinkReadinessTargetKind) -> Int {
  match self {
    LinkTargetWindowsNpcap => 1
    LinkTargetLinuxRaw => 2
    LinkTargetStm32Threadx => 3
  }
}

///|
fn LinkDriverSource::code(self : LinkDriverSource) -> Int {
  match self {
    MoonEcatHalNative => 1
    ProfinetRawNet => 2
    ProfinetUdpNet => 3
    ProfinetPcapDump => 4
  }
}

///|
fn LinkDriverKind::code(self : LinkDriverKind) -> Int {
  match self {
    RawEthernetSocket => 1
    UdpDatagramSocket => 2
    PacketCaptureWriter => 3
    InterfaceListing => 4
    HighResolutionClock => 5
    ZeroCopyFramePool => 6
  }
}

///|
fn LinkDriverRuntime::code(self : LinkDriverRuntime) -> Int {
  match self {
    WindowsNpcap => 1
    LinuxRawSocket => 2
    WinsockUdp => 3
    BsdUdpSocket => 4
    PcapFileWriter => 5
    MoonEcatFramePool => 6
    NativeClock => 7
  }
}