local function RequireApi(name, value)
  if value == nil then
    value = rawget(_G, name)
  end
  if value == nil then
    local api = rawget(_G, "LIDCOUNCIL_API")
    if type(api) == "table" then
      value = api[name]
    end
  end
  if value == nil then
    error("LidCouncil missing API: " .. tostring(name))
  end
  return value
end

local EnsureApiRegistry = rawget(_G, "LIDCOUNCIL_EnsureApiRegistry")
local API, INTERNAL_API
if type(EnsureApiRegistry) == "function" then
  API, INTERNAL_API = EnsureApiRegistry()
else
  API = rawget(_G, "LIDCOUNCIL_API")
  if type(API) ~= "table" then
    API = {}
    _G.LIDCOUNCIL_API = API
  end
  if type(API.__internal) ~= "table" then
    API.__internal = {}
  end
  INTERNAL_API = API.__internal
end

local function ResolveOptionalApiFunction(name)
  local api = rawget(_G, "LIDCOUNCIL_API")
  if type(api) == "table" and type(api[name]) == "function" then
    return api[name]
  end
  local fallback = rawget(_G, name)
  if type(fallback) == "function" then
    return fallback
  end
  return nil
end

local function PublishApi(name, value, opts)
  API[name] = value
  if type(opts) == "table" and opts.global == false then
    _G[name] = nil
    return
  end
  _G[name] = value
end

local RAID_TRACE_COMM_OPCODES = {
  START = true, IACK = true, BEGIN = true, JOIN = true, JACK = true,
  DECLINE = true, LEAVE = true, STOP = true, STOP_ACK = true,
  PSTATE = true, PSYNC_START = true, PSYNC_END = true, PSYNC_ACK = true,
  PDELTA = true, PDELTA_ACK = true, PDELTA_NACK = true,
  CHOICE = true, RCHOICE = true, RCHOICE_ACK = true,
  ITEM_REPORT = true, ITEM_OPEN = true, ITEM_ACK = true,
  AWARD = true, UNASSIGN = true, TRADE = true, VOTE = true,
  BSYNC_START = true, BSYNC_END = true, BSYNC_ACK = true,
}

local function RecordRaidTestTraceEvent(eventName, detail, fields)
  local recorder = INTERNAL_API.LIDCOUNCIL_RecordRaidTestTraceEvent_Impl
  if type(recorder) ~= "function" then return false end
  local ok, recorded = pcall(recorder, eventName, detail, fields)
  return ok and recorded == true
end

local function BeginRaidTestTracePhase(phaseName, detail, fields)
  local beginPhase = INTERNAL_API.LIDCOUNCIL_BeginRaidTestTracePhase_Impl
  if type(beginPhase) ~= "function" then return nil end
  local ok, token = pcall(beginPhase, phaseName, detail, fields)
  return ok and token or nil
end

local function EndRaidTestTracePhase(token, detail, fields)
  local endPhase = INTERNAL_API.LIDCOUNCIL_EndRaidTestTracePhase_Impl
  if type(endPhase) ~= "function" or type(token) ~= "table" then return false end
  local ok, ended = pcall(endPhase, token, detail, fields)
  return ok and ended == true
end

local commApi = {
  RootDB = RequireApi("LIDCOUNCIL_RootDB", _G.LIDCOUNCIL_RootDB),
  Print = RequireApi("LIDCOUNCIL_Print", _G.LIDCOUNCIL_Print),
  GetCharacterKey = RequireApi("LIDCOUNCIL_GetCharacterKey", _G.LIDCOUNCIL_GetCharacterKey),
  GetEnglishClassAndSpec = RequireApi("LIDCOUNCIL_GetEnglishClassAndSpec", nil),
  AddCharacterToList = RequireApi("LIDCOUNCIL_AddCharacterToList", _G.LIDCOUNCIL_AddCharacterToList),
  StartLootSession = RequireApi("LIDCOUNCIL_StartLootSession", _G.LIDCOUNCIL_StartLootSession),
  ActivateLootSession = RequireApi("LIDCOUNCIL_ActivateLootSession", _G.LIDCOUNCIL_ActivateLootSession),
  GetActiveLootSession = RequireApi("LIDCOUNCIL_GetActiveLootSession", _G.LIDCOUNCIL_GetActiveLootSession),
  StopLootSession = RequireApi("LIDCOUNCIL_StopLootSession", _G.LIDCOUNCIL_StopLootSession),
  JoinLootSession = RequireApi("LIDCOUNCIL_JoinLootSession", _G.LIDCOUNCIL_JoinLootSession),
  UpsertLootSessionMember = RequireApi("LIDCOUNCIL_UpsertLootSessionMember", _G.LIDCOUNCIL_UpsertLootSessionMember),
  RemoveLootSessionMember = RequireApi("LIDCOUNCIL_RemoveLootSessionMember", _G.LIDCOUNCIL_RemoveLootSessionMember),
  FinishLootSession = RequireApi("LIDCOUNCIL_FinishLootSession", _G.LIDCOUNCIL_FinishLootSession),
  GetLootProfile = RequireApi("LIDCOUNCIL_GetLootProfile", _G.LIDCOUNCIL_GetLootProfile),
  GetLootProfileRole = RequireApi("LIDCOUNCIL_GetLootProfileRole", _G.LIDCOUNCIL_GetLootProfileRole),
  GetLootProfileMaster = RequireApi("LIDCOUNCIL_GetLootProfileMaster", _G.LIDCOUNCIL_GetLootProfileMaster),
  SyncLootProfilePermissionState = RequireApi("LIDCOUNCIL_SyncLootProfilePermissionState", _G.LIDCOUNCIL_SyncLootProfilePermissionState),
  EnsureLootProfileMemberRole = RequireApi("LIDCOUNCIL_EnsureLootProfileMemberRole", _G.LIDCOUNCIL_EnsureLootProfileMemberRole),
  GetLocalAutoPassEnabled = RequireApi("LIDCOUNCIL_GetLocalAutoPassEnabled", _G.LIDCOUNCIL_GetLocalAutoPassEnabled),
  SetLocalAutoPassEnabled = RequireApi("LIDCOUNCIL_SetLocalAutoPassEnabled", _G.LIDCOUNCIL_SetLocalAutoPassEnabled),
  GetLootProfileId = RequireApi("LIDCOUNCIL_GetLootProfileId", _G.LIDCOUNCIL_GetLootProfileId),
  FindLootProfileNameById = RequireApi("LIDCOUNCIL_FindLootProfileNameById", _G.LIDCOUNCIL_FindLootProfileNameById),
  ExportLootProfileSnapshot = RequireApi("LIDCOUNCIL_ExportLootProfileSnapshot", _G.LIDCOUNCIL_ExportLootProfileSnapshot),
  ImportLootProfileSnapshot = RequireApi("LIDCOUNCIL_ImportLootProfileSnapshot", _G.LIDCOUNCIL_ImportLootProfileSnapshot),
  PreviewLootProfileSnapshot = RequireApi("LIDCOUNCIL_PreviewLootProfileSnapshot", _G.LIDCOUNCIL_PreviewLootProfileSnapshot),
  BuildLootProfileSnapshotDiff = RequireApi("LIDCOUNCIL_BuildLootProfileSnapshotDiff", _G.LIDCOUNCIL_BuildLootProfileSnapshotDiff),
  ExportLootProfileDomainSnapshot = RequireApi("LIDCOUNCIL_ExportLootProfileDomainSnapshot", _G.LIDCOUNCIL_ExportLootProfileDomainSnapshot),
  ImportLootProfileDomainSnapshot = RequireApi("LIDCOUNCIL_ImportLootProfileDomainSnapshot", _G.LIDCOUNCIL_ImportLootProfileDomainSnapshot),
  PreviewLootProfileDomainSnapshot = RequireApi("LIDCOUNCIL_PreviewLootProfileDomainSnapshot", _G.LIDCOUNCIL_PreviewLootProfileDomainSnapshot),
  BuildLootProfileDomainSnapshotDiff = RequireApi("LIDCOUNCIL_BuildLootProfileDomainSnapshotDiff", _G.LIDCOUNCIL_BuildLootProfileDomainSnapshotDiff),
  ExportLootProfileSubdomainSnapshot = RequireApi("LIDCOUNCIL_ExportLootProfileSubdomainSnapshot", _G.LIDCOUNCIL_ExportLootProfileSubdomainSnapshot),
  ImportLootProfileSubdomainSnapshot = RequireApi("LIDCOUNCIL_ImportLootProfileSubdomainSnapshot", _G.LIDCOUNCIL_ImportLootProfileSubdomainSnapshot),
  PreviewLootProfileSubdomainSnapshot = RequireApi("LIDCOUNCIL_PreviewLootProfileSubdomainSnapshot", _G.LIDCOUNCIL_PreviewLootProfileSubdomainSnapshot),
  BuildLootProfileSubdomainSnapshotDiff = RequireApi("LIDCOUNCIL_BuildLootProfileSubdomainSnapshotDiff", _G.LIDCOUNCIL_BuildLootProfileSubdomainSnapshotDiff),
  ExportLootProfileSubdomainPatch = RequireApi("LIDCOUNCIL_ExportLootProfileSubdomainPatch", _G.LIDCOUNCIL_ExportLootProfileSubdomainPatch),
  ImportLootProfileSubdomainPatch = RequireApi("LIDCOUNCIL_ImportLootProfileSubdomainPatch", _G.LIDCOUNCIL_ImportLootProfileSubdomainPatch),
  PreviewLootProfileSubdomainPatch = RequireApi("LIDCOUNCIL_PreviewLootProfileSubdomainPatch", _G.LIDCOUNCIL_PreviewLootProfileSubdomainPatch),
  BuildLootProfileSubdomainPatchDiff = RequireApi("LIDCOUNCIL_BuildLootProfileSubdomainPatchDiff", _G.LIDCOUNCIL_BuildLootProfileSubdomainPatchDiff),
  ExportLootProfileConflictRowPatch = RequireApi("LIDCOUNCIL_ExportLootProfileConflictRowPatch", _G.LIDCOUNCIL_ExportLootProfileConflictRowPatch),
  ImportLootProfileConflictRowPatch = RequireApi("LIDCOUNCIL_ImportLootProfileConflictRowPatch", _G.LIDCOUNCIL_ImportLootProfileConflictRowPatch),
  PreviewLootProfileConflictRowPatch = RequireApi("LIDCOUNCIL_PreviewLootProfileConflictRowPatch", _G.LIDCOUNCIL_PreviewLootProfileConflictRowPatch),
  BuildLootProfileConflictRowPatchDiff = RequireApi("LIDCOUNCIL_BuildLootProfileConflictRowPatchDiff", _G.LIDCOUNCIL_BuildLootProfileConflictRowPatchDiff),
  BuildLootProfileTransferConflictPreview = RequireApi("LIDCOUNCIL_BuildLootProfileTransferConflictPreview", _G.LIDCOUNCIL_BuildLootProfileTransferConflictPreview),
  ApplyLootProfileTransferConflictResolution = RequireApi("LIDCOUNCIL_ApplyLootProfileTransferConflictResolution", _G.LIDCOUNCIL_ApplyLootProfileTransferConflictResolution),
  CalculateStableChecksum = RequireApi("LIDCOUNCIL_CalculateStableChecksum", _G.LIDCOUNCIL_CalculateStableChecksum),
  BuildLootProfileCurrentSessionChecksumSource = RequireApi("LIDCOUNCIL_BuildLootProfileCurrentSessionChecksumSource", nil),
  BuildLootProfileLiveBoardSnapshotChecksumSource = RequireApi("LIDCOUNCIL_BuildLootProfileLiveBoardSnapshotChecksumSource", nil),
  BuildLootProfileLiveBoardChecksumSource = RequireApi("LIDCOUNCIL_BuildLootProfileLiveBoardChecksumSource", nil),
  ExportLootProfileSubdomainPatchManifest = RequireApi("LIDCOUNCIL_ExportLootProfileSubdomainPatchManifest", _G.LIDCOUNCIL_ExportLootProfileSubdomainPatchManifest),
  PreviewLootProfileSubdomainPatchManifest = RequireApi("LIDCOUNCIL_PreviewLootProfileSubdomainPatchManifest", _G.LIDCOUNCIL_PreviewLootProfileSubdomainPatchManifest),
  GetLootProfileSubchecksumManifest = RequireApi("LIDCOUNCIL_GetLootProfileSubchecksumManifest", _G.LIDCOUNCIL_GetLootProfileSubchecksumManifest),
  NormalizeLootProfileSubdomainList = RequireApi("LIDCOUNCIL_NormalizeLootProfileSubdomainList", _G.LIDCOUNCIL_NormalizeLootProfileSubdomainList),
  CloneLootProfileSubdomainList = RequireApi("LIDCOUNCIL_CloneLootProfileSubdomainList", _G.LIDCOUNCIL_CloneLootProfileSubdomainList),
  FilterLootProfilePatchCapableSubdomains = RequireApi("LIDCOUNCIL_FilterLootProfilePatchCapableSubdomains", _G.LIDCOUNCIL_FilterLootProfilePatchCapableSubdomains),
  GetLootProfileSubdomainKeysForDomain = RequireApi("LIDCOUNCIL_GetLootProfileSubdomainKeysForDomain", _G.LIDCOUNCIL_GetLootProfileSubdomainKeysForDomain),
  GetLootProfileSubdomainLabel = RequireApi("LIDCOUNCIL_GetLootProfileSubdomainLabel", _G.LIDCOUNCIL_GetLootProfileSubdomainLabel),
  GetLootProfileSubdomainParentDomain = RequireApi("LIDCOUNCIL_GetLootProfileSubdomainParentDomain", _G.LIDCOUNCIL_GetLootProfileSubdomainParentDomain),
  ResolveLootProfileDomainsForSubdomains = RequireApi("LIDCOUNCIL_ResolveLootProfileDomainsForSubdomains", _G.LIDCOUNCIL_ResolveLootProfileDomainsForSubdomains),
  ValidateSimulationVoteExclusion = RequireApi("LIDCOUNCIL_ValidateSimulationVoteExclusion", nil),
  GetLootProfileRevisionSummary = RequireApi("LIDCOUNCIL_GetLootProfileRevisionSummary", _G.LIDCOUNCIL_GetLootProfileRevisionSummary),
  TouchLootProfileDomain = RequireApi("LIDCOUNCIL_TouchLootProfileDomain", _G.LIDCOUNCIL_TouchLootProfileDomain),
  ApplyIncomingLootProfileDelta = RequireApi("LIDCOUNCIL_ApplyIncomingLootProfileDelta", _G.LIDCOUNCIL_ApplyIncomingLootProfileDelta),
}

local COMM_PREFIX = "LIDLOOT1"
local COMM_PROTOCOL_VERSION = 7
local COMM_PROTOCOL_CONTRACT_VERSION = 7
local prefixRegistered = false
local COMM_LIMITS = {
  DEFAULT_PROFILE_SNAPSHOT_CHUNK_SIZE = 120,
  MIN_PROFILE_SNAPSHOT_CHUNK_SIZE = 80,
  MAX_PROFILE_SNAPSHOT_CHUNK_SIZE = 190,
  SAFE_PAYLOAD_BYTES = 240,
  WARNING_THROTTLE_SECONDS = 5,
  DEFAULT_OUTBOUND_INTERVAL_SECONDS = 0.12,
  MIN_OUTBOUND_INTERVAL_SECONDS = 0.08,
  MAX_OUTBOUND_INTERVAL_SECONDS = 0.25,
  PROFILE_SYNC_IDLE_INTERVAL_SECONDS = 0.06,
  RECENT_REQUEST_SUPPRESSION_SECONDS = 1.5,
  -- Receipts are sent immediately after transport or staged combat application.
  -- Recover missing acknowledgements promptly without timing out active transfer work.
  PROFILE_ACK_TIMEOUT_SECONDS = 60,
  COMPLETED_TRANSFER_RETENTION_SECONDS = 90,
  TERMINAL_TRANSFER_RETENTION_SECONDS = 300,
}
local COMM_SAFE_PAYLOAD_LIMIT = COMM_LIMITS.SAFE_PAYLOAD_BYTES
local COMM_PROTOCOL_FIELD_CONTRACTS = {
  START = { minimumFields = 7, category = "session", owner = "session_flow" },
  IACK = { minimumFields = 5, category = "session", owner = "session_flow" },
  BEGIN = { minimumFields = 7, category = "session", owner = "session_flow" },
  JOIN = { minimumFields = 18, category = "session", owner = "session_flow" },
  JACK = { minimumFields = 9, category = "session", owner = "session_flow" },
  -- MEMBER carries the host-authoritative roster plus the seven-state sync matrix.
  -- Keep its expanded ceiling local to this opcode; unrelated messages retain the
  -- stricter global field limit.
  MEMBER = { minimumFields = 30, maximumFields = 45, category = "session", owner = "session_flow" },
  LOCALAP = { minimumFields = 5, category = "session", owner = "session_flow" },
  APNOTICE = { minimumFields = 5, category = "session", owner = "session_flow" },
  DECLINE = { minimumFields = 4, category = "session", owner = "session_flow" },
  LEAVE = { minimumFields = 5, category = "session", owner = "session_flow" },
  PSTATE = { minimumFields = 19, category = "session", owner = "session_flow" },
  PSTATE_PART = { minimumFields = 9, category = "session", owner = "session_flow" },
  STOP = { minimumFields = 5, category = "session", owner = "session_flow" },
  STOP_ACK = { minimumFields = 6, category = "session", owner = "session_flow" },
  PSYNC_START = { minimumFields = 6, category = "profile_snapshot", owner = "profile_sync" },
  PSYNC_REQ = { minimumFields = 3, category = "profile_snapshot", owner = "profile_sync" },
  PSYNC_CHUNK = { minimumFields = 4, category = "profile_snapshot", owner = "profile_sync" },
  PSYNC_END = { minimumFields = 2, category = "profile_snapshot", owner = "profile_sync" },
  PSYNC_ACK = { minimumFields = 17, category = "profile_snapshot", owner = "profile_sync" },
  PSUB_REQ = { minimumFields = 5, category = "profile_checksum", owner = "profile_sync" },
  PSUB_STATE = { minimumFields = 7, category = "profile_checksum", owner = "profile_sync" },
  PSUBPATCH_REQ = { minimumFields = 5, category = "profile_checksum", owner = "profile_sync" },
  PSUBPATCH_STATE = { minimumFields = 8, category = "profile_checksum", owner = "profile_sync" },
  PDELTA_REQ = { minimumFields = 16, category = "profile_delta", owner = "session_flow" },
  PDELTA = { minimumFields = 16, category = "profile_delta", owner = "session_flow" },
  PDELTA_ACK = { minimumFields = 17, category = "profile_delta", owner = "session_flow" },
  PDELTA_NACK = { minimumFields = 7, category = "profile_delta", owner = "session_flow" },
  CHOICE = { minimumFields = 11, category = "loot_runtime", owner = "loot_runtime" },
  RCHOICE = { minimumFields = 11, category = "loot_runtime", owner = "loot_runtime" },
  RCHOICE_ACK = { minimumFields = 7, maximumFields = 7, category = "loot_runtime", owner = "loot_runtime" },
  ITEM_REPORT = { minimumFields = 12, category = "loot_runtime", owner = "loot_runtime" },
  ITEM_OPEN = { minimumFields = 13, maximumFields = 15, category = "loot_runtime", owner = "loot_runtime" },
  ITEM_ACK = { minimumFields = 7, maximumFields = 7, category = "loot_runtime", owner = "loot_runtime" },
  AWARD = { minimumFields = 10, category = "loot_runtime", owner = "loot_runtime" },
  UNASSIGN = { minimumFields = 5, category = "loot_runtime", owner = "loot_runtime" },
  TRADE = { minimumFields = 7, category = "loot_runtime", owner = "loot_runtime" },
  VOTE = { minimumFields = 8, category = "loot_runtime", owner = "loot_runtime" },
  LL_ADD_REQ = { minimumFields = 9, category = "loot_ledger", owner = "loot_runtime" },
  LL_ADD = { minimumFields = 10, category = "loot_ledger", owner = "loot_runtime" },
  LL_DEL_REQ = { minimumFields = 7, category = "loot_ledger", owner = "loot_runtime" },
  LL_DEL = { minimumFields = 6, category = "loot_ledger", owner = "loot_runtime" },
  LL_MA_REQ = { minimumFields = 8, category = "loot_ledger", owner = "loot_runtime" },
  LL_MA = { minimumFields = 8, category = "loot_ledger", owner = "loot_runtime" },
  LL_NOTE_REQ = { minimumFields = 7, category = "loot_ledger", owner = "loot_runtime" },
  LL_NOTE = { minimumFields = 7, category = "loot_ledger", owner = "loot_runtime" },
  LL_CHAR_DEL_REQ = { minimumFields = 6, category = "loot_ledger", owner = "loot_runtime" },
  LL_CHAR_DEL = { minimumFields = 6, category = "loot_ledger", owner = "loot_runtime" },
  BSYNC_START = { minimumFields = 7, category = "board_sync", owner = "loot_runtime" },
  BSYNC_ITEM = { minimumFields = 18, category = "board_sync", owner = "loot_runtime" },
  BSYNC_SEL = { minimumFields = 17, category = "board_sync", owner = "loot_runtime" },
  BSYNC_VOTE = { minimumFields = 8, category = "board_sync", owner = "loot_runtime" },
  BSYNC_END = { minimumFields = 5, category = "board_sync", owner = "loot_runtime" },
  BSYNC_MISS = { minimumFields = 7, category = "board_sync", owner = "loot_runtime" },
  BSYNC_ACK = { minimumFields = 10, category = "board_sync", owner = "loot_runtime" },
}
local recentCommWarnings = {}
local outboundCommQueue = {}
local outboundCommQueueRunning = false
local outboundCommFlushState = {
  token = 0,
  nextAt = 0,
}
local outboundCommStats = {
  queuedTotal = 0,
  coalescedTotal = 0,
  attemptedTotal = 0,
  sentTotal = 0,
  throttledTotal = 0,
  failedTotal = 0,
  bytesAttempted = 0,
  bytesSent = 0,
  byLane = {},
  opcodeTelemetry = {
    byOpcode = {},
    other = {},
    maxTrackedOpcodes = 48,
  },
  opcodePressureThresholds = {
    queuedNow = 12,
    throttled = 3,
    failed = 2,
    bytesSent = 24576,
    maxItems = 3,
  },
  lanePressureThresholds = {
    live = { queuedNow = 8, throttled = 2, failed = 2, bytesSent = 16384 },
    bootstrap = { queuedNow = 12, throttled = 3, failed = 2, bytesSent = 32768 },
    archive = { queuedNow = 24, throttled = 4, failed = 2, bytesSent = 65536 },
    stats = { queuedNow = 16, throttled = 4, failed = 2, bytesSent = 32768 },
    control = { queuedNow = 8, throttled = 2, failed = 2, bytesSent = 16384 },
    maxItems = 3,
  },
  memberTelemetry = {
    byMember = {},
    group = {},
    other = {},
    maxTrackedMembers = 24,
  },
  sessionTelemetryBaseline = nil,
  activeProfileSyncQueueSessionId = "",
  staleSessionBoundPrunedTotal = 0,
  lastStaleSessionBoundPrunedAt = 0,
  lastQueuedAt = 0,
  lastAttemptAt = 0,
  lastSentAt = 0,
  lastThrottleAt = 0,
  lastFailureAt = 0,
  lastFailureReason = "",
  timerFallbackTotal = 0,
  lastTimerFallbackAt = 0,
  lastTimerFallbackReason = "",
  maxQueueDepth = 6000,
  maxCriticalQueueOverflow = 64,
  maxFailureRetries = 2,
  maxThrottleRetries = 30,
  globalThrottleNotBeforeAt = 0,
  globalThrottleStreak = 0,
  globalThrottleBaseSeconds = 1.05,
  globalThrottleMaxSeconds = 6,
  lastGlobalThrottleCooldownSeconds = 0,
  lastGlobalThrottleRecoveryIntervalSeconds = 0,
  chatLockdownActive = false,
  chatLockdownStartedAt = 0,
  chatLockdownDeferredTotal = 0,
  lastChatLockdownAt = 0,
  lastChatLockdownReleasedAt = 0,
  archiveYieldSeconds = 0.75,
  archiveYieldPressureCacheSeconds = 0.20,
  archiveYieldPressureCache = {
    at = 0,
    sessionId = "",
    shouldYield = false,
    lane = "",
    severity = "",
  },
  archiveTargetBurstLimit = 2,
  archiveTargetPacing = {
    lastTarget = "",
    consecutiveChunks = 0,
    preemptionsTotal = 0,
    lastPreemptedTarget = "",
    lastPreemptedAt = 0,
  },
  obsoleteProfileQueuePrunedTotal = 0,
  lastObsoleteProfileQueuePrunedAt = 0,
  archivePressureDeferredTotal = 0,
  lastArchivePressureDeferredAt = 0,
  lastArchivePressureDeferredReason = "",
  retriedFailureTotal = 0,
  retriedThrottleTotal = 0,
  terminalFailureTotal = 0,
  profileAckTimeoutTotal = 0,
  profileAckTimeoutTimerFallbackTotal = 0,
  lastProfileAckTimeoutTimerFallbackAt = 0,
  lastProfileAckTimeoutTimerFallbackReason = "",
  lateProfileAckTotal = 0,
  droppedOverflowTotal = 0,
  prefixRegistrationAttempts = 0,
  prefixRegistrationFailures = 0,
  prefixRegistrationActiveFailure = false,
  prefixRegistrationUnavailable = false,
  prefixRegistrationEvidence = "",
  lastPrefixRegistrationSuccessAt = 0,
  lastPrefixRegistrationError = "",
  rejectedProtocolFieldTotal = 0,
  rejectedProtocolMinimumTotal = 0,
  lastRejectedProtocolMinimumKind = "",
  rejectedPayloadTotal = 0,
  lastRejectedPayloadKind = "",
  lastRejectedPayloadReason = "",
  lastRejectedPayloadBytes = 0,
  lastRejectedPayloadAt = 0,
  payloadRejectHistory = {},
  apiFailureTotal = 0,
  throttleExhaustedTotal = 0,
  lastOutboundIssueCategory = "",
  lastOutboundIssueKind = "",
  lastOutboundIssueReason = "",
  lastOutboundIssueBytes = 0,
  lastOutboundIssueAt = 0,
  outboundIssueHistory = {},
  outboundIssueDiagnosticsByScope = {},
  outboundIssueScopeOrder = {},
  performance = {
    metrics = {},
  },
}
local inboundCommTelemetry, inboundCommOps
local inboundRateLimiter
local outboundCommSendWindow = {}
local outboundProfileTransfers = {}
local outboundProfileTransferOrder = {}
local outboundProfileTransferGenerationByScope = {}
local pendingOutboundProfileAckReconciliations = {}
local recentOutboundRequestItems = {}
local PruneRecentOutboundRequestItems
local ShouldSuppressRecentOutboundRequest
local RememberRecentOutboundRequest
local profileSyncHelpers
local flowHelpers
local commProtocolHandlerRegistry
local GetCommProtocolHandlerRegistryStatus
local ProcessPendingOutboundProfileAckReconciliations
local outboundTimerAdapter
local RefreshEditor
local BuildOutboundProfileTransferScopeSignature
local NormalizeProfileSyncTransferLaneText
local GetOutboundCommQueueItemPriority
local profileSyncRuntimeState = {
  sessionId = "",
  profileName = "",
  mode = "idle",
  severity = "info",
  message = "",
  sender = "",
  updatedAt = 0,
  remoteDomains = {},
  localDomains = {},
  detailDiff = nil,
  recentRosterEvents = {},
}
local PROFILE_SYNC_ROSTER_EVENT_LIMIT = 6
local PROFILE_SYNC_DECISION_HISTORY_LIMIT = 120
local profileSyncDecisionStats
local PROFILE_REVISION_DOMAINS = { "settings", "permissions", "loot", "session" }
local PROFILE_REVISION_DOMAIN_LABELS = {
  settings = "Settings",
  permissions = "Permissions",
  operational = "Legacy Operational Data",
  loot = "Loot Data",
  session = "Session Data",
}

local function TrimText(value)
  value = tostring(value or "")
  value = value:gsub("^%s+", "")
  value = value:gsub("%s+$", "")
  return value
end

local function GetProfileSyncTuning()
  local root = type(commApi.RootDB) == "function" and commApi.RootDB() or nil
  local ui = type(root) == "table" and type(root.ui) == "table" and root.ui or nil
  local developerMode = type(ui) == "table" and ui.developerMode == true
  local chunkSize = COMM_LIMITS.DEFAULT_PROFILE_SNAPSHOT_CHUNK_SIZE
  local intervalSeconds = COMM_LIMITS.DEFAULT_OUTBOUND_INTERVAL_SECONDS
  if developerMode then
    chunkSize = math.max(1, math.floor((tonumber(ui.profileSyncChunkSize) or COMM_LIMITS.DEFAULT_PROFILE_SNAPSHOT_CHUNK_SIZE) + 0.5))
    intervalSeconds = math.max(0, tonumber(ui.profileSyncDelaySeconds) or COMM_LIMITS.DEFAULT_OUTBOUND_INTERVAL_SECONDS)
  end
  return {
    developerMode = developerMode,
    chunkSize = math.floor(chunkSize + 0.5),
    intervalSeconds = intervalSeconds,
    defaultChunkSize = COMM_LIMITS.DEFAULT_PROFILE_SNAPSHOT_CHUNK_SIZE,
    minChunkSize = COMM_LIMITS.MIN_PROFILE_SNAPSHOT_CHUNK_SIZE,
    maxChunkSize = COMM_LIMITS.MAX_PROFILE_SNAPSHOT_CHUNK_SIZE,
    defaultIntervalSeconds = COMM_LIMITS.DEFAULT_OUTBOUND_INTERVAL_SECONDS,
    minIntervalSeconds = COMM_LIMITS.MIN_OUTBOUND_INTERVAL_SECONDS,
    maxIntervalSeconds = COMM_LIMITS.MAX_OUTBOUND_INTERVAL_SECONDS,
    safePayloadLimit = COMM_LIMITS.SAFE_PAYLOAD_BYTES,
  }
end

local function SetProfileSyncTuning(chunkSize, intervalSeconds)
  local root = type(commApi.RootDB) == "function" and commApi.RootDB() or nil
  if type(root) ~= "table" then
    return GetProfileSyncTuning()
  end
  root.ui = root.ui or {}
  root.ui.profileSyncChunkSize = math.max(1, math.floor((tonumber(chunkSize) or COMM_LIMITS.DEFAULT_PROFILE_SNAPSHOT_CHUNK_SIZE) + 0.5))
  root.ui.profileSyncDelaySeconds = math.max(0, tonumber(intervalSeconds) or COMM_LIMITS.DEFAULT_OUTBOUND_INTERVAL_SECONDS)
  return GetProfileSyncTuning()
end

local function ResetProfileSyncTuning()
  return SetProfileSyncTuning(
    COMM_LIMITS.DEFAULT_PROFILE_SNAPSHOT_CHUNK_SIZE,
    COMM_LIMITS.DEFAULT_OUTBOUND_INTERVAL_SECONDS
  )
end

local function GetProfileSnapshotChunkSize()
  return GetProfileSyncTuning().chunkSize
end

local function GetCommOutboundIntervalSeconds()
  return GetProfileSyncTuning().intervalSeconds
end

local function GetArchiveSyncPaused()
  local root = type(commApi.RootDB) == "function" and commApi.RootDB() or nil
  local ui = type(root) == "table" and type(root.ui) == "table" and root.ui or nil
  return type(ui) == "table" and ui.profileSyncPauseArchive == true
end

local function SetArchiveSyncPaused(paused)
  local root = type(commApi.RootDB) == "function" and commApi.RootDB() or nil
  if type(root) ~= "table" then
    return GetArchiveSyncPaused()
  end
  root.ui = root.ui or {}
  root.ui.profileSyncPauseArchive = paused == true
  return root.ui.profileSyncPauseArchive == true
end

local function NormalizeCharacterKey(value)
  local text = TrimText(value)
  if text == "" then
    return ""
  end
  text = text:gsub("%s*%-%s*", "-")
  text = text:gsub("%s+", "")
  return text
end

local function FirstNonEmptyText(...)
  for index = 1, select("#", ...) do
    local candidate = TrimText(select(index, ...))
    if candidate ~= "" then
      return candidate
    end
  end
  return ""
end

local function NormalizeEnabledFlag(value, defaultValue)
  if value == nil then
    if defaultValue == nil then
      return nil
    end
    return defaultValue and true or false
  end
  if type(value) == "boolean" then
    return value
  end
  local normalized = string.lower(TrimText(value))
  if normalized == "1" or normalized == "true" or normalized == "on" or normalized == "enabled" then
    return true
  end
  if normalized == "0" or normalized == "false" or normalized == "off" or normalized == "disabled" then
    return false
  end
  if defaultValue == nil then
    return nil
  end
  return defaultValue and true or false
end

local function BuildCommProtocolMarker(version)
  local resolved = math.max(1, tonumber(version) or COMM_PROTOCOL_VERSION)
  return "P" .. tostring(resolved)
end

local function ParseCommProtocolMarker(value)
  local text = TrimText(value)
  local version = tonumber(text:match("^P(%d+)$"))
  if version and version > 0 then
    return math.floor(version)
  end
  return nil
end

local function CloneProfileSyncDomainList(domains)
  local clone = {}
  if type(domains) == "table" then
    for index, value in ipairs(domains) do
      clone[index] = tostring(value)
    end
  end
  return clone
end

local function AreProfileSyncDomainListsEqual(left, right)
  left = type(left) == "table" and left or {}
  right = type(right) == "table" and right or {}
  if #left ~= #right then
    return false
  end
  for index = 1, #left do
    if tostring(left[index]) ~= tostring(right[index]) then
      return false
    end
  end
  return true
end

local function GetStableValueSignatureSortKey(value)
  local valueType = type(value)
  if valueType == "string" then
    return "1:" .. value
  elseif valueType == "number" then
    return "2:" .. tostring(value)
  elseif valueType == "boolean" then
    return "3:" .. (value and "1" or "0")
  elseif valueType == "nil" then
    return "4:"
  end
  return valueType .. ":" .. tostring(value)
end

local function BuildStableValueSignature(value, seen)
  local valueType = type(value)
  if valueType == "string" then
    return "s:" .. value
  elseif valueType == "number" then
    return "n:" .. tostring(value)
  elseif valueType == "boolean" then
    return "b:" .. (value and "1" or "0")
  elseif valueType == "nil" then
    return "z:"
  elseif valueType ~= "table" then
    return valueType .. ":" .. tostring(value)
  end

  seen = type(seen) == "table" and seen or {}
  if seen[value] then
    return "r:"
  end
  seen[value] = true

  local keys = {}
  for key in pairs(value) do
    keys[#keys + 1] = key
  end
  table.sort(keys, function(left, right)
    return GetStableValueSignatureSortKey(left) < GetStableValueSignatureSortKey(right)
  end)

  local parts = {}
  for _, key in ipairs(keys) do
    parts[#parts + 1] = BuildStableValueSignature(key, seen) .. "=" .. BuildStableValueSignature(value[key], seen)
  end
  seen[value] = nil
  return "{" .. table.concat(parts, "\30") .. "}"
end

INTERNAL_API.LIDCOUNCIL_AppendProfileSyncRosterEvent_Impl = function(existingEvents, event, eventAt, limit)
  local retainedEvents = {}
  for _, existingEvent in ipairs(type(existingEvents) == "table" and existingEvents or {}) do
    if type(existingEvent) == "table" then
      local existingAction = string.lower(TrimText(existingEvent.action))
      local existingMemberKey = NormalizeCharacterKey(existingEvent.memberKey)
      if (existingAction == "joined" or existingAction == "left") and existingMemberKey ~= "" then
        retainedEvents[#retainedEvents + 1] = {
          action = existingAction,
          memberKey = existingMemberKey,
          at = math.max(0, tonumber(existingEvent.at) or 0),
        }
      end
    end
  end

  local action = string.lower(TrimText(type(event) == "table" and event.action or ""))
  local memberKey = NormalizeCharacterKey(type(event) == "table" and event.memberKey or "")
  if (action == "joined" or action == "left") and memberKey ~= "" then
    table.insert(retainedEvents, 1, {
      action = action,
      memberKey = memberKey,
      at = math.max(0, tonumber(eventAt) or 0),
    })
  end

  local resolvedLimit = math.max(1, tonumber(limit) or PROFILE_SYNC_ROSTER_EVENT_LIMIT)
  while #retainedEvents > resolvedLimit do
    table.remove(retainedEvents)
  end
  return retainedEvents
end

local function SetProfileSyncRuntimeState(sessionId, profileName, mode, severity, message, extra)
  extra = type(extra) == "table" and extra or {}
  local resolvedSessionId = TrimText(sessionId)
  local resolvedProfileName = TrimText(profileName)
  local resolvedMode = TrimText(mode ~= "" and mode or "info")
  local resolvedSeverity = TrimText(severity ~= "" and severity or "info")
  local resolvedMessage = TrimText(message)
  local resolvedSender = NormalizeCharacterKey(extra.sender)
  local resolvedRemoteDomains = CloneProfileSyncDomainList(extra.remoteDomains)
  local resolvedLocalDomains = CloneProfileSyncDomainList(extra.localDomains)
  local resolvedDetailDiff = type(extra.detailDiff) == "table" and extra.detailDiff or nil
  local resolvedDetailConflict = type(extra.detailConflict) == "table" and extra.detailConflict or nil
  local resolvedDetailSnapshotData = type(extra.detailSnapshotData) == "string" and extra.detailSnapshotData or nil
  local resolvedDetailPreviewSummary = type(extra.detailPreviewSummary) == "table" and extra.detailPreviewSummary or nil
  local resolvedDetailBaseSummary = type(extra.detailBaseSummary) == "table" and extra.detailBaseSummary or nil
  local resolvedRosterEvent = type(extra.rosterEvent) == "table" and extra.rosterEvent or nil
  local resolvedDetailDiffSignature = BuildStableValueSignature(resolvedDetailDiff)
  local resolvedDetailConflictSignature = BuildStableValueSignature(resolvedDetailConflict)
  local resolvedDetailPreviewSummarySignature = BuildStableValueSignature(resolvedDetailPreviewSummary)
  local resolvedDetailBaseSummarySignature = BuildStableValueSignature(resolvedDetailBaseSummary)
  if extra.skipIfSame == true
    and profileSyncRuntimeState.sessionId == resolvedSessionId
    and profileSyncRuntimeState.profileName == resolvedProfileName
    and profileSyncRuntimeState.mode == resolvedMode
    and profileSyncRuntimeState.severity == resolvedSeverity
    and profileSyncRuntimeState.message == resolvedMessage
    and profileSyncRuntimeState.sender == resolvedSender
    and AreProfileSyncDomainListsEqual(profileSyncRuntimeState.remoteDomains, resolvedRemoteDomains)
    and AreProfileSyncDomainListsEqual(profileSyncRuntimeState.localDomains, resolvedLocalDomains)
    and profileSyncRuntimeState.detailDiffSignature == resolvedDetailDiffSignature
    and profileSyncRuntimeState.detailConflictSignature == resolvedDetailConflictSignature
    and profileSyncRuntimeState.detailSnapshotData == resolvedDetailSnapshotData
    and profileSyncRuntimeState.detailPreviewSummarySignature == resolvedDetailPreviewSummarySignature
    and profileSyncRuntimeState.detailBaseSummarySignature == resolvedDetailBaseSummarySignature
  then
    return false
  end
  profileSyncRuntimeState.sessionId = resolvedSessionId
  profileSyncRuntimeState.profileName = resolvedProfileName
  profileSyncRuntimeState.mode = resolvedMode
  profileSyncRuntimeState.severity = resolvedSeverity
  profileSyncRuntimeState.message = resolvedMessage
  profileSyncRuntimeState.sender = resolvedSender
  profileSyncRuntimeState.updatedAt = tonumber(extra.updatedAt) or ((type(GetServerTime) == "function" and GetServerTime()) or (time and time() or 0))
  profileSyncRuntimeState.remoteDomains = resolvedRemoteDomains
  profileSyncRuntimeState.localDomains = resolvedLocalDomains
  profileSyncRuntimeState.detailDiff = resolvedDetailDiff
  profileSyncRuntimeState.detailConflict = resolvedDetailConflict
  profileSyncRuntimeState.detailDiffSignature = resolvedDetailDiffSignature
  profileSyncRuntimeState.detailConflictSignature = resolvedDetailConflictSignature
  profileSyncRuntimeState.detailSnapshotData = resolvedDetailSnapshotData
  profileSyncRuntimeState.detailPreviewSummary = resolvedDetailPreviewSummary
  profileSyncRuntimeState.detailBaseSummary = resolvedDetailBaseSummary
  profileSyncRuntimeState.detailPreviewSummarySignature = resolvedDetailPreviewSummarySignature
  profileSyncRuntimeState.detailBaseSummarySignature = resolvedDetailBaseSummarySignature
  if type(resolvedRosterEvent) == "table" then
    profileSyncRuntimeState.recentRosterEvents = INTERNAL_API.LIDCOUNCIL_AppendProfileSyncRosterEvent_Impl(
      profileSyncRuntimeState.recentRosterEvents,
      resolvedRosterEvent,
      profileSyncRuntimeState.updatedAt,
      PROFILE_SYNC_ROSTER_EVENT_LIMIT
    )
  end
  if extra.refreshEditor ~= false then
    RefreshEditor({
      defer = true,
      refreshPages = {
        Panels = true,
      },
      lootSessionSections = {
        SYNCMGMT = true,
      },
    })
  end
  return true
end

local function GetNow()
  return (type(GetServerTime) == "function" and GetServerTime()) or (time and time() or 0)
end

INTERNAL_API.LIDCOUNCIL_GetSyncPerformanceClock_Impl = function()
  if type(GetTimePreciseSec) == "function" then
    return math.max(0, tonumber(GetTimePreciseSec()) or 0)
  end
  if type(debugprofilestop) == "function" then
    return math.max(0, (tonumber(debugprofilestop()) or 0) / 1000)
  end
  if type(GetTime) == "function" then
    return math.max(0, tonumber(GetTime()) or 0)
  end
  return math.max(0, tonumber(GetNow()) or 0)
end

INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl = function(metricName, sampleEvery)
  local metricKey = TrimText(metricName)
  if metricKey == "" then
    return nil
  end
  local performance = type(outboundCommStats.performance) == "table"
    and outboundCommStats.performance
    or { metrics = {} }
  outboundCommStats.performance = performance
  performance.metrics = type(performance.metrics) == "table" and performance.metrics or {}
  local metric = type(performance.metrics[metricKey]) == "table"
    and performance.metrics[metricKey]
    or {}
  performance.metrics[metricKey] = metric
  metric.observedCalls = math.max(0, tonumber(metric.observedCalls) or 0) + 1
  local cadence = math.max(1, math.floor((tonumber(sampleEvery) or 1) + 0.5))
  if metric.observedCalls ~= 1 and metric.observedCalls % cadence ~= 0 then
    return nil
  end
  return INTERNAL_API.LIDCOUNCIL_GetSyncPerformanceClock_Impl()
end

INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl = function(metricName, startedAt, metadata)
  if type(startedAt) ~= "number" then
    return false
  end
  local metricKey = TrimText(metricName)
  if metricKey == "" then
    return false
  end
  local performance = type(outboundCommStats.performance) == "table"
    and outboundCommStats.performance
    or { metrics = {} }
  outboundCommStats.performance = performance
  performance.metrics = type(performance.metrics) == "table" and performance.metrics or {}
  local metric = type(performance.metrics[metricKey]) == "table"
    and performance.metrics[metricKey]
    or {}
  performance.metrics[metricKey] = metric
  local completedAt = INTERNAL_API.LIDCOUNCIL_GetSyncPerformanceClock_Impl()
  local elapsedMs = math.max(0, (completedAt - startedAt) * 1000)
  metric.samples = math.max(0, tonumber(metric.samples) or 0) + 1
  metric.totalMs = math.max(0, tonumber(metric.totalMs) or 0) + elapsedMs
  metric.lastMs = elapsedMs
  metric.maxMs = math.max(math.max(0, tonumber(metric.maxMs) or 0), elapsedMs)
  metric.lastAt = GetNow()
  metric.lastClock = completedAt
  metadata = type(metadata) == "table" and metadata or {}
  metric.lastQueueDepth = math.max(0, tonumber(metadata.queueDepth) or 0)
  metric.lastChunkCount = math.max(0, tonumber(metadata.chunkCount) or 0)
  metric.lastBytes = math.max(0, tonumber(metadata.bytes) or 0)
  metric.lastContext = TrimText(metadata.context)
  local tracePerformance = INTERNAL_API.LIDCOUNCIL_RecordRaidTestTracePerformance_Impl
  if type(tracePerformance) == "function" then
    pcall(tracePerformance, metricKey, elapsedMs, metadata)
  end
  return true
end

INTERNAL_API.LIDCOUNCIL_GetSyncPerformanceSnapshot_Impl = function()
  local performance = type(outboundCommStats.performance) == "table"
    and outboundCommStats.performance
    or {}
  local snapshot = {
    capturedAt = GetNow(),
    metrics = {},
  }
  for metricName, metric in pairs(type(performance.metrics) == "table" and performance.metrics or {}) do
    if type(metric) == "table" then
      local samples = math.max(0, tonumber(metric.samples) or 0)
      snapshot.metrics[metricName] = {
        observedCalls = math.max(samples, tonumber(metric.observedCalls) or 0),
        samples = samples,
        totalMs = math.max(0, tonumber(metric.totalMs) or 0),
        averageMs = samples > 0 and math.max(0, tonumber(metric.totalMs) or 0) / samples or 0,
        lastMs = math.max(0, tonumber(metric.lastMs) or 0),
        maxMs = math.max(0, tonumber(metric.maxMs) or 0),
        lastAt = math.max(0, tonumber(metric.lastAt) or 0),
        lastClock = math.max(0, tonumber(metric.lastClock) or 0),
        lastQueueDepth = math.max(0, tonumber(metric.lastQueueDepth) or 0),
        lastChunkCount = math.max(0, tonumber(metric.lastChunkCount) or 0),
        lastBytes = math.max(0, tonumber(metric.lastBytes) or 0),
        lastContext = TrimText(metric.lastContext),
      }
    end
  end
  return snapshot
end

if type(INTERNAL_API.LIDCOUNCIL_CreateInboundTelemetryOps_Impl) == "function" then
  inboundCommTelemetry, inboundCommOps = INTERNAL_API.LIDCOUNCIL_CreateInboundTelemetryOps_Impl({
    TrimText = TrimText,
    NormalizeCharacterKey = NormalizeCharacterKey,
    GetNow = GetNow,
  })
end
if type(inboundCommTelemetry) ~= "table" or type(inboundCommOps) ~= "table" then
  error("LidCouncil missing inbound telemetry helpers.")
end

local function GetCommProtocolContractSnapshot()
  local opcodes = {}
  for opcode in pairs(COMM_PROTOCOL_FIELD_CONTRACTS) do
    opcodes[#opcodes + 1] = opcode
  end
  table.sort(opcodes)

  local contracts = {}
  local categories = {}
  for _, opcode in ipairs(opcodes) do
    local contract = COMM_PROTOCOL_FIELD_CONTRACTS[opcode] or {}
    local category = TrimText(contract.category)
    local owner = TrimText(contract.owner)
    contracts[opcode] = {
      minimumFields = math.max(1, tonumber(contract.minimumFields) or 1),
      maximumFields = math.max(1, tonumber(contract.maximumFields)
        or tonumber(inboundCommTelemetry.maxPayloadFields)
        or 40),
      category = category,
      owner = owner,
    }
    categories[category] = (tonumber(categories[category]) or 0) + 1
  end

  return {
    version = COMM_PROTOCOL_CONTRACT_VERSION,
    opcodeCount = #opcodes,
    maxPayloadFields = math.max(1, tonumber(inboundCommTelemetry.maxPayloadFields) or 40),
    opcodes = opcodes,
    contracts = contracts,
    categoryCounts = categories,
  }
end

local function ValidateCommProtocolFieldCount(kind, fieldCount)
  local resolvedKind = TrimText(kind)
  local resolvedFieldCount = math.max(0, math.floor(tonumber(fieldCount) or 0))
  local contract = COMM_PROTOCOL_FIELD_CONTRACTS[resolvedKind]
  local fieldLimit = type(contract) == "table"
    and math.max(1, tonumber(contract.maximumFields)
      or tonumber(inboundCommTelemetry.maxPayloadFields)
      or 40)
    or math.max(1, tonumber(inboundCommTelemetry.maxPayloadFields) or 40)
  if resolvedFieldCount > fieldLimit then
    return false, "field_count_exceeds_limit", contract
  end

  local minimumFields = type(contract) == "table" and math.max(1, tonumber(contract.minimumFields) or 1) or 0
  if minimumFields > 0 and resolvedFieldCount < minimumFields then
    return false, "below_opcode_minimum", contract
  end
  return true, "accepted", contract
end

local function DispatchCommProtocolPayload(kind, fields, sender, handlerRegistry, activeSessionIdOverride)
  local resolvedKind = TrimText(kind)
  local contract = COMM_PROTOCOL_FIELD_CONTRACTS[resolvedKind]
  if type(contract) ~= "table" then
    return false, "unknown_opcode"
  end

  local registry = type(handlerRegistry) == "table" and handlerRegistry or commProtocolHandlerRegistry
  local entry = type(registry) == "table" and registry[resolvedKind] or nil
  if type(entry) ~= "table" or type(entry.handler) ~= "function" then
    return false, "missing_protocol_handler"
  end
  if TrimText(entry.owner) ~= TrimText(contract.owner) then
    return false, "protocol_handler_owner_mismatch"
  end

  local shouldRejectInbound = INTERNAL_API.LIDCOUNCIL_ShouldRejectInboundSessionBoundMessage_Impl
  if type(shouldRejectInbound) == "function" then
    local activeSessionId = ""
    if type(activeSessionIdOverride) == "string" then
      activeSessionId = TrimText(activeSessionIdOverride)
    else
      local activeSession = type(commApi.GetActiveLootSession) == "function" and commApi.GetActiveLootSession() or nil
      activeSessionId = TrimText(type(activeSession) == "table" and activeSession.id or "")
    end
    if shouldRejectInbound(resolvedKind, fields, activeSessionId) then
      return false, "stale_session_bound_message"
    end
  end

  local traceToken
  if registry == commProtocolHandlerRegistry and RAID_TRACE_COMM_OPCODES[resolvedKind] then
    traceToken = BeginRaidTestTracePhase("COMM_INBOUND_" .. resolvedKind, "", {
      sender = TrimText(sender),
      fields = type(fields) == "table" and #fields or 0,
      category = TrimText(contract.category),
    })
  end
  local handlerSucceeded, handlerError = pcall(entry.handler, fields, sender)
  EndRaidTestTracePhase(traceToken, handlerSucceeded and "dispatched" or "handler error", {
    sender = TrimText(sender),
    success = handlerSucceeded == true,
  })
  if not handlerSucceeded then
    if registry == commProtocolHandlerRegistry then
      local logError = rawget(_G, "LIDCOUNCIL_LogError")
      if type(logError) == "function" then
        pcall(logError, "Comm handler failed for " .. resolvedKind .. " from " .. TrimText(sender)
          .. ": " .. tostring(handlerError))
      end
    end
    return false, "protocol_handler_error", tostring(handlerError)
  end
  return true, "dispatched"
end

local function CloneProfileSyncTextList(list)
  local clone = {}
  local seen = {}
  for _, value in ipairs(type(list) == "table" and list or {}) do
    local text = TrimText(value)
    local key = string.lower(text)
    if text ~= "" and not seen[key] then
      seen[key] = true
      clone[#clone + 1] = text
    end
  end
  return clone
end

local function CloneProfileSyncDecisionCounterMap(source)
  local clone = {}
  for key, value in pairs(type(source) == "table" and source or {}) do
    local normalizedKey = TrimText(key)
    if normalizedKey ~= "" then
      clone[normalizedKey] = math.max(0, tonumber(value) or 0)
    end
  end
  return clone
end

local function BuildEmptyProfileSyncDecisionStats()
  return {
    totalEvents = 0,
    observedTotalEvents = 0,
    totalFallbackEvents = 0,
    observedTotalFallbackEvents = 0,
    suppressedDuplicates = 0,
    byStage = {},
    byTransferKind = {},
    byMode = {},
    byReason = {},
    byFallbackReason = {},
    recentEvents = {},
    updatedAt = GetNow(),
  }
end

local function IncrementProfileSyncDecisionCounter(counterMap, key)
  local normalizedKey = TrimText(key)
  if normalizedKey == "" then
    return
  end
  counterMap[normalizedKey] = math.max(0, tonumber(counterMap[normalizedKey]) or 0) + 1
end

local function CloneProfileSyncDecisionEvent(event)
  event = type(event) == "table" and event or {}
  local transferKinds = CloneProfileSyncTextList(event.transferKinds)
  local transferKind = string.upper(TrimText(event.transferKind))
  if transferKind ~= "" and #transferKinds == 0 then
    transferKinds[1] = transferKind
  elseif transferKind == "" and #transferKinds == 1 then
    transferKind = string.upper(TrimText(transferKinds[1]))
  end

  local fallbackReasons = CloneProfileSyncTextList(event.fallbackReasons)
  local fallbackReason = TrimText(event.fallbackReason)
  if fallbackReason ~= "" and #fallbackReasons == 0 then
    fallbackReasons[1] = fallbackReason
  elseif fallbackReason == "" and #fallbackReasons == 1 then
    fallbackReason = TrimText(fallbackReasons[1])
  end

  local snapshotFallbackSubdomains = CloneProfileSyncTextList(event.snapshotFallbackSubdomains)
  local patchSubdomains = CloneProfileSyncTextList(event.patchSubdomains)
  local fallback = event.fallback == true
    or fallbackReason ~= ""
    or #fallbackReasons > 0
    or #snapshotFallbackSubdomains > 0

  return {
    recordedAt = math.max(0, tonumber(event.recordedAt) or 0),
    firstRecordedAt = math.max(0, tonumber(event.firstRecordedAt or event.recordedAt) or 0),
    lastRecordedAt = math.max(0, tonumber(event.lastRecordedAt or event.recordedAt) or 0),
    repeatCount = math.max(1, tonumber(event.repeatCount) or 1),
    stage = TrimText(event.stage),
    action = TrimText(event.action),
    sessionId = TrimText(event.sessionId),
    profileName = TrimText(event.profileName),
    mode = TrimText(event.mode),
    reason = TrimText(event.reason),
    fallback = fallback,
    fallbackReason = fallbackReason,
    fallbackReasons = fallbackReasons,
    transferKind = transferKind,
    transferKinds = transferKinds,
    target = NormalizeCharacterKey(event.target),
    targetCount = math.max(0, tonumber(event.targetCount) or 0),
    queuedCount = math.max(0, tonumber(event.queuedCount) or 0),
    transferCount = math.max(0, tonumber(event.transferCount) or 0),
    chunkCount = math.max(0, tonumber(event.chunkCount) or 0),
    domains = CloneProfileSyncTextList(event.domains),
    subdomains = CloneProfileSyncTextList(event.subdomains),
    requestedDomains = CloneProfileSyncTextList(event.requestedDomains),
    requestedSubdomains = CloneProfileSyncTextList(event.requestedSubdomains),
    effectiveDomains = CloneProfileSyncTextList(event.effectiveDomains),
    effectiveSubdomains = CloneProfileSyncTextList(event.effectiveSubdomains),
    prunedDomains = CloneProfileSyncTextList(event.prunedDomains),
    prunedSubdomains = CloneProfileSyncTextList(event.prunedSubdomains),
    patchSubdomains = patchSubdomains,
    snapshotFallbackSubdomains = snapshotFallbackSubdomains,
    error = TrimText(event.error),
  }
end

local function ResetProfileSyncDecisionStats()
  profileSyncDecisionStats = BuildEmptyProfileSyncDecisionStats()
  return profileSyncDecisionStats
end

local function RecordProfileSyncDecision(stage, data)
  local stats = type(profileSyncDecisionStats) == "table" and profileSyncDecisionStats or ResetProfileSyncDecisionStats()
  local event = CloneProfileSyncDecisionEvent(data)
  local dedupeWindowSeconds = math.max(0, tonumber(type(data) == "table" and data.dedupeWindowSeconds or 3) or 3)
  local resolvedStage = TrimText(stage)
  event.stage = resolvedStage ~= "" and resolvedStage or event.stage
  if event.stage == "" then
    event.stage = "unknown"
  end
  if event.recordedAt <= 0 then
    event.recordedAt = GetNow()
  end
  event.firstRecordedAt = math.max(0, tonumber(event.firstRecordedAt) or event.recordedAt)
  event.lastRecordedAt = math.max(0, tonumber(event.lastRecordedAt) or event.recordedAt)
  event.repeatCount = math.max(1, tonumber(event.repeatCount) or 1)
  stats.observedTotalEvents = math.max(0, tonumber(stats.observedTotalEvents) or 0) + 1
  stats.updatedAt = event.recordedAt
  if event.fallback then
    stats.observedTotalFallbackEvents = math.max(0, tonumber(stats.observedTotalFallbackEvents) or 0) + 1
  end

  local recentEvents = type(stats.recentEvents) == "table" and stats.recentEvents or {}
  local dedupeKey = table.concat({
    string.lower(event.stage),
    string.lower(event.action),
    string.lower(event.sessionId),
    string.lower(event.profileName),
    string.lower(event.mode),
    string.lower(event.reason),
    event.fallback == true and "1" or "0",
    string.lower(event.fallbackReason),
    string.upper(event.transferKind),
    string.lower(event.target),
    tostring(event.targetCount),
    tostring(event.queuedCount),
    tostring(event.transferCount),
    tostring(event.chunkCount),
    table.concat(event.transferKinds, "\30"),
    table.concat(event.fallbackReasons, "\30"),
    table.concat(event.domains, "\30"),
    table.concat(event.subdomains, "\30"),
    table.concat(event.requestedDomains, "\30"),
    table.concat(event.requestedSubdomains, "\30"),
    table.concat(event.effectiveDomains, "\30"),
    table.concat(event.effectiveSubdomains, "\30"),
    table.concat(event.prunedDomains, "\30"),
    table.concat(event.prunedSubdomains, "\30"),
    table.concat(event.patchSubdomains, "\30"),
    table.concat(event.snapshotFallbackSubdomains, "\30"),
    event.error,
  }, "\31")
  if dedupeWindowSeconds > 0 then
    local earliestRecordedAt = math.max(0, event.recordedAt - dedupeWindowSeconds)
    for index = #recentEvents, 1, -1 do
      local existing = recentEvents[index]
      if type(existing) == "table" then
        local existingLastRecordedAt = math.max(0, tonumber(existing.lastRecordedAt or existing.recordedAt) or 0)
        if existingLastRecordedAt < earliestRecordedAt then
          break
        end
        if TrimText(existing.dedupeKey) == dedupeKey then
          existing.firstRecordedAt = math.max(0, tonumber(existing.firstRecordedAt) or existing.recordedAt)
          existing.recordedAt = event.recordedAt
          existing.lastRecordedAt = event.recordedAt
          existing.repeatCount = math.max(1, tonumber(existing.repeatCount) or 1) + 1
          if TrimText(existing.error) == "" and event.error ~= "" then
            existing.error = event.error
          end
          if index < #recentEvents then
            table.remove(recentEvents, index)
            recentEvents[#recentEvents + 1] = existing
          end
          stats.suppressedDuplicates = math.max(0, tonumber(stats.suppressedDuplicates) or 0) + 1
          stats.recentEvents = recentEvents
          return
        end
      end
    end
  end

  stats.totalEvents = math.max(0, tonumber(stats.totalEvents) or 0) + 1
  IncrementProfileSyncDecisionCounter(stats.byStage, event.stage)
  IncrementProfileSyncDecisionCounter(stats.byMode, event.mode)
  IncrementProfileSyncDecisionCounter(stats.byReason, event.reason)

  local transferKinds = CloneProfileSyncTextList(event.transferKinds)
  if #transferKinds == 0 and event.transferKind ~= "" then
    transferKinds[1] = event.transferKind
  end
  for _, transferKind in ipairs(transferKinds) do
    IncrementProfileSyncDecisionCounter(stats.byTransferKind, string.upper(TrimText(transferKind)))
  end

  local fallbackReasons = CloneProfileSyncTextList(event.fallbackReasons)
  if #fallbackReasons == 0 and event.fallbackReason ~= "" then
    fallbackReasons[1] = event.fallbackReason
  end
  for _, fallbackReason in ipairs(fallbackReasons) do
    IncrementProfileSyncDecisionCounter(stats.byFallbackReason, fallbackReason)
  end
  if event.fallback then
    stats.totalFallbackEvents = math.max(0, tonumber(stats.totalFallbackEvents) or 0) + 1
  end

  event.dedupeKey = dedupeKey
  recentEvents[#recentEvents + 1] = event
  while #recentEvents > PROFILE_SYNC_DECISION_HISTORY_LIMIT do
    table.remove(recentEvents, 1)
  end
  stats.recentEvents = recentEvents
end

local function GetProfileSyncDecisionStats()
  local stats = type(profileSyncDecisionStats) == "table" and profileSyncDecisionStats or ResetProfileSyncDecisionStats()
  local summary = {
    totalEvents = math.max(0, tonumber(stats.totalEvents) or 0),
    observedTotalEvents = math.max(0, tonumber(stats.observedTotalEvents) or 0),
    totalFallbackEvents = math.max(0, tonumber(stats.totalFallbackEvents) or 0),
    observedTotalFallbackEvents = math.max(0, tonumber(stats.observedTotalFallbackEvents) or 0),
    suppressedDuplicates = math.max(0, tonumber(stats.suppressedDuplicates) or 0),
    byStage = CloneProfileSyncDecisionCounterMap(stats.byStage),
    byTransferKind = CloneProfileSyncDecisionCounterMap(stats.byTransferKind),
    byMode = CloneProfileSyncDecisionCounterMap(stats.byMode),
    byReason = CloneProfileSyncDecisionCounterMap(stats.byReason),
    byFallbackReason = CloneProfileSyncDecisionCounterMap(stats.byFallbackReason),
    updatedAt = math.max(0, tonumber(stats.updatedAt) or 0),
  }
  local recentEvents = {}
  for index, event in ipairs(type(stats.recentEvents) == "table" and stats.recentEvents or {}) do
    recentEvents[index] = CloneProfileSyncDecisionEvent(event)
  end
  summary.recentEvents = recentEvents
  return summary
end

local function GetProfileSyncDecisionStatsSummary(sessionId)
  local stats = type(profileSyncDecisionStats) == "table" and profileSyncDecisionStats or ResetProfileSyncDecisionStats()
  local resolvedSessionId = TrimText(sessionId)
  local summary = {
    totalEvents = math.max(0, tonumber(stats.totalEvents) or 0),
    observedTotalEvents = math.max(0, tonumber(stats.observedTotalEvents) or 0),
    totalFallbackEvents = math.max(0, tonumber(stats.totalFallbackEvents) or 0),
    observedTotalFallbackEvents = math.max(0, tonumber(stats.observedTotalFallbackEvents) or 0),
    suppressedDuplicates = math.max(0, tonumber(stats.suppressedDuplicates) or 0),
    byStage = CloneProfileSyncDecisionCounterMap(stats.byStage),
    byTransferKind = CloneProfileSyncDecisionCounterMap(stats.byTransferKind),
    byMode = CloneProfileSyncDecisionCounterMap(stats.byMode),
    byReason = CloneProfileSyncDecisionCounterMap(stats.byReason),
    byFallbackReason = CloneProfileSyncDecisionCounterMap(stats.byFallbackReason),
    updatedAt = math.max(0, tonumber(stats.updatedAt) or 0),
  }
  local recentEvents = type(stats.recentEvents) == "table" and stats.recentEvents or {}
  summary.recentEvents = {}
  for index = #recentEvents, 1, -1 do
    local event = recentEvents[index]
    if type(event) == "table"
      and (resolvedSessionId == "" or TrimText(event.sessionId) == resolvedSessionId)
    then
      summary.recentEvents[#summary.recentEvents + 1] = CloneProfileSyncDecisionEvent(event)
      if #summary.recentEvents >= 6 then
        break
      end
    end
  end
  return summary
end

ResetProfileSyncDecisionStats()

local function BuildLocalMemberPayloadDetails()
  local className = ""
  local classFile = ""
  if type(UnitClass) == "function" then
    className, classFile = UnitClass("player")
    className = TrimText(className)
    classFile = TrimText(classFile)
  end

  local specName = ""
  local specIcon = ""
  local specID = nil
  if type(GetSpecialization) == "function" and type(GetSpecializationInfo) == "function" then
    local specIndex = GetSpecialization()
    if specIndex then
      local resolvedSpecID, localizedSpecName, _, localizedSpecIcon = GetSpecializationInfo(specIndex)
      specID = tonumber(resolvedSpecID)
      specName = TrimText(localizedSpecName)
      specIcon = TrimText(localizedSpecIcon)
    end
  end
  if type(commApi.GetEnglishClassAndSpec) == "function" then
    className, specName = commApi.GetEnglishClassAndSpec(classFile, specID, className, specName, specIcon)
  end

  local addonVersion = ""
  if type(GetAddOnMetadata) == "function" then
    addonVersion = TrimText(GetAddOnMetadata("LidCouncil", "Version"))
  end
  if addonVersion == "" and type(C_AddOns) == "table" and type(C_AddOns.GetAddOnMetadata) == "function" then
    addonVersion = TrimText(C_AddOns.GetAddOnMetadata("LidCouncil", "Version"))
  end

  local clientVersion = ""
  if type(GetBuildInfo) == "function" then
    clientVersion = TrimText(select(1, GetBuildInfo()))
  end

  local localAutoPassEnabled = true
  if type(commApi.GetLocalAutoPassEnabled) == "function" then
    localAutoPassEnabled = commApi.GetLocalAutoPassEnabled() and true or false
  end

  return {
    addonVersion = addonVersion,
    clientVersion = clientVersion,
    className = className,
    classFile = classFile,
    specName = specName,
    specIcon = specIcon,
    localAutoPassEnabled = localAutoPassEnabled,
  }
end

local function GetMemberPayloadDetails(details, useLocalFallback)
  local incoming = type(details) == "table" and details or {}
  local fallback = useLocalFallback and BuildLocalMemberPayloadDetails() or {}
  return {
    addonVersion = FirstNonEmptyText(incoming.addonVersion, fallback.addonVersion),
    clientVersion = FirstNonEmptyText(incoming.clientVersion, fallback.clientVersion),
    className = FirstNonEmptyText(incoming.className, fallback.className),
    classFile = FirstNonEmptyText(incoming.classFile, fallback.classFile),
    specName = FirstNonEmptyText(incoming.specName, fallback.specName),
    specIcon = FirstNonEmptyText(incoming.specIcon, fallback.specIcon),
    localAutoPassEnabled = NormalizeEnabledFlag(
      incoming.localAutoPassEnabled,
      fallback.localAutoPassEnabled ~= nil and fallback.localAutoPassEnabled or true
    ),
  }
end

local EDITOR_SYNC_REFRESH_MIN_INTERVAL_SECONDS = 0.75
INTERNAL_API.LIDCOUNCIL_ResolveDeferredEditorRefreshDelay_Impl = function(
  requestedDelay,
  lastPerformedAt,
  now,
  minimumInterval
)
  local delay = math.max(0, tonumber(requestedDelay) or 0.05)
  local lastAt = math.max(0, tonumber(lastPerformedAt) or 0)
  local currentAt = math.max(0, tonumber(now) or 0)
  local minimum = math.max(0, tonumber(minimumInterval) or EDITOR_SYNC_REFRESH_MIN_INTERVAL_SECONDS)
  if lastAt > 0 then
    delay = math.max(delay, minimum - math.max(0, currentAt - lastAt))
  end
  return math.max(0, delay)
end

local deferredEditorRefreshState = {
  dirty = false,
  refreshAll = false,
  refreshPages = {},
  lootSessionSections = {},
  flushScheduled = false,
  flushToken = 0,
  lastPerformedAt = 0,
  timerFallbackTotal = 0,
  lastTimerFallbackAt = 0,
  lastTimerFallbackReason = "",
}

local function IsEditorUiCombatLocked()
  if type(InCombatLockdown) == "function" and InCombatLockdown() then
    return true
  end
  return type(INTERNAL_API.LIDCOUNCIL_IsCombatSyncInboxFlushRunning_Impl) == "function"
    and INTERNAL_API.LIDCOUNCIL_IsCombatSyncInboxFlushRunning_Impl() == true
end

local function MergeNamedFlagSet(current, incoming)
  local merged = {}
  if type(current) == "table" then
    for name, enabled in pairs(current) do
      if enabled then
        merged[name] = true
      end
    end
  end
  if type(incoming) == "table" then
    for name, enabled in pairs(incoming) do
      if enabled then
        merged[name] = true
      end
    end
  end
  return merged
end

local function NormalizeEditorRefreshPages(refreshPages)
  if type(refreshPages) ~= "table" then
    return nil
  end
  local normalized = {}
  for pageName, enabled in pairs(refreshPages) do
    if enabled then
      if pageName == "lootSession" then
        normalized.Panels = true
      else
        normalized[pageName] = true
      end
    end
  end
  return normalized
end

local function NormalizeLootSessionRefreshSections(sections)
  if type(sections) ~= "table" then
    return nil
  end
  local normalized = {}
  for sectionName, enabled in pairs(sections) do
    if enabled then
      local resolvedSection = string.upper(TrimText(sectionName))
      if resolvedSection ~= "" then
        normalized[resolvedSection] = true
      end
    end
  end
  return normalized
end

local function MergeRefreshPages(current, incoming)
  return MergeNamedFlagSet(
    NormalizeEditorRefreshPages(current),
    NormalizeEditorRefreshPages(incoming)
  )
end

local function NormalizeEditorRefreshOptions(opts)
  if type(opts) ~= "table" then
    return nil
  end
  local normalized = {}
  for key, value in pairs(opts) do
    normalized[key] = value
  end
  if opts.refreshPages ~= nil then
    normalized.refreshPages = NormalizeEditorRefreshPages(opts.refreshPages) or {}
  end
  local defaultLootSessionSections = nil
  if type(opts.refreshPages) == "table" and opts.refreshPages.lootSession == true then
    defaultLootSessionSections = {
      CURRENT = true,
      SYNCMGMT = true,
    }
  end
  normalized.lootSessionSections = NormalizeLootSessionRefreshSections(opts.lootSessionSections or defaultLootSessionSections) or nil
  return normalized
end

local FlushDeferredEditorRefresh

local function QueueDeferredEditorRefresh(opts)
  opts = NormalizeEditorRefreshOptions(opts)
  deferredEditorRefreshState.dirty = true
  if type(opts) ~= "table" or opts.refreshPages == nil then
    deferredEditorRefreshState.refreshAll = true
    deferredEditorRefreshState.refreshPages = {}
    deferredEditorRefreshState.lootSessionSections = {}
    return
  end
  if deferredEditorRefreshState.refreshAll then
    return
  end
  deferredEditorRefreshState.refreshPages = MergeRefreshPages(
    deferredEditorRefreshState.refreshPages,
    opts.refreshPages
  )
  deferredEditorRefreshState.lootSessionSections = MergeNamedFlagSet(
    deferredEditorRefreshState.lootSessionSections,
    opts.lootSessionSections
  )
end

local function ScheduleDeferredEditorRefreshFlush(delaySeconds)
  if deferredEditorRefreshState.flushScheduled then
    return false
  end
  deferredEditorRefreshState.flushScheduled = true
  deferredEditorRefreshState.flushToken = math.max(0, tonumber(deferredEditorRefreshState.flushToken) or 0) + 1
  local token = deferredEditorRefreshState.flushToken
  local delay = INTERNAL_API.LIDCOUNCIL_ResolveDeferredEditorRefreshDelay_Impl(
    delaySeconds,
    deferredEditorRefreshState.lastPerformedAt,
    GetNow(),
    EDITOR_SYNC_REFRESH_MIN_INTERVAL_SECONDS
  )
  local function RunDeferredRefresh()
    if deferredEditorRefreshState.flushToken ~= token then
      return
    end
    deferredEditorRefreshState.flushScheduled = false
    if not deferredEditorRefreshState.dirty or IsEditorUiCombatLocked() then
      if deferredEditorRefreshState.dirty
        and type(INTERNAL_API.LIDCOUNCIL_QueueCombatUiRefreshChannel_Impl) == "function"
      then
        INTERNAL_API.LIDCOUNCIL_QueueCombatUiRefreshChannel_Impl("EDITOR", "timer_blocked_by_combat")
      end
      return
    end
    FlushDeferredEditorRefresh()
  end
  local scheduled, timerReason = false, "unavailable"
  if type(outboundTimerAdapter) == "table" and type(outboundTimerAdapter.ScheduleTimer) == "function" then
    scheduled, timerReason = outboundTimerAdapter.ScheduleTimer(delay, RunDeferredRefresh)
  end
  if not scheduled then
    deferredEditorRefreshState.timerFallbackTotal = math.max(0,
      tonumber(deferredEditorRefreshState.timerFallbackTotal) or 0) + 1
    deferredEditorRefreshState.lastTimerFallbackAt = GetNow()
    deferredEditorRefreshState.lastTimerFallbackReason = TrimText(timerReason)
    RunDeferredRefresh()
  end
  return true
end

local function ResetDeferredEditorRefreshState()
  deferredEditorRefreshState.dirty = false
  deferredEditorRefreshState.refreshAll = false
  deferredEditorRefreshState.refreshPages = {}
  deferredEditorRefreshState.lootSessionSections = {}
  deferredEditorRefreshState.flushScheduled = false
  deferredEditorRefreshState.flushToken = math.max(0, tonumber(deferredEditorRefreshState.flushToken) or 0) + 1
  if type(INTERNAL_API.LIDCOUNCIL_CancelCombatUiRefreshChannel_Impl) == "function" then
    INTERNAL_API.LIDCOUNCIL_CancelCombatUiRefreshChannel_Impl("EDITOR")
  end
end

local function GetVisibleEditorRefreshContext()
  local editor = rawget(_G, "LIDCOUNCIL_Editor")
  if not (editor and editor.__lidCouncilEditor and editor.IsShown and editor:IsShown()) then
    return {
      shown = false,
      editor = nil,
      currentPage = "",
      lootSessionSection = "",
      aboutSection = "",
    }
  end
  return {
    shown = true,
    editor = editor,
    currentPage = tostring(editor.currentPage or "Profiles"),
    lootSessionSection = string.upper(TrimText(editor.lootSessionSection or "CURRENT")),
    aboutSection = TrimText(editor.aboutSection),
  }
end

local function PerformImmediateEditorRefresh(opts)
  local performanceStartedAt = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("editor_refresh", 1)
  local refreshContext = GetVisibleEditorRefreshContext()
  local editor = refreshContext.editor
  if editor then
    local normalizedOpts = NormalizeEditorRefreshOptions(opts)
    local requestWorkflowRefresh = type(editor.RequestWorkflowRefresh) == "function"
      and editor.RequestWorkflowRefresh
      or (type(INTERNAL_API.LIDCOUNCIL_RequestEditorWorkflowRefresh_Impl) == "function"
        and INTERNAL_API.LIDCOUNCIL_RequestEditorWorkflowRefresh_Impl
        or nil)
    if type(requestWorkflowRefresh) == "function" then
      requestWorkflowRefresh(editor, normalizedOpts)
    elseif editor.Refresh then
      editor:Refresh()
    end
    if refreshContext.aboutSection == "Developer" and editor.RefreshDeveloperSection then
      editor:RefreshDeveloperSection()
    end
  end
  INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("editor_refresh", performanceStartedAt, {
    context = refreshContext.currentPage,
  })
  deferredEditorRefreshState.lastPerformedAt = GetNow()
end

RefreshEditor = function(opts)
  local refreshContext = GetVisibleEditorRefreshContext()
  if refreshContext.shown ~= true then
    if deferredEditorRefreshState.dirty then
      ResetDeferredEditorRefreshState()
    end
    return
  end
  if IsEditorUiCombatLocked() then
    QueueDeferredEditorRefresh(opts)
    if type(INTERNAL_API.LIDCOUNCIL_QueueCombatUiRefreshChannel_Impl) == "function" then
      INTERNAL_API.LIDCOUNCIL_QueueCombatUiRefreshChannel_Impl("EDITOR", "editor_refresh")
    end
    return
  end
  if type(opts) == "table" and opts.forceImmediate == true then
    if deferredEditorRefreshState.dirty then
      ResetDeferredEditorRefreshState()
    end
    PerformImmediateEditorRefresh(opts)
    return
  end
  if type(opts) == "table" and opts.defer == true then
    QueueDeferredEditorRefresh(opts)
    ScheduleDeferredEditorRefreshFlush(opts.delaySeconds)
    return
  end
  if deferredEditorRefreshState.dirty then
    ResetDeferredEditorRefreshState()
  end
  PerformImmediateEditorRefresh(opts)
end

FlushDeferredEditorRefresh = function()
  if not deferredEditorRefreshState.dirty or IsEditorUiCombatLocked() then
    return false
  end
  local opts = nil
  if deferredEditorRefreshState.refreshAll then
    opts = { forceImmediate = true }
  elseif next(deferredEditorRefreshState.refreshPages) then
    opts = {
      forceImmediate = true,
      refreshPages = deferredEditorRefreshState.refreshPages,
      lootSessionSections = next(deferredEditorRefreshState.lootSessionSections) and deferredEditorRefreshState.lootSessionSections or nil,
    }
  end
  ResetDeferredEditorRefreshState()
  PerformImmediateEditorRefresh(opts)
  return true
end

INTERNAL_API.LIDCOUNCIL_RequestCombatSafeEditorRefresh_Impl = RefreshEditor
INTERNAL_API.LIDCOUNCIL_ResetDeferredEditorRefresh_Impl = ResetDeferredEditorRefreshState
if type(INTERNAL_API.LIDCOUNCIL_RegisterCombatUiRefreshChannel_Impl) ~= "function"
  or not INTERNAL_API.LIDCOUNCIL_RegisterCombatUiRefreshChannel_Impl(
    "EDITOR",
    "LootSessionComm",
    FlushDeferredEditorRefresh
  )
then
  error("LidCouncil missing combat UI refresh coordinator.")
end

INTERNAL_API.LIDCOUNCIL_ClearInactiveCombatDeferredState_Impl = function()
  local activeSession = type(commApi.GetActiveLootSession) == "function"
    and commApi.GetActiveLootSession()
    or nil
  if type(activeSession) == "table" then
    return false, "active_session"
  end
  if type(INTERNAL_API.LIDCOUNCIL_ClearCombatSyncInbox_Impl) == "function" then
    INTERNAL_API.LIDCOUNCIL_ClearCombatSyncInbox_Impl()
  end
  ResetDeferredEditorRefreshState()
  if type(INTERNAL_API.LIDCOUNCIL_ResetDeferredRuntimeUiRefreshState_Impl) == "function" then
    INTERNAL_API.LIDCOUNCIL_ResetDeferredRuntimeUiRefreshState_Impl()
  end
  if type(INTERNAL_API.LIDCOUNCIL_ClearLootRuntimeCommSessionState_Impl) == "function" then
    INTERNAL_API.LIDCOUNCIL_ClearLootRuntimeCommSessionState_Impl()
  end
  return true, "cleared"
end

local function GetCommWarningTime()
  if type(GetServerTime) == "function" then
    return tonumber(GetServerTime()) or 0
  end
  return tonumber(time and time() or 0) or 0
end

local function WarnCommIssue(kind, message)
  if type(commApi.Print) ~= "function" then
    return
  end
  local warningKey = tostring(kind or "?") .. "|" .. tostring(message or "")
  local now = GetCommWarningTime()
  local previousAt = tonumber(recentCommWarnings[warningKey]) or 0
  local warningCooldown = COMM_LIMITS.WARNING_THROTTLE_SECONDS
  local resolvedKind = TrimText(kind)
  local resolvedMessage = tostring(message or "")
  if resolvedMessage:find("addon message throttle detected", 1, true) then
    -- A throttle is shared by the addon-message channel, not isolated to the
    -- opcode which happened to observe it.  Use one warning key so a raid-wide
    -- burst cannot print the same condition once for every active packet type.
    warningKey = "ADDON_MESSAGE_THROTTLE"
    warningCooldown = math.max(warningCooldown, 20)
  end
  if previousAt > 0 and (now - previousAt) < warningCooldown then
    return
  end
  recentCommWarnings[warningKey] = now
  commApi.Print(tostring(message or "LidCouncil comm warning.") .. " (" .. tostring(kind or "?") .. ")")
end

local outboundRetryHelpers = type(INTERNAL_API.LIDCOUNCIL_CreateOutboundRetryHelpers_Impl) == "function"
  and INTERNAL_API.LIDCOUNCIL_CreateOutboundRetryHelpers_Impl({ TrimText = TrimText })
  or nil
if type(outboundRetryHelpers) ~= "table"
  or type(outboundRetryHelpers.GetSendAddonResultState) ~= "function"
  or type(outboundRetryHelpers.FormatSendAddonResult) ~= "function"
  or type(outboundRetryHelpers.ResolveOutboundCommRetryDecision) ~= "function"
  or type(outboundRetryHelpers.ResolveGlobalThrottleCooldownSeconds) ~= "function"
  or type(outboundRetryHelpers.ResolveGlobalThrottleRecoveryIntervalSeconds) ~= "function"
then
  error("LidCouncil missing outbound retry helpers.")
end

INTERNAL_API.LIDCOUNCIL_ResolvePrefixRegistrationOutcome_Impl = function(input)
  input = type(input) == "table" and input or {}
  if math.max(0, tonumber(input.successfulSends) or 0) > 0 then
    return {
      registered = true,
      activeFailure = false,
      evidence = "successful_send",
      reason = "",
    }
  end
  if input.queryAvailable == true and input.queryOk == true and input.queryValue == true then
    return {
      registered = true,
      activeFailure = false,
      evidence = "registry_query",
      reason = "",
    }
  end
  if input.callOk == true and input.returnValue ~= nil and input.returnValue ~= false then
    return {
      registered = true,
      activeFailure = false,
      evidence = "register_return",
      reason = "",
    }
  end
  if input.callOk == true and input.returnValue == nil
    and (input.queryAvailable ~= true or input.queryOk ~= true or input.queryValue == nil)
  then
    return {
      registered = true,
      activeFailure = false,
      evidence = "register_side_effect",
      reason = "",
    }
  end
  return {
    registered = false,
    activeFailure = true,
    evidence = "",
    reason = input.callOk == true and "registration_declined" or "registration_call_failed",
  }
end

INTERNAL_API.LIDCOUNCIL_AppendPrefixRegistrationValidationChecks_Impl = function(addCheck)
  if type(addCheck) ~= "function" then
    return
  end
  local resolve = INTERNAL_API.LIDCOUNCIL_ResolvePrefixRegistrationOutcome_Impl
  local function outcome(input)
    local result = type(resolve) == "function" and resolve(input) or {}
    return table.concat({
      tostring(result.registered == true),
      tostring(result.evidence or ""),
      tostring(result.activeFailure == true),
      tostring(result.reason or ""),
    }, "/")
  end
  addCheck("prefix registration accepts nil side-effect return",
    "true/register_side_effect/false/", outcome({ callOk = true }))
  addCheck("prefix registration accepts registry query proof",
    "true/registry_query/false/", outcome({ callOk = true, returnValue = false, queryAvailable = true, queryOk = true, queryValue = true }))
  addCheck("prefix registration accepts direct return proof",
    "true/register_return/false/", outcome({ callOk = true, returnValue = true }))
  addCheck("prefix registration rejects verified decline",
    "false//true/registration_declined", outcome({ callOk = true, returnValue = false, queryAvailable = true, queryOk = true, queryValue = false }))
  addCheck("prefix registration reports call failure",
    "false//true/registration_call_failed", outcome({ callOk = false }))
  addCheck("prefix successful send clears stale registration failure",
    "true/successful_send/false/", outcome({ callOk = false, successfulSends = 1 }))
end

outboundCommStats.markPrefixRegistered = function(evidence)
  prefixRegistered = true
  outboundCommStats.prefixRegistrationActiveFailure = false
  outboundCommStats.prefixRegistrationUnavailable = false
  outboundCommStats.prefixRegistrationEvidence = TrimText(evidence)
  outboundCommStats.lastPrefixRegistrationSuccessAt = GetNow()
  outboundCommStats.lastPrefixRegistrationError = ""
end

local function EnsurePrefixRegistered()
  if prefixRegistered then
    return true
  end
  if type(C_ChatInfo) ~= "table" or type(C_ChatInfo.RegisterAddonMessagePrefix) ~= "function" then
    outboundCommStats.prefixRegistrationFailures = math.max(0, tonumber(outboundCommStats.prefixRegistrationFailures) or 0) + 1
    -- The addon can be loaded after PLAYER_LOGIN. Keep this retryable so the
    -- next world-entry or outbound message can register once the API exists.
    outboundCommStats.prefixRegistrationActiveFailure = true
    outboundCommStats.prefixRegistrationUnavailable = true
    outboundCommStats.lastPrefixRegistrationError = "Addon message prefix API is unavailable."
    WarnCommIssue("COMM", outboundCommStats.lastPrefixRegistrationError)
    return false
  end
  local queryAvailable = type(C_ChatInfo.IsAddonMessagePrefixRegistered) == "function"
  local queryOk, queryValue = false, nil
  if queryAvailable then
    queryOk, queryValue = pcall(C_ChatInfo.IsAddonMessagePrefixRegistered, COMM_PREFIX)
    if queryOk and queryValue == true then
      outboundCommStats.markPrefixRegistered("registry_query")
      return true
    end
  end
  outboundCommStats.prefixRegistrationAttempts = math.max(0, tonumber(outboundCommStats.prefixRegistrationAttempts) or 0) + 1
  local ok, registered = pcall(C_ChatInfo.RegisterAddonMessagePrefix, COMM_PREFIX)
  if queryAvailable then
    queryOk, queryValue = pcall(C_ChatInfo.IsAddonMessagePrefixRegistered, COMM_PREFIX)
  end
  local outcome = INTERNAL_API.LIDCOUNCIL_ResolvePrefixRegistrationOutcome_Impl({
    callOk = ok,
    returnValue = ok and registered or nil,
    queryAvailable = queryAvailable,
    queryOk = queryOk,
    queryValue = queryValue,
  })
  if outcome.registered == true then
    outboundCommStats.markPrefixRegistered(outcome.evidence)
    return true
  end
  outboundCommStats.prefixRegistrationFailures = math.max(0, tonumber(outboundCommStats.prefixRegistrationFailures) or 0) + 1
  outboundCommStats.prefixRegistrationActiveFailure = true
  outboundCommStats.prefixRegistrationUnavailable = true
  outboundCommStats.prefixRegistrationEvidence = ""
  outboundCommStats.lastPrefixRegistrationError = ok
    and "Addon message prefix registration was declined."
    or tostring(registered or "Addon message prefix registration failed.")
  WarnCommIssue("COMM", outboundCommStats.lastPrefixRegistrationError)
  return false
end

local payloadCodec = type(INTERNAL_API.LIDCOUNCIL_CreateLootSessionPayloadCodec_Impl) == "function"
  and INTERNAL_API.LIDCOUNCIL_CreateLootSessionPayloadCodec_Impl()
  or nil
if type(payloadCodec) ~= "table"
  or type(payloadCodec.BuildPayload) ~= "function"
  or type(payloadCodec.ParsePayload) ~= "function"
  or type(payloadCodec.BuildRollOptionFields) ~= "function"
  or type(payloadCodec.ParseRollOptionFields) ~= "function"
then
  error("LidCouncil missing loot session payload codec.")
end
local BuildPayload = payloadCodec.BuildPayload
local ParsePayload = payloadCodec.ParsePayload

-- The timeout and recovery gates are intentionally pure. They are shared by the
-- live state machine and developer validation, without scheduling real work.
INTERNAL_API.LIDCOUNCIL_GetOutboundProfileAckTimeoutTransition_Impl = function(transfer, now)
  if type(transfer) ~= "table" then
    return false, "missing_transfer"
  end
  if TrimText(transfer.state) ~= "waiting_ack" then
    return false, "not_waiting_ack"
  end
  local completedAt = math.max(0, tonumber(transfer.completedAt) or 0)
  if completedAt <= 0 then
    return false, "missing_completed_at"
  end
  local currentTime = math.max(0, tonumber(now) or 0)
  if currentTime - completedAt < COMM_LIMITS.PROFILE_ACK_TIMEOUT_SECONDS then
    return false, "timeout_not_reached"
  end
  return true, "ack_timeout_due"
end

INTERNAL_API.LIDCOUNCIL_GetOutboundProfileAckReconciliationDispatch_Impl = function(transfer)
  if type(transfer) ~= "table" then
    return false, "missing_transfer"
  end
  if TrimText(transfer.state) ~= "ack_timeout" then
    return false, "not_ack_timeout"
  end
  if math.max(0, tonumber(transfer.ackTimeoutRecoveryAttemptedAt) or 0) > 0 then
    return false, "recovery_already_attempted"
  end
  return true, "reconciliation_due"
end

local function PruneOutboundProfileTransfers()
  local now = GetNow()
  local nextOrder = {}
  for _, transferId in ipairs(outboundProfileTransferOrder) do
    local transfer = outboundProfileTransfers[transferId]
    if type(transfer) == "table" then
      local age = now - math.max(
        tonumber(transfer.queuedAt) or now,
        tonumber(transfer.completedAt) or 0,
        tonumber(transfer.queuedAckAt) or 0,
        tonumber(transfer.ackedAt) or 0
      )
      if transfer.state == "cancelled" then
        outboundProfileTransfers[transferId] = nil
        pendingOutboundProfileAckReconciliations[transferId] = nil
      else
        local timeoutDue = INTERNAL_API.LIDCOUNCIL_GetOutboundProfileAckTimeoutTransition_Impl(transfer, now)
        if timeoutDue then
          transfer.state = "ack_timeout"
          transfer.failedAt = now
          transfer.terminalReason = "ack_timeout"
          transfer.failureReason = "Profile snapshot acknowledgement timed out."
          outboundCommStats.profileAckTimeoutTotal = (tonumber(outboundCommStats.profileAckTimeoutTotal) or 0) + 1
          RecordProfileSyncDecision("outbound_profile_transfer", {
            action = "ack_timeout",
            sessionId = TrimText(transfer.sessionId),
            profileName = TrimText(transfer.profileName),
            mode = TrimText(transfer.mode),
            reason = TrimText(transfer.reason),
            transferKind = TrimText(transfer.transferKind),
            target = NormalizeCharacterKey(transfer.target),
            chunkCount = math.max(0, tonumber(transfer.totalChunks) or 0),
            error = transfer.failureReason,
          })
          pendingOutboundProfileAckReconciliations[transferId] = true
        end
        local retentionSeconds = COMM_LIMITS.TERMINAL_TRANSFER_RETENTION_SECONDS
        if transfer.state == "acked" or transfer.state == "superseded_acked"
          or transfer.state == "completed_preview" or transfer.state == "superseded"
        then
          retentionSeconds = COMM_LIMITS.COMPLETED_TRANSFER_RETENTION_SECONDS
        end
        if age <= retentionSeconds or transfer.state == "sending" or transfer.state == "queued"
          or transfer.state == "waiting_apply" or transfer.state == "superseded_waiting_apply"
        then
          nextOrder[#nextOrder + 1] = transferId
        else
          outboundProfileTransfers[transferId] = nil
        end
      end
    end
  end
  outboundProfileTransferOrder = nextOrder
end

ProcessPendingOutboundProfileAckReconciliations = function()
  local pendingReconciliations = pendingOutboundProfileAckReconciliations
  pendingOutboundProfileAckReconciliations = {}
  for transferId in pairs(pendingReconciliations) do
    local transfer = outboundProfileTransfers[transferId]
    local reconciliationDue = INTERNAL_API.LIDCOUNCIL_GetOutboundProfileAckReconciliationDispatch_Impl(transfer)
    if reconciliationDue then
      local reconciliationOk = false
      local reconciliation = nil
      transfer.ackTimeoutRecoveryAttemptedAt = GetNow()
      transfer.ackTimeoutRecoveryOutcome = "dispatching"
      if type(flowHelpers) == "table" and type(flowHelpers.ReconcileOutboundProfileAckTimeout) == "function" then
        local recovered, result, detail = pcall(flowHelpers.ReconcileOutboundProfileAckTimeout, transfer)
        if recovered then
          reconciliationOk = result == true
          reconciliation = detail
        else
          reconciliation = {
            outcome = "recovery_error",
            error = tostring(result or "Host reconciliation failed."),
          }
        end
      else
        reconciliation = {
          outcome = "recovery_unavailable",
          error = "Host reconciliation helpers are unavailable.",
        }
      end
      transfer.ackTimeoutRecoverySucceeded = reconciliationOk == true
      transfer.ackTimeoutRecoveryOutcome = TrimText(type(reconciliation) == "table" and reconciliation.outcome or "")
      transfer.ackTimeoutRecoveryQueuedCount = math.max(0, tonumber(type(reconciliation) == "table" and reconciliation.queuedCount or 0) or 0)
      transfer.ackTimeoutRecoveryError = TrimText(type(reconciliation) == "table" and reconciliation.error or reconciliation)
    end
  end
end

local function EnsureOutboundProfileTransfer(transferId, metadata)
  transferId = TrimText(transferId)
  if transferId == "" then
    return nil
  end
  local transfer = outboundProfileTransfers[transferId]
  if type(transfer) ~= "table" then
    transfer = {
      transferId = transferId,
      queuedAt = GetNow(),
      state = "queued",
      sentChunks = 0,
      totalChunks = 0,
      queuedMessages = 0,
      attemptedMessages = 0,
      sentMessages = 0,
      throttledMessages = 0,
      failedMessages = 0,
      bytesAttempted = 0,
      bytesSent = 0,
    }
    outboundProfileTransfers[transferId] = transfer
    outboundProfileTransferOrder[#outboundProfileTransferOrder + 1] = transferId
  end
  metadata = type(metadata) == "table" and metadata or {}
  transfer.target = FirstNonEmptyText(metadata.target, transfer.target)
  transfer.sessionId = FirstNonEmptyText(metadata.sessionId, transfer.sessionId)
  transfer.profileName = FirstNonEmptyText(metadata.profileName, transfer.profileName)
  transfer.profileId = FirstNonEmptyText(metadata.profileId, transfer.profileId)
  transfer.mode = FirstNonEmptyText(metadata.mode, transfer.mode)
  transfer.reason = FirstNonEmptyText(metadata.reason, transfer.reason)
  transfer.lane = FirstNonEmptyText(NormalizeProfileSyncTransferLaneText(metadata.lane), transfer.lane)
  transfer.domains = FirstNonEmptyText(metadata.domains, transfer.domains)
  transfer.transferKind = FirstNonEmptyText(metadata.transferKind, transfer.transferKind)
  transfer.subdomains = FirstNonEmptyText(metadata.subdomains, transfer.subdomains)
  transfer.authoritativeArchiveScope = FirstNonEmptyText(
    metadata.authoritativeArchiveScope,
    transfer.authoritativeArchiveScope
  )
  if metadata.hostAuthoritativeOverride == true then
    transfer.hostAuthoritativeOverride = true
  end
  if type(metadata.scopeDomains) == "table" then
    transfer.scopeDomains = metadata.scopeDomains
  end
  if type(metadata.scopeSubdomains) == "table" then
    transfer.scopeSubdomains = metadata.scopeSubdomains
  end
  if type(metadata.patchManifestSummary) == "table" then
    transfer.patchManifestSummary = metadata.patchManifestSummary
  end
  local scopeSignature = BuildOutboundProfileTransferScopeSignature(metadata)
  if scopeSignature ~= "" then
    transfer.scopeSignature = scopeSignature
    if not tonumber(transfer.generation) then
      local nextGeneration = (tonumber(outboundProfileTransferGenerationByScope[scopeSignature]) or 0) + 1
      outboundProfileTransferGenerationByScope[scopeSignature] = nextGeneration
      transfer.generation = nextGeneration
    end
  end
  transfer.totalChunks = math.max(tonumber(transfer.totalChunks) or 0, tonumber(metadata.totalChunks) or 0)
  return transfer
end

local outboundProfileTransferTelemetry = type(INTERNAL_API.LIDCOUNCIL_CreateOutboundProfileTransferTelemetryHelpers_Impl) == "function"
  and INTERNAL_API.LIDCOUNCIL_CreateOutboundProfileTransferTelemetryHelpers_Impl({
    TrimText = TrimText,
    EnsureOutboundProfileTransfer = EnsureOutboundProfileTransfer,
  })
  or nil
if type(outboundProfileTransferTelemetry) ~= "table"
  or type(outboundProfileTransferTelemetry.IsOutboundProfileTransferTelemetryItem) ~= "function"
  or type(outboundProfileTransferTelemetry.RecordOutboundProfileTransferTelemetry) ~= "function"
then
  error("LidCouncil missing outbound profile transfer telemetry helpers.")
end
INTERNAL_API.LIDCOUNCIL_IsOutboundProfileTransferTelemetryItem_Impl =
  outboundProfileTransferTelemetry.IsOutboundProfileTransferTelemetryItem
INTERNAL_API.LIDCOUNCIL_RecordOutboundProfileTransferTelemetry_Impl =
  outboundProfileTransferTelemetry.RecordOutboundProfileTransferTelemetry

local function CloneTransferScopeList(list)
  local clone = {}
  local seen = {}
  for _, value in ipairs(type(list) == "table" and list or {}) do
    local text = TrimText(value)
    local key = string.lower(text)
    if text ~= "" and not seen[key] then
      seen[key] = true
      clone[#clone + 1] = text
    end
  end
  return clone
end

local function SplitTransferScopeCsv(value)
  local parts = {}
  for token in string.gmatch(tostring(value or ""), "([^,]+)") do
    local text = TrimText(token)
    if text ~= "" then
      parts[#parts + 1] = text
    end
  end
  return CloneTransferScopeList(parts)
end

BuildOutboundProfileTransferScopeSignature = function(metadata)
  metadata = type(metadata) == "table" and metadata or {}
  local target = NormalizeCharacterKey(metadata.target)
  local sessionId = string.lower(TrimText(metadata.sessionId))
  local profileName = string.lower(TrimText(metadata.profileName))
  local transferKind = string.upper(TrimText(metadata.transferKind))
  local scopeDomains = type(metadata.scopeDomains) == "table" and CloneTransferScopeList(metadata.scopeDomains) or SplitTransferScopeCsv(metadata.domains)
  local scopeSubdomains = type(metadata.scopeSubdomains) == "table" and CloneTransferScopeList(metadata.scopeSubdomains) or SplitTransferScopeCsv(metadata.subdomains)
  table.sort(scopeDomains, function(left, right)
    return string.lower(tostring(left)) < string.lower(tostring(right))
  end)
  table.sort(scopeSubdomains, function(left, right)
    return string.lower(tostring(left)) < string.lower(tostring(right))
  end)
  if target == "" or sessionId == "" then
    return ""
  end
  return table.concat({
    target,
    sessionId,
    profileName,
    transferKind,
    table.concat(scopeDomains, ","),
    table.concat(scopeSubdomains, ","),
  }, "|")
end

local function BuildTransferScopeLookup(list)
  local lookup = {}
  for _, value in ipairs(type(list) == "table" and list or {}) do
    local key = string.lower(TrimText(value))
    if key ~= "" then
      lookup[key] = true
    end
  end
  return lookup
end

local function IsTransferScopeSubset(left, right)
  local leftLookup = BuildTransferScopeLookup(left)
  local rightLookup = BuildTransferScopeLookup(right)
  local hasAny = false
  for key in pairs(leftLookup) do
    hasAny = true
    if not rightLookup[key] then
      return false
    end
  end
  return hasAny
end

local function AreTransferScopesEqual(left, right)
  return IsTransferScopeSubset(left, right) and IsTransferScopeSubset(right, left)
end

local function BuildQueuedTransferScopeDescriptor(transfer)
  transfer = type(transfer) == "table" and transfer or {}
  local scopeDomains = type(transfer.scopeDomains) == "table" and transfer.scopeDomains or SplitTransferScopeCsv(transfer.domains)
  local scopeSubdomains = type(transfer.scopeSubdomains) == "table" and transfer.scopeSubdomains or SplitTransferScopeCsv(transfer.subdomains)
  local transferKind = TrimText(transfer.transferKind)
  local full = transferKind == "FULL" or (transferKind == "" and #scopeDomains == 0 and #scopeSubdomains == 0)
  if transferKind == "" then
    if #scopeSubdomains > 0 then
      transferKind = "SUBDOMAINS"
    elseif #scopeDomains > 0 then
      transferKind = "DOMAINS"
    else
      transferKind = "FULL"
    end
  end
  return {
    target = NormalizeCharacterKey(transfer.target),
    sessionId = TrimText(transfer.sessionId),
    profileName = TrimText(transfer.profileName),
    transferKind = transferKind,
    domains = CloneTransferScopeList(scopeDomains),
    subdomains = CloneTransferScopeList(scopeSubdomains),
    full = full,
  }
end

local function BuildReplacementTransferScopeDescriptor(sessionId, targetName, preparedSnapshot, metadata)
  local descriptor = BuildQueuedTransferScopeDescriptor(metadata)
  descriptor.target = NormalizeCharacterKey(targetName)
  descriptor.sessionId = TrimText(sessionId)
  if type(preparedSnapshot) == "table" then
    descriptor.profileName = FirstNonEmptyText(preparedSnapshot.profileName, descriptor.profileName)
    descriptor.transferKind = TrimText(preparedSnapshot.transferKind ~= "" and preparedSnapshot.transferKind or descriptor.transferKind)
    descriptor.domains = CloneTransferScopeList(preparedSnapshot.domains)
    descriptor.subdomains = CloneTransferScopeList(preparedSnapshot.subdomains)
    descriptor.full = descriptor.transferKind == "FULL"
  end
  if descriptor.transferKind == "" then
    if #descriptor.subdomains > 0 then
      descriptor.transferKind = "SUBDOMAINS"
    elseif #descriptor.domains > 0 then
      descriptor.transferKind = "DOMAINS"
    else
      descriptor.transferKind = "FULL"
      descriptor.full = true
    end
  end
  if descriptor.transferKind == "FULL" then
    descriptor.full = true
  end
  return descriptor
end

local function IsSupersededTransferState(state)
  return string.sub(TrimText(state), 1, 10) == "superseded"
end

INTERNAL_API.LIDCOUNCIL_ShouldPruneQueuedOutboundProfileTransfer_Impl = function(item, transfer)
  if not INTERNAL_API.LIDCOUNCIL_IsOutboundProfileTransferTelemetryItem_Impl(item) then
    return false, "not_profile_transfer"
  end
  if type(transfer) ~= "table" then
    return false, "unknown_transfer"
  end
  local state = TrimText(transfer.state)
  if transfer.obsolete == true or IsSupersededTransferState(state) then
    return true, "superseded_transfer"
  end
  if state == "acked" or state == "cancelled" or state == "failed" or state == "completed_preview" then
    return true, "terminal_transfer"
  end
  return false, "active_transfer"
end

INTERNAL_API.LIDCOUNCIL_PruneQueuedObsoleteProfileTransfers_Impl = function()
  local keptQueue = {}
  local removedCount = 0
  local prunedSessionId = ""
  for _, item in ipairs(outboundCommQueue) do
    local metadata = type(item) == "table" and type(item.metadata) == "table" and item.metadata or {}
    local transferId = TrimText(metadata.transferId)
    local transfer = transferId ~= "" and outboundProfileTransfers[transferId] or nil
    local shouldPrune = INTERNAL_API.LIDCOUNCIL_ShouldPruneQueuedOutboundProfileTransfer_Impl(item, transfer)
    if shouldPrune then
      removedCount = removedCount + 1
      if prunedSessionId == "" then
        prunedSessionId = TrimText(type(transfer) == "table" and transfer.sessionId or metadata.sessionId)
      end
    else
      keptQueue[#keptQueue + 1] = item
    end
  end
  if removedCount > 0 then
    INTERNAL_API.LIDCOUNCIL_EnsureOutboundSessionTelemetryBaseline_Impl(prunedSessionId)
    outboundCommQueue = keptQueue
    outboundCommStats.obsoleteProfileQueuePrunedTotal = math.max(0,
      tonumber(outboundCommStats.obsoleteProfileQueuePrunedTotal) or 0) + removedCount
    outboundCommStats.lastObsoleteProfileQueuePrunedAt = GetNow()
  end
  return removedCount
end

local function ResolveProfileSyncTransferReason(metadata)
  metadata = type(metadata) == "table" and metadata or {}
  local reason = TrimText(metadata.reason)
  local transferId = TrimText(metadata.transferId)
  if transferId ~= "" then
    local transfer = outboundProfileTransfers[transferId]
    if type(transfer) == "table" then
      reason = FirstNonEmptyText(reason, transfer.reason)
    end
  end
  return reason
end

NormalizeProfileSyncTransferLaneText = function(lane)
  local resolvedLane = string.lower(TrimText(lane))
  if resolvedLane == "live" or resolvedLane == "stats" or resolvedLane == "archive" then
    return resolvedLane
  end
  return ""
end

local function ResolveProfileSyncTransferLane(metadata)
  metadata = type(metadata) == "table" and metadata or {}
  local lane = NormalizeProfileSyncTransferLaneText(metadata.lane)
  local transferId = TrimText(metadata.transferId)
  if lane == "" and transferId ~= "" then
    local transfer = outboundProfileTransfers[transferId]
    if type(transfer) == "table" then
      lane = NormalizeProfileSyncTransferLaneText(transfer.lane)
    end
  end
  if lane ~= "" then
    return lane
  end
  local reasonLower = string.lower(ResolveProfileSyncTransferReason(metadata))
  if string.find(reasonLower, "archive", 1, true) ~= nil then
    return "archive"
  end
  if string.find(reasonLower, "stats", 1, true) ~= nil
    or string.find(reasonLower, "award", 1, true) ~= nil
    or string.find(reasonLower, "vote", 1, true) ~= nil
  then
    return "stats"
  end
  return "live"
end

local outboundEndpointTelemetry = type(INTERNAL_API.LIDCOUNCIL_CreateOutboundEndpointTelemetryHelpers_Impl) == "function"
  and INTERNAL_API.LIDCOUNCIL_CreateOutboundEndpointTelemetryHelpers_Impl({
    Stats = outboundCommStats,
    TrimText = TrimText,
    NormalizeCharacterKey = NormalizeCharacterKey,
    ResolveProfileSyncTransferReason = ResolveProfileSyncTransferReason,
    ResolveProfileSyncTransferLane = ResolveProfileSyncTransferLane,
  })
  or nil
if type(outboundEndpointTelemetry) ~= "table"
  or type(outboundEndpointTelemetry.ResolveOutboundCommTelemetryLane) ~= "function"
  or type(outboundEndpointTelemetry.RecordOutboundCommLaneTelemetry) ~= "function"
  or type(outboundEndpointTelemetry.GetOutboundCommLaneTelemetry) ~= "function"
  or type(outboundEndpointTelemetry.ResolveOutboundCommTelemetryTarget) ~= "function"
  or type(outboundEndpointTelemetry.SelectOutboundCommTelemetryMemberBucket) ~= "function"
  or type(outboundEndpointTelemetry.RecordOutboundCommMemberTelemetry) ~= "function"
  or type(outboundEndpointTelemetry.GetOutboundCommMemberTelemetry) ~= "function"
then
  error("LidCouncil missing outbound endpoint telemetry helpers.")
end
INTERNAL_API.LIDCOUNCIL_ResolveOutboundCommTelemetryLane_Impl =
  outboundEndpointTelemetry.ResolveOutboundCommTelemetryLane
INTERNAL_API.LIDCOUNCIL_RecordOutboundCommLaneTelemetry_Impl =
  outboundEndpointTelemetry.RecordOutboundCommLaneTelemetry
INTERNAL_API.LIDCOUNCIL_GetOutboundCommLaneTelemetry_Impl =
  outboundEndpointTelemetry.GetOutboundCommLaneTelemetry
INTERNAL_API.LIDCOUNCIL_ResolveOutboundCommTelemetryTarget_Impl =
  outboundEndpointTelemetry.ResolveOutboundCommTelemetryTarget
INTERNAL_API.LIDCOUNCIL_SelectOutboundCommTelemetryMemberBucket_Impl =
  outboundEndpointTelemetry.SelectOutboundCommTelemetryMemberBucket
INTERNAL_API.LIDCOUNCIL_RecordOutboundCommMemberTelemetry_Impl =
  outboundEndpointTelemetry.RecordOutboundCommMemberTelemetry
INTERNAL_API.LIDCOUNCIL_GetOutboundCommMemberTelemetry_Impl =
  outboundEndpointTelemetry.GetOutboundCommMemberTelemetry

INTERNAL_API.LIDCOUNCIL_ResolveArchiveQueuePacingTarget_Impl = function(item)
  item = type(item) == "table" and item or {}
  local kind = TrimText(item.kind)
  if kind ~= "PSYNC_START" and kind ~= "PSYNC_CHUNK" and kind ~= "PSYNC_END" then
    return ""
  end
  if INTERNAL_API.LIDCOUNCIL_ResolveOutboundCommTelemetryLane_Impl(item) ~= "archive" then
    return ""
  end
  local metadata = type(item.metadata) == "table" and item.metadata or {}
  return NormalizeCharacterKey(FirstNonEmptyText(metadata.target, item.targetName))
end

INTERNAL_API.LIDCOUNCIL_RecordArchiveTargetPacingSent_Impl = function(item, preempted)
  local target = INTERNAL_API.LIDCOUNCIL_ResolveArchiveQueuePacingTarget_Impl(item)
  if target == "" then
    return nil
  end
  local pacing = type(outboundCommStats.archiveTargetPacing) == "table"
    and outboundCommStats.archiveTargetPacing
    or {}
  outboundCommStats.archiveTargetPacing = pacing
  if preempted == true then
    pacing.preemptionsTotal = math.max(0, tonumber(pacing.preemptionsTotal) or 0) + 1
    pacing.lastPreemptedTarget = target
    pacing.lastPreemptedAt = GetNow()
  end
  if TrimText(item.kind) == "PSYNC_CHUNK" then
    if NormalizeCharacterKey(pacing.lastTarget) == target then
      pacing.consecutiveChunks = math.max(0, tonumber(pacing.consecutiveChunks) or 0) + 1
    else
      pacing.lastTarget = target
      pacing.consecutiveChunks = 1
    end
  end
  return pacing
end

local outboundOpcodeTelemetryHelpers = type(INTERNAL_API.LIDCOUNCIL_CreateOutboundOpcodeTelemetryHelpers_Impl) == "function"
  and INTERNAL_API.LIDCOUNCIL_CreateOutboundOpcodeTelemetryHelpers_Impl({
    Stats = outboundCommStats,
    TrimText = TrimText,
    EnsureSessionBaseline = function(sessionId)
      local ensureBaseline = INTERNAL_API.LIDCOUNCIL_EnsureOutboundSessionTelemetryBaseline_Impl
      if type(ensureBaseline) == "function" then
        return ensureBaseline(sessionId)
      end
      return nil
    end,
  })
  or nil
if type(outboundOpcodeTelemetryHelpers) ~= "table"
  or type(outboundOpcodeTelemetryHelpers.SelectOutboundCommTelemetryOpcodeBucket) ~= "function"
  or type(outboundOpcodeTelemetryHelpers.RecordOutboundCommOpcodeTelemetry) ~= "function"
  or type(outboundOpcodeTelemetryHelpers.GetOutboundCommOpcodeTelemetry) ~= "function"
then
  error("LidCouncil missing outbound opcode telemetry helpers.")
end
INTERNAL_API.LIDCOUNCIL_SelectOutboundCommTelemetryOpcodeBucket_Impl =
  outboundOpcodeTelemetryHelpers.SelectOutboundCommTelemetryOpcodeBucket
INTERNAL_API.LIDCOUNCIL_RecordOutboundCommOpcodeTelemetry_Impl =
  outboundOpcodeTelemetryHelpers.RecordOutboundCommOpcodeTelemetry
INTERNAL_API.LIDCOUNCIL_GetOutboundCommOpcodeTelemetry_Impl =
  outboundOpcodeTelemetryHelpers.GetOutboundCommOpcodeTelemetry

local outboundPressureRules = type(INTERNAL_API.LIDCOUNCIL_CreateOutboundPressureRules_Impl) == "function"
  and INTERNAL_API.LIDCOUNCIL_CreateOutboundPressureRules_Impl({ TrimText = TrimText })
  or nil
if type(outboundPressureRules) ~= "table"
  or type(outboundPressureRules.BuildOutboundOpcodePressure) ~= "function"
  or type(outboundPressureRules.BuildOutboundLanePressure) ~= "function"
  or type(outboundPressureRules.ShouldYieldArchiveForLanePressure) ~= "function"
then
  error("LidCouncil missing outbound pressure rules.")
end
INTERNAL_API.LIDCOUNCIL_BuildOutboundOpcodePressure_Impl = outboundPressureRules.BuildOutboundOpcodePressure
INTERNAL_API.LIDCOUNCIL_BuildOutboundLanePressure_Impl = outboundPressureRules.BuildOutboundLanePressure
INTERNAL_API.LIDCOUNCIL_ShouldYieldArchiveForLanePressure_Impl = outboundPressureRules.ShouldYieldArchiveForLanePressure

local outboundSessionTelemetry = type(INTERNAL_API.LIDCOUNCIL_CreateOutboundSessionTelemetryHelpers_Impl) == "function"
  and INTERNAL_API.LIDCOUNCIL_CreateOutboundSessionTelemetryHelpers_Impl({
    Stats = outboundCommStats,
    TrimText = TrimText,
    NormalizeCharacterKey = NormalizeCharacterKey,
    GetNow = GetNow,
    GetActiveSessionId = function()
      local activeSession = type(commApi.GetActiveLootSession) == "function" and commApi.GetActiveLootSession() or nil
      return TrimText(type(activeSession) == "table" and activeSession.id or "")
    end,
    GetLaneTelemetry = function()
      return INTERNAL_API.LIDCOUNCIL_GetOutboundCommLaneTelemetry_Impl()
    end,
    GetOpcodeTelemetry = function()
      return INTERNAL_API.LIDCOUNCIL_GetOutboundCommOpcodeTelemetry_Impl()
    end,
    GetMemberTelemetry = function()
      return INTERNAL_API.LIDCOUNCIL_GetOutboundCommMemberTelemetry_Impl()
    end,
    GetDeferredEditorRefreshTimerFallbackTotal = function()
      return math.max(0, tonumber(deferredEditorRefreshState.timerFallbackTotal) or 0)
    end,
  })
  or nil
if type(outboundSessionTelemetry) ~= "table"
  or type(outboundSessionTelemetry.EnsureOutboundSessionTelemetryBaseline) ~= "function"
  or type(outboundSessionTelemetry.GetOutboundSessionTelemetry) ~= "function"
then
  error("LidCouncil missing outbound session telemetry helpers.")
end
INTERNAL_API.LIDCOUNCIL_EnsureOutboundSessionTelemetryBaseline_Impl =
  outboundSessionTelemetry.EnsureOutboundSessionTelemetryBaseline
INTERNAL_API.LIDCOUNCIL_GetOutboundSessionTelemetry_Impl =
  outboundSessionTelemetry.GetOutboundSessionTelemetry

local outboundArchivePressure = type(INTERNAL_API.LIDCOUNCIL_CreateOutboundArchivePressureHelpers_Impl) == "function"
  and INTERNAL_API.LIDCOUNCIL_CreateOutboundArchivePressureHelpers_Impl({
    Stats = outboundCommStats,
    TrimText = TrimText,
    GetNow = GetNow,
    GetActiveSessionId = function()
      local activeSession = type(commApi.GetActiveLootSession) == "function" and commApi.GetActiveLootSession() or nil
      return TrimText(type(activeSession) == "table" and activeSession.id or "")
    end,
    GetQueue = function()
      return outboundCommQueue
    end,
    ResolveLane = function(item)
      return INTERNAL_API.LIDCOUNCIL_ResolveOutboundCommTelemetryLane_Impl(item)
    end,
    ResolveQueueSessionId = function(kind, metadata)
      local resolveSessionId = INTERNAL_API.LIDCOUNCIL_ResolveOutboundSessionBoundQueueSessionId_Impl
      if type(resolveSessionId) == "function" then
        return resolveSessionId(kind, metadata)
      end
      return TrimText(type(metadata) == "table" and metadata.sessionId or "")
    end,
    BuildLanePressure = function(laneTelemetry, thresholds)
      return INTERNAL_API.LIDCOUNCIL_BuildOutboundLanePressure_Impl(laneTelemetry, thresholds)
    end,
    ShouldYieldArchiveForLanePressure = function(lanePressure)
      return INTERNAL_API.LIDCOUNCIL_ShouldYieldArchiveForLanePressure_Impl(lanePressure)
    end,
  })
  or nil
if type(outboundArchivePressure) ~= "table"
  or type(outboundArchivePressure.ShouldDeferNewArchiveQueueItem) ~= "function"
then
  error("LidCouncil missing outbound archive pressure helpers.")
end
INTERNAL_API.LIDCOUNCIL_ShouldDeferNewArchiveQueueItem_Impl =
  outboundArchivePressure.ShouldDeferNewArchiveQueueItem

local function ShouldSupersedeQueuedTransfer(existingDescriptor, replacementDescriptor)
  if type(existingDescriptor) ~= "table" or type(replacementDescriptor) ~= "table" then
    return false
  end
  if existingDescriptor.target ~= replacementDescriptor.target then
    return false
  end
  if existingDescriptor.sessionId ~= replacementDescriptor.sessionId then
    return false
  end
  if existingDescriptor.profileName ~= "" and replacementDescriptor.profileName ~= ""
    and string.lower(existingDescriptor.profileName) ~= string.lower(replacementDescriptor.profileName) then
    return false
  end
  if replacementDescriptor.full then
    return true
  end
  if existingDescriptor.full then
    return false
  end
  if #existingDescriptor.subdomains > 0 or #replacementDescriptor.subdomains > 0 then
    if #existingDescriptor.subdomains == 0 or #replacementDescriptor.subdomains == 0 then
      return false
    end
    return AreTransferScopesEqual(existingDescriptor.subdomains, replacementDescriptor.subdomains)
      or IsTransferScopeSubset(existingDescriptor.subdomains, replacementDescriptor.subdomains)
  end
  return AreTransferScopesEqual(existingDescriptor.domains, replacementDescriptor.domains)
    or IsTransferScopeSubset(existingDescriptor.domains, replacementDescriptor.domains)
end

local function CancelQueuedProfileTransfersForScope(sessionId, targetName, preparedSnapshot, metadata)
  local replacementDescriptor = BuildReplacementTransferScopeDescriptor(sessionId, targetName, preparedSnapshot, metadata)
  if replacementDescriptor.target == "" or replacementDescriptor.sessionId == "" then
    return 0
  end

  local cancelledCount = 0
  local supersededInFlightCount = 0
  for _, transferId in ipairs(outboundProfileTransferOrder) do
    local transfer = outboundProfileTransfers[transferId]
    local transferState = TrimText(type(transfer) == "table" and transfer.state or "")
    if type(transfer) == "table"
      and (transferState == "queued" or transferState == "sending" or transferState == "waiting_ack"
        or transferState == "waiting_apply")
    then
      local existingDescriptor = BuildQueuedTransferScopeDescriptor(transfer)
      if ShouldSupersedeQueuedTransfer(existingDescriptor, replacementDescriptor) then
        transfer.obsolete = true
        transfer.supersededAt = GetNow()
        transfer.terminalReason = "superseded"
        if transferState == "queued" then
          transfer.state = "superseded"
          transfer.completedAt = transfer.supersededAt
          cancelledCount = cancelledCount + 1
        else
          transfer.state = "superseded_" .. transferState
          supersededInFlightCount = supersededInFlightCount + 1
        end
      end
    end
  end

  if cancelledCount == 0 and supersededInFlightCount == 0 then
    return 0
  end

  INTERNAL_API.LIDCOUNCIL_PruneQueuedObsoleteProfileTransfers_Impl()
  PruneOutboundProfileTransfers()
  return cancelledCount + supersededInFlightCount
end

local function BuildOutboundCommMetadata(kind, distribution, targetName, ...)
  local resolvedKind = TrimText(kind)
  local function BuildScopePreview(csvText, limit)
    local resolvedLimit = math.max(1, tonumber(limit) or 1)
    local parts = {}
    local total = 0
    for token in string.gmatch(TrimText(csvText), "([^,]+)") do
      local text = TrimText(token)
      if text ~= "" then
        total = total + 1
        if #parts < resolvedLimit then
          parts[#parts + 1] = text
        end
      end
    end
    local preview = table.concat(parts, ", ")
    if total > #parts then
      preview = preview .. " +" .. tostring(total - #parts)
    end
    return preview, total
  end
  if resolvedKind == "START" or resolvedKind == "IACK" or resolvedKind == "BEGIN"
    or resolvedKind == "STOP" or resolvedKind == "STOP_ACK" or resolvedKind == "JOIN"
    or resolvedKind == "JACK" or resolvedKind == "LEAVE" or resolvedKind == "DECLINE"
  then
    local memberKey = ""
    if resolvedKind == "JOIN" or resolvedKind == "IACK" then
      memberKey = NormalizeCharacterKey(select(3, ...))
    elseif resolvedKind == "START" or resolvedKind == "JACK" then
      memberKey = NormalizeCharacterKey(targetName)
    end
    return {
      sessionId = TrimText(select(1, ...)),
      profileName = TrimText(select(2, ...)),
      target = TrimText(targetName),
      memberKey = memberKey,
    }
  elseif resolvedKind == "PSYNC_START" then
    local domains = TrimText(select(7, ...))
    local subdomains = TrimText(select(9, ...))
    local domainsPreview = BuildScopePreview(domains, 3)
    local subdomainsPreview = BuildScopePreview(subdomains, 2)
    return {
      transferId = TrimText(select(1, ...)),
      sessionId = TrimText(select(2, ...)),
      profileName = TrimText(select(3, ...)),
      profileId = TrimText(select(4, ...)),
      totalChunks = tonumber((select(5, ...))) or 0,
      mode = TrimText(select(6, ...)),
      domains = domains,
      domainsPreview = domainsPreview,
      transferKind = TrimText(select(8, ...)),
      subdomains = subdomains,
      subdomainsPreview = subdomainsPreview,
      generation = math.max(0, tonumber((select(10, ...))) or 0),
      lane = NormalizeProfileSyncTransferLaneText(select(11, ...)),
      target = TrimText(targetName),
    }
  elseif resolvedKind == "PSYNC_CHUNK" or resolvedKind == "PSYNC_END" then
    return {
      transferId = TrimText(select(1, ...)),
      target = TrimText(targetName),
    }
  elseif resolvedKind == "PSYNC_ACK" then
    return {
      transferId = TrimText(select(1, ...)),
      sessionId = TrimText(select(2, ...)),
      profileName = TrimText(select(3, ...)),
      profileId = TrimText(select(4, ...)),
      totalChunks = tonumber((select(5, ...))) or 0,
      ackPhase = TrimText(select(18, ...)),
      target = TrimText(targetName),
    }
  elseif resolvedKind == "MEMBER" then
    return {
      sessionId = TrimText(select(1, ...)),
      profileName = TrimText(select(2, ...)),
      memberKey = NormalizeCharacterKey(select(3, ...)),
      status = TrimText(select(4, ...)),
      joinedAt = math.max(0, tonumber((select(5, ...))) or 0),
      localAutoPassEnabled = NormalizeEnabledFlag(select(12, ...), nil),
      sharedProfileId = TrimText(select(15, ...)),
      target = TrimText(targetName),
    }
  elseif resolvedKind == "LOCALAP" or resolvedKind == "APNOTICE" then
    return {
      sessionId = TrimText(select(1, ...)),
      profileName = TrimText(select(2, ...)),
      memberKey = NormalizeCharacterKey(select(3, ...)),
      enabled = NormalizeEnabledFlag(select(4, ...), nil),
      target = TrimText(targetName),
    }
  elseif resolvedKind == "PSTATE" or resolvedKind == "PSTATE_PART" then
    return {
      sessionId = TrimText(select(1, ...)),
      profileName = TrimText(select(2, ...)),
      actor = NormalizeCharacterKey(select(3, ...)),
      profileId = TrimText(select(4, ...)),
      reason = "profile_state",
      responseToken = resolvedKind == "PSTATE_PART" and TrimText(select(5, ...)) or "",
      partIndex = resolvedKind == "PSTATE_PART" and math.max(0, tonumber((select(6, ...))) or 0) or 0,
      partCount = resolvedKind == "PSTATE_PART" and math.max(0, tonumber((select(7, ...))) or 0) or 0,
      target = TrimText(targetName),
    }
  elseif resolvedKind == "BSYNC_ITEM" then
    return {
      sessionId = TrimText(select(1, ...)),
      profileName = TrimText(select(2, ...)),
      orderIndex = math.max(0, tonumber((select(3, ...))) or 0),
      itemKey = TrimText(select(4, ...)),
      scope = "Live Board item",
      target = TrimText(targetName),
    }
  elseif resolvedKind == "BSYNC_END" then
    return {
      sessionId = TrimText(select(1, ...)),
      profileName = TrimText(select(2, ...)),
      boardId = TrimText(select(3, ...)),
      selectedItemKey = TrimText(select(4, ...)),
      token = TrimText(select(5, ...)),
      scope = "Live Board transaction end",
      target = TrimText(targetName),
    }
  elseif string.sub(resolvedKind, 1, 6) == "BSYNC" then
    return {
      sessionId = TrimText(select(1, ...)),
      profileName = TrimText(select(2, ...)),
      scope = "Live Board transaction",
      target = TrimText(targetName),
    }
  elseif resolvedKind == "PDELTA" or resolvedKind == "PDELTA_REQ" then
    return {
      sessionId = TrimText(select(1, ...)),
      profileName = TrimText(select(2, ...)),
      profileId = TrimText(select(3, ...)),
      changeId = TrimText(select(4, ...)),
      actor = NormalizeCharacterKey(select(5, ...)),
      domain = TrimText(select(6, ...)),
      action = TrimText(select(7, ...)),
      sequence = math.max(0, tonumber((select(12, ...))) or 0),
      target = TrimText(targetName),
    }
  elseif resolvedKind == "PDELTA_ACK" then
    return {
      sessionId = TrimText(select(1, ...)),
      profileName = TrimText(select(2, ...)),
      changeId = TrimText(select(3, ...)),
      actor = NormalizeCharacterKey(select(4, ...)),
      sequence = math.max(0, tonumber((select(5, ...))) or 0),
      ackPhase = TrimText(select(17, ...)),
      target = TrimText(targetName),
    }
  elseif resolvedKind == "PDELTA_NACK" then
    return {
      sessionId = TrimText(select(1, ...)),
      profileName = TrimText(select(2, ...)),
      changeId = TrimText(select(3, ...)),
      actor = NormalizeCharacterKey(select(4, ...)),
      sequence = math.max(0, tonumber((select(5, ...))) or 0),
      reason = TrimText(select(6, ...)),
      target = TrimText(targetName),
    }
  elseif resolvedKind == "PSUB_REQ" then
    local requestDomains = TrimText(select(4, ...))
    local requestDomainsPreview = BuildScopePreview(requestDomains, 3)
    return {
      sessionId = TrimText(select(1, ...)),
      profileName = TrimText(select(2, ...)),
      profileId = TrimText(select(3, ...)),
      requestDomains = requestDomains,
      requestDomainsPreview = requestDomainsPreview,
      requestToken = TrimText(select(5, ...)),
      target = TrimText(targetName),
    }
  elseif resolvedKind == "PSUB_STATE" then
    return {
      sessionId = TrimText(select(1, ...)),
      profileName = TrimText(select(2, ...)),
      profileId = TrimText(select(3, ...)),
      domain = TrimText(select(4, ...)),
      domainChecksum = TrimText(select(5, ...)),
      responsePart = tostring(select(6, ...) or ""),
      responseToken = TrimText(select(7, ...)),
      partIndex = math.max(0, tonumber((select(8, ...))) or 0),
      partCount = math.max(0, tonumber((select(9, ...))) or 0),
      requestToken = TrimText(select(10, ...)),
      target = TrimText(targetName),
    }
  elseif resolvedKind == "PSUBPATCH_REQ" then
    local requestSubdomains = TrimText(select(4, ...))
    local requestSubdomainsPreview = BuildScopePreview(requestSubdomains, 2)
    return {
      sessionId = TrimText(select(1, ...)),
      profileName = TrimText(select(2, ...)),
      profileId = TrimText(select(3, ...)),
      requestSubdomains = requestSubdomains,
      requestSubdomainsPreview = requestSubdomainsPreview,
      requestToken = TrimText(select(5, ...)),
      target = TrimText(targetName),
    }
  elseif resolvedKind == "PSYNC_REQ" then
    local requestDomains = TrimText(select(5, ...))
    local requestSubdomains = TrimText(select(6, ...))
    local requestDomainsPreview = BuildScopePreview(requestDomains, 3)
    local requestSubdomainsPreview = BuildScopePreview(requestSubdomains, 2)
    return {
      sessionId = TrimText(select(1, ...)),
      profileName = TrimText(select(2, ...)),
      profileId = TrimText(select(3, ...)),
      requestMode = TrimText(select(4, ...)),
      requestDomains = requestDomains,
      requestDomainsPreview = requestDomainsPreview,
      requestSubdomains = requestSubdomains,
      requestSubdomainsPreview = requestSubdomainsPreview,
      expectedPatchManifestToken = TrimText(select(7, ...)),
      target = TrimText(targetName),
    }
  elseif resolvedKind == "PSUBPATCH_STATE" then
    return {
      sessionId = TrimText(select(1, ...)),
      profileName = TrimText(select(2, ...)),
      profileId = TrimText(select(3, ...)),
      responseToken = TrimText(select(4, ...)),
      partIndex = math.max(0, tonumber((select(5, ...))) or 0),
      partCount = math.max(0, tonumber((select(6, ...))) or 0),
      responsePart = tostring(select(7, ...) or ""),
      requestToken = TrimText(select(8, ...)),
      target = TrimText(targetName),
    }
  end
  return nil
end

local function BuildQueuedCommPreviewSummary(item)
  item = type(item) == "table" and item or {}
  local kind = TrimText(item.kind)
  local parts = {}
  local target = NormalizeCharacterKey(item.target)
  local distribution = TrimText(item.distribution)
  local scopePreview = ""

  if kind == "PDELTA" or kind == "PDELTA_REQ" then
    scopePreview = TrimText(item.domain)
    if TrimText(item.action) ~= "" then
      scopePreview = scopePreview ~= "" and (scopePreview .. ":" .. TrimText(item.action)) or TrimText(item.action)
    end
  elseif kind == "PDELTA_NACK" then
    scopePreview = TrimText(item.reason)
  elseif kind == "MEMBER" then
    scopePreview = TrimText(item.memberKey)
    if TrimText(item.status) ~= "" then
      scopePreview = scopePreview ~= "" and (scopePreview .. ":" .. TrimText(item.status)) or TrimText(item.status)
    end
  elseif kind == "LOCALAP" or kind == "APNOTICE" then
    local enabledLabel = item.enabled == true and "enabled" or (item.enabled == false and "disabled" or "")
    scopePreview = TrimText(item.memberKey)
    if enabledLabel ~= "" then
      scopePreview = scopePreview ~= "" and (scopePreview .. ":" .. enabledLabel) or enabledLabel
    end
  elseif kind == "PSTATE" or kind == "PSTATE_PART" then
    scopePreview = TrimText(item.actor)
    scopePreview = scopePreview ~= "" and (scopePreview .. ":profile state") or "profile state"
  elseif kind == "PSUB_REQ" then
    scopePreview = TrimText(item.requestDomainsPreview)
  elseif kind == "PSUBPATCH_REQ" then
    scopePreview = TrimText(item.requestSubdomainsPreview)
  elseif kind == "PSYNC_REQ" then
    local requestMode = string.lower(TrimText(item.requestMode))
    scopePreview = TrimText(item.requestSubdomainsPreview ~= "" and item.requestSubdomainsPreview or item.requestDomainsPreview)
    if scopePreview == "" then
      scopePreview = "full sync request"
    end
    if requestMode ~= "" then
      scopePreview = requestMode .. ":" .. scopePreview
    end
  elseif kind == "PSUB_STATE" then
    scopePreview = TrimText(item.domain)
  elseif kind == "PSYNC_START" then
    scopePreview = TrimText(item.subdomainsPreview ~= "" and item.subdomainsPreview or item.domainsPreview)
  end

  if target ~= "" then
    parts[#parts + 1] = target
  elseif distribution ~= "" then
    parts[#parts + 1] = distribution
  end
  if scopePreview ~= "" then
    parts[#parts + 1] = scopePreview
  end
  if math.max(0, tonumber(item.partCount) or 0) > 0 then
    parts[#parts + 1] = "part " .. tostring(math.max(0, tonumber(item.partIndex) or 0)) .. "/" .. tostring(math.max(0, tonumber(item.partCount) or 0))
  end
  return table.concat(parts, " | ")
end

local function BuildQueuedCommPreviewItem(item)
  item = type(item) == "table" and item or {}
  local metadata = type(item.metadata) == "table" and item.metadata or {}
  local resolvedReason = ResolveProfileSyncTransferReason(metadata)
  local resolvedLane = ResolveProfileSyncTransferLane(metadata)
  local preview = {
    kind = TrimText(item.kind),
    priority = math.max(0, tonumber(item.priority) or 0),
    distribution = TrimText(item.distribution),
    target = NormalizeCharacterKey(FirstNonEmptyText(metadata.target, item.targetName)),
    sessionId = TrimText(metadata.sessionId),
    profileName = TrimText(metadata.profileName),
    profileId = TrimText(metadata.profileId),
    memberKey = NormalizeCharacterKey(metadata.memberKey),
    status = TrimText(metadata.status),
    enabled = metadata.enabled,
    localAutoPassEnabled = metadata.localAutoPassEnabled,
    actor = NormalizeCharacterKey(metadata.actor),
    changeId = TrimText(metadata.changeId),
    domain = TrimText(metadata.domain),
    action = TrimText(metadata.action),
    sequence = math.max(0, tonumber(metadata.sequence) or 0),
    reason = resolvedReason,
    mode = TrimText(metadata.mode),
    lane = resolvedLane,
    transferKind = TrimText(metadata.transferKind),
    requestDomains = TrimText(metadata.requestDomains),
    requestDomainsPreview = TrimText(metadata.requestDomainsPreview),
    requestSubdomains = TrimText(metadata.requestSubdomains),
    requestSubdomainsPreview = TrimText(metadata.requestSubdomainsPreview),
    requestMode = TrimText(metadata.requestMode),
    expectedPatchManifestToken = TrimText(metadata.expectedPatchManifestToken),
    domainsPreview = TrimText(metadata.domainsPreview),
    subdomainsPreview = TrimText(metadata.subdomainsPreview),
    responseToken = TrimText(metadata.responseToken),
    partIndex = math.max(0, tonumber(metadata.partIndex) or 0),
    partCount = math.max(0, tonumber(metadata.partCount) or 0),
    queuedAt = math.max(0, tonumber(item.queuedAt) or 0),
    notBeforeAt = math.max(0, tonumber(item.notBeforeAt) or 0),
    archiveYieldDeferred = item.archiveYieldDeferred == true,
    archiveYieldReason = TrimText(item.archiveYieldReason),
    throttleCount = math.max(0, tonumber(item.throttleCount) or 0),
    failureRetryCount = math.max(0, tonumber(item.failureRetryCount) or 0),
  }
  preview.summary = BuildQueuedCommPreviewSummary(preview)
  return preview
end

local function RecordOutboundItemQueued(kind, metadata)
  outboundCommStats.queuedTotal = (tonumber(outboundCommStats.queuedTotal) or 0) + 1
  outboundCommStats.lastQueuedAt = GetNow()

  local resolvedKind = TrimText(kind)
  metadata = type(metadata) == "table" and metadata or {}
  if resolvedKind == "PSYNC_START" or resolvedKind == "PSYNC_CHUNK" or resolvedKind == "PSYNC_END" then
    local transfer = EnsureOutboundProfileTransfer(metadata.transferId, metadata)
    if transfer then
      transfer.queuedMessages = (tonumber(transfer.queuedMessages) or 0) + 1
      if resolvedKind == "PSYNC_START" then
        transfer.state = "queued"
      end
    end
  end
  if RAID_TRACE_COMM_OPCODES[resolvedKind] then
    RecordRaidTestTraceEvent("COMM_QUEUED", "", {
      opcode = resolvedKind,
      session = TrimText(metadata.sessionId),
      target = FirstNonEmptyText(metadata.target, metadata.memberKey),
      transfer = TrimText(metadata.transferId),
      queue = #outboundCommQueue,
    })
  end
end

local function PruneOutboundSendWindow(now)
  local cutoff = (tonumber(now) or GetNow()) - 10
  while outboundCommSendWindow[1] and (tonumber(outboundCommSendWindow[1].at) or 0) < cutoff do
    table.remove(outboundCommSendWindow, 1)
  end
end

local function RecordOutboundItemAttempt(item)
  local payload = type(item) == "table" and tostring(item.payload or "") or ""
  outboundCommStats.attemptedTotal = (tonumber(outboundCommStats.attemptedTotal) or 0) + 1
  outboundCommStats.bytesAttempted = (tonumber(outboundCommStats.bytesAttempted) or 0) + #payload
  outboundCommStats.lastAttemptAt = GetNow()
  INTERNAL_API.LIDCOUNCIL_RecordOutboundCommOpcodeTelemetry_Impl(item, "attempted")
  INTERNAL_API.LIDCOUNCIL_RecordOutboundCommLaneTelemetry_Impl(item, "attempted")
  INTERNAL_API.LIDCOUNCIL_RecordOutboundCommMemberTelemetry_Impl(item, "attempted")
  INTERNAL_API.LIDCOUNCIL_RecordOutboundProfileTransferTelemetry_Impl(item, "attempted")
end

local function RecordOutboundItemThrottle(item, result)
  local now = GetNow()
  local wasCooldownActive = math.max(0,
    tonumber(outboundCommStats.globalThrottleNotBeforeAt) or 0) > now
  outboundCommStats.throttledTotal = (tonumber(outboundCommStats.throttledTotal) or 0) + 1
  if now - math.max(0, tonumber(outboundCommStats.lastThrottleAt) or 0) > 8 then
    outboundCommStats.globalThrottleStreak = 0
  end
  outboundCommStats.globalThrottleStreak = math.max(0,
    tonumber(outboundCommStats.globalThrottleStreak) or 0) + 1
  local baseSeconds = math.max(0.50, tonumber(outboundCommStats.globalThrottleBaseSeconds) or 1.05)
  local maxSeconds = math.max(baseSeconds, tonumber(outboundCommStats.globalThrottleMaxSeconds) or 6)
  local cooldownSeconds = outboundRetryHelpers.ResolveGlobalThrottleCooldownSeconds(
    outboundCommStats.globalThrottleStreak,
    baseSeconds,
    maxSeconds
  )
  outboundCommStats.globalThrottleNotBeforeAt = math.max(
    math.max(0, tonumber(outboundCommStats.globalThrottleNotBeforeAt) or 0),
    now + cooldownSeconds
  )
  outboundCommStats.lastGlobalThrottleCooldownSeconds = cooldownSeconds
  if type(item) == "table" then
    item.notBeforeAt = math.max(
      math.max(0, tonumber(item.notBeforeAt) or 0),
      outboundCommStats.globalThrottleNotBeforeAt
    )
  end
  outboundCommStats.lastThrottleAt = now
  outboundCommStats.lastFailureReason = outboundRetryHelpers.FormatSendAddonResult(result)
  if not wasCooldownActive then
    RecordRaidTestTraceEvent("THROTTLE_COOLDOWN_ENTER", "Shared outbound cooldown started.", {
      opcode = TrimText(type(item) == "table" and item.kind or ""),
      queue = #outboundCommQueue,
      seconds = cooldownSeconds,
      streak = math.max(0, tonumber(outboundCommStats.globalThrottleStreak) or 0),
    })
  end
  INTERNAL_API.LIDCOUNCIL_RecordOutboundCommOpcodeTelemetry_Impl(item, "throttled")
  INTERNAL_API.LIDCOUNCIL_RecordOutboundCommLaneTelemetry_Impl(item, "throttled")
  INTERNAL_API.LIDCOUNCIL_RecordOutboundCommMemberTelemetry_Impl(item, "throttled")
  INTERNAL_API.LIDCOUNCIL_RecordOutboundProfileTransferTelemetry_Impl(item, "throttled")
end

local function RecordOutboundItemFailed(item, reason, terminalIssueCategory)
  outboundCommStats.failedTotal = (tonumber(outboundCommStats.failedTotal) or 0) + 1
  outboundCommStats.lastFailureAt = GetNow()
  outboundCommStats.lastFailureReason = TrimText(reason)
  local failedKind = TrimText(type(item) == "table" and item.kind or "")
  if RAID_TRACE_COMM_OPCODES[failedKind] or TrimText(terminalIssueCategory) ~= "" then
    local failedMetadata = type(item) == "table" and type(item.metadata) == "table" and item.metadata or {}
    RecordRaidTestTraceEvent("COMM_FAILURE", TrimText(reason), {
      opcode = failedKind,
      category = TrimText(terminalIssueCategory),
      target = FirstNonEmptyText(failedMetadata.target, type(item) == "table" and item.targetName or ""),
      queue = #outboundCommQueue,
    })
  end
  if TrimText(terminalIssueCategory) ~= "" and type(INTERNAL_API.LIDCOUNCIL_RecordOutboundFailureDiagnostic_Impl) == "function" then
    local metadata = type(item) == "table" and type(item.metadata) == "table" and item.metadata or {}
    INTERNAL_API.LIDCOUNCIL_RecordOutboundFailureDiagnostic_Impl(
      terminalIssueCategory,
      type(item) == "table" and item.kind or "",
      reason,
      #(type(item) == "table" and tostring(item.payload or "") or ""),
      {
        sessionId = TrimText(metadata.sessionId),
        target = FirstNonEmptyText(metadata.target, type(item) == "table" and item.targetName or ""),
      }
    )
  end
  INTERNAL_API.LIDCOUNCIL_RecordOutboundCommOpcodeTelemetry_Impl(item, "failed")
  INTERNAL_API.LIDCOUNCIL_RecordOutboundCommLaneTelemetry_Impl(item, "failed")
  INTERNAL_API.LIDCOUNCIL_RecordOutboundCommMemberTelemetry_Impl(item, "failed")
  INTERNAL_API.LIDCOUNCIL_RecordOutboundProfileTransferTelemetry_Impl(item, "failed")
  if TrimText(type(item) == "table" and item.kind or "") == "BSYNC_END"
    and TrimText(terminalIssueCategory) ~= ""
    and type(INTERNAL_API.LIDCOUNCIL_NotifyOutboundBoardSyncEnd_Impl) == "function"
  then
    pcall(
      INTERNAL_API.LIDCOUNCIL_NotifyOutboundBoardSyncEnd_Impl,
      "failed",
      type(item.metadata) == "table" and item.metadata or {},
      GetNow(),
      TrimText(reason)
    )
  end
end

local function RemoveQueuedOutboundProfileTransferItems(transferId)
  local resolvedTransferId = TrimText(transferId)
  if resolvedTransferId == "" then
    return 0
  end
  local keptItems = {}
  local removedCount = 0
  for _, queued in ipairs(outboundCommQueue) do
    local metadata = type(queued) == "table" and type(queued.metadata) == "table" and queued.metadata or {}
    if resolvedTransferId == TrimText(metadata.transferId) then
      removedCount = removedCount + 1
    else
      keptItems[#keptItems + 1] = queued
    end
  end
  outboundCommQueue = keptItems
  return removedCount
end

local function MarkOutboundProfileTransferFailed(item, reason)
  local kind = TrimText(type(item) == "table" and item.kind or "")
  if kind ~= "PSYNC_START" and kind ~= "PSYNC_CHUNK" and kind ~= "PSYNC_END" then
    return
  end
  local metadata = type(item.metadata) == "table" and item.metadata or {}
  local transfer = EnsureOutboundProfileTransfer(metadata.transferId, metadata)
  if not transfer then
    return
  end
  transfer.failedAt = GetNow()
  transfer.completedAt = transfer.failedAt
  transfer.terminalReason = "send_failure"
  transfer.failureReason = TrimText(reason)
  transfer.failedKind = TrimText(item.kind)
  transfer.failureRetries = math.max(0, tonumber(item.failureRetryCount) or 0)
  transfer.droppedMessages = (tonumber(transfer.droppedMessages) or 0)
    + RemoveQueuedOutboundProfileTransferItems(metadata.transferId)
  if transfer.obsolete ~= true and not IsSupersededTransferState(transfer.state) then
    transfer.state = "failed"
  end
  outboundCommStats.terminalFailureTotal = (tonumber(outboundCommStats.terminalFailureTotal) or 0) + 1
  RecordProfileSyncDecision("outbound_profile_transfer", {
    action = "failed",
    sessionId = TrimText(transfer.sessionId),
    profileName = TrimText(transfer.profileName),
    mode = TrimText(transfer.mode),
    reason = TrimText(transfer.reason),
    transferKind = TrimText(transfer.transferKind),
    target = NormalizeCharacterKey(transfer.target),
    chunkCount = math.max(0, tonumber(transfer.totalChunks) or 0),
    error = transfer.failureReason,
  })
end

local function RecordOutboundItemSent(item, archiveTargetPreempted)
  outboundCommStats.sentTotal = (tonumber(outboundCommStats.sentTotal) or 0) + 1
  outboundCommStats.markPrefixRegistered("successful_send")
  local now = GetNow()
  if now >= math.max(0, tonumber(outboundCommStats.globalThrottleNotBeforeAt) or 0) then
    outboundCommStats.globalThrottleNotBeforeAt = 0
  end
  -- Do not erase raid-wide pressure after the first packet that succeeds at the
  -- end of a cooldown. A large fan-out can otherwise alternate one success with
  -- one throttle forever and keep every packet at the shortest retry interval.
  -- The streak expires only after a genuinely quiet throttle window.
  if now - math.max(0, tonumber(outboundCommStats.lastThrottleAt) or 0) > 8 then
    outboundCommStats.globalThrottleStreak = 0
  end
  outboundCommStats.lastSentAt = now
  local payloadBytes = #(type(item) == "table" and tostring(item.payload or "") or "")
  outboundCommStats.bytesSent = (tonumber(outboundCommStats.bytesSent) or 0) + payloadBytes
  INTERNAL_API.LIDCOUNCIL_RecordOutboundCommOpcodeTelemetry_Impl(item, "sent", payloadBytes)
  INTERNAL_API.LIDCOUNCIL_RecordOutboundCommLaneTelemetry_Impl(item, "sent")
  INTERNAL_API.LIDCOUNCIL_RecordOutboundCommMemberTelemetry_Impl(item, "sent")
  INTERNAL_API.LIDCOUNCIL_RecordOutboundProfileTransferTelemetry_Impl(item, "sent")
  INTERNAL_API.LIDCOUNCIL_RecordArchiveTargetPacingSent_Impl(item, archiveTargetPreempted)
  outboundCommSendWindow[#outboundCommSendWindow + 1] = {
    at = now,
    bytes = payloadBytes,
  }
  PruneOutboundSendWindow(now)
  RememberRecentOutboundRequest(item)

  if type(item) ~= "table" then
    return
  end
  local metadata = type(item.metadata) == "table" and item.metadata or {}
  if type(INTERNAL_API.LIDCOUNCIL_RecordOutboundDiagnosticResolved_Impl) == "function" then
    INTERNAL_API.LIDCOUNCIL_RecordOutboundDiagnosticResolved_Impl(item.kind, {
      sessionId = TrimText(metadata.sessionId),
      target = FirstNonEmptyText(metadata.target, item.targetName),
    })
  end
  local resolvedKind = TrimText(item.kind)
  if RAID_TRACE_COMM_OPCODES[resolvedKind] then
    RecordRaidTestTraceEvent("COMM_SENT", "", {
      opcode = resolvedKind,
      distribution = TrimText(item.distribution),
      target = FirstNonEmptyText(metadata.target, item.targetName),
      session = TrimText(metadata.sessionId),
      transfer = TrimText(metadata.transferId),
      bytes = payloadBytes,
      queue = #outboundCommQueue,
    })
  end
  if resolvedKind == "JOIN"
    and type(flowHelpers) == "table"
    and type(flowHelpers.HandleOutboundJoinSent) == "function"
  then
    pcall(flowHelpers.HandleOutboundJoinSent, metadata, now)
  end
  if resolvedKind == "START"
    and type(flowHelpers) == "table"
    and type(flowHelpers.HandleOutboundStartSent) == "function"
  then
    pcall(flowHelpers.HandleOutboundStartSent, metadata, now)
  end
  if resolvedKind == "BSYNC_END"
    and type(INTERNAL_API.LIDCOUNCIL_NotifyOutboundBoardSyncEnd_Impl) == "function"
  then
    pcall(
      INTERNAL_API.LIDCOUNCIL_NotifyOutboundBoardSyncEnd_Impl,
      "sent",
      metadata,
      now,
      ""
    )
  end
  if resolvedKind ~= "PSYNC_START" and resolvedKind ~= "PSYNC_CHUNK" and resolvedKind ~= "PSYNC_END" then
    return
  end
  local transfer = EnsureOutboundProfileTransfer(metadata.transferId, metadata)
  if not transfer then
    return
  end
  local transferObsolete = transfer.obsolete == true or IsSupersededTransferState(transfer.state)
  if resolvedKind == "PSYNC_START" then
    transfer.startedAt = transfer.startedAt or GetNow()
    if not transferObsolete then
      transfer.state = "sending"
    end
  elseif resolvedKind == "PSYNC_CHUNK" then
    transfer.sentChunks = math.max(tonumber(transfer.sentChunks) or 0, tonumber(metadata.chunkIndex) or 0, (tonumber(transfer.sentChunks) or 0) + 1)
    if not transferObsolete then
      transfer.state = "sending"
    end
  elseif resolvedKind == "PSYNC_END" then
    transfer.completedAt = GetNow()
    if not transferObsolete then
      if string.upper(TrimText(transfer.mode)) == "PREVIEW" then
        -- Preview snapshots are inspected only and intentionally do not apply or ACK.
        transfer.state = "completed_preview"
      else
        transfer.state = "waiting_ack"
        local transferId = TrimText(metadata.transferId)
        local completedAt = transfer.completedAt
        if transferId ~= "" then
          local scheduled, timerReason = outboundTimerAdapter.ScheduleTimer(COMM_LIMITS.PROFILE_ACK_TIMEOUT_SECONDS + 1, function()
            local currentTransfer = outboundProfileTransfers[transferId]
            if type(currentTransfer) == "table" and currentTransfer.state == "waiting_ack"
              and tonumber(currentTransfer.completedAt) == tonumber(completedAt)
            then
              PruneOutboundProfileTransfers()
              if type(ProcessPendingOutboundProfileAckReconciliations) == "function" then
                ProcessPendingOutboundProfileAckReconciliations()
              end
            end
          end)
          transfer.ackTimeoutTimerScheduled = scheduled == true
          if not scheduled then
            transfer.ackTimeoutTimerFallbackAt = GetNow()
            transfer.ackTimeoutTimerFallbackReason = TrimText(timerReason)
            outboundCommStats.profileAckTimeoutTimerFallbackTotal = math.max(0,
              tonumber(outboundCommStats.profileAckTimeoutTimerFallbackTotal) or 0) + 1
            outboundCommStats.lastProfileAckTimeoutTimerFallbackAt = transfer.ackTimeoutTimerFallbackAt
            outboundCommStats.lastProfileAckTimeoutTimerFallbackReason = transfer.ackTimeoutTimerFallbackReason
          end
        end
      end
    end
  end
end

INTERNAL_API.LIDCOUNCIL_ValidateOutboundProfileTransferAcknowledgement_Impl = function(
  transfer,
  sender,
  expectedSessionId,
  expectedProfileName,
  appliedGeneration,
  appliedProfileId,
  appliedChunkCount
)
  if type(transfer) ~= "table" then
    return false, "unknown_outbound_transfer"
  end
  local resolvedSender = NormalizeCharacterKey(sender)
  local expectedTarget = NormalizeCharacterKey(transfer.target)
  if resolvedSender == "" or (expectedTarget ~= "" and resolvedSender ~= expectedTarget) then
    return false, "outbound_transfer_target_mismatch"
  end
  local transferState = TrimText(transfer.state)
  if string.upper(TrimText(transfer.mode)) == "PREVIEW" then
    return false, "outbound_preview_transfer_does_not_accept_ack"
  end
  if transferState == "cancelled" or transferState == "failed" or transferState == "acked" or transferState == "superseded_acked" then
    return false, "outbound_transfer_is_terminal"
  end
  local resolvedSessionId = TrimText(expectedSessionId)
  if resolvedSessionId ~= "" and TrimText(transfer.sessionId) ~= "" and TrimText(transfer.sessionId) ~= resolvedSessionId then
    return false, "outbound_transfer_session_mismatch"
  end
  local resolvedProfileName = TrimText(expectedProfileName)
  if resolvedProfileName ~= "" and TrimText(transfer.profileName) ~= ""
    and string.lower(TrimText(transfer.profileName)) ~= string.lower(resolvedProfileName)
  then
    return false, "outbound_transfer_profile_mismatch"
  end
  local expectedProfileId = TrimText(transfer.profileId)
  local receivedProfileId = TrimText(appliedProfileId)
  if expectedProfileId ~= "" and receivedProfileId ~= ""
    and string.lower(expectedProfileId) ~= string.lower(receivedProfileId)
  then
    return false, "outbound_transfer_profile_id_mismatch"
  end
  local expectedChunkCount = math.max(0, tonumber(transfer.totalChunks) or 0)
  local receivedChunkCount = math.max(0, tonumber(appliedChunkCount) or 0)
  if expectedChunkCount > 0 and receivedChunkCount > 0 and expectedChunkCount ~= receivedChunkCount then
    return false, "outbound_transfer_chunk_count_mismatch"
  end
  local expectedGeneration = math.max(0, tonumber(transfer.generation) or 0)
  local receivedGeneration = math.max(0, tonumber(appliedGeneration) or 0)
  if expectedGeneration > 0 and receivedGeneration > 0 and receivedGeneration ~= expectedGeneration then
    if receivedGeneration < expectedGeneration then
      return false, "outbound_transfer_generation_stale"
    end
    return false, "outbound_transfer_generation_mismatch"
  end
  return true, transfer.state == "ack_timeout", resolvedSender
end

local function MarkOutboundProfileTransferAcked(
  transferId,
  sender,
  expectedSessionId,
  expectedProfileName,
  appliedGeneration,
  appliedProfileId,
  appliedChunkCount
)
  local resolvedTransferId = TrimText(transferId)
  local transfer = resolvedTransferId ~= "" and outboundProfileTransfers[resolvedTransferId] or nil
  local acknowledged, acknowledgedAfterTimeout, resolvedSender = INTERNAL_API.LIDCOUNCIL_ValidateOutboundProfileTransferAcknowledgement_Impl(
    transfer,
    sender,
    expectedSessionId,
    expectedProfileName,
    appliedGeneration,
    appliedProfileId,
    appliedChunkCount
  )
  if not acknowledged then
    return nil, acknowledgedAfterTimeout
  end
  transfer.ackedAt = GetNow()
  transfer.ackPhase = "APPLIED"
  transfer.target = FirstNonEmptyText(resolvedSender, transfer.target)
  if acknowledgedAfterTimeout then
    transfer.acknowledgedAfterTimeout = true
    outboundCommStats.lateProfileAckTotal = (tonumber(outboundCommStats.lateProfileAckTotal) or 0) + 1
  end
  if transfer.obsolete == true or IsSupersededTransferState(transfer.state) then
    transfer.state = "superseded_acked"
    transfer.terminalReason = "superseded_acknowledged"
  else
    transfer.state = "acked"
    transfer.terminalReason = acknowledgedAfterTimeout and "late_acknowledged" or "acknowledged"
  end
  INTERNAL_API.LIDCOUNCIL_PruneQueuedObsoleteProfileTransfers_Impl()
  PruneOutboundProfileTransfers()
  return transfer
end

INTERNAL_API.LIDCOUNCIL_MarkOutboundProfileTransferQueued_Impl = function(
  transferId,
  sender,
  expectedSessionId,
  expectedProfileName,
  appliedGeneration,
  appliedProfileId,
  appliedChunkCount
)
  local resolvedTransferId = TrimText(transferId)
  local transfer = resolvedTransferId ~= "" and outboundProfileTransfers[resolvedTransferId] or nil
  local acknowledged, acknowledgedAfterTimeout, resolvedSender = INTERNAL_API.LIDCOUNCIL_ValidateOutboundProfileTransferAcknowledgement_Impl(
    transfer,
    sender,
    expectedSessionId,
    expectedProfileName,
    appliedGeneration,
    appliedProfileId,
    appliedChunkCount
  )
  if not acknowledged then
    return nil, acknowledgedAfterTimeout
  end
  transfer.queuedAckAt = GetNow()
  transfer.ackPhase = "QUEUED"
  transfer.target = FirstNonEmptyText(resolvedSender, transfer.target)
  if acknowledgedAfterTimeout then
    transfer.acknowledgedAfterTimeout = true
    transfer.ackTimeoutRecoveryOutcome = "apply_queued_after_timeout"
  end
  transfer.failedAt = nil
  transfer.failureReason = ""
  if transfer.obsolete == true or IsSupersededTransferState(transfer.state) then
    transfer.state = "superseded_waiting_apply"
    transfer.terminalReason = "superseded_waiting_for_apply"
  else
    transfer.state = "waiting_apply"
    transfer.terminalReason = "waiting_for_remote_apply"
  end
  pendingOutboundProfileAckReconciliations[resolvedTransferId] = nil
  return transfer
end

local function AnnotateOutboundProfileTransfer(transferId, metadata)
  return EnsureOutboundProfileTransfer(transferId, metadata)
end

INTERNAL_API.LIDCOUNCIL_IsOutboundProfileTransferForSession_Impl = function(transfer, sessionId)
  local resolvedSessionId = TrimText(sessionId)
  return resolvedSessionId ~= ""
    and type(transfer) == "table"
    and TrimText(transfer.sessionId) == resolvedSessionId
end

INTERNAL_API.LIDCOUNCIL_GetOutboundProfileTransferAckTimerStatus_Impl = function(transfer)
  transfer = type(transfer) == "table" and transfer or {}
  return {
    scheduled = transfer.ackTimeoutTimerScheduled == true,
    fallbackAt = math.max(0, tonumber(transfer.ackTimeoutTimerFallbackAt) or 0),
    fallbackReason = TrimText(transfer.ackTimeoutTimerFallbackReason),
  }
end

local function GetSessionCommQueueStatus()
  INTERNAL_API.LIDCOUNCIL_PruneQueuedObsoleteProfileTransfers_Impl()
  PruneOutboundProfileTransfers()
  ProcessPendingOutboundProfileAckReconciliations()
  local byKind = {}
  local byPriority = {}
  local queuedItems = {}
  local nextReadyItem
  local queueNow = GetNow()
  for _, item in ipairs(outboundCommQueue) do
    local kind = TrimText(type(item) == "table" and item.kind or "")
    if kind ~= "" then
      byKind[kind] = (tonumber(byKind[kind]) or 0) + 1
    end
    local priority = math.max(1, GetOutboundCommQueueItemPriority(item))
    byPriority[tostring(priority)] = (tonumber(byPriority[tostring(priority)]) or 0) + 1
    if not nextReadyItem
      and math.max(0, tonumber(type(item) == "table" and item.notBeforeAt or 0) or 0) <= queueNow
    then
      nextReadyItem = BuildQueuedCommPreviewItem(item)
    end
    if #queuedItems < 6 then
      queuedItems[#queuedItems + 1] = BuildQueuedCommPreviewItem(item)
    end
  end
  local statusArchivePacing = type(outboundCommStats.archiveTargetPacing) == "table"
    and outboundCommStats.archiveTargetPacing
    or {}
  outboundCommStats.archiveTargetPacing = statusArchivePacing
  statusArchivePacing.burstLimit = math.max(1, tonumber(outboundCommStats.archiveTargetBurstLimit) or 2)
  if type(INTERNAL_API.LIDCOUNCIL_SelectReadyOutboundCommQueueIndex_Impl) == "function" then
    local pacedReadyIndex = INTERNAL_API.LIDCOUNCIL_SelectReadyOutboundCommQueueIndex_Impl(
      outboundCommQueue,
      queueNow,
      statusArchivePacing
    )
    if pacedReadyIndex then
      nextReadyItem = BuildQueuedCommPreviewItem(outboundCommQueue[pacedReadyIndex])
    end
  end

  local activeTransferSessionId = ""
  if type(commApi.GetActiveLootSession) == "function" then
    local activeSession = commApi.GetActiveLootSession()
    activeTransferSessionId = TrimText(type(activeSession) == "table" and activeSession.id or "")
  end
  local transfers = {}
  local activeProfileTransferCount = 0
  local awaitingProfileAckCount = 0
  local awaitingProfileApplyCount = 0
  local ackTimeoutProfileTransferCount = 0
  local unreconciledAckTimeoutCount = 0
  local pendingAckTimeoutRevalidationCount = 0
  local coalescedAckTimeoutRevalidationCount = 0
  local queuedAckTimeoutRecoveryCount = 0
  local skippedAckTimeoutRecoveryCount = 0
  local failedAckTimeoutRecoveryCount = 0
  local lateAcknowledgementCount = 0
  local failedProfileTransferCount = 0
  local completedPreviewTransferCount = 0
  local now = GetNow()
  for _, transferId in ipairs(outboundProfileTransferOrder) do
    local transfer = outboundProfileTransfers[transferId]
    if type(transfer) == "table" then
      local transferState = TrimText(transfer.state)
      local completedAt = math.max(0, tonumber(transfer.completedAt) or 0)
      local ackExpected = string.upper(TrimText(transfer.mode)) ~= "PREVIEW"
      local countsForActiveSession = INTERNAL_API.LIDCOUNCIL_IsOutboundProfileTransferForSession_Impl(transfer, activeTransferSessionId)
      if countsForActiveSession and (transferState == "queued" or transferState == "sending"
        or transferState == "waiting_ack" or transferState == "waiting_apply")
      then
        activeProfileTransferCount = activeProfileTransferCount + 1
      end
      if countsForActiveSession and transferState == "waiting_ack" then
        awaitingProfileAckCount = awaitingProfileAckCount + 1
      elseif countsForActiveSession and transferState == "waiting_apply" then
        awaitingProfileApplyCount = awaitingProfileApplyCount + 1
      elseif countsForActiveSession and transferState == "ack_timeout" then
        ackTimeoutProfileTransferCount = ackTimeoutProfileTransferCount + 1
        local recoveryOutcome = TrimText(transfer.ackTimeoutRecoveryOutcome)
        if math.max(0, tonumber(transfer.ackTimeoutRecoveryAttemptedAt) or 0) <= 0 or recoveryOutcome == "dispatching" then
          unreconciledAckTimeoutCount = unreconciledAckTimeoutCount + 1
        elseif recoveryOutcome == "revalidation_pending" then
          pendingAckTimeoutRevalidationCount = pendingAckTimeoutRevalidationCount + 1
          if transfer.ackTimeoutRevalidationCoalesced == true then
            coalescedAckTimeoutRevalidationCount = coalescedAckTimeoutRevalidationCount + 1
          end
        elseif recoveryOutcome == "queued" or recoveryOutcome == "deferred" then
          queuedAckTimeoutRecoveryCount = queuedAckTimeoutRecoveryCount + 1
        elseif recoveryOutcome == "not_host" or recoveryOutcome == "session_changed"
          or recoveryOutcome == "member_not_joined" or recoveryOutcome == "invalid_transfer"
        then
          skippedAckTimeoutRecoveryCount = skippedAckTimeoutRecoveryCount + 1
        elseif transfer.ackTimeoutRecoverySucceeded ~= true then
          failedAckTimeoutRecoveryCount = failedAckTimeoutRecoveryCount + 1
        end
      elseif countsForActiveSession and transferState == "failed" then
        failedProfileTransferCount = failedProfileTransferCount + 1
      elseif countsForActiveSession and transferState == "completed_preview" then
        completedPreviewTransferCount = completedPreviewTransferCount + 1
      end
      if countsForActiveSession and transfer.acknowledgedAfterTimeout == true then
        lateAcknowledgementCount = lateAcknowledgementCount + 1
      end
      local ackTimeoutTimerStatus = INTERNAL_API.LIDCOUNCIL_GetOutboundProfileTransferAckTimerStatus_Impl(transfer)
      transfers[#transfers + 1] = {
        transferId = transferId,
        target = TrimText(transfer.target),
        sessionId = TrimText(transfer.sessionId),
        profileName = TrimText(transfer.profileName),
        profileId = TrimText(transfer.profileId),
        mode = TrimText(transfer.mode),
        reason = TrimText(transfer.reason),
        transferKind = TrimText(transfer.transferKind),
        hostAuthoritativeOverride = transfer.hostAuthoritativeOverride == true,
        authoritativeArchiveScope = TrimText(transfer.authoritativeArchiveScope),
        domains = TrimText(transfer.domains),
        subdomains = TrimText(transfer.subdomains),
        scopeDomains = CloneProfileSyncTextList(transfer.scopeDomains),
        scopeSubdomains = CloneProfileSyncTextList(transfer.scopeSubdomains),
        lane = TrimText(transfer.lane),
        state = transferState,
        sentChunks = math.max(0, tonumber(transfer.sentChunks) or 0),
        totalChunks = math.max(0, tonumber(transfer.totalChunks) or 0),
        queuedMessages = math.max(0, tonumber(transfer.queuedMessages) or 0),
        attemptedMessages = math.max(0, tonumber(transfer.attemptedMessages) or 0),
        sentMessages = math.max(0, tonumber(transfer.sentMessages) or 0),
        throttledMessages = math.max(0, tonumber(transfer.throttledMessages) or 0),
        failedMessages = math.max(0, tonumber(transfer.failedMessages) or 0),
        bytesAttempted = math.max(0, tonumber(transfer.bytesAttempted) or 0),
        bytesSent = math.max(0, tonumber(transfer.bytesSent) or 0),
        failedKind = TrimText(transfer.failedKind),
        terminalReason = TrimText(transfer.terminalReason),
        failureReason = TrimText(transfer.failureReason),
        failureRetries = math.max(0, tonumber(transfer.failureRetries) or 0),
        droppedMessages = math.max(0, tonumber(transfer.droppedMessages) or 0),
        generation = math.max(0, tonumber(transfer.generation) or 0),
        queuedAt = tonumber(transfer.queuedAt) or 0,
        startedAt = tonumber(transfer.startedAt) or 0,
        completedAt = completedAt,
        queuedAckAt = tonumber(transfer.queuedAckAt) or 0,
        ackedAt = tonumber(transfer.ackedAt) or 0,
        failedAt = tonumber(transfer.failedAt) or 0,
        ackExpected = ackExpected,
        awaitingAck = transferState == "waiting_ack",
        awaitingApply = transferState == "waiting_apply",
        ageSeconds = math.max(0, now - math.max(0, tonumber(transfer.queuedAt) or 0)),
        acknowledgementAgeSeconds = transferState == "waiting_ack" and math.max(0, now - completedAt) or 0,
        acknowledgementDeadlineAt = ackExpected and completedAt > 0 and (completedAt + COMM_LIMITS.PROFILE_ACK_TIMEOUT_SECONDS) or 0,
        ackTimeoutRecoveryAttemptedAt = tonumber(transfer.ackTimeoutRecoveryAttemptedAt) or 0,
        ackTimeoutRecoverySucceeded = transfer.ackTimeoutRecoverySucceeded == true,
        ackTimeoutRecoveryOutcome = TrimText(transfer.ackTimeoutRecoveryOutcome),
        ackTimeoutRecoveryQueuedCount = math.max(0, tonumber(transfer.ackTimeoutRecoveryQueuedCount) or 0),
        ackTimeoutRecoveryError = TrimText(transfer.ackTimeoutRecoveryError),
        ackTimeoutRevalidationRequestedAt = tonumber(transfer.ackTimeoutRevalidationRequestedAt) or 0,
        ackTimeoutRevalidationDueAt = tonumber(transfer.ackTimeoutRevalidationDueAt) or 0,
        ackTimeoutRevalidationDomains = CloneProfileSyncTextList(transfer.ackTimeoutRevalidationDomains),
        ackTimeoutRevalidationKey = TrimText(transfer.ackTimeoutRevalidationKey),
        ackTimeoutRevalidationCoalesced = transfer.ackTimeoutRevalidationCoalesced == true,
        ackTimeoutRevalidationFresh = transfer.ackTimeoutRevalidationFresh == true,
        ackTimeoutRevalidationLoadedCount = math.max(0, tonumber(transfer.ackTimeoutRevalidationLoadedCount) or 0),
        ackTimeoutRevalidationFreshCount = math.max(0, tonumber(transfer.ackTimeoutRevalidationFreshCount) or 0),
        ackTimeoutTimerScheduled = ackTimeoutTimerStatus.scheduled,
        ackTimeoutTimerFallbackAt = ackTimeoutTimerStatus.fallbackAt,
        ackTimeoutTimerFallbackReason = ackTimeoutTimerStatus.fallbackReason,
        acknowledgedAfterTimeout = transfer.acknowledgedAfterTimeout == true,
      }
    end
  end
  local profileSnapshotBatch = type(profileSyncHelpers) == "table"
    and type(profileSyncHelpers.GetProfileSnapshotBatchStatus) == "function"
    and profileSyncHelpers.GetProfileSnapshotBatchStatus()
    or {}
  local preciseResponseSafety = type(profileSyncHelpers) == "table"
    and type(profileSyncHelpers.GetPreciseResponseSafetyStatus) == "function"
    and profileSyncHelpers.GetPreciseResponseSafetyStatus()
    or {}
  local optionalApiSafety = type(profileSyncHelpers) == "table"
    and type(profileSyncHelpers.GetOptionalApiSafetyStatus) == "function"
    and profileSyncHelpers.GetOptionalApiSafetyStatus()
    or {}
  local deltaAckStatus = {}
  if type(flowHelpers) == "table" and type(flowHelpers.GetProfileDeltaAckStatus) == "function" then
    local statusOk, status = pcall(flowHelpers.GetProfileDeltaAckStatus)
    if statusOk and type(status) == "table" then
      deltaAckStatus = status
    end
  end
  local ackTimeoutRevalidationStats = {}
  if type(flowHelpers) == "table" and type(flowHelpers.GetAckTimeoutRevalidationStats) == "function" then
    local activeSession = type(commApi.GetActiveLootSession) == "function" and commApi.GetActiveLootSession() or nil
    if type(activeSession) == "table" then
      local statsOk, stats = pcall(flowHelpers.GetAckTimeoutRevalidationStats, activeSession.id)
      if statsOk and type(stats) == "table" then
        ackTimeoutRevalidationStats = stats
      end
    end
  end
  local batchPendingTargets = math.max(0, tonumber(type(profileSnapshotBatch) == "table" and profileSnapshotBatch.pendingTargets) or 0)
  local batchRunning = type(profileSnapshotBatch) == "table" and profileSnapshotBatch.running == true
  PruneOutboundSendWindow(now)
  PruneRecentOutboundRequestItems(now)
  local rollingBytes = 0
  for _, sample in ipairs(outboundCommSendWindow) do
    rollingBytes = rollingBytes + math.max(0, tonumber(sample.bytes) or 0)
  end
  local rollingWindowSeconds = 10
  local inboundStatus = inboundCommOps.snapshot()
  local inboundRateLimitStatus = {}
  if type(inboundRateLimiter) == "table" and type(inboundRateLimiter.Snapshot) == "function" then
    local statusOk, status = pcall(inboundRateLimiter.Snapshot)
    if statusOk and type(status) == "table" then
      inboundRateLimitStatus = status
    end
  end
  local protocolContractSnapshot = GetCommProtocolContractSnapshot()
  local protocolHandlerStatus = type(GetCommProtocolHandlerRegistryStatus) == "function"
    and GetCommProtocolHandlerRegistryStatus()
    or {}
  local outboundLaneTelemetry = INTERNAL_API.LIDCOUNCIL_GetOutboundCommLaneTelemetry_Impl()
  local outboundMemberTelemetry = INTERNAL_API.LIDCOUNCIL_GetOutboundCommMemberTelemetry_Impl()
  local outboundSessionTelemetry = INTERNAL_API.LIDCOUNCIL_GetOutboundSessionTelemetry_Impl()
  local timerFallbackStatus = {
    queue = outboundTimerAdapter.BuildSessionTimerFallbackStatus(
      outboundSessionTelemetry.timerFallbackTotal,
      outboundCommStats.timerFallbackTotal,
      outboundCommStats.lastTimerFallbackAt,
      outboundCommStats.lastTimerFallbackReason
    ),
    profileAck = outboundTimerAdapter.BuildSessionTimerFallbackStatus(
      outboundSessionTelemetry.profileAckTimeoutTimerFallbackTotal,
      outboundCommStats.profileAckTimeoutTimerFallbackTotal,
      outboundCommStats.lastProfileAckTimeoutTimerFallbackAt,
      outboundCommStats.lastProfileAckTimeoutTimerFallbackReason
    ),
    deferredEditorRefresh = outboundTimerAdapter.BuildSessionTimerFallbackStatus(
      outboundSessionTelemetry.deferredEditorRefreshTimerFallbackTotal,
      deferredEditorRefreshState.timerFallbackTotal,
      deferredEditorRefreshState.lastTimerFallbackAt,
      deferredEditorRefreshState.lastTimerFallbackReason
    ),
  }
  local compatTimerStatus = {}
  do
    local compat = rawget(_G, "LIDCOUNCIL_Compat")
    if type(compat) == "table" and type(compat.GetTimerStatus) == "function" then
      local statusOk, status = pcall(compat.GetTimerStatus)
      if statusOk and type(status) == "table" then
        compatTimerStatus = status
      end
    end
  end
  local queuedByOpcode = {}
  local queuedByLane = {}
  for _, item in ipairs(outboundCommQueue) do
    local kind = TrimText(type(item) == "table" and item.kind or "")
    local metadata = type(item) == "table" and type(item.metadata) == "table" and item.metadata or {}
    local queuedSessionId = type(INTERNAL_API.LIDCOUNCIL_ResolveOutboundSessionBoundQueueSessionId_Impl) == "function"
      and INTERNAL_API.LIDCOUNCIL_ResolveOutboundSessionBoundQueueSessionId_Impl(kind, metadata)
      or TrimText(metadata.sessionId)
    local includeQueuedItem = activeTransferSessionId == ""
      and queuedSessionId == ""
      or activeTransferSessionId ~= ""
        and (queuedSessionId == "" or queuedSessionId == activeTransferSessionId)
    if includeQueuedItem and kind ~= "" then
      queuedByOpcode[kind] = math.max(0, tonumber(queuedByOpcode[kind]) or 0) + 1
      local lane = type(INTERNAL_API.LIDCOUNCIL_ResolveOutboundCommTelemetryLane_Impl) == "function"
        and INTERNAL_API.LIDCOUNCIL_ResolveOutboundCommTelemetryLane_Impl(item)
        or "control"
      lane = TrimText(lane)
      if lane == "" then
        lane = "control"
      end
      queuedByLane[lane] = math.max(0, tonumber(queuedByLane[lane]) or 0) + 1
    end
  end
  local sessionLaneTelemetry = type(outboundSessionTelemetry.outboundLaneTelemetry) == "table"
    and outboundSessionTelemetry.outboundLaneTelemetry
    or {}
  for _, lane in ipairs({ "live", "bootstrap", "archive", "stats", "control" }) do
    local entry = type(sessionLaneTelemetry[lane]) == "table" and sessionLaneTelemetry[lane] or {}
    entry.queuedNow = math.max(0, tonumber(queuedByLane[lane]) or 0)
    sessionLaneTelemetry[lane] = entry
  end
  outboundSessionTelemetry.outboundLaneTelemetry = sessionLaneTelemetry
  outboundSessionTelemetry.outboundLanePressure = type(INTERNAL_API.LIDCOUNCIL_BuildOutboundLanePressure_Impl) == "function"
    and INTERNAL_API.LIDCOUNCIL_BuildOutboundLanePressure_Impl(
      sessionLaneTelemetry,
      outboundCommStats.lanePressureThresholds
    )
    or {}
  local sessionOpcodeTelemetry = type(outboundSessionTelemetry.outboundOpcodeTelemetry) == "table"
    and outboundSessionTelemetry.outboundOpcodeTelemetry
    or { opcodes = {} }
  local sessionOpcodeRows = type(sessionOpcodeTelemetry.opcodes) == "table" and sessionOpcodeTelemetry.opcodes or {}
  local sessionOpcodeRowsByKind = {}
  for _, opcode in ipairs(sessionOpcodeRows) do
    if type(opcode) == "table" then
      opcode.queuedNow = math.max(0, tonumber(queuedByOpcode[TrimText(opcode.kind)]) or 0)
      sessionOpcodeRowsByKind[TrimText(opcode.kind)] = opcode
    end
  end
  for kind, queuedNow in pairs(queuedByOpcode) do
    if type(sessionOpcodeRowsByKind[kind]) ~= "table" then
      sessionOpcodeRows[#sessionOpcodeRows + 1] = {
        kind = kind,
        queuedTotal = 0,
        queuedNow = math.max(0, tonumber(queuedNow) or 0),
        attempted = 0,
        sent = 0,
        throttled = 0,
        failed = 0,
        payloadRejected = 0,
        bytesQueued = 0,
        bytesAttempted = 0,
        bytesSent = 0,
        bytesRejected = 0,
      }
    end
  end
  table.sort(sessionOpcodeRows, function(left, right)
    if left.bytesSent ~= right.bytesSent then
      return left.bytesSent > right.bytesSent
    end
    if left.bytesAttempted ~= right.bytesAttempted then
      return left.bytesAttempted > right.bytesAttempted
    end
    if left.queuedNow ~= right.queuedNow then
      return left.queuedNow > right.queuedNow
    end
    if left.queuedTotal ~= right.queuedTotal then
      return left.queuedTotal > right.queuedTotal
    end
    return string.lower(TrimText(left.kind)) < string.lower(TrimText(right.kind))
  end)
  sessionOpcodeTelemetry.opcodes = sessionOpcodeRows
  sessionOpcodeTelemetry.pressure = type(INTERNAL_API.LIDCOUNCIL_BuildOutboundOpcodePressure_Impl) == "function"
    and INTERNAL_API.LIDCOUNCIL_BuildOutboundOpcodePressure_Impl(
      sessionOpcodeRows,
      outboundCommStats.opcodePressureThresholds
    )
    or {}
  outboundSessionTelemetry.outboundOpcodeTelemetry = sessionOpcodeTelemetry
  local outboundIssueDiagnostics = type(INTERNAL_API.LIDCOUNCIL_GetOutboundIssueDiagnosticsForSession_Impl) == "function"
    and INTERNAL_API.LIDCOUNCIL_GetOutboundIssueDiagnosticsForSession_Impl(activeTransferSessionId)
    or {}
  local payloadRejectHistory = {}
  for _, entry in ipairs(type(outboundCommStats.payloadRejectHistory) == "table" and outboundCommStats.payloadRejectHistory or {}) do
    if type(entry) == "table" then
      payloadRejectHistory[#payloadRejectHistory + 1] = {
        kind = TrimText(entry.kind),
        reason = TrimText(entry.reason),
        bytes = math.max(0, tonumber(entry.bytes) or 0),
        sessionId = TrimText(entry.sessionId),
        target = NormalizeCharacterKey(entry.target),
        scope = TrimText(entry.scope),
        transferId = TrimText(entry.transferId),
        lane = TrimText(entry.lane),
        mode = TrimText(entry.mode),
        transferKind = TrimText(entry.transferKind),
        at = math.max(0, tonumber(entry.at) or 0),
      }
    end
  end
  local outboundIssueHistory = {}
  for _, entry in ipairs(type(outboundCommStats.outboundIssueHistory) == "table" and outboundCommStats.outboundIssueHistory or {}) do
    if type(entry) == "table" and #outboundIssueHistory < 8 then
      outboundIssueHistory[#outboundIssueHistory + 1] = {
        category = TrimText(entry.category),
        kind = TrimText(entry.kind),
        reason = TrimText(entry.reason),
        bytes = math.max(0, tonumber(entry.bytes) or 0),
        sessionId = TrimText(entry.sessionId),
        target = NormalizeCharacterKey(entry.target),
        scope = TrimText(entry.scope),
        transferId = TrimText(entry.transferId),
        lane = TrimText(entry.lane),
        mode = TrimText(entry.mode),
        transferKind = TrimText(entry.transferKind),
        at = math.max(0, tonumber(entry.at) or 0),
      }
    end
  end

  local nextDispatchItem = nextReadyItem or queuedItems[1]
  local startupHealthStatus = {}
  do
    local getStartupHealthStatus = ResolveOptionalApiFunction("LIDCOUNCIL_GetStartupHealthStatus")
    if type(getStartupHealthStatus) == "function" then
      local statusOk, status = pcall(getStartupHealthStatus)
      if statusOk and type(status) == "table" then
        startupHealthStatus = status
      end
    end
  end
  return {
    running = outboundCommQueueRunning and true or false,
    pending = #outboundCommQueue,
    atCapacity = #outboundCommQueue >= math.max(1, tonumber(outboundCommStats.maxQueueDepth) or 6000),
    usingCriticalOverflow = #outboundCommQueue > math.max(1, tonumber(outboundCommStats.maxQueueDepth) or 6000),
    busy = outboundCommQueueRunning or #outboundCommQueue > 0 or batchPendingTargets > 0 or batchRunning,
    intervalSeconds = GetCommOutboundIntervalSeconds(),
    profileSyncChunkSize = GetProfileSnapshotChunkSize(),
    byKind = byKind,
    byPriority = byPriority,
    nextKind = TrimText(type(nextDispatchItem) == "table" and nextDispatchItem.kind or ""),
    nextPriority = math.max(0, tonumber(type(nextDispatchItem) == "table" and nextDispatchItem.priority or 0) or 0),
    nextFlushAt = math.max(0, tonumber(outboundCommFlushState.nextAt) or 0),
    nextItem = nextDispatchItem,
    queuedItems = queuedItems,
    queuedTotal = tonumber(outboundCommStats.queuedTotal) or 0,
    coalescedTotal = tonumber(outboundCommStats.coalescedTotal) or 0,
    archiveYieldSeconds = math.max(0.05, tonumber(outboundCommStats.archiveYieldSeconds) or 0.75),
    archivePressureDeferredTotal = math.max(0, tonumber(outboundSessionTelemetry.archivePressureDeferredTotal) or 0),
    totalArchivePressureDeferredTotal = math.max(0, tonumber(outboundCommStats.archivePressureDeferredTotal) or 0),
    lastArchivePressureDeferredAt = math.max(0, tonumber(outboundCommStats.lastArchivePressureDeferredAt) or 0),
    lastArchivePressureDeferredReason = TrimText(outboundCommStats.lastArchivePressureDeferredReason),
    archiveTargetBurstLimit = math.max(1, tonumber(outboundCommStats.archiveTargetBurstLimit) or 2),
    archiveTargetPacingPreemptionsTotal = math.max(0,
      tonumber(outboundSessionTelemetry.archiveTargetPacingPreemptionsTotal) or 0),
    totalArchiveTargetPacingPreemptionsTotal = math.max(0,
      tonumber(type(outboundCommStats.archiveTargetPacing) == "table" and outboundCommStats.archiveTargetPacing.preemptionsTotal or 0) or 0),
    lastArchiveTargetPacingTarget = NormalizeCharacterKey(
      type(outboundCommStats.archiveTargetPacing) == "table" and outboundCommStats.archiveTargetPacing.lastPreemptedTarget or ""
    ),
    lastArchiveTargetPacingAt = math.max(0,
      tonumber(type(outboundCommStats.archiveTargetPacing) == "table" and outboundCommStats.archiveTargetPacing.lastPreemptedAt or 0) or 0),
    obsoleteProfileQueuePrunedTotal = math.max(0,
      tonumber(outboundSessionTelemetry.obsoleteProfileQueuePrunedTotal) or 0),
    totalObsoleteProfileQueuePrunedTotal = math.max(0, tonumber(outboundCommStats.obsoleteProfileQueuePrunedTotal) or 0),
    lastObsoleteProfileQueuePrunedAt = math.max(0, tonumber(outboundCommStats.lastObsoleteProfileQueuePrunedAt) or 0),
    attemptedTotal = tonumber(outboundCommStats.attemptedTotal) or 0,
    sentTotal = tonumber(outboundCommStats.sentTotal) or 0,
    throttledTotal = tonumber(outboundCommStats.throttledTotal) or 0,
    failedTotal = tonumber(outboundCommStats.failedTotal) or 0,
    timerFallbackTotal = timerFallbackStatus.queue.sessionTotal,
    totalTimerFallbackTotal = timerFallbackStatus.queue.runtimeTotal,
    lastTimerFallbackAt = timerFallbackStatus.queue.lastAt,
    lastTimerFallbackReason = timerFallbackStatus.queue.lastReason,
    deferredEditorRefreshTimerFallbackTotal = timerFallbackStatus.deferredEditorRefresh.sessionTotal,
    totalDeferredEditorRefreshTimerFallbackTotal = timerFallbackStatus.deferredEditorRefresh.runtimeTotal,
    lastDeferredEditorRefreshTimerFallbackAt = timerFallbackStatus.deferredEditorRefresh.lastAt,
    lastDeferredEditorRefreshTimerFallbackReason = timerFallbackStatus.deferredEditorRefresh.lastReason,
    compatTimerStatus = compatTimerStatus,
    startupHealthStatus = startupHealthStatus,
    startupHealthRan = startupHealthStatus.ran == true,
    startupHealthReady = startupHealthStatus.ready == true,
    startupHealthSeverity = TrimText(startupHealthStatus.severity),
    startupHealthCheckCount = math.max(0, tonumber(startupHealthStatus.checkCount) or 0),
    startupHealthPassedCount = math.max(0, tonumber(startupHealthStatus.passedCount) or 0),
    startupHealthWarningCount = math.max(0, tonumber(startupHealthStatus.warningCount) or 0),
    startupHealthErrorCount = math.max(0, tonumber(startupHealthStatus.errorCount) or 0),
    compatTimerFallbackTotal = math.max(0, tonumber(compatTimerStatus.fallbackTotal) or 0),
    compatTimerFrameFallbackTotal = math.max(0, tonumber(compatTimerStatus.frameFallbackTotal) or 0),
    compatTimerImmediateFallbackTotal = math.max(0, tonumber(compatTimerStatus.immediateFallbackTotal) or 0),
    compatTimerNativeFailureTotal = math.max(0, tonumber(compatTimerStatus.nativeFailureTotal) or 0),
    compatTimerNativeUnavailableTotal = math.max(0, tonumber(compatTimerStatus.nativeUnavailableTotal) or 0),
    lastCompatTimerFallbackAt = math.max(0, tonumber(compatTimerStatus.lastFallbackAt) or 0),
    lastCompatTimerFallbackReason = TrimText(compatTimerStatus.lastFallbackReason),
    lastCompatTimerNativeError = TrimText(compatTimerStatus.lastNativeError),
    activeProfileSyncQueueSessionId = TrimText(outboundCommStats.activeProfileSyncQueueSessionId),
    staleSessionBoundPrunedTotal = math.max(0, tonumber(outboundCommStats.staleSessionBoundPrunedTotal) or 0),
    lastStaleSessionBoundPrunedAt = math.max(0, tonumber(outboundCommStats.lastStaleSessionBoundPrunedAt) or 0),
    retriedFailureTotal = tonumber(outboundCommStats.retriedFailureTotal) or 0,
    retriedThrottleTotal = tonumber(outboundCommStats.retriedThrottleTotal) or 0,
    globalThrottleCooldownRemaining = math.max(0,
      math.max(0, tonumber(outboundCommStats.globalThrottleNotBeforeAt) or 0) - GetNow()),
    globalThrottleStreak = math.max(0, tonumber(outboundCommStats.globalThrottleStreak) or 0),
    lastGlobalThrottleCooldownSeconds = math.max(0,
      tonumber(outboundCommStats.lastGlobalThrottleCooldownSeconds) or 0),
    lastGlobalThrottleRecoveryIntervalSeconds = math.max(0,
      tonumber(outboundCommStats.lastGlobalThrottleRecoveryIntervalSeconds) or 0),
    chatLockdownActive = outboundCommStats.chatLockdownActive == true
      or INTERNAL_API.LIDCOUNCIL_IsChatMessagingLockdownActive_Impl() == true,
    chatLockdownDeferredTotal = math.max(0, tonumber(outboundCommStats.chatLockdownDeferredTotal) or 0),
    chatLockdownStartedAt = math.max(0, tonumber(outboundCommStats.chatLockdownStartedAt) or 0),
    lastChatLockdownAt = math.max(0, tonumber(outboundCommStats.lastChatLockdownAt) or 0),
    lastChatLockdownReleasedAt = math.max(0,
      tonumber(outboundCommStats.lastChatLockdownReleasedAt) or 0),
    terminalFailureTotal = tonumber(outboundCommStats.terminalFailureTotal) or 0,
    profileAckTimeoutTotal = tonumber(outboundCommStats.profileAckTimeoutTotal) or 0,
    profileAckTimeoutTimerFallbackTotal = timerFallbackStatus.profileAck.sessionTotal,
    totalProfileAckTimeoutTimerFallbackTotal = timerFallbackStatus.profileAck.runtimeTotal,
    lastProfileAckTimeoutTimerFallbackAt = timerFallbackStatus.profileAck.lastAt,
    lastProfileAckTimeoutTimerFallbackReason = timerFallbackStatus.profileAck.lastReason,
    lateProfileAckTotal = tonumber(outboundCommStats.lateProfileAckTotal) or 0,
    droppedOverflowTotal = tonumber(outboundCommStats.droppedOverflowTotal) or 0,
    prefixRegistrationAttempts = math.max(0, tonumber(outboundCommStats.prefixRegistrationAttempts) or 0),
    prefixRegistrationFailures = math.max(0, tonumber(outboundCommStats.prefixRegistrationFailures) or 0),
    prefixRegistered = prefixRegistered == true,
    prefixRegistrationActiveFailure = outboundCommStats.prefixRegistrationActiveFailure == true,
    prefixRegistrationUnavailable = outboundCommStats.prefixRegistrationUnavailable == true,
    prefixRegistrationEvidence = TrimText(outboundCommStats.prefixRegistrationEvidence),
    lastPrefixRegistrationSuccessAt = math.max(0, tonumber(outboundCommStats.lastPrefixRegistrationSuccessAt) or 0),
    lastPrefixRegistrationError = TrimText(outboundCommStats.lastPrefixRegistrationError),
    rejectedProtocolFieldTotal = math.max(0, tonumber(outboundCommStats.rejectedProtocolFieldTotal) or 0),
    rejectedProtocolMinimumTotal = math.max(0, tonumber(outboundCommStats.rejectedProtocolMinimumTotal) or 0),
    lastRejectedProtocolMinimumKind = TrimText(outboundCommStats.lastRejectedProtocolMinimumKind),
    rejectedPayloadTotal = math.max(0, tonumber(outboundIssueDiagnostics.payloadRejectedTotal) or 0),
    totalRejectedPayloadTotal = math.max(0, tonumber(outboundCommStats.rejectedPayloadTotal) or 0),
    lastRejectedPayloadKind = TrimText(outboundCommStats.lastRejectedPayloadKind),
    lastRejectedPayloadReason = TrimText(outboundCommStats.lastRejectedPayloadReason),
    lastRejectedPayloadBytes = math.max(0, tonumber(outboundCommStats.lastRejectedPayloadBytes) or 0),
    lastRejectedPayloadAt = math.max(0, tonumber(outboundCommStats.lastRejectedPayloadAt) or 0),
    payloadRejectHistory = payloadRejectHistory,
    apiFailureTotal = math.max(0, tonumber(outboundIssueDiagnostics.apiFailureTotal) or 0),
    totalApiFailureTotal = math.max(0, tonumber(outboundCommStats.apiFailureTotal) or 0),
    throttleExhaustedTotal = math.max(0, tonumber(outboundIssueDiagnostics.throttleExhaustedTotal) or 0),
    totalThrottleExhaustedTotal = math.max(0, tonumber(outboundCommStats.throttleExhaustedTotal) or 0),
    lastOutboundIssueCategory = TrimText(outboundIssueDiagnostics.lastCategory),
    lastOutboundIssueKind = TrimText(outboundIssueDiagnostics.lastKind),
    lastOutboundIssueReason = TrimText(outboundIssueDiagnostics.lastReason),
    lastOutboundIssueBytes = math.max(0, tonumber(outboundIssueDiagnostics.lastBytes) or 0),
    lastOutboundIssueAt = math.max(0, tonumber(outboundIssueDiagnostics.lastAt) or 0),
    lastOutboundIssueResolvedKind = TrimText(outboundIssueDiagnostics.lastResolvedKind),
    lastOutboundIssueResolvedTarget = NormalizeCharacterKey(outboundIssueDiagnostics.lastResolvedTarget),
    lastOutboundIssueResolvedAt = math.max(0, tonumber(outboundIssueDiagnostics.lastResolvedAt) or 0),
    outboundDiagnosticState = TrimText(outboundIssueDiagnostics.state),
    outboundIssueUnresolved = outboundIssueDiagnostics.unresolved == true,
    outboundIssueRecovered = outboundIssueDiagnostics.recovered == true,
    outboundPayloadFallbackRecovered = outboundIssueDiagnostics.fallbackRecovered == true,
    outboundIssueHistory = type(outboundIssueDiagnostics.history) == "table" and outboundIssueDiagnostics.history or outboundIssueHistory,
    outboundIssueScopeSessionId = TrimText(outboundIssueDiagnostics.sessionId),
    maxQueueDepth = math.max(1, tonumber(outboundCommStats.maxQueueDepth) or 6000),
    maxCriticalQueueOverflow = math.max(0, tonumber(outboundCommStats.maxCriticalQueueOverflow) or 0),
    maxFailureRetries = math.max(0, tonumber(outboundCommStats.maxFailureRetries) or 0),
    maxThrottleRetries = math.max(0, tonumber(outboundCommStats.maxThrottleRetries) or 0),
    bytesAttempted = tonumber(outboundCommStats.bytesAttempted) or 0,
    bytesSent = tonumber(outboundCommStats.bytesSent) or 0,
    outboundLaneTelemetry = outboundLaneTelemetry,
    outboundMemberTelemetry = outboundMemberTelemetry,
    outboundSessionTelemetry = outboundSessionTelemetry,
    sendRatePerSecond = #outboundCommSendWindow / rollingWindowSeconds,
    byteRatePerSecond = rollingBytes / rollingWindowSeconds,
    currentThrottleActive = (outboundCommQueueRunning or #outboundCommQueue > 0)
      and (math.max(0, tonumber(outboundCommStats.globalThrottleNotBeforeAt) or 0) > GetNow()
        or (math.max(0, tonumber(outboundCommStats.lastThrottleAt) or 0) > 0
          and GetNow() - math.max(0, tonumber(outboundCommStats.lastThrottleAt) or 0) <= 3)),
    currentFailureRetryActive = (outboundCommQueueRunning or #outboundCommQueue > 0)
      and math.max(0, tonumber(outboundCommStats.lastFailureAt) or 0) > 0
      and GetNow() - math.max(0, tonumber(outboundCommStats.lastFailureAt) or 0) <= 3,
    inboundTotal = math.max(0, tonumber(inboundStatus.receivedTotal) or 0),
    inboundBytes = math.max(0, tonumber(inboundStatus.receivedBytes) or 0),
    inboundDispatchedTotal = math.max(0, tonumber(inboundStatus.dispatchedTotal) or 0),
    inboundRejectedTotal = math.max(0, tonumber(inboundStatus.rejectedTotal) or 0),
    inboundRejectedContractTotal = math.max(0, tonumber(inboundStatus.rejectedContractTotal) or 0),
    inboundUnknownOpcodeTotal = math.max(0, tonumber(inboundStatus.unknownOpcodeTotal) or 0),
    inboundStaleSessionBoundDropTotal = math.max(0, tonumber(inboundStatus.staleSessionBoundDropTotal) or 0),
    inboundHandlerErrorTotal = math.max(0, tonumber(inboundStatus.handlerErrorTotal) or 0),
    inboundRateLimitStatus = inboundRateLimitStatus,
    inboundRateLimitedTotal = math.max(0, tonumber(inboundRateLimitStatus.rateLimitedTotal) or 0),
    inboundRateLimitedByLane = inboundRateLimitStatus.rateLimitedByLane,
    inboundRateLimitedByKind = inboundRateLimitStatus.rateLimitedByKind,
    inboundByKind = inboundStatus.byKind,
    inboundStageByKind = inboundStatus.stageByKind,
    inboundDispatchedByKind = inboundStatus.dispatchedByKind,
    inboundBytesByKind = inboundStatus.bytesByKind,
    inboundRejectedByKind = inboundStatus.rejectedByKind,
    inboundRejectedByReason = inboundStatus.rejectedByReason,
    inboundRejectionCategories = inboundStatus.rejectionCategories,
    inboundMalformedTotal = math.max(0, tonumber(type(inboundStatus.rejectionCategories) == "table"
      and inboundStatus.rejectionCategories.malformed or 0) or 0),
    inboundAdmissionDropTotal = math.max(0, tonumber(type(inboundStatus.rejectionCategories) == "table"
      and inboundStatus.rejectionCategories.admission_drop or 0) or 0),
    inboundClassifiedRateLimitedTotal = math.max(0, tonumber(type(inboundStatus.rejectionCategories) == "table"
      and inboundStatus.rejectionCategories.rate_limited or 0) or 0),
    inboundClassifiedStaleTotal = math.max(0, tonumber(type(inboundStatus.rejectionCategories) == "table"
      and inboundStatus.rejectionCategories.stale or 0) or 0),
    inboundRejectedContractByKind = inboundStatus.rejectedContractByKind,
    inboundUnknownOpcodeByKind = inboundStatus.unknownOpcodeByKind,
    inboundHandlerErrorByKind = inboundStatus.handlerErrorByKind,
    inboundBySender = inboundStatus.bySender,
    inboundRatePerSecond = tonumber(inboundStatus.messageRatePerSecond) or 0,
    inboundByteRatePerSecond = tonumber(inboundStatus.byteRatePerSecond) or 0,
    inboundDispatchedRatePerSecond = tonumber(inboundStatus.dispatchedMessageRatePerSecond) or 0,
    inboundDispatchedByteRatePerSecond = tonumber(inboundStatus.dispatchedByteRatePerSecond) or 0,
    inboundWindowSeconds = math.max(1, tonumber(inboundStatus.windowSeconds) or 10),
    maxInboundPayloadBytes = math.max(1, tonumber(inboundStatus.maxPayloadBytes) or 1024),
    maxInboundPayloadFields = math.max(1, tonumber(inboundStatus.maxPayloadFields) or 40),
    lastInboundAt = math.max(0, tonumber(inboundStatus.lastReceivedAt) or 0),
    lastInboundDispatchedAt = math.max(0, tonumber(inboundStatus.lastDispatchedAt) or 0),
    lastInboundDispatchedSender = NormalizeCharacterKey(inboundStatus.lastDispatchedSender),
    lastInboundRejectedAt = math.max(0, tonumber(inboundStatus.lastRejectedAt) or 0),
    lastInboundRejectedReason = TrimText(inboundStatus.lastRejectedReason),
    lastInboundRejectedContractKind = TrimText(inboundStatus.lastRejectedContractKind),
    lastInboundRejectedContractAt = math.max(0, tonumber(inboundStatus.lastRejectedContractAt) or 0),
    lastInboundUnknownOpcode = TrimText(inboundStatus.lastUnknownOpcode),
    lastInboundUnknownOpcodeAt = math.max(0, tonumber(inboundStatus.lastUnknownOpcodeAt) or 0),
    lastInboundHandlerErrorAt = math.max(0, tonumber(inboundStatus.lastHandlerErrorAt) or 0),
    lastInboundHandlerErrorKind = TrimText(inboundStatus.lastHandlerErrorKind),
    lastInboundHandlerErrorSender = TrimText(inboundStatus.lastHandlerErrorSender),
    lastInboundHandlerErrorDetail = TrimText(inboundStatus.lastHandlerErrorDetail),
    lastInboundRateLimitedAt = math.max(0, tonumber(inboundRateLimitStatus.lastRateLimitedAt) or 0),
    lastInboundRateLimitedSender = TrimText(inboundRateLimitStatus.lastRateLimitedSender),
    lastInboundRateLimitedKind = TrimText(inboundRateLimitStatus.lastRateLimitedKind),
    lastInboundRateLimitedLane = TrimText(inboundRateLimitStatus.lastRateLimitedLane),
    lastInboundRateLimitedReason = TrimText(inboundRateLimitStatus.lastRateLimitedReason),
    commProtocolContractVersion = math.max(1, tonumber(protocolContractSnapshot.version) or 1),
    commProtocolContractCount = math.max(0, tonumber(protocolContractSnapshot.opcodeCount) or 0),
    commProtocolContractCategories = protocolContractSnapshot.categoryCounts,
    commProtocolHandlerCount = math.max(0, tonumber(protocolHandlerStatus.handlerCount) or 0),
    commProtocolMissingHandlerCount = math.max(0, tonumber(protocolHandlerStatus.missingCount) or 0),
    commProtocolMissingHandlers = protocolHandlerStatus.missingHandlers,
    commProtocolOwnerMismatchCount = math.max(0, tonumber(protocolHandlerStatus.ownerMismatchCount) or 0),
    commProtocolOwnerMismatches = protocolHandlerStatus.ownerMismatches,
    commProtocolUncontractedHandlerCount = math.max(0, tonumber(protocolHandlerStatus.uncontractedCount) or 0),
    stalePreciseResponseDrops = math.max(0, tonumber(preciseResponseSafety.staleResponseDrops) or 0),
    lastStalePreciseResponseDropAt = math.max(0, tonumber(preciseResponseSafety.lastStaleResponseDropAt) or 0),
    pendingProfileDeltaAcks = math.max(0, tonumber(deltaAckStatus.pending) or 0),
    pendingProfileDeltaAckMembers = math.max(0, tonumber(deltaAckStatus.pendingMembers) or 0),
    queuedProfileDeltaAckMembers = math.max(0, tonumber(deltaAckStatus.queuedMembers) or 0),
    profileDeltaAckSupersededTotal = math.max(0, tonumber(deltaAckStatus.supersededTotal) or 0),
    optionalApiUnavailableCount = math.max(0, tonumber(optionalApiSafety.unavailableCount) or 0),
    optionalApiFailureCount = math.max(0, tonumber(optionalApiSafety.failureCount) or 0),
    recentSuppressedRequestWindowSeconds = COMM_LIMITS.RECENT_REQUEST_SUPPRESSION_SECONDS,
    recentSuppressedRequestCount = #recentOutboundRequestItems,
    lastQueuedAt = tonumber(outboundCommStats.lastQueuedAt) or 0,
    lastAttemptAt = tonumber(outboundCommStats.lastAttemptAt) or 0,
    lastSentAt = tonumber(outboundCommStats.lastSentAt) or 0,
    lastThrottleAt = tonumber(outboundCommStats.lastThrottleAt) or 0,
    lastFailureAt = tonumber(outboundCommStats.lastFailureAt) or 0,
    lastFailureReason = TrimText(outboundCommStats.lastFailureReason),
    profileTransfers = transfers,
    profileTransferStatus = {
      sessionId = activeTransferSessionId,
      active = activeProfileTransferCount,
      awaitingAcknowledgement = awaitingProfileAckCount,
      awaitingApplication = awaitingProfileApplyCount,
      acknowledgementTimeouts = ackTimeoutProfileTransferCount,
      unreconciledAcknowledgementTimeouts = unreconciledAckTimeoutCount,
      pendingAcknowledgementTimeoutRevalidations = pendingAckTimeoutRevalidationCount,
      coalescedAcknowledgementTimeoutRevalidations = coalescedAckTimeoutRevalidationCount,
      queuedAcknowledgementTimeoutRecoveries = queuedAckTimeoutRecoveryCount,
      skippedAcknowledgementTimeoutRecoveries = skippedAckTimeoutRecoveryCount,
      failedAcknowledgementTimeoutRecoveries = failedAckTimeoutRecoveryCount,
      acknowledgementsReceivedAfterTimeout = lateAcknowledgementCount,
      failed = failedProfileTransferCount,
      completedPreviews = completedPreviewTransferCount,
    },
    ackTimeoutRevalidationStats = {
      sessionId = TrimText(ackTimeoutRevalidationStats.sessionId),
      suppressedDomainTotal = math.max(0, tonumber(ackTimeoutRevalidationStats.suppressedDomainTotal) or 0),
      coalescedRecoveryCallbackTotal = math.max(0, tonumber(ackTimeoutRevalidationStats.coalescedRecoveryCallbackTotal) or 0),
      sharedRecoveryBatchTotal = math.max(0, tonumber(ackTimeoutRevalidationStats.sharedRecoveryBatchTotal) or 0),
      sharedRecoveryTransferTotal = math.max(0, tonumber(ackTimeoutRevalidationStats.sharedRecoveryTransferTotal) or 0),
      lastSuppressedDomainCount = math.max(0, tonumber(ackTimeoutRevalidationStats.lastSuppressedDomainCount) or 0),
      lastSharedRecoveryTransferCount = math.max(0, tonumber(ackTimeoutRevalidationStats.lastSharedRecoveryTransferCount) or 0),
    },
    profileSnapshotBatch = profileSnapshotBatch,
    profileSyncDecisionStats = GetProfileSyncDecisionStatsSummary(activeTransferSessionId),
    syncPerformance = INTERNAL_API.LIDCOUNCIL_GetSyncPerformanceSnapshot_Impl(),
    archiveSyncPaused = GetArchiveSyncPaused(),
  }
end

local function GetCommHeaderActivityStatus()
  local now = GetNow()
  PruneOutboundSendWindow(now)
  local targets = {}
  local seenTargets = {}
  local targetsTruncated = false
  local activeTransferSessionId = ""
  if type(commApi.GetActiveLootSession) == "function" then
    local activeSession = commApi.GetActiveLootSession()
    activeTransferSessionId = TrimText(type(activeSession) == "table" and activeSession.id or "")
  end

  -- The message queue can be empty while a profile snapshot is waiting for
  -- recipient acknowledgement or deferred application. Keep that handshake
  -- visible in the header instead of reporting an incorrect idle state.
  local activeTransferCount = 0
  local awaitingProfileAckCount = 0
  local awaitingProfileApplyCount = 0
  local activeTransferPreview
  for _, transferId in ipairs(outboundProfileTransferOrder) do
    local transfer = outboundProfileTransfers[transferId]
    local transferState = TrimText(type(transfer) == "table" and transfer.state or "")
    local matchesActiveSession = activeTransferSessionId ~= ""
      and type(transfer) == "table"
      and (
        type(INTERNAL_API.LIDCOUNCIL_IsOutboundProfileTransferForSession_Impl) == "function"
          and INTERNAL_API.LIDCOUNCIL_IsOutboundProfileTransferForSession_Impl(transfer, activeTransferSessionId)
        or TrimText(transfer.sessionId) == activeTransferSessionId
      )
    if matchesActiveSession and (
      transferState == "queued"
      or transferState == "sending"
      or transferState == "waiting_ack"
      or transferState == "waiting_apply"
    ) then
      activeTransferCount = activeTransferCount + 1
      if transferState == "waiting_ack" then
        awaitingProfileAckCount = awaitingProfileAckCount + 1
      elseif transferState == "waiting_apply" then
        awaitingProfileApplyCount = awaitingProfileApplyCount + 1
      end
      local target = NormalizeCharacterKey(transfer.target)
      local targetKey = string.lower(target)
      if target ~= "" and not seenTargets[targetKey] then
        seenTargets[targetKey] = true
        if #targets < 3 then
          targets[#targets + 1] = target
        else
          targetsTruncated = true
        end
      end
      if not activeTransferPreview then
        activeTransferPreview = {
          target = target,
          state = transferState,
          reason = TrimText(transfer.reason),
          lane = TrimText(transfer.lane),
          sentChunks = math.max(0, tonumber(transfer.sentChunks) or 0),
          totalChunks = math.max(0, tonumber(transfer.totalChunks) or 0),
        }
      end
    end
  end

  for _, item in ipairs(outboundCommQueue) do
    local target = NormalizeCharacterKey(type(item) == "table" and item.targetName or "")
    local targetKey = string.lower(target)
    if target ~= "" and not seenTargets[targetKey] then
      seenTargets[targetKey] = true
      if #targets < 3 then
        targets[#targets + 1] = target
      else
        targetsTruncated = true
        break
      end
    end
  end

  local nextItem = nil
  if #outboundCommQueue > 0 then
    local nextReadyIndex = nil
    if type(INTERNAL_API.LIDCOUNCIL_SelectReadyOutboundCommQueueIndex_Impl) == "function" then
      local pacing = type(outboundCommStats.archiveTargetPacing) == "table" and outboundCommStats.archiveTargetPacing or {}
      nextReadyIndex = INTERNAL_API.LIDCOUNCIL_SelectReadyOutboundCommQueueIndex_Impl(
        outboundCommQueue,
        now,
        {
          burstLimit = math.max(1, tonumber(outboundCommStats.archiveTargetBurstLimit) or 2),
          lastTarget = pacing.lastTarget,
          consecutiveChunks = pacing.consecutiveChunks,
        }
      )
    end
    if nextReadyIndex then
      nextItem = BuildQueuedCommPreviewItem(outboundCommQueue[nextReadyIndex])
    end
  end

  -- Retain completed inbound packets briefly so short profile patches are visible
  -- across the editor's refresh cadence without reporting rejected packets as data.
  local inbound = type(inboundCommOps.activitySnapshot) == "function"
    and inboundCommOps.activitySnapshot(4)
    or {}
  local profileSnapshotBatch = type(profileSyncHelpers) == "table"
    and type(profileSyncHelpers.GetProfileSnapshotBatchStatus) == "function"
    and profileSyncHelpers.GetProfileSnapshotBatchStatus()
    or {}
  local incomingTransfer = type(profileSnapshotBatch) == "table" and type(profileSnapshotBatch.incomingTransfer) == "table"
    and profileSnapshotBatch.incomingTransfer or {}
  local pendingIncomingTransfers = math.max(0, tonumber(type(profileSnapshotBatch) == "table"
    and profileSnapshotBatch.pendingIncomingTransfers or 0) or 0)
  local rollingWindowSeconds = 10
  return {
    outbound = {
      active = outboundCommQueueRunning == true or #outboundCommQueue > 0 or activeTransferCount > 0,
      running = outboundCommQueueRunning == true,
      pending = #outboundCommQueue,
      messageRatePerSecond = #outboundCommSendWindow / rollingWindowSeconds,
      targets = targets,
      targetsTruncated = targetsTruncated,
      nextItem = nextItem,
      nextPriority = math.max(0, tonumber(type(nextItem) == "table" and nextItem.priority or 0) or 0),
      activeProfileTransfers = activeTransferCount,
      awaitingProfileAck = awaitingProfileAckCount,
      awaitingProfileApply = awaitingProfileApplyCount,
      activeTransfer = activeTransferPreview,
    },
    inbound = {
      active = inbound.active == true or pendingIncomingTransfers > 0,
      messageRatePerSecond = math.max(0, tonumber(inbound.messageRatePerSecond) or 0),
      byteRatePerSecond = math.max(0, tonumber(inbound.byteRatePerSecond) or 0),
      lastDispatchedAt = math.max(0, tonumber(inbound.lastDispatchedAt) or 0),
      lastDispatchedSender = NormalizeCharacterKey(inbound.lastDispatchedSender),
      sources = CloneProfileSyncTextList(inbound.recentSenders),
      sourcesTruncated = inbound.recentSendersTruncated == true,
      transfer = {
        sender = NormalizeCharacterKey(incomingTransfer.sender),
        sessionId = TrimText(incomingTransfer.sessionId),
        mode = string.upper(TrimText(incomingTransfer.mode)),
        lane = string.lower(TrimText(incomingTransfer.lane)),
        transferKind = string.upper(TrimText(incomingTransfer.transferKind)),
        liveSync = incomingTransfer.liveSync == true,
        chunkCount = math.max(0, tonumber(incomingTransfer.chunkCount) or 0),
        receivedChunkCount = math.max(0, tonumber(incomingTransfer.receivedChunkCount) or 0),
      },
    },
    profileSnapshotBatch = {
      running = type(profileSnapshotBatch) == "table" and profileSnapshotBatch.running == true,
      pendingTargets = math.max(0, tonumber(type(profileSnapshotBatch) == "table" and profileSnapshotBatch.pendingTargets) or 0),
      holdRemaining = math.max(0, tonumber(type(profileSnapshotBatch) == "table" and profileSnapshotBatch.holdRemaining) or 0),
      heldSessionId = TrimText(type(profileSnapshotBatch) == "table" and profileSnapshotBatch.heldSessionId),
      holdReason = TrimText(type(profileSnapshotBatch) == "table" and profileSnapshotBatch.holdReason),
      firstQueuedTarget = NormalizeCharacterKey(type(profileSnapshotBatch) == "table" and profileSnapshotBatch.firstQueuedTarget),
      firstQueuedTransferKind = TrimText(type(profileSnapshotBatch) == "table" and profileSnapshotBatch.firstQueuedTransferKind),
      firstQueuedPriority = math.max(0, tonumber(type(profileSnapshotBatch) == "table" and profileSnapshotBatch.firstQueuedPriority) or 0),
      nextTarget = NormalizeCharacterKey(type(profileSnapshotBatch) == "table" and profileSnapshotBatch.nextTarget),
      nextTransferKind = TrimText(type(profileSnapshotBatch) == "table" and profileSnapshotBatch.nextTransferKind),
      nextPriority = math.max(0, tonumber(type(profileSnapshotBatch) == "table" and profileSnapshotBatch.nextPriority) or 0),
    },
  }
end

INTERNAL_API.LIDCOUNCIL_GetSessionPresentationStatus_Impl = function()
  local activeSession, profileName = commApi.GetActiveLootSession()
  local snapshot = {
    state = "inactive",
    label = "NO SESSION",
    accent = "neutral",
    active = false,
    preparing = false,
    participating = false,
    isHost = false,
    memberCount = 0,
    elapsedSeconds = 0,
    host = "",
    profileName = TrimText(profileName),
    sessionId = "",
  }
  if type(activeSession) ~= "table" then
    return snapshot
  end

  local selfKey = NormalizeCharacterKey(commApi.GetCharacterKey() or "")
  local hostKey = NormalizeCharacterKey(activeSession.host)
  local status = string.upper(TrimText(activeSession.status))
  local selfKeyLower = string.lower(selfKey)
  local selfJoined = false
  for memberKey, member in pairs(type(activeSession.members) == "table" and activeSession.members or {}) do
    local memberStatus = string.upper(TrimText(type(member) == "table" and member.status or ""))
    if memberStatus == "JOINED" then
      snapshot.memberCount = snapshot.memberCount + 1
      local resolvedMemberKey = NormalizeCharacterKey(
        type(member) == "table" and member.name or memberKey
      )
      if selfKeyLower ~= "" and (
        string.lower(NormalizeCharacterKey(memberKey)) == selfKeyLower
        or string.lower(resolvedMemberKey) == selfKeyLower
      ) then
        selfJoined = true
      end
    end
  end

  snapshot.host = hostKey
  snapshot.profileName = TrimText(profileName)
  if snapshot.profileName == "" then
    snapshot.profileName = TrimText(activeSession.profileName)
  end
  snapshot.sessionId = TrimText(activeSession.id)
  snapshot.isHost = selfKeyLower ~= "" and string.lower(hostKey) == selfKeyLower
  snapshot.preparing = status == "PREPARING"
  snapshot.active = status == "ACTIVE" and selfJoined
  snapshot.participating = snapshot.active

  if status == "PREPARING" and snapshot.isHost then
    snapshot.state = "preparing"
    snapshot.label = "PREPARING SESSION"
    snapshot.accent = "amber"
  elseif status == "ACTIVE" and selfJoined and snapshot.isHost then
    snapshot.state = "hosting"
    snapshot.label = "HOSTING SESSION"
    snapshot.accent = "green"
  elseif status == "ACTIVE" and selfJoined then
    snapshot.state = "joined"
    snapshot.label = "JOINED AS MEMBER"
    snapshot.accent = "green"
  else
    snapshot.state = "session_available"
    snapshot.label = "SESSION AVAILABLE"
    snapshot.accent = "amber"
  end

  local startedAt = status == "ACTIVE"
    and (tonumber(activeSession.activatedAt) or tonumber(activeSession.startedAt))
    or tonumber(activeSession.startedAt)
  snapshot.startedAt = math.max(0, startedAt or 0)
  if snapshot.startedAt > 0 then
    snapshot.elapsedSeconds = math.max(0, GetNow() - snapshot.startedAt)
  end
  return snapshot
end

local function GetProfileSyncEstimate(byteCount)
  local bytes = math.max(0, tonumber(byteCount) or 0)
  local chunkSize = math.max(1, tonumber(GetProfileSnapshotChunkSize()) or COMM_LIMITS.DEFAULT_PROFILE_SNAPSHOT_CHUNK_SIZE)
  local chunks = math.max(1, math.ceil(bytes / chunkSize))
  local messages = chunks + 2
  local intervalSeconds = math.max(0, tonumber(GetCommOutboundIntervalSeconds()) or COMM_LIMITS.DEFAULT_OUTBOUND_INTERVAL_SECONDS)
  return {
    bytes = bytes,
    chunkSize = chunkSize,
    chunks = chunks,
    messages = messages,
    intervalSeconds = intervalSeconds,
    seconds = messages * intervalSeconds,
  }
end

local function CancelQueuedProfileSyncForSession(sessionId)
  local resolvedSessionId = TrimText(sessionId)
  if resolvedSessionId == "" then
    return 0
  end

  inboundCommOps.clear()
  if type(inboundRateLimiter) == "table" and type(inboundRateLimiter.Clear) == "function" then
    inboundRateLimiter.Clear()
  end

  local cancelledAt = GetNow()
  for _, transferId in ipairs(outboundProfileTransferOrder) do
    local transfer = outboundProfileTransfers[transferId]
    if type(transfer) == "table" and TrimText(transfer.sessionId) == resolvedSessionId then
      transfer.state = "cancelled"
      transfer.completedAt = cancelledAt
      transfer.terminalReason = "session_stopped"
      pendingOutboundProfileAckReconciliations[transferId] = nil
    end
  end

  local removed = 0
  local keptQueue = {}
  for _, item in ipairs(outboundCommQueue) do
    local kind = TrimText(type(item) == "table" and item.kind or "")
    local metadata = type(item) == "table" and type(item.metadata) == "table" and item.metadata or {}
    local transfer = outboundProfileTransfers[TrimText(metadata.transferId)]
    local transferSessionId = TrimText(metadata.sessionId)
    if transferSessionId == "" and type(transfer) == "table" then
      transferSessionId = TrimText(transfer.sessionId)
    end
    local isProfileSync = kind == "PSYNC_START" or kind == "PSYNC_CHUNK" or kind == "PSYNC_END"
    if isProfileSync and transferSessionId == resolvedSessionId then
      removed = removed + 1
      if type(transfer) == "table" then
        transfer.state = "cancelled"
        transfer.completedAt = cancelledAt
        transfer.terminalReason = "session_stopped"
      end
    else
      keptQueue[#keptQueue + 1] = item
    end
  end
  outboundCommQueue = keptQueue
  PruneOutboundProfileTransfers()
  return removed
end

INTERNAL_API.LIDCOUNCIL_ShouldRejectOutboundProfileSyncForActiveSession_Impl = function(kind, itemSessionId, activeSessionId)
  local resolvedKind = TrimText(kind)
  local isProfileSync = resolvedKind == "PSYNC_START" or resolvedKind == "PSYNC_CHUNK" or resolvedKind == "PSYNC_END"
  local resolvedItemSessionId = TrimText(itemSessionId)
  local resolvedActiveSessionId = TrimText(activeSessionId)
  return isProfileSync
    and resolvedItemSessionId ~= ""
    and resolvedActiveSessionId ~= ""
    and resolvedItemSessionId ~= resolvedActiveSessionId
end

INTERNAL_API.LIDCOUNCIL_IsOutboundSessionBoundLiveUpdate_Impl = function(kind)
  local resolvedKind = TrimText(kind)
  return resolvedKind == "PDELTA"
    or resolvedKind == "PDELTA_REQ"
    or resolvedKind == "PDELTA_ACK"
    or resolvedKind == "PDELTA_NACK"
    or resolvedKind == "PSTATE"
    or resolvedKind == "PSTATE_PART"
    or string.sub(resolvedKind, 1, 6) == "BSYNC"
end

INTERNAL_API.LIDCOUNCIL_IsOutboundSessionBoundProfileRepairResponse_Impl = function(kind)
  local resolvedKind = TrimText(kind)
  return resolvedKind == "PSYNC_ACK"
    or resolvedKind == "PSUB_STATE"
    or resolvedKind == "PSUBPATCH_STATE"
end

INTERNAL_API.LIDCOUNCIL_IsOutboundSessionBoundProfileRepairRequest_Impl = function(kind)
  local resolvedKind = TrimText(kind)
  return resolvedKind == "PSYNC_REQ"
    or resolvedKind == "PSUB_REQ"
    or resolvedKind == "PSUBPATCH_REQ"
end

INTERNAL_API.LIDCOUNCIL_ShouldRejectOutboundSessionBoundMessage_Impl = function(kind, itemSessionId, activeSessionId)
  if INTERNAL_API.LIDCOUNCIL_ShouldRejectOutboundProfileSyncForActiveSession_Impl(kind, itemSessionId, activeSessionId) then
    return true
  end
  local resolvedItemSessionId = TrimText(itemSessionId)
  local resolvedActiveSessionId = TrimText(activeSessionId)
  local sessionBound = INTERNAL_API.LIDCOUNCIL_IsOutboundSessionBoundLiveUpdate_Impl(kind)
    or INTERNAL_API.LIDCOUNCIL_IsOutboundSessionBoundProfileRepairResponse_Impl(kind)
    or INTERNAL_API.LIDCOUNCIL_IsOutboundSessionBoundProfileRepairRequest_Impl(kind)
  return sessionBound
    and resolvedItemSessionId ~= ""
    and resolvedActiveSessionId ~= ""
    and resolvedItemSessionId ~= resolvedActiveSessionId
end

INTERNAL_API.LIDCOUNCIL_IsInboundSessionBoundProfileMessage_Impl = function(kind)
  local resolvedKind = TrimText(kind)
  return resolvedKind == "PSYNC_START"
    or INTERNAL_API.LIDCOUNCIL_IsOutboundSessionBoundLiveUpdate_Impl(resolvedKind)
    or INTERNAL_API.LIDCOUNCIL_IsOutboundSessionBoundProfileRepairResponse_Impl(resolvedKind)
    or INTERNAL_API.LIDCOUNCIL_IsOutboundSessionBoundProfileRepairRequest_Impl(resolvedKind)
end

INTERNAL_API.LIDCOUNCIL_ResolveInboundSessionBoundMessageSessionId_Impl = function(kind, fields)
  local resolvedKind = TrimText(kind)
  if not INTERNAL_API.LIDCOUNCIL_IsInboundSessionBoundProfileMessage_Impl(resolvedKind)
    or type(fields) ~= "table"
  then
    return ""
  end
  if resolvedKind == "PSYNC_START" or resolvedKind == "PSYNC_ACK" then
    return TrimText(fields[3])
  end
  return TrimText(fields[2])
end

INTERNAL_API.LIDCOUNCIL_ShouldRejectInboundSessionBoundMessage_Impl = function(kind, fields, activeSessionId)
  local incomingSessionId = INTERNAL_API.LIDCOUNCIL_ResolveInboundSessionBoundMessageSessionId_Impl(kind, fields)
  local resolvedActiveSessionId = TrimText(activeSessionId)
  return incomingSessionId ~= ""
    and resolvedActiveSessionId ~= ""
    and incomingSessionId ~= resolvedActiveSessionId
end

INTERNAL_API.LIDCOUNCIL_ResolveOutboundProfileSyncQueueSessionId_Impl = function(kind, metadata)
  local resolvedKind = TrimText(kind)
  if resolvedKind ~= "PSYNC_START" and resolvedKind ~= "PSYNC_CHUNK" and resolvedKind ~= "PSYNC_END" then
    return ""
  end
  metadata = type(metadata) == "table" and metadata or {}
  local sessionId = TrimText(metadata.sessionId)
  if sessionId ~= "" then
    return sessionId
  end
  local transfer = outboundProfileTransfers[TrimText(metadata.transferId)]
  return TrimText(type(transfer) == "table" and transfer.sessionId or "")
end

INTERNAL_API.LIDCOUNCIL_ResolveOutboundSessionBoundQueueSessionId_Impl = function(kind, metadata)
  local sessionId = INTERNAL_API.LIDCOUNCIL_ResolveOutboundProfileSyncQueueSessionId_Impl(kind, metadata)
  if sessionId ~= "" then
    return sessionId
  end
  if INTERNAL_API.LIDCOUNCIL_IsOutboundSessionBoundLiveUpdate_Impl(kind)
    or INTERNAL_API.LIDCOUNCIL_IsOutboundSessionBoundProfileRepairResponse_Impl(kind)
    or INTERNAL_API.LIDCOUNCIL_IsOutboundSessionBoundProfileRepairRequest_Impl(kind)
  then
    return TrimText(type(metadata) == "table" and metadata.sessionId or "")
  end
  return ""
end

INTERNAL_API.LIDCOUNCIL_PruneQueuedProfileSyncForActiveSession_Impl = function(sessionId)
  local resolvedSessionId = TrimText(sessionId)
  if resolvedSessionId == "" or TrimText(outboundCommStats.activeProfileSyncQueueSessionId) == resolvedSessionId then
    return 0
  end
  outboundCommStats.activeProfileSyncQueueSessionId = resolvedSessionId
  local cancelledAt = GetNow()
  for _, transferId in ipairs(outboundProfileTransferOrder) do
    local transfer = outboundProfileTransfers[transferId]
    local transferState = TrimText(type(transfer) == "table" and transfer.state or "")
    if type(transfer) == "table"
      and TrimText(transfer.sessionId) ~= ""
      and TrimText(transfer.sessionId) ~= resolvedSessionId
      and (transferState == "queued" or transferState == "sending" or transferState == "waiting_ack"
        or transferState == "waiting_apply" or transferState == "superseded_waiting_apply"
        or transferState == "ack_timeout")
    then
      transfer.state = "cancelled"
      transfer.completedAt = cancelledAt
      transfer.terminalReason = "session_replaced"
      pendingOutboundProfileAckReconciliations[transferId] = nil
    end
  end
  local removed = 0
  local keptQueue = {}
  for _, item in ipairs(outboundCommQueue) do
    local kind = TrimText(type(item) == "table" and item.kind or "")
    local metadata = type(item) == "table" and type(item.metadata) == "table" and item.metadata or {}
    local itemSessionId = INTERNAL_API.LIDCOUNCIL_ResolveOutboundSessionBoundQueueSessionId_Impl(kind, metadata)
    if itemSessionId ~= "" and itemSessionId ~= resolvedSessionId then
      removed = removed + 1
    else
      keptQueue[#keptQueue + 1] = item
    end
  end
  outboundCommQueue = keptQueue
  if removed > 0 then
    outboundCommStats.staleSessionBoundPrunedTotal = math.max(0, tonumber(outboundCommStats.staleSessionBoundPrunedTotal) or 0) + removed
    outboundCommStats.lastStaleSessionBoundPrunedAt = cancelledAt
  end
  PruneOutboundProfileTransfers()
  return removed
end

INTERNAL_API.LIDCOUNCIL_PrepareOutboundProfileSyncSessionQueue_Impl = function(kind, metadata)
  metadata = type(metadata) == "table" and metadata or {}
  local itemSessionId = INTERNAL_API.LIDCOUNCIL_ResolveOutboundSessionBoundQueueSessionId_Impl(kind, metadata)
  if itemSessionId == "" then
    itemSessionId = TrimText(metadata.sessionId)
  end
  local activeSession = type(commApi.GetActiveLootSession) == "function" and commApi.GetActiveLootSession() or nil
  local activeSessionId = TrimText(type(activeSession) == "table" and activeSession.id or "")
  if INTERNAL_API.LIDCOUNCIL_ShouldRejectOutboundSessionBoundMessage_Impl(kind, itemSessionId, activeSessionId) then
    return false, "Session-bound update belongs to a previous session."
  end
  local targetSessionId = activeSessionId ~= "" and activeSessionId or itemSessionId
  if targetSessionId ~= "" then
    INTERNAL_API.LIDCOUNCIL_EnsureOutboundSessionTelemetryBaseline_Impl(targetSessionId)
    INTERNAL_API.LIDCOUNCIL_PruneQueuedProfileSyncForActiveSession_Impl(targetSessionId)
  end
  return true, targetSessionId
end

INTERNAL_API.LIDCOUNCIL_SplitProfileSnapshotPayload_Impl = function(snapshot, transferId, chunkSize, safePayloadLimit)
  local text = tostring(snapshot or "")
  local resolvedTransferId = TrimText(transferId)
  local resolvedChunkSize = math.max(1, tonumber(chunkSize) or 1)
  local resolvedPayloadLimit = math.max(1, tonumber(safePayloadLimit) or COMM_SAFE_PAYLOAD_LIMIT)
  if resolvedTransferId == "" then
    return nil, "profile_sync_chunk_transfer_id_missing"
  end

  local chunks = {}
  local textLength = #text
  if textLength <= 0 then
    if #BuildPayload("PSYNC_CHUNK", resolvedTransferId, "1", "") > resolvedPayloadLimit then
      return nil, "profile_sync_chunk_envelope_exceeds_limit"
    end
    return { "" }
  end
  local startIndex = 1
  local chunkIndex = 1
  repeat
    local endIndex = math.min(textLength, startIndex + resolvedChunkSize - 1)
    local chunkData = text:sub(startIndex, endIndex)
    -- Escape expansion is measured inside the real PSYNC_CHUNK envelope.
    while endIndex >= startIndex and #BuildPayload("PSYNC_CHUNK", resolvedTransferId, tostring(chunkIndex), chunkData) > resolvedPayloadLimit do
      endIndex = endIndex - 1
      chunkData = text:sub(startIndex, endIndex)
    end
    if endIndex < startIndex then
      return nil, "profile_sync_chunk_envelope_exceeds_limit"
    end
    chunks[#chunks + 1] = chunkData
    startIndex = endIndex + 1
    chunkIndex = chunkIndex + 1
  until startIndex > textLength
  return chunks
end

INTERNAL_API.LIDCOUNCIL_ValidateProfileSnapshotStartPayload_Impl = function(...)
  local payload = BuildPayload("PSYNC_START", ...)
  if #payload > COMM_SAFE_PAYLOAD_LIMIT then
    return false, "profile_sync_start_payload_exceeds_limit", #payload
  end
  return true, nil, #payload
end

INTERNAL_API.LIDCOUNCIL_ValidateCommPayload_Impl = function(kind, ...)
  local resolvedKind = TrimText(kind)
  if resolvedKind == "" then
    return false, "comm_payload_kind_missing", 0
  end
  local fieldAccepted, fieldReason = ValidateCommProtocolFieldCount(resolvedKind, 1 + select("#", ...))
  if not fieldAccepted then
    return false, "comm_" .. TrimText(fieldReason), 0
  end
  local payload = BuildPayload(resolvedKind, ...)
  if #payload > COMM_SAFE_PAYLOAD_LIMIT then
    return false, "comm_payload_exceeds_safe_limit", #payload
  end
  return true, nil, #payload
end

INTERNAL_API.LIDCOUNCIL_SplitCommPayloadField_Impl = function(kind, source, prefixFields, suffixFields, chunkSize, safePayloadLimit)
  local resolvedKind = TrimText(kind)
  local text = tostring(source or "")
  local prefix = type(prefixFields) == "table" and prefixFields or {}
  local suffix = type(suffixFields) == "table" and suffixFields or {}
  local resolvedChunkSize = math.max(1, tonumber(chunkSize) or 1)
  local resolvedPayloadLimit = math.max(1, tonumber(safePayloadLimit) or COMM_SAFE_PAYLOAD_LIMIT)
  if resolvedKind == "" then
    return nil, "comm_payload_kind_missing"
  end

  local function fits(chunkData)
    local fields = {}
    for index = 1, #prefix do
      fields[#fields + 1] = prefix[index]
    end
    fields[#fields + 1] = chunkData
    for index = 1, #suffix do
      fields[#fields + 1] = suffix[index]
    end
    return #BuildPayload(resolvedKind, unpack(fields)) <= resolvedPayloadLimit
  end

  if #text <= 0 then
    local emptyFits = fits("")
    if not emptyFits then
      return nil, "comm_payload_field_envelope_exceeds_limit"
    end
    return { "" }
  end
  local chunks = {}
  local startIndex = 1
  repeat
    local endIndex = math.min(#text, startIndex + resolvedChunkSize - 1)
    local chunkData = text:sub(startIndex, endIndex)
    while endIndex >= startIndex and not fits(chunkData) do
      endIndex = endIndex - 1
      chunkData = text:sub(startIndex, endIndex)
    end
    if endIndex < startIndex then
      return nil, "comm_payload_field_envelope_exceeds_limit"
    end
    chunks[#chunks + 1] = chunkData
    startIndex = endIndex + 1
  until startIndex > #text
  return chunks
end

INTERNAL_API.LIDCOUNCIL_PreviewOutboundProfileTransferGeneration_Impl = function(metadata)
  local scopeSignature = BuildOutboundProfileTransferScopeSignature(metadata)
  if scopeSignature == "" then
    return 0
  end
  return math.max(0, tonumber(outboundProfileTransferGenerationByScope[scopeSignature]) or 0) + 1
end

INTERNAL_API.LIDCOUNCIL_IsChatMessagingLockdownActive_Impl = function()
  local chatInfo = type(C_ChatInfo) == "table" and C_ChatInfo or nil
  local queryLockdown = type(chatInfo) == "table" and chatInfo.InChatMessagingLockdown or nil
  if type(queryLockdown) ~= "function" then
    return nil
  end
  local ok, active = pcall(queryLockdown)
  if not ok then
    return nil
  end
  return active == true
end

INTERNAL_API.LIDCOUNCIL_SetChatMessagingLockdownState_Impl = function(active)
  local now = GetNow()
  local wasActive = outboundCommStats.chatLockdownActive == true
  outboundCommStats.chatLockdownActive = active == true
  if active == true then
    if not wasActive then
      outboundCommStats.chatLockdownStartedAt = now
      RecordRaidTestTraceEvent("LOCKDOWN_ENTER", "WoW addon-message restriction became active.", {
        queue = #outboundCommQueue,
      })
    end
    outboundCommStats.lastChatLockdownAt = now
  elseif wasActive then
    outboundCommStats.lastChatLockdownReleasedAt = now
    outboundCommStats.chatLockdownStartedAt = 0
    RecordRaidTestTraceEvent("LOCKDOWN_EXIT", "WoW addon-message restriction cleared.", {
      queue = #outboundCommQueue,
    })
  end
  return outboundCommStats.chatLockdownActive
end

local function SendAddonPayloadNow(kind, distribution, targetName, payload)
  local ok, result = pcall(C_ChatInfo.SendAddonMessage, COMM_PREFIX, payload, distribution, targetName)
  if not ok then
    WarnCommIssue(kind, "LidCouncil could not send an addon message.")
    return false, "failed", "SendAddonMessage failed."
  end
  local state = outboundRetryHelpers.GetSendAddonResultState(result)
  if state == "success" then
    return true, "success", result
  end
  if state == "throttle" then
    return false, "throttled", result
  end
  if state == "lockdown" then
    return false, "lockdown", result
  end
  if state == "permanent_failure" or state == "target_offline" then
    return false, state, result
  end
  return false, "failed", result
end

local function GetProfileSyncTransferPriority(kind, metadata)
  metadata = type(metadata) == "table" and metadata or {}
  local resolvedMode = TrimText(metadata.mode)
  local resolvedTransferKind = TrimText(metadata.transferKind)
  local resolvedReason = ResolveProfileSyncTransferReason(metadata)
  local resolvedLane = ResolveProfileSyncTransferLane(metadata)
  local transferId = TrimText(metadata.transferId)
  local transfer = transferId ~= "" and outboundProfileTransfers[transferId] or nil
  if type(transfer) == "table" then
    resolvedMode = FirstNonEmptyText(resolvedMode, transfer.mode)
    resolvedTransferKind = FirstNonEmptyText(resolvedTransferKind, transfer.transferKind)
    resolvedLane = FirstNonEmptyText(resolvedLane, NormalizeProfileSyncTransferLaneText(transfer.lane))
  end
  local reasonLower = string.lower(resolvedReason)

  if resolvedMode == "BACKGROUND" then
    if resolvedLane == "archive"
      or (string.find(reasonLower, "archive", 1, true) and string.find(reasonLower, "background", 1, true))
    then
      if resolvedTransferKind == "PATCHES" or resolvedTransferKind == "ROWPATCHES" then
        return 46
      elseif resolvedTransferKind == "SUBDOMAINS" then
        return 52
      elseif resolvedTransferKind == "DOMAINS" then
        return 60
      end
      return 70
    elseif resolvedLane == "stats"
      or (string.find(reasonLower, "stats", 1, true) and string.find(reasonLower, "background", 1, true))
    then
      if resolvedTransferKind == "PATCHES" or resolvedTransferKind == "ROWPATCHES" then
        return 28
      elseif resolvedTransferKind == "SUBDOMAINS" then
        return 32
      elseif resolvedTransferKind == "DOMAINS" then
        return 38
      end
      return 46
    elseif resolvedLane == "live" then
      if resolvedTransferKind == "PATCHES" or resolvedTransferKind == "ROWPATCHES" then
        return 22
      elseif resolvedTransferKind == "SUBDOMAINS" then
        return 26
      elseif resolvedTransferKind == "DOMAINS" then
        return 32
      end
      return 40
    end
    if resolvedTransferKind == "PATCHES" or resolvedTransferKind == "ROWPATCHES" then
      return 34
    elseif resolvedTransferKind == "SUBDOMAINS" then
      return 38
    elseif resolvedTransferKind == "DOMAINS" then
      return 45
    end
    return 55
  end

  if string.find(reasonLower, "bootstrap", 1, true) then
    if resolvedTransferKind == "PATCHES" or resolvedTransferKind == "ROWPATCHES" then
      return resolvedLane == "live" and 8 or 9
    elseif resolvedTransferKind == "SUBDOMAINS" then
      return resolvedLane == "live" and 10 or 11
    elseif resolvedTransferKind == "DOMAINS" then
      return resolvedLane == "live" and 12 or 13
    end
    return resolvedLane == "live" and 14 or 15
  end

  if resolvedLane == "archive" then
    if resolvedTransferKind == "PATCHES" or resolvedTransferKind == "ROWPATCHES" then
      return 32
    elseif resolvedTransferKind == "SUBDOMAINS" then
      return 36
    elseif resolvedTransferKind == "DOMAINS" then
      return 42
    end
    return 50
  end

  if resolvedLane == "stats" then
    if resolvedTransferKind == "PATCHES" or resolvedTransferKind == "ROWPATCHES" then
      return 22
    elseif resolvedTransferKind == "SUBDOMAINS" then
      return 26
    elseif resolvedTransferKind == "DOMAINS" then
      return 30
    end
    return 36
  end

  if resolvedTransferKind == "PATCHES" or resolvedTransferKind == "ROWPATCHES" then
    return 18
  elseif resolvedTransferKind == "SUBDOMAINS" then
    return 22
  elseif resolvedTransferKind == "DOMAINS" then
    return 26
  end
  return 34
end

local function GetOutboundCommPriority(kind, metadata)
  local resolvedKind = TrimText(kind)
  if resolvedKind == "START"
      or resolvedKind == "IACK"
      or resolvedKind == "BEGIN"
      or resolvedKind == "JOIN"
      or resolvedKind == "JACK"
      or resolvedKind == "MEMBER"
      or resolvedKind == "LEAVE"
      or resolvedKind == "STOP"
      or resolvedKind == "STOP_ACK"
      or resolvedKind == "DECLINE" then
    return 1
  end
  if resolvedKind == "CHOICE"
      or resolvedKind == "RCHOICE"
      or resolvedKind == "RCHOICE_ACK"
      or resolvedKind == "VOTE"
      or resolvedKind == "AWARD"
      or resolvedKind == "UNASSIGN"
      or resolvedKind == "TRADE"
      or resolvedKind == "ITEM_OPEN"
      or resolvedKind == "ITEM_ACK"
      or resolvedKind == "ITEM_REPORT"
      or resolvedKind == "LOCALAP"
      or resolvedKind == "APNOTICE" then
    return 2
  end
  if resolvedKind == "PDELTA"
      or resolvedKind == "PDELTA_REQ" then
    return 3
  end
  if resolvedKind == "PDELTA_ACK"
      or resolvedKind == "PDELTA_NACK" then
    return 4
  end
  if resolvedKind == "BSYNC_ACK"
      or resolvedKind == "BSYNC_MISS" then
    return 4
  end
  if resolvedKind == "PSTATE" or resolvedKind == "PSTATE_PART" then
    return 5
  end
  -- Snapshot ACKs unblock host-side convergence tracking and should beat ledger traffic.
  if resolvedKind == "PSYNC_ACK" then
    return 5
  end
  if resolvedKind == "LL_ADD_REQ"
      or resolvedKind == "LL_ADD"
      or resolvedKind == "LL_DEL_REQ"
      or resolvedKind == "LL_DEL"
      or resolvedKind == "LL_MA_REQ"
      or resolvedKind == "LL_MA"
      or resolvedKind == "LL_NOTE_REQ"
      or resolvedKind == "LL_NOTE"
      or resolvedKind == "LL_CHAR_DEL_REQ"
      or resolvedKind == "LL_CHAR_DEL" then
    return 6
  end
  if resolvedKind == "BSYNC_START"
      or resolvedKind == "BSYNC_ITEM"
      or resolvedKind == "BSYNC_SEL"
      or resolvedKind == "BSYNC_VOTE"
      or resolvedKind == "BSYNC_END" then
    return 7
  end
  if resolvedKind == "PSYNC_REQ" then
    return 8
  end
  if resolvedKind == "PSUB_REQ"
      or resolvedKind == "PSUB_STATE" then
    return 16
  end
  if resolvedKind == "PSUBPATCH_REQ"
      or resolvedKind == "PSUBPATCH_STATE" then
    return 17
  end
  if resolvedKind == "PSYNC_START"
      or resolvedKind == "PSYNC_CHUNK"
      or resolvedKind == "PSYNC_END" then
    return GetProfileSyncTransferPriority(resolvedKind, metadata)
  end
  return 10
end

local function IsChunkedProfileSyncKind(kind)
  local resolvedKind = TrimText(kind)
  return resolvedKind == "PSYNC_START"
    or resolvedKind == "PSYNC_CHUNK"
    or resolvedKind == "PSYNC_END"
end

local function CanCoalesceDuplicateOutboundRequest(kind)
  local resolvedKind = TrimText(kind)
  return resolvedKind == "PDELTA_REQ"
    or resolvedKind == "PSUB_REQ"
    or resolvedKind == "PSUB_STATE"
    or resolvedKind == "PSUBPATCH_REQ"
    or resolvedKind == "PSUBPATCH_STATE"
    or resolvedKind == "PSYNC_REQ"
end

local function CanCoalesceCoveredOutboundRequest(kind)
  local resolvedKind = TrimText(kind)
  return resolvedKind == "PSUB_REQ"
    or resolvedKind == "PSUBPATCH_REQ"
    or resolvedKind == "PSYNC_REQ"
end

local function BuildQueuedOutboundRequestScopeList(kind, metadata)
  metadata = type(metadata) == "table" and metadata or {}
  local resolvedKind = TrimText(kind)
  if resolvedKind == "PSUB_REQ" then
    return SplitTransferScopeCsv(metadata.requestDomains)
  elseif resolvedKind == "PSUBPATCH_REQ" then
    return SplitTransferScopeCsv(metadata.requestSubdomains)
  elseif resolvedKind == "PSYNC_REQ" then
    if TrimText(metadata.requestSubdomains) ~= "" then
      return SplitTransferScopeCsv(metadata.requestSubdomains)
    elseif TrimText(metadata.requestDomains) ~= "" then
      return SplitTransferScopeCsv(metadata.requestDomains)
    end
  end
  return {}
end

local function BuildQueuedOutboundRequestScopeDescriptor(kind, metadata)
  metadata = type(metadata) == "table" and metadata or {}
  local resolvedKind = TrimText(kind)
  if resolvedKind == "PSUB_REQ" then
    return {
      scopeType = "domains",
      scopeList = SplitTransferScopeCsv(metadata.requestDomains),
    }
  elseif resolvedKind == "PSUBPATCH_REQ" then
    return {
      scopeType = "subdomains",
      scopeList = SplitTransferScopeCsv(metadata.requestSubdomains),
    }
  elseif resolvedKind == "PSYNC_REQ" then
    if TrimText(metadata.requestSubdomains) ~= "" then
      return {
        scopeType = "subdomains",
        scopeList = SplitTransferScopeCsv(metadata.requestSubdomains),
      }
    elseif TrimText(metadata.requestDomains) ~= "" then
      return {
        scopeType = "domains",
        scopeList = SplitTransferScopeCsv(metadata.requestDomains),
      }
    end
    return {
      scopeType = "full",
      scopeList = {},
    }
  end
  return {
    scopeType = "",
    scopeList = {},
  }
end

local function AreEquivalentQueuedOutboundRequests(existingItem, replacementItem)
  if type(existingItem) ~= "table" or type(replacementItem) ~= "table" then
    return false
  end
  local existingKind = TrimText(existingItem.kind)
  local replacementKind = TrimText(replacementItem.kind)
  if existingKind == "" or existingKind ~= replacementKind or not CanCoalesceDuplicateOutboundRequest(existingKind) then
    return false
  end
  if TrimText(existingItem.distribution) ~= TrimText(replacementItem.distribution) then
    return false
  end
  if NormalizeCharacterKey(existingItem.targetName) ~= NormalizeCharacterKey(replacementItem.targetName) then
    return false
  end

  local existingMetadata = type(existingItem.metadata) == "table" and existingItem.metadata or {}
  local replacementMetadata = type(replacementItem.metadata) == "table" and replacementItem.metadata or {}
  if TrimText(existingMetadata.sessionId) ~= TrimText(replacementMetadata.sessionId) then
    return false
  end
  if TrimText(existingMetadata.profileName) ~= TrimText(replacementMetadata.profileName) then
    return false
  end
  if TrimText(existingMetadata.profileId) ~= TrimText(replacementMetadata.profileId) then
    return false
  end

  if existingKind == "PDELTA_REQ" then
    return TrimText(existingMetadata.changeId) ~= ""
      and TrimText(existingMetadata.changeId) == TrimText(replacementMetadata.changeId)
      and NormalizeCharacterKey(existingMetadata.actor) == NormalizeCharacterKey(replacementMetadata.actor)
      and TrimText(existingMetadata.domain) == TrimText(replacementMetadata.domain)
      and TrimText(existingMetadata.action) == TrimText(replacementMetadata.action)
      and math.max(0, tonumber(existingMetadata.sequence) or 0) == math.max(0, tonumber(replacementMetadata.sequence) or 0)
      and tostring(existingItem.payload or "") == tostring(replacementItem.payload or "")
  elseif existingKind == "PSUB_REQ" then
    return TrimText(existingMetadata.requestToken) == TrimText(replacementMetadata.requestToken)
      and TrimText(existingMetadata.requestDomains) ~= ""
      and AreTransferScopesEqual(
        BuildQueuedOutboundRequestScopeList(existingKind, existingMetadata),
        BuildQueuedOutboundRequestScopeList(replacementKind, replacementMetadata)
      )
  elseif existingKind == "PSUBPATCH_REQ" then
    return TrimText(existingMetadata.requestToken) == TrimText(replacementMetadata.requestToken)
      and TrimText(existingMetadata.requestSubdomains) ~= ""
      and AreTransferScopesEqual(
        BuildQueuedOutboundRequestScopeList(existingKind, existingMetadata),
        BuildQueuedOutboundRequestScopeList(replacementKind, replacementMetadata)
      )
  elseif existingKind == "PSUB_STATE" then
    local existingRequestToken = TrimText(existingMetadata.requestToken)
    local replacementRequestToken = TrimText(replacementMetadata.requestToken)
    local requestIdentityMatches = existingRequestToken ~= ""
      and existingRequestToken == replacementRequestToken
      or (existingRequestToken == ""
        and replacementRequestToken == ""
        and TrimText(existingMetadata.responseToken) ~= ""
        and TrimText(existingMetadata.responseToken) == TrimText(replacementMetadata.responseToken))
    return requestIdentityMatches
      and string.lower(TrimText(existingMetadata.domain)) == string.lower(TrimText(replacementMetadata.domain))
      and TrimText(existingMetadata.domainChecksum) == TrimText(replacementMetadata.domainChecksum)
      and tostring(existingMetadata.responsePart or "") == tostring(replacementMetadata.responsePart or "")
      and math.max(0, tonumber(existingMetadata.partIndex) or 0) == math.max(0, tonumber(replacementMetadata.partIndex) or 0)
      and math.max(0, tonumber(existingMetadata.partCount) or 0) == math.max(0, tonumber(replacementMetadata.partCount) or 0)
  elseif existingKind == "PSUBPATCH_STATE" then
    local existingRequestToken = TrimText(existingMetadata.requestToken)
    local replacementRequestToken = TrimText(replacementMetadata.requestToken)
    local requestIdentityMatches = existingRequestToken ~= ""
      and existingRequestToken == replacementRequestToken
      or (existingRequestToken == ""
        and replacementRequestToken == ""
        and TrimText(existingMetadata.responseToken) ~= ""
        and TrimText(existingMetadata.responseToken) == TrimText(replacementMetadata.responseToken))
    return requestIdentityMatches
      and tostring(existingMetadata.responsePart or "") == tostring(replacementMetadata.responsePart or "")
      and math.max(0, tonumber(existingMetadata.partIndex) or 0) == math.max(0, tonumber(replacementMetadata.partIndex) or 0)
      and math.max(0, tonumber(existingMetadata.partCount) or 0) == math.max(0, tonumber(replacementMetadata.partCount) or 0)
  elseif existingKind == "PSYNC_REQ" then
    local existingScope = BuildQueuedOutboundRequestScopeDescriptor(existingKind, existingMetadata)
    local replacementScope = BuildQueuedOutboundRequestScopeDescriptor(replacementKind, replacementMetadata)
    return TrimText(existingMetadata.requestMode) == TrimText(replacementMetadata.requestMode)
      and TrimText(existingMetadata.expectedPatchManifestToken) == TrimText(replacementMetadata.expectedPatchManifestToken)
      and existingScope.scopeType == replacementScope.scopeType
      and (
        existingScope.scopeType == "full"
        or AreTransferScopesEqual(existingScope.scopeList, replacementScope.scopeList)
      )
  end
  return false
end

local function BuildQueuedOutboundRequestCoverage(existingItem, replacementItem)
  if type(existingItem) ~= "table" or type(replacementItem) ~= "table" then
    return nil
  end
  local existingKind = TrimText(existingItem.kind)
  local replacementKind = TrimText(replacementItem.kind)
  if existingKind == ""
    or replacementKind == ""
    or existingKind ~= replacementKind
    or not CanCoalesceCoveredOutboundRequest(existingKind)
  then
    return nil
  end
  if TrimText(existingItem.distribution) ~= TrimText(replacementItem.distribution) then
    return nil
  end
  if NormalizeCharacterKey(existingItem.targetName) ~= NormalizeCharacterKey(replacementItem.targetName) then
    return nil
  end

  local existingMetadata = type(existingItem.metadata) == "table" and existingItem.metadata or {}
  local replacementMetadata = type(replacementItem.metadata) == "table" and replacementItem.metadata or {}
  if TrimText(existingMetadata.sessionId) ~= TrimText(replacementMetadata.sessionId) then
    return nil
  end
  if TrimText(existingMetadata.profileName) ~= TrimText(replacementMetadata.profileName) then
    return nil
  end
  if TrimText(existingMetadata.profileId) ~= TrimText(replacementMetadata.profileId) then
    return nil
  end
  if (existingKind == "PSUB_REQ" or existingKind == "PSUBPATCH_REQ")
    and TrimText(existingMetadata.requestToken) ~= TrimText(replacementMetadata.requestToken)
  then
    return nil
  end

  if existingKind == "PSYNC_REQ" then
    if TrimText(existingMetadata.requestMode) ~= TrimText(replacementMetadata.requestMode) then
      return nil
    end
    if TrimText(existingMetadata.expectedPatchManifestToken) ~= TrimText(replacementMetadata.expectedPatchManifestToken) then
      return nil
    end

    local existingScopeDescriptor = BuildQueuedOutboundRequestScopeDescriptor(existingKind, existingMetadata)
    local replacementScopeDescriptor = BuildQueuedOutboundRequestScopeDescriptor(replacementKind, replacementMetadata)
    if existingScopeDescriptor.scopeType == ""
      or existingScopeDescriptor.scopeType ~= replacementScopeDescriptor.scopeType
    then
      return nil
    end
    if existingScopeDescriptor.scopeType == "full" then
      return {
        replacementCoveredByExisting = true,
        existingCoveredByReplacement = true,
      }
    end

    local existingScope = existingScopeDescriptor.scopeList
    local replacementScope = replacementScopeDescriptor.scopeList
    if #existingScope == 0 or #replacementScope == 0 then
      return nil
    end

    local scopesEqual = AreTransferScopesEqual(existingScope, replacementScope)
    return {
      replacementCoveredByExisting = scopesEqual or IsTransferScopeSubset(replacementScope, existingScope),
      existingCoveredByReplacement = scopesEqual or IsTransferScopeSubset(existingScope, replacementScope),
    }
  end

  local existingScope = BuildQueuedOutboundRequestScopeList(existingKind, existingMetadata)
  local replacementScope = BuildQueuedOutboundRequestScopeList(replacementKind, replacementMetadata)
  if #existingScope == 0 or #replacementScope == 0 then
    return nil
  end

  local scopesEqual = AreTransferScopesEqual(existingScope, replacementScope)
  return {
    replacementCoveredByExisting = scopesEqual or IsTransferScopeSubset(replacementScope, existingScope),
    existingCoveredByReplacement = scopesEqual or IsTransferScopeSubset(existingScope, replacementScope),
  }
end

local function CloneRecentOutboundRequestMetadata(metadata)
  local clone = {}
  for key, value in pairs(type(metadata) == "table" and metadata or {}) do
    if type(value) ~= "table" then
      clone[key] = value
    end
  end
  return next(clone) ~= nil and clone or nil
end

local function CloneRecentOutboundRequestItem(item, expiresAt)
  return {
    kind = TrimText(type(item) == "table" and item.kind or ""),
    distribution = TrimText(type(item) == "table" and item.distribution or ""),
    targetName = NormalizeCharacterKey(type(item) == "table" and item.targetName or ""),
    payload = tostring(type(item) == "table" and item.payload or ""),
    metadata = CloneRecentOutboundRequestMetadata(type(item) == "table" and item.metadata or nil),
    expiresAt = math.max(0, tonumber(expiresAt) or 0),
  }
end

PruneRecentOutboundRequestItems = function(now)
  local currentTime = math.max(0, tonumber(now) or 0)
  if currentTime <= 0 then
    currentTime = GetNow()
  end
  local keptItems = {}
  for _, recentItem in ipairs(recentOutboundRequestItems) do
    if type(recentItem) == "table" and math.max(0, tonumber(recentItem.expiresAt) or 0) > currentTime then
      keptItems[#keptItems + 1] = recentItem
    end
  end
  recentOutboundRequestItems = keptItems
end

ShouldSuppressRecentOutboundRequest = function(item)
  if type(item) ~= "table" or not CanCoalesceDuplicateOutboundRequest(item.kind) then
    return false
  end
  PruneRecentOutboundRequestItems(GetNow())
  for _, recentItem in ipairs(recentOutboundRequestItems) do
    if AreEquivalentQueuedOutboundRequests(recentItem, item) then
      return true
    end
  end
  return false
end

RememberRecentOutboundRequest = function(item)
  if type(item) ~= "table" or not CanCoalesceDuplicateOutboundRequest(item.kind) then
    return false
  end
  local now = GetNow()
  PruneRecentOutboundRequestItems(now)
  recentOutboundRequestItems[#recentOutboundRequestItems + 1] = CloneRecentOutboundRequestItem(
    item,
    now + COMM_LIMITS.RECENT_REQUEST_SUPPRESSION_SECONDS
  )
  return true
end

local outboundQueueCoalescing = type(INTERNAL_API.LIDCOUNCIL_CreateOutboundQueueCoalescingHelpers_Impl) == "function"
  and INTERNAL_API.LIDCOUNCIL_CreateOutboundQueueCoalescingHelpers_Impl({
    TrimText = TrimText,
    NormalizeCharacterKey = NormalizeCharacterKey,
    CanCoalesceDuplicateOutboundRequest = CanCoalesceDuplicateOutboundRequest,
    AreEquivalentQueuedOutboundRequests = AreEquivalentQueuedOutboundRequests,
    BuildQueuedOutboundRequestCoverage = BuildQueuedOutboundRequestCoverage,
    GetQueue = function()
      return outboundCommQueue
    end,
    ReplaceQueue = function(queue)
      outboundCommQueue = queue
    end,
  })
  or nil
if type(outboundQueueCoalescing) ~= "table"
  or type(outboundQueueCoalescing.ResolveQueuedOutboundRequestCoalescing) ~= "function"
  or type(outboundQueueCoalescing.ResolveQueuedOutboundStatePacketReplacement) ~= "function"
  or type(outboundQueueCoalescing.RemoveQueuedOutboundRequestsByIndexes) ~= "function"
then
  error("LidCouncil missing outbound queue coalescing helpers.")
end

GetOutboundCommQueueItemPriority = function(item)
  return math.max(0, tonumber(type(item) == "table" and item.priority or 10) or 10)
end

local outboundQueueSelection = type(INTERNAL_API.LIDCOUNCIL_CreateOutboundQueueSelectionHelpers_Impl) == "function"
  and INTERNAL_API.LIDCOUNCIL_CreateOutboundQueueSelectionHelpers_Impl({
    TrimText = TrimText,
    NormalizeCharacterKey = NormalizeCharacterKey,
    GetNow = GetNow,
    GetQueueItemPriority = GetOutboundCommQueueItemPriority,
    GetQueue = function()
      return outboundCommQueue
    end,
    ResolveArchiveQueuePacingTarget = function(item)
      return INTERNAL_API.LIDCOUNCIL_ResolveArchiveQueuePacingTarget_Impl(item)
    end,
    GetArchivePacingState = function()
      return outboundCommStats.archiveTargetPacing
    end,
  })
  or nil
if type(outboundQueueSelection) ~= "table"
  or type(outboundQueueSelection.SelectReadyOutboundCommQueueIndex) ~= "function"
  or type(outboundQueueSelection.InsertOutboundCommQueueItem) ~= "function"
then
  error("LidCouncil missing outbound queue selection helpers.")
end
INTERNAL_API.LIDCOUNCIL_SelectReadyOutboundCommQueueIndex_Impl =
  outboundQueueSelection.SelectReadyOutboundCommQueueIndex

local outboundFlushPolicy = type(INTERNAL_API.LIDCOUNCIL_CreateOutboundFlushPolicyHelpers_Impl) == "function"
  and INTERNAL_API.LIDCOUNCIL_CreateOutboundFlushPolicyHelpers_Impl({
    GetQueue = function()
      return outboundCommQueue
    end,
    GetIntervalSeconds = GetCommOutboundIntervalSeconds,
    GetQueueItemPriority = GetOutboundCommQueueItemPriority,
    ResolveProfileSyncTransferLane = ResolveProfileSyncTransferLane,
    IsChunkedProfileSyncKind = IsChunkedProfileSyncKind,
    ProfileSyncIdleIntervalSeconds = COMM_LIMITS.PROFILE_SYNC_IDLE_INTERVAL_SECONDS,
  })
  or nil
if type(outboundFlushPolicy) ~= "table"
  or type(outboundFlushPolicy.GetQueuedOutboundCommDelay) ~= "function"
  or type(outboundFlushPolicy.ResolveOutboundCommFlushSchedule) ~= "function"
then
  error("LidCouncil missing outbound flush policy helpers.")
end

local outboundFlushTimerOps = type(INTERNAL_API.LIDCOUNCIL_CreateOutboundFlushTimerStateHelpers_Impl) == "function"
  and INTERNAL_API.LIDCOUNCIL_CreateOutboundFlushTimerStateHelpers_Impl()
  or nil
if type(outboundFlushTimerOps) ~= "table"
  or type(outboundFlushTimerOps.ClearOutboundCommFlushSchedule) ~= "function"
  or type(outboundFlushTimerOps.BeginOutboundCommFlushSchedule) ~= "function"
  or type(outboundFlushTimerOps.ConsumeOutboundCommFlushSchedule) ~= "function"
  or type(outboundFlushTimerOps.GetOutboundCommFlushNextAt) ~= "function"
then
  error("LidCouncil missing outbound flush timer state helpers.")
end

outboundTimerAdapter = type(INTERNAL_API.LIDCOUNCIL_CreateOutboundTimerAdapterHelpers_Impl) == "function"
  and INTERNAL_API.LIDCOUNCIL_CreateOutboundTimerAdapterHelpers_Impl({
    GetTimerAfter = function()
      local compat = rawget(_G, "LIDCOUNCIL_Compat")
      if type(compat) == "table" and type(compat.After) == "function" then
        return compat.After
      end
      return nil
    end,
    TrimText = TrimText,
  })
  or nil
if type(outboundTimerAdapter) ~= "table"
  or type(outboundTimerAdapter.ScheduleTimer) ~= "function"
  or type(outboundTimerAdapter.ScheduleOutboundFlushTimer) ~= "function"
  or type(outboundTimerAdapter.BuildSessionTimerFallbackStatus) ~= "function"
then
  error("LidCouncil missing outbound timer adapter helpers.")
end

local function ClearScheduledOutboundCommFlush()
  outboundFlushTimerOps.ClearOutboundCommFlushSchedule(outboundCommFlushState)
end

local FlushOutboundCommQueue
local GetPostLiveTrafficQueueDelay

local function ScheduleOutboundCommQueueFlush(delaySeconds)
  local resolvedDelay = math.max(0, tonumber(delaySeconds) or 0)
  local shouldSchedule, shouldClear, dueAt = outboundFlushPolicy.ResolveOutboundCommFlushSchedule(
    #outboundCommQueue,
    GetNow(),
    resolvedDelay,
    outboundFlushTimerOps.GetOutboundCommFlushNextAt(outboundCommFlushState)
  )
  if shouldClear then
    ClearScheduledOutboundCommFlush()
    return false
  end
  if not shouldSchedule then
    return false
  end

  local token = outboundFlushTimerOps.BeginOutboundCommFlushSchedule(outboundCommFlushState, dueAt)
  local function runScheduledFlush()
    if not outboundFlushTimerOps.ConsumeOutboundCommFlushSchedule(outboundCommFlushState, token) then
      return
    end
    FlushOutboundCommQueue()
  end
  local scheduled, timerReason = outboundTimerAdapter.ScheduleOutboundFlushTimer(resolvedDelay, runScheduledFlush)
  if not scheduled then
    outboundCommStats.timerFallbackTotal = math.max(0, tonumber(outboundCommStats.timerFallbackTotal) or 0) + 1
    outboundCommStats.lastTimerFallbackAt = GetNow()
    outboundCommStats.lastTimerFallbackReason = TrimText(timerReason)
    runScheduledFlush()
  end
  return true
end

-- Keep retry budgets deterministic so developer validation can exercise the same
-- decision rules without sending addon messages or mutating the live queue.
INTERNAL_API.LIDCOUNCIL_ResolveOutboundCommRetryDecision_Impl = outboundRetryHelpers.ResolveOutboundCommRetryDecision

FlushOutboundCommQueue = function()
  local performanceTiming = {
    total = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("queue_flush_total", 20),
  }
  local now = GetNow()
  local queriedChatLockdown = INTERNAL_API.LIDCOUNCIL_IsChatMessagingLockdownActive_Impl()
  if queriedChatLockdown ~= nil then
    INTERNAL_API.LIDCOUNCIL_SetChatMessagingLockdownState_Impl(queriedChatLockdown)
  end
  if outboundCommStats.chatLockdownActive == true then
    outboundCommQueueRunning = #outboundCommQueue > 0
    ScheduleOutboundCommQueueFlush(1.0)
    INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("queue_flush_total", performanceTiming.total, {
      queueDepth = #outboundCommQueue,
      context = "chat_lockdown",
    })
    return
  end
  local globalThrottleNotBeforeAt = math.max(0,
    tonumber(outboundCommStats.globalThrottleNotBeforeAt) or 0)
  if #outboundCommQueue > 0 and globalThrottleNotBeforeAt > now then
    outboundCommQueueRunning = true
    ScheduleOutboundCommQueueFlush(math.max(0.05, globalThrottleNotBeforeAt - now))
    INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("queue_flush_total", performanceTiming.total, {
      queueDepth = #outboundCommQueue,
      context = "global_throttle_cooldown",
    })
    return
  end
  local archivePacing = type(outboundCommStats.archiveTargetPacing) == "table"
    and outboundCommStats.archiveTargetPacing
    or {}
  outboundCommStats.archiveTargetPacing = archivePacing
  archivePacing.burstLimit = math.max(1, tonumber(outboundCommStats.archiveTargetBurstLimit) or 2)
  performanceTiming.select = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("queue_select", 20)
  local nextReadyIndex, nextDeferredAt, archiveTargetPreempted = INTERNAL_API.LIDCOUNCIL_SelectReadyOutboundCommQueueIndex_Impl(
    outboundCommQueue,
    now,
    archivePacing,
    { fastReadyHead = true }
  )
  INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("queue_select", performanceTiming.select, {
    queueDepth = #outboundCommQueue,
  })
  local selectedItem = nextReadyIndex and outboundCommQueue[nextReadyIndex] or nil
  if selectedItem then
    local selectedMetadata = type(selectedItem.metadata) == "table" and selectedItem.metadata or {}
    local selectedTransferId = TrimText(selectedMetadata.transferId)
    local selectedTransfer = selectedTransferId ~= "" and outboundProfileTransfers[selectedTransferId] or nil
    local shouldPruneSelected = INTERNAL_API.LIDCOUNCIL_ShouldPruneQueuedOutboundProfileTransfer_Impl(
      selectedItem,
      selectedTransfer
    )
    if shouldPruneSelected then
      performanceTiming.prune = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("queue_prune", 1)
      INTERNAL_API.LIDCOUNCIL_PruneQueuedObsoleteProfileTransfers_Impl()
      INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("queue_prune", performanceTiming.prune, {
        queueDepth = #outboundCommQueue,
        context = "terminal_selected",
      })
      if #outboundCommQueue > 0 then
        outboundCommQueueRunning = true
        ScheduleOutboundCommQueueFlush(0.01)
      else
        outboundCommQueueRunning = false
        ClearScheduledOutboundCommFlush()
      end
      INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("queue_flush_total", performanceTiming.total, {
        queueDepth = #outboundCommQueue,
        context = "terminal_prune",
      })
      return
    end
  end
  performanceTiming.remove = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("queue_remove", 20)
  local item = nextReadyIndex and table.remove(outboundCommQueue, nextReadyIndex) or nil
  INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("queue_remove", performanceTiming.remove, {
    queueDepth = #outboundCommQueue,
  })
  if not item and #outboundCommQueue > 0 and nextDeferredAt > now then
    outboundCommQueueRunning = true
    ScheduleOutboundCommQueueFlush(math.max(0.05, nextDeferredAt - now))
    INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("queue_flush_total", performanceTiming.total, {
      queueDepth = #outboundCommQueue,
      context = "deferred",
    })
    return
  end
  local wasThrottled = false
  local wasFailureRetry = false
  if item then
    RecordOutboundItemAttempt(item)
    local ok, state, result = SendAddonPayloadNow(item.kind, item.distribution, item.targetName, item.payload)
    if ok then
      RecordOutboundItemSent(item, archiveTargetPreempted)
    else
      local retryDecision = INTERNAL_API.LIDCOUNCIL_ResolveOutboundCommRetryDecision_Impl(item, state, outboundCommStats)
      if retryDecision.lockdown then
        item.notBeforeAt = math.max(math.max(0, tonumber(item.notBeforeAt) or 0), now + 1.0)
        outboundCommStats.chatLockdownDeferredTotal = math.max(0,
          tonumber(outboundCommStats.chatLockdownDeferredTotal) or 0) + 1
        INTERNAL_API.LIDCOUNCIL_SetChatMessagingLockdownState_Impl(true)
        outboundQueueSelection.InsertOutboundCommQueueItem(item, true)
      elseif retryDecision.throttled then
        wasThrottled = true
        RecordOutboundItemThrottle(item, result)
        if retryDecision.retry then
          outboundCommStats.retriedThrottleTotal = (tonumber(outboundCommStats.retriedThrottleTotal) or 0) + 1
          outboundQueueSelection.InsertOutboundCommQueueItem(item, true)
          WarnCommIssue(item.kind, "LidCouncil addon message throttle detected; requeueing more slowly.")
        else
          local reason = "LidCouncil addon message exceeded its throttle retry budget."
          RecordOutboundItemFailed(item, reason, "throttle_exhausted")
          MarkOutboundProfileTransferFailed(item, reason)
          WarnCommIssue(item.kind, reason)
        end
      else
        RecordOutboundItemFailed(item, outboundRetryHelpers.FormatSendAddonResult(result), retryDecision.retry and "" or "api_failure")
        if retryDecision.retry then
          outboundCommStats.retriedFailureTotal = (tonumber(outboundCommStats.retriedFailureTotal) or 0) + 1
          wasFailureRetry = true
          item.notBeforeAt = math.max(
            math.max(0, tonumber(item.notBeforeAt) or 0),
            now + math.min(4, math.max(1, tonumber(item.failureRetryCount) or 1))
          )
          outboundQueueSelection.InsertOutboundCommQueueItem(item, true)
          WarnCommIssue(item.kind, "LidCouncil addon message failed; retrying with backoff.")
        else
          MarkOutboundProfileTransferFailed(item, outboundRetryHelpers.FormatSendAddonResult(result))
          WarnCommIssue(item.kind, "LidCouncil addon message failed: " .. outboundRetryHelpers.FormatSendAddonResult(result))
        end
      end
    end
  end

  if #outboundCommQueue > 0 then
    local nextDelay = outboundFlushPolicy.GetQueuedOutboundCommDelay(item, wasThrottled, wasFailureRetry)
    if outboundCommStats.chatLockdownActive == true then
      nextDelay = math.max(nextDelay, 1.0)
    else
      local throttleRemaining = math.max(0,
        math.max(0, tonumber(outboundCommStats.globalThrottleNotBeforeAt) or 0) - GetNow())
      nextDelay = math.max(nextDelay, throttleRemaining)
      local throttleAge = GetNow() - math.max(0, tonumber(outboundCommStats.lastThrottleAt) or 0)
      local throttleStreak = math.max(0, tonumber(outboundCommStats.globalThrottleStreak) or 0)
      if throttleStreak > 0 and throttleAge >= 0 and throttleAge <= 8 then
        local recoveryInterval = outboundRetryHelpers.ResolveGlobalThrottleRecoveryIntervalSeconds(throttleStreak)
        outboundCommStats.lastGlobalThrottleRecoveryIntervalSeconds = recoveryInterval
        nextDelay = math.max(nextDelay, recoveryInterval)
      end
    end
    -- After a loot choice/vote/award, leave a short quiet window before the
    -- next background chunk. A newly queued priority-1/2 packet still pulls the
    -- timer forward through the normal priority insertion path.
    ScheduleOutboundCommQueueFlush(GetPostLiveTrafficQueueDelay(item, nextDelay, outboundCommQueue))
  else
    outboundCommQueueRunning = false
    ClearScheduledOutboundCommFlush()
  end
  INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("queue_flush_total", performanceTiming.total, {
    queueDepth = #outboundCommQueue,
    context = item and "message" or "idle",
  })
end

INTERNAL_API.LIDCOUNCIL_ShouldArmOutboundFlushWatchdog_Impl = function(queueRunning, nextFlushAt)
  return queueRunning ~= true or math.max(0, tonumber(nextFlushAt) or 0) <= 0
end

local function IsQueuedLiveReceiptDuplicate(item, queue)
  if type(item) ~= "table" or (item.kind ~= "RCHOICE" and item.kind ~= "RCHOICE_ACK" and item.kind ~= "VOTE") then
    return false
  end
  for index, queued in ipairs(type(queue) == "table" and queue or {}) do
    if index > 128 then
      break
    end
    if type(queued) == "table"
      and queued.kind == item.kind
      and queued.distribution == item.distribution
      and NormalizeCharacterKey(queued.targetName) == NormalizeCharacterKey(item.targetName)
      and queued.payload == item.payload
    then
      return true
    end
  end
  return false
end

local LIVE_LOOT_ARCHIVE_YIELD_KINDS = {
  CHOICE = true,
  RCHOICE = true,
  RCHOICE_ACK = true,
  VOTE = true,
  AWARD = true,
  UNASSIGN = true,
  TRADE = true,
  ITEM_OPEN = true,
  ITEM_ACK = true,
  ITEM_REPORT = true,
}

GetPostLiveTrafficQueueDelay = function(item, delaySeconds, queue)
  local resolvedDelay = math.max(0.01, tonumber(delaySeconds) or 0.01)
  if type(item) ~= "table" or LIVE_LOOT_ARCHIVE_YIELD_KINDS[TrimText(item.kind)] ~= true then
    return resolvedDelay
  end
  local nextQueued = type(queue) == "table" and queue[1] or nil
  if type(nextQueued) ~= "table"
    or INTERNAL_API.LIDCOUNCIL_ResolveOutboundCommTelemetryLane_Impl(nextQueued) ~= "archive"
  then
    return resolvedDelay
  end
  return math.max(resolvedDelay, math.max(0.05, tonumber(outboundCommStats.archiveYieldSeconds) or 0.75))
end

-- Keep validation access behind the already-captured INTERNAL_API table.  The
-- transport validator is intentionally large and must not acquire additional
-- direct upvalues under WoW Lua's per-function upvalue limit.
INTERNAL_API.LIDCOUNCIL_IsQueuedLiveReceiptDuplicate_Impl = IsQueuedLiveReceiptDuplicate
INTERNAL_API.LIDCOUNCIL_GetPostLiveTrafficQueueDelay_Impl = GetPostLiveTrafficQueueDelay

local function QueueAddonPayload(kind, distribution, targetName, payload, metadata)
  local now = GetNow()
  local item = {
    kind = kind,
    distribution = distribution,
    targetName = targetName,
    payload = payload,
    priority = GetOutboundCommPriority(kind, metadata),
    metadata = type(metadata) == "table" and metadata or nil,
    queuedAt = now,
  }
  -- Receipt retries can fire while an identical live packet is still waiting
  -- behind WoW's throttle.  Keep one queued copy; once the first copy has left
  -- the queue a later retry is still allowed normally.
  if IsQueuedLiveReceiptDuplicate(item, outboundCommQueue) then
    outboundCommStats.coalescedTotal = (tonumber(outboundCommStats.coalescedTotal) or 0) + 1
    return true
  end
  local coveredByExisting, supersededIndexes = outboundQueueCoalescing.ResolveQueuedOutboundRequestCoalescing(item)
  if coveredByExisting then
    outboundCommStats.coalescedTotal = (tonumber(outboundCommStats.coalescedTotal) or 0) + 1
    return true
  end
  if ShouldSuppressRecentOutboundRequest(item) then
    outboundCommStats.coalescedTotal = (tonumber(outboundCommStats.coalescedTotal) or 0) + 1
    return true
  end
  local stateSupersededIndexes = outboundQueueCoalescing.ResolveQueuedOutboundStatePacketReplacement(item)
  for _, index in ipairs(stateSupersededIndexes) do
    supersededIndexes[#supersededIndexes + 1] = index
  end
  local supersededCount = outboundQueueCoalescing.RemoveQueuedOutboundRequestsByIndexes(supersededIndexes)
  if supersededCount > 0 then
    outboundCommStats.coalescedTotal = (tonumber(outboundCommStats.coalescedTotal) or 0) + supersededCount
  end
  local maxQueueDepth = math.max(1, tonumber(outboundCommStats.maxQueueDepth) or 6000)
  local criticalOverflow = math.max(0, tonumber(outboundCommStats.maxCriticalQueueOverflow) or 0)
  -- Session control, profile state, and snapshot ACKs use priorities 1-5 and must
  -- still be able to report convergence while lower-priority bulk sync is capped.
  local allowCriticalOverflow = item.priority <= 5 and #outboundCommQueue < (maxQueueDepth + criticalOverflow)
  if #outboundCommQueue >= maxQueueDepth and not allowCriticalOverflow then
    outboundCommStats.droppedOverflowTotal = (tonumber(outboundCommStats.droppedOverflowTotal) or 0) + 1
    INTERNAL_API.LIDCOUNCIL_RecordOutboundCommOpcodeTelemetry_Impl(item, "failed")
    MarkOutboundProfileTransferFailed(item, "Outbound addon message queue is full.")
    WarnCommIssue(kind, "LidCouncil outbound queue is full; the message was not queued.")
    return false, "Outbound addon message queue is full."
  end
  local shouldYieldArchive, pressureLane, pressureSeverity = INTERNAL_API.LIDCOUNCIL_ShouldDeferNewArchiveQueueItem_Impl(item)
  if shouldYieldArchive then
    INTERNAL_API.LIDCOUNCIL_EnsureOutboundSessionTelemetryBaseline_Impl(
      TrimText(type(item.metadata) == "table" and item.metadata.sessionId or "")
    )
    item.notBeforeAt = now + math.max(0.05, tonumber(outboundCommStats.archiveYieldSeconds) or 0.75)
    item.archiveYieldDeferred = true
    item.archiveYieldReason = TrimText(pressureLane) .. "_" .. TrimText(pressureSeverity)
    outboundCommStats.archivePressureDeferredTotal = math.max(0,
      tonumber(outboundCommStats.archivePressureDeferredTotal) or 0) + 1
    outboundCommStats.lastArchivePressureDeferredAt = now
    outboundCommStats.lastArchivePressureDeferredReason = item.archiveYieldReason
  end
  local performanceStartedAt = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("queue_insert", 20)
  local insertAt = outboundQueueSelection.InsertOutboundCommQueueItem(item)
  INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("queue_insert", performanceStartedAt, {
    queueDepth = #outboundCommQueue,
  })
  RecordOutboundItemQueued(kind, item.metadata)
  INTERNAL_API.LIDCOUNCIL_RecordOutboundCommOpcodeTelemetry_Impl(item, "queued")

  local nextFlushAt = outboundFlushTimerOps.GetOutboundCommFlushNextAt(outboundCommFlushState)
  if INTERNAL_API.LIDCOUNCIL_ShouldArmOutboundFlushWatchdog_Impl(outboundCommQueueRunning, nextFlushAt) then
    outboundCommQueueRunning = true
    ScheduleOutboundCommQueueFlush(0.01)
  elseif insertAt == 1 then
    ScheduleOutboundCommQueueFlush(outboundFlushPolicy.GetQueuedOutboundCommDelay(nil, false))
  end
  return true
end

inboundRateLimiter = type(INTERNAL_API.LIDCOUNCIL_CreateInboundRateLimitHelpers_Impl) == "function"
  and INTERNAL_API.LIDCOUNCIL_CreateInboundRateLimitHelpers_Impl({
    TrimText = TrimText,
    NormalizeCharacterKey = NormalizeCharacterKey,
    GetNow = GetNow,
  })
  or nil
if type(inboundRateLimiter) ~= "table"
  or type(inboundRateLimiter.Check) ~= "function"
  or type(inboundRateLimiter.Snapshot) ~= "function"
  or type(inboundRateLimiter.Clear) ~= "function"
then
  error("LidCouncil missing inbound rate-limit helpers.")
end

local inboundAdmission = type(INTERNAL_API.LIDCOUNCIL_CreateInboundAdmissionHelpers_Impl) == "function"
  and INTERNAL_API.LIDCOUNCIL_CreateInboundAdmissionHelpers_Impl({
    CommPrefix = COMM_PREFIX,
    TrimText = TrimText,
    NormalizeCharacterKey = NormalizeCharacterKey,
    ParsePayload = ParsePayload,
    ValidateCommProtocolFieldCount = ValidateCommProtocolFieldCount,
    DispatchCommProtocolPayload = DispatchCommProtocolPayload,
    GetMaxPayloadBytes = function()
      return inboundCommTelemetry.maxPayloadBytes
    end,
    InboundOps = inboundCommOps,
    InboundRateLimiter = inboundRateLimiter,
  })
  or nil
if type(inboundAdmission) ~= "table" or type(inboundAdmission.ProcessInboundAddonMessage) ~= "function" then
  error("LidCouncil missing inbound admission helpers.")
end
INTERNAL_API.LIDCOUNCIL_ProcessInboundAddonMessage_Impl = inboundAdmission.ProcessInboundAddonMessage

local function RunCommProtocolValidation()
  local checks = {}
  local passedCount = 0
  local function addCheck(name, expected, actual)
    local passed = expected == actual
    checks[#checks + 1] = {
      name = name,
      passed = passed,
      expected = tostring(expected),
      actual = tostring(actual),
    }
    if passed then
      passedCount = passedCount + 1
    end
  end

  local createPayloadCodec = INTERNAL_API.LIDCOUNCIL_CreateLootSessionPayloadCodec_Impl
  addCheck("protocol payload codec factory available", true, type(createPayloadCodec) == "function")
  local copyArchivePreviewMetadata = INTERNAL_API.LIDCOUNCIL_CopyProfileSyncArchivePreviewMetadata_Impl
  addCheck("profile snapshot preview preserves authoritative archive scope", "FUN_AWARDS",
    type(copyArchivePreviewMetadata) == "function"
      and copyArchivePreviewMetadata({}, { authoritativeArchiveScope = "fun_awards" }, TrimText).authoritativeArchiveScope
      or "missing")
  local parseJoinAckPayload = INTERNAL_API.LIDCOUNCIL_ParseInboundJoinAckPayload_Impl
  addCheck("join confirmation Auto-Pass parser available", true, type(parseJoinAckPayload) == "function")
  if type(parseJoinAckPayload) == "function" then
    local joinAckBase = {
      "JACK", "SESSION-VALIDATION", "ValidationProfile", "profile-id",
      "ValidationHost-Realm", "ValidationMaster-Realm", "100", "PREPARING", "",
      BuildCommProtocolMarker(COMM_PROTOCOL_VERSION), "ValidationMember-Realm",
    }
    local legacyJoinAck = select(1, parseJoinAckPayload(joinAckBase, "ValidationHost-Realm"))
    local offJoinAckFields = { unpack(joinAckBase) }
    offJoinAckFields[12] = "0"
    local offJoinAck = select(1, parseJoinAckPayload(offJoinAckFields, "ValidationHost-Realm"))
    local onJoinAckFields = { unpack(joinAckBase) }
    onJoinAckFields[12] = "1"
    local onJoinAck = select(1, parseJoinAckPayload(onJoinAckFields, "ValidationHost-Realm"))
    addCheck("legacy join confirmation leaves host Auto-Pass unspecified", nil,
      type(legacyJoinAck) == "table" and legacyJoinAck.hostAutoPassEnabled or nil)
    addCheck("join confirmation preserves host Auto-Pass OFF", false,
      type(offJoinAck) == "table" and offJoinAck.hostAutoPassEnabled)
    addCheck("join confirmation preserves host Auto-Pass ON", true,
      type(onJoinAck) == "table" and onJoinAck.hostAutoPassEnabled)
  end
  local buildPriorityPresentation = INTERNAL_API.LIDCOUNCIL_BuildCurrentSessionPriorityPresentation_Impl
  local resolveTransferScopeLabel = INTERNAL_API.LIDCOUNCIL_ResolveCurrentSessionTransferScopeLabel_Impl
  addCheck("current-session priority presentation helper available", true,
    type(buildPriorityPresentation) == "function")
  addCheck("current-session archive transfer scope label helper available", true,
    type(resolveTransferScopeLabel) == "function")
  if type(resolveTransferScopeLabel) == "function" then
    addCheck("archive transfer scope labels distinguish Items from Sessions", "Item History/Session History",
      tostring(resolveTransferScopeLabel({
        reason = "missing_member_item_history_archive_background_deferred",
        scopeDomains = { "session" },
        scopeSubdomains = { "session_live_board" },
      })) .. "/" .. tostring(resolveTransferScopeLabel({
        reason = "missing_member_session_history_archive_background_deferred",
        scopeDomains = { "session" },
        scopeSubdomains = { "ssr:id:completed-session" },
      })))
  end
  if type(buildPriorityPresentation) == "function" then
    local alignedReceipt = buildPriorityPresentation("READY", {
      primaryState = "waiting_ack",
      waiting_ack = 1,
      acknowledgementAgeSeconds = 12,
    }, false)
    addCheck("aligned data remains ready while receipt is pending", true,
      type(alignedReceipt) == "table" and alignedReceipt.dataReady)
    addCheck("aligned receipt remains separate delivery state", "receipt_pending",
      type(alignedReceipt) == "table" and alignedReceipt.deliveryState or "missing")
    addCheck("aligned receipt uses explicit row label", "Receipt pending",
      type(alignedReceipt) == "table" and alignedReceipt.rowLabel or "missing")
    addCheck("aligned receipt tooltip separates data and delivery", true,
      type(alignedReceipt) == "table"
        and string.find(tostring(alignedReceipt.tooltip or ""), "Data ready | Delivery:", 1, true) ~= nil)

    local alignedTimeout = buildPriorityPresentation("READY", {
      primaryState = "ack_timeout",
      ack_timeout = 1,
      scopeLabel = "Session History",
    }, true)
    addCheck("aligned timeout remains ready", true,
      type(alignedTimeout) == "table" and alignedTimeout.dataReady)
    addCheck("aligned scoped timeout retains delivery warning", "Sessions timeout",
      type(alignedTimeout) == "table" and alignedTimeout.rowLabel or "missing")

    local unalignedTransfer = buildPriorityPresentation("PENDING", {
      primaryState = "sending",
      sending = 1,
      sentChunks = 4,
      totalChunks = 10,
    }, false)
    addCheck("unaligned active transfer remains non-ready", false,
      type(unalignedTransfer) == "table" and unalignedTransfer.dataReady)
    addCheck("unaligned active transfer retains progress", "Send 4/10",
      type(unalignedTransfer) == "table" and unalignedTransfer.rowLabel or "missing")

    local itemHistoryProgress = buildPriorityPresentation("VALIDATING", {
      primaryState = "sending",
      sending = 1,
      sentChunks = 1,
      totalChunks = 300,
      scopeLabel = "Item History",
    }, true)
    local sessionHistoryProgress = buildPriorityPresentation("VALIDATING", {
      primaryState = "sending",
      sending = 1,
      sentChunks = 1,
      totalChunks = 500,
      scopeLabel = "Session History",
    }, true)
    addCheck("archive progress names the Items and Sessions columns", "Items 1/300/Sessions 1/500",
      tostring(type(itemHistoryProgress) == "table" and itemHistoryProgress.rowLabel or "missing")
        .. "/" .. tostring(type(sessionHistoryProgress) == "table" and sessionHistoryProgress.rowLabel or "missing"))

    local validating = buildPriorityPresentation("VALIDATING", {}, true)
    local stale = buildPriorityPresentation("STALE", {}, true)
    local unknown = buildPriorityPresentation("PENDING", {}, true)
    local review = buildPriorityPresentation("REVIEW", {}, true)
    local activeRepair = buildPriorityPresentation("STALE", { sending = 1 }, true)
    addCheck("current-session indicator language keeps exact, progress, difference, unknown, and failure distinct",
      "ALIGNED/PROGRESS/PROGRESS/DIFFERS/UNKNOWN/FAILED/PROGRESS",
      table.concat({
        tostring(type(alignedReceipt) == "table" and alignedReceipt.indicatorKind or "missing"),
        tostring(type(validating) == "table" and validating.indicatorKind or "missing"),
        tostring(type(unalignedTransfer) == "table" and unalignedTransfer.indicatorKind or "missing"),
        tostring(type(stale) == "table" and stale.indicatorKind or "missing"),
        tostring(type(unknown) == "table" and unknown.indicatorKind or "missing"),
        tostring(type(review) == "table" and review.indicatorKind or "missing"),
        tostring(type(activeRepair) == "table" and activeRepair.indicatorKind or "missing"),
      }, "/"))
    addCheck("current-session indicator meanings use independent assets", true,
      type(alignedReceipt) == "table"
        and type(unalignedTransfer) == "table"
        and type(validating) == "table"
        and type(stale) == "table"
        and type(unknown) == "table"
        and type(review) == "table"
        and alignedReceipt.indicatorTexture ~= unalignedTransfer.indicatorTexture
        and alignedReceipt.indicatorTexture ~= validating.indicatorTexture
        and alignedReceipt.indicatorTexture ~= stale.indicatorTexture
        and alignedReceipt.indicatorTexture ~= unknown.indicatorTexture
        and alignedReceipt.indicatorTexture ~= review.indicatorTexture
        and validating.indicatorTexture ~= stale.indicatorTexture
        and validating.indicatorTexture ~= unknown.indicatorTexture
        and validating.indicatorTexture ~= review.indicatorTexture
        and stale.indicatorTexture ~= unknown.indicatorTexture
        and stale.indicatorTexture ~= review.indicatorTexture
        and unknown.indicatorTexture ~= review.indicatorTexture)
    addCheck("difference and unknown wording do not imply active transfer", "Archive differs/Proof pending",
      tostring(type(stale) == "table" and stale.rowLabel or "missing")
        .. "/" .. tostring(type(unknown) == "table" and unknown.rowLabel or "missing"))
  end
  do
    local resolveSyncPresentation = INTERNAL_API.LIDCOUNCIL_ResolveCurrentSessionSyncPresentationState_Impl
    addCheck("current-session archive-aware summary helper available", true,
      type(resolveSyncPresentation) == "function")
    if type(resolveSyncPresentation) == "function" then
      local function makeSummaryRow(liveState, archiveState, phase)
        return {
          status = "JOINED",
          syncState = liveState,
          bootstrapState = "READY",
          historyState = archiveState,
          archiveStates = {
            lootList = archiveState,
            itemHistory = archiveState,
            sessionHistory = archiveState,
            funAwards = archiveState,
          },
          priorityProgress = { [3] = type(phase) == "table" and phase or {} },
        }
      end
      local bootstrapPendingRow = makeSummaryRow("SYNCED", "READY")
      bootstrapPendingRow.bootstrapState = "PENDING"
      addCheck("current-session summary reserves Fully Synced for exact P1-P3 proof",
        "SYNCED/ARCHIVE_SYNCING/ARCHIVE_DIFFERS/ARCHIVE_UNKNOWN/ARCHIVE_REVIEW/PARTIAL/PARTIAL",
        table.concat({
          resolveSyncPresentation({ makeSummaryRow("SYNCED", "READY") }),
          resolveSyncPresentation({ makeSummaryRow("SYNCED", "STALE", { sending = 1 }) }),
          resolveSyncPresentation({ makeSummaryRow("SYNCED", "STALE") }),
          resolveSyncPresentation({ makeSummaryRow("SYNCED", "PENDING") }),
          resolveSyncPresentation({ makeSummaryRow("SYNCED", "REVIEW") }),
          resolveSyncPresentation({ makeSummaryRow("PARTIAL", "READY") }),
          resolveSyncPresentation({ bootstrapPendingRow }),
        }, "/"))
    end
  end
  do
    local buildMemberColumnLayout = INTERNAL_API.LIDCOUNCIL_BuildCurrentSessionMemberColumnLayout_Impl
    addCheck("current-session member column layout helper available", true,
      type(buildMemberColumnLayout) == "function")
    if type(buildMemberColumnLayout) == "function" then
      local narrowLayout = buildMemberColumnLayout(260)
      local compactLayout = buildMemberColumnLayout(440)
      local archiveLayout = buildMemberColumnLayout(520)
      local wideLayout = buildMemberColumnLayout(1200)
      local function layoutFits(layout)
        if type(layout) ~= "table"
          or (tonumber(layout.nameWidth) or 0) > 220
          or (tonumber(layout.nameX) or 0) + (tonumber(layout.nameWidth) or 0) > (tonumber(layout.priority1X) or 0)
          or (tonumber(layout.priority1X) or 0) + (tonumber(layout.priorityWidth) or 0) > (tonumber(layout.priority2X) or 0)
          or (tonumber(layout.autoPassX) or 0) + (tonumber(layout.autoPassWidth) or 0) > (tonumber(layout.rowWidth) or 0)
        then
          return false
        end
        if layout.showArchiveDetails then
          return layout.showPriority3 == true
            and (tonumber(layout.priority2X) or 0) + (tonumber(layout.priorityWidth) or 0) <= (tonumber(layout.priority3X) or 0)
            and (tonumber(layout.priority3X) or 0) + (tonumber(layout.archiveWidth) or 0) <= (tonumber(layout.itemHistoryX) or 0)
            and (tonumber(layout.itemHistoryX) or 0) + (tonumber(layout.archiveWidth) or 0) <= (tonumber(layout.sessionHistoryX) or 0)
            and (tonumber(layout.sessionHistoryX) or 0) + (tonumber(layout.archiveWidth) or 0) <= (tonumber(layout.funAwardsX) or 0)
            and (tonumber(layout.funAwardsX) or 0) + (tonumber(layout.archiveWidth) or 0) <= (tonumber(layout.autoPassX) or 0)
        end
        if layout.showPriority3 then
          return (tonumber(layout.priority2X) or 0) + (tonumber(layout.priorityWidth) or 0) <= (tonumber(layout.priority3X) or 0)
            and (tonumber(layout.priority3X) or 0) + (tonumber(layout.priority3Width) or 0) <= (tonumber(layout.autoPassX) or 0)
        end
        return (tonumber(layout.priority2X) or 0) + (tonumber(layout.priorityWidth) or 0) <= (tonumber(layout.autoPassX) or 0)
      end
      addCheck("current-session compact P3 breakpoint is stable", "false/true",
        tostring(buildMemberColumnLayout(439).showPriority3 == true) .. "/" .. tostring(compactLayout.showPriority3 == true))
      addCheck("current-session archive breakpoint is stable", "false/true",
        tostring(buildMemberColumnLayout(519).showArchiveDetails == true) .. "/" .. tostring(archiveLayout.showArchiveDetails == true))
      addCheck("current-session identity column remains capped", true,
        (tonumber(narrowLayout.nameWidth) or 0) <= 220
          and (tonumber(compactLayout.nameWidth) or 0) <= 220
          and (tonumber(archiveLayout.nameWidth) or 0) <= 220
          and (tonumber(wideLayout.nameWidth) or 0) <= 220)
      addCheck("current-session narrow columns remain bounded", true, layoutFits(narrowLayout))
      addCheck("current-session compact P3 columns remain bounded", true, layoutFits(compactLayout))
      addCheck("current-session split archive columns remain bounded", true, layoutFits(archiveLayout))
      addCheck("current-session popout archive columns remain bounded", true, layoutFits(wideLayout))
      addCheck("current-session archive progress remains role-independent", true,
        archiveLayout.showPriority3Detail == true and wideLayout.showPriority3Detail == true)
    end
  end
  local resolveSessionFinalizationReceiptAction =
    INTERNAL_API.LIDCOUNCIL_ResolveSessionFinalizationReceiptAction_Impl
  addCheck("session finalization receipt policy available", true,
    type(resolveSessionFinalizationReceiptAction) == "function")
  if type(resolveSessionFinalizationReceiptAction) == "function" then
    addCheck("session finalization completes after all receipts", "complete",
      resolveSessionFinalizationReceiptAction(0, 1, 3))
    addCheck("session finalization retries only missing receipts", "retry",
      resolveSessionFinalizationReceiptAction(1, 1, 3))
    addCheck("session finalization permits the second bounded retry", "retry",
      resolveSessionFinalizationReceiptAction(1, 2, 3))
    addCheck("session finalization defers exhausted receipts to P3", "defer_p3",
      resolveSessionFinalizationReceiptAction(1, 3, 3))
  end
  if type(createPayloadCodec) == "function" then
    local validationCodec = createPayloadCodec()
    addCheck("protocol payload codec exposes required functions", true,
      type(validationCodec) == "table"
        and type(validationCodec.BuildPayload) == "function"
        and type(validationCodec.ParsePayload) == "function"
        and type(validationCodec.BuildRollOptionFields) == "function"
        and type(validationCodec.ParseRollOptionFields) == "function")
    if type(validationCodec) == "table"
      and type(validationCodec.BuildPayload) == "function"
      and type(validationCodec.ParsePayload) == "function"
      and type(validationCodec.BuildRollOptionFields) == "function"
      and type(validationCodec.ParseRollOptionFields) == "function"
    then
      local codecFields = validationCodec.ParsePayload(
        validationCodec.BuildPayload("VALIDATE", "100%\tline\nreturn\r")
      )
      addCheck("protocol payload codec preserves escaped field", "VALIDATE/100%\tline\nreturn\r", table.concat(codecFields, "/"))
      local rollOptionFields = {
        validationCodec.BuildRollOptionFields({
          { key = "NEED", label = "Need", color = { 1, 0, 1 }, icon = "icon" },
        }),
      }
      local rollOptions = validationCodec.ParseRollOptionFields(rollOptionFields, 1)
      local rollOption = type(rollOptions) == "table" and rollOptions[1] or {}
      addCheck("protocol payload codec preserves roll options", "NEED/Need/1/0/1/icon", table.concat({
        tostring(type(rollOption) == "table" and rollOption.key or ""),
        tostring(type(rollOption) == "table" and rollOption.label or ""),
        tostring(type(rollOption) == "table" and type(rollOption.color) == "table" and rollOption.color[1] or ""),
        tostring(type(rollOption) == "table" and type(rollOption.color) == "table" and rollOption.color[2] or ""),
        tostring(type(rollOption) == "table" and type(rollOption.color) == "table" and rollOption.color[3] or ""),
        tostring(type(rollOption) == "table" and rollOption.icon or ""),
      }, "/"))
    end
  end
  do
    local resolveJoinedSessionRollOptions = INTERNAL_API.LIDCOUNCIL_ResolveJoinedSessionRollOptions_Impl
    addCheck("joined-session roll-option resolver available", true,
      type(resolveJoinedSessionRollOptions) == "function")
    if type(resolveJoinedSessionRollOptions) == "function" then
      local function cloneOptions(options)
        local output = {}
        for index, option in ipairs(type(options) == "table" and options or {}) do
          output[index] = {
            key = tostring(type(option) == "table" and option.key or ""),
            label = tostring(type(option) == "table" and option.label or ""),
          }
        end
        return output
      end
      local localOptions = { { key = "bis", label = "BiS" } }
      local inviteOptions = { { key = "need", label = "Need" } }
      local returningOptions, returningSource = resolveJoinedSessionRollOptions(
        localOptions,
        inviteOptions,
        true,
        cloneOptions
      )
      local bootstrapOptions, bootstrapSource = resolveJoinedSessionRollOptions(
        nil,
        inviteOptions,
        false,
        cloneOptions
      )
      local pendingOptions, pendingSource = resolveJoinedSessionRollOptions(
        nil,
        nil,
        false,
        cloneOptions
      )
      addCheck("returning session reuses synchronized profile roll options", "local_profile/bis",
        tostring(returningSource) .. "/" .. tostring(type(returningOptions[1]) == "table" and returningOptions[1].key or ""))
      addCheck("first join can retain legacy invite roll options until profile sync", "invite/need",
        tostring(bootstrapSource) .. "/" .. tostring(type(bootstrapOptions[1]) == "table" and bootstrapOptions[1].key or ""))
      addCheck("first join without profile or invite options remains pending", "pending_profile/0",
        tostring(pendingSource) .. "/" .. tostring(#pendingOptions))
    end
  end

  local fieldLimit = math.max(1, tonumber(inboundCommTelemetry.maxPayloadFields) or 40)
  local boundaryArgs = {}
  for index = 1, fieldLimit - 1 do
    boundaryArgs[index] = "f" .. tostring(index)
  end
  local boundaryFields = ParsePayload(BuildPayload("VALIDATE", unpack(boundaryArgs)))
  local overflowArgs = {}
  for index = 1, fieldLimit do
    overflowArgs[index] = "f" .. tostring(index)
  end
  local overflowFields = ParsePayload(BuildPayload("VALIDATE", unpack(overflowArgs)))
  local boundaryAccepted, boundaryReason = ValidateCommProtocolFieldCount("VALIDATE", #boundaryFields)
  local overflowAccepted, overflowReason = ValidateCommProtocolFieldCount("VALIDATE", #overflowFields)
  local unknownAccepted, unknownReason, unknownContract = ValidateCommProtocolFieldCount("FUTURE_OPCODE", 1)
  local escapedValue = "100%\tline\nreturn\r"
  local escapedFields = ParsePayload(BuildPayload("VALIDATE", escapedValue))
  local marker = BuildCommProtocolMarker(COMM_PROTOCOL_VERSION)
  local contractSnapshot = GetCommProtocolContractSnapshot()
  local handlerStatus = type(GetCommProtocolHandlerRegistryStatus) == "function"
    and GetCommProtocolHandlerRegistryStatus()
    or nil
  local dispatchFixtureCalls = { total = 0 }
  local dispatchFixtureRegistry = {}
  for _, opcode in ipairs(contractSnapshot.opcodes) do
    local contract = contractSnapshot.contracts[opcode] or {}
    local fixtureOpcode = opcode
    dispatchFixtureCalls[fixtureOpcode] = 0
    dispatchFixtureRegistry[fixtureOpcode] = {
      owner = TrimText(contract.owner),
      handler = function()
        dispatchFixtureCalls[fixtureOpcode] = (tonumber(dispatchFixtureCalls[fixtureOpcode]) or 0) + 1
        dispatchFixtureCalls.total = (tonumber(dispatchFixtureCalls.total) or 0) + 1
      end,
    }
  end
  local exactPayloadBaseLength = #BuildPayload("V", "")
  local safeArgumentLength = math.max(0, COMM_SAFE_PAYLOAD_LIMIT - exactPayloadBaseLength)
  local boundaryPayload = BuildPayload("V", string.rep("x", safeArgumentLength))
  local oversizedPayload = BuildPayload("V", string.rep("x", safeArgumentLength + 1))

  addCheck("protocol marker round trip", COMM_PROTOCOL_VERSION, ParseCommProtocolMarker(marker))
  addCheck("protocol marker rejects malformed value", nil, ParseCommProtocolMarker("Pinvalid"))
  addCheck("protocol field boundary", fieldLimit, #boundaryFields)
  addCheck("protocol field overflow", true, #overflowFields > fieldLimit)
  addCheck("protocol field gate accepts boundary", true, #boundaryFields <= fieldLimit)
  addCheck("protocol field validator accepts boundary", true, boundaryAccepted)
  addCheck("protocol field validator boundary reason", "accepted", boundaryReason)
  addCheck("protocol field validator rejects overflow", false, overflowAccepted)
  addCheck("protocol field validator overflow reason", "field_count_exceeds_limit", overflowReason)
  addCheck("protocol field validator permits unknown structure", true, unknownAccepted)
  addCheck("protocol field validator unknown reason", "accepted", unknownReason)
  addCheck("protocol field validator unknown contract", nil, unknownContract)
  addCheck("protocol escape round trip", escapedValue, escapedFields[2])
  addCheck("protocol payload boundary", COMM_SAFE_PAYLOAD_LIMIT, #boundaryPayload)
  addCheck("protocol payload overflow", true, #oversizedPayload > COMM_SAFE_PAYLOAD_LIMIT)
  local function runSnapshotChunkPayloadBoundaryValidation()
    local splitProfileSnapshotPayload = INTERNAL_API.LIDCOUNCIL_SplitProfileSnapshotPayload_Impl
    local validateProfileSnapshotStartPayload = INTERNAL_API.LIDCOUNCIL_ValidateProfileSnapshotStartPayload_Impl
    addCheck("protocol snapshot chunk payload splitter available", true, type(splitProfileSnapshotPayload) == "function")
    if type(splitProfileSnapshotPayload) ~= "function" then
      return
    end
    local function validateSnapshotChunks(chunks, transferId, source)
      local payloadsSafe = true
      local roundTrip = true
      for index, chunk in ipairs(type(chunks) == "table" and chunks or {}) do
        local fields = ParsePayload(BuildPayload("PSYNC_CHUNK", transferId, tostring(index), chunk))
        if #BuildPayload("PSYNC_CHUNK", transferId, tostring(index), chunk) > COMM_SAFE_PAYLOAD_LIMIT then
          payloadsSafe = false
        end
        if fields[4] ~= chunk then
          roundTrip = false
        end
      end
      return table.concat(chunks or {}) == source and payloadsSafe and roundTrip
    end
    local fullFixture = string.rep("F", 240)
    local fullChunks = splitProfileSnapshotPayload(fullFixture, "PX-validation-1001", 120, COMM_SAFE_PAYLOAD_LIMIT)
    addCheck("protocol full snapshot chunks preserve boundary payload", "2/true", table.concat({
      tostring(type(fullChunks) == "table" and #fullChunks or 0),
      tostring(validateSnapshotChunks(fullChunks, "PX-validation-1001", fullFixture)),
    }, "/"))
    local emptyChunks = splitProfileSnapshotPayload("", "PX-validation-1001", 120, COMM_SAFE_PAYLOAD_LIMIT)
    addCheck("protocol empty snapshot keeps one safe chunk", "1/true", table.concat({
      tostring(type(emptyChunks) == "table" and #emptyChunks or 0),
      tostring(validateSnapshotChunks(emptyChunks, "PX-validation-1001", "")),
    }, "/"))
    local patchFixture = string.rep("%\t\n\r", 40)
    local patchChunks = splitProfileSnapshotPayload(patchFixture, "PX-validation-1001", 190, COMM_SAFE_PAYLOAD_LIMIT)
    addCheck("protocol escaped patch chunks preserve payload limit", "3/true", table.concat({
      tostring(type(patchChunks) == "table" and #patchChunks or 0),
      tostring(validateSnapshotChunks(patchChunks, "PX-validation-1001", patchFixture)),
    }, "/"))
    local impossibleChunks, impossibleReason = splitProfileSnapshotPayload(
      "x",
      string.rep("T", COMM_SAFE_PAYLOAD_LIMIT),
      120,
      COMM_SAFE_PAYLOAD_LIMIT
    )
    addCheck("protocol snapshot chunk splitter rejects oversized envelope", "nil/profile_sync_chunk_envelope_exceeds_limit", table.concat({
      tostring(impossibleChunks),
      tostring(impossibleReason),
    }, "/"))
    addCheck("protocol snapshot start payload validator available", true, type(validateProfileSnapshotStartPayload) == "function")
    if type(validateProfileSnapshotStartPayload) ~= "function" then
      return
    end
    local startPrefixArgs = {
      "PX-validation-1001", "session-validation", "", "profile-id", "1", "LIVE", "", "FULL", "", "1", "live",
    }
    local startPayloadBaseLength = #BuildPayload("PSYNC_START", unpack(startPrefixArgs))
    startPrefixArgs[3] = string.rep("S", math.max(0, COMM_SAFE_PAYLOAD_LIMIT - startPayloadBaseLength))
    local startAccepted, startReason, startLength = validateProfileSnapshotStartPayload(unpack(startPrefixArgs))
    addCheck("protocol snapshot start accepts exact payload boundary", "true/nil/" .. tostring(COMM_SAFE_PAYLOAD_LIMIT), table.concat({
      tostring(startAccepted),
      tostring(startReason),
      tostring(startLength),
    }, "/"))
    startPrefixArgs[3] = startPrefixArgs[3] .. "S"
    local overflowAccepted, overflowReason = validateProfileSnapshotStartPayload(unpack(startPrefixArgs))
    addCheck("protocol snapshot start rejects payload overflow", "false/profile_sync_start_payload_exceeds_limit", table.concat({
      tostring(overflowAccepted),
      tostring(overflowReason),
    }, "/"))
    local escapedStartAccepted, escapedStartReason = validateProfileSnapshotStartPayload(
      "PX-validation-1001", "session-validation", string.rep("%\t\n\r", 24), "profile-id", "1", "LIVE", "", "FULL", "", "1", "live"
    )
    addCheck("protocol snapshot start counts escaped metadata", "false/profile_sync_start_payload_exceeds_limit", table.concat({
      tostring(escapedStartAccepted),
      tostring(escapedStartReason),
    }, "/"))
    local previewTransferGeneration = INTERNAL_API.LIDCOUNCIL_PreviewOutboundProfileTransferGeneration_Impl
    addCheck("protocol snapshot start generation preview available", true, type(previewTransferGeneration) == "function")
    if type(previewTransferGeneration) == "function" then
      local generationMetadata = {
        target = "Member-Realm",
        sessionId = "validation-session",
        profileName = "Validation",
        transferKind = "FULL",
      }
      local firstGeneration = previewTransferGeneration(generationMetadata)
      local secondGeneration = previewTransferGeneration(generationMetadata)
      addCheck("protocol snapshot start generation preview is stable", true,
        firstGeneration > 0 and firstGeneration == secondGeneration)
    end
    local validateCommPayload = INTERNAL_API.LIDCOUNCIL_ValidateCommPayload_Impl
    local splitCommPayloadField = INTERNAL_API.LIDCOUNCIL_SplitCommPayloadField_Impl
    addCheck("protocol generic payload validator available", true, type(validateCommPayload) == "function")
    addCheck("protocol generic payload splitter available", true, type(splitCommPayloadField) == "function")
    if type(validateCommPayload) == "function" then
      local ackArgs = {
        "PX-validation-1001", "session-validation", "", "profile-id", "1", "1", "1", "1", "1",
        "settings", "permissions", "operational", "1", "1", "loot", "session", "1",
      }
      local ackPayloadBaseLength = #BuildPayload("PSYNC_ACK", unpack(ackArgs))
      ackArgs[3] = string.rep("A", math.max(0, COMM_SAFE_PAYLOAD_LIMIT - ackPayloadBaseLength))
      local ackAccepted, ackReason, ackLength = validateCommPayload("PSYNC_ACK", unpack(ackArgs))
      addCheck("protocol snapshot ACK accepts exact payload boundary", "true/nil/" .. tostring(COMM_SAFE_PAYLOAD_LIMIT), table.concat({
        tostring(ackAccepted),
        tostring(ackReason),
        tostring(ackLength),
      }, "/"))
      ackArgs[3] = ackArgs[3] .. "A"
      local ackOverflowAccepted, ackOverflowReason = validateCommPayload("PSYNC_ACK", unpack(ackArgs))
      addCheck("protocol snapshot ACK rejects payload overflow", "false/comm_payload_exceeds_safe_limit", table.concat({
        tostring(ackOverflowAccepted),
        tostring(ackOverflowReason),
      }, "/"))
      do
        local deltaFieldArgs = {}
        for index = 1, fieldLimit do
          deltaFieldArgs[index] = "field" .. tostring(index)
        end
        local deltaFieldAccepted, deltaFieldReason = validateCommPayload("PDELTA", unpack(deltaFieldArgs))
        local memberFieldArgs = {}
        for index = 1, 44 do
          memberFieldArgs[index] = "m"
        end
        local memberAccepted, memberReason = validateCommPayload("MEMBER", unpack(memberFieldArgs))
        memberFieldArgs[45] = "m"
        local memberOverflowAccepted, memberOverflowReason = validateCommPayload("MEMBER", unpack(memberFieldArgs))
        addCheck("protocol validators enforce generic and MEMBER field ceilings",
          "false/comm_field_count_exceeds_limit/true/nil/false/comm_field_count_exceeds_limit", table.concat({
          tostring(deltaFieldAccepted),
          tostring(deltaFieldReason),
          tostring(memberAccepted),
          tostring(memberReason),
          tostring(memberOverflowAccepted),
          tostring(memberOverflowReason),
        }, "/"))
      end
      local profileStateArgs = {
        "session-validation", "", "Member-Realm", "profile-id", "1", "1", "1", "1",
        "settings", "permissions", "operational", "1", "1", "loot", "session", "live", "archive", "P6",
      }
      local profileStateBaseLength = #BuildPayload("PSTATE", unpack(profileStateArgs))
      profileStateArgs[2] = string.rep("S", math.max(0, COMM_SAFE_PAYLOAD_LIMIT - profileStateBaseLength))
      local profileStateAccepted, profileStateReason, profileStateLength = validateCommPayload("PSTATE", unpack(profileStateArgs))
      addCheck("protocol profile state accepts exact payload boundary", "true/nil/" .. tostring(COMM_SAFE_PAYLOAD_LIMIT), table.concat({
        tostring(profileStateAccepted),
        tostring(profileStateReason),
        tostring(profileStateLength),
      }, "/"))
    end
    if type(splitCommPayloadField) == "function" then
      local responsePrefix = { "session-validation", "profile", "profile-id", "PSP-validation-1001", "256", "256" }
      local responseSuffix = { "request-validation" }
      local emptyResponseChunks, emptyResponseReason = splitCommPayloadField(
        "PSUBPATCH_STATE",
        "",
        responsePrefix,
        responseSuffix,
        120,
        COMM_SAFE_PAYLOAD_LIMIT
      )
      addCheck("protocol precise response splitter keeps one empty safe field", "1/nil", table.concat({
        tostring(type(emptyResponseChunks) == "table" and #emptyResponseChunks or 0),
        tostring(emptyResponseReason),
      }, "/"))
      local responseFixture = string.rep("%\t\n\r", 40)
      local responseChunks = splitCommPayloadField(
        "PSUBPATCH_STATE",
        responseFixture,
        responsePrefix,
        responseSuffix,
        120,
        COMM_SAFE_PAYLOAD_LIMIT
      )
      local responseSafe = type(responseChunks) == "table" and #responseChunks > 1 and table.concat(responseChunks) == responseFixture
      for _, chunk in ipairs(type(responseChunks) == "table" and responseChunks or {}) do
        local responseFields = {}
        for index = 1, #responsePrefix do
          responseFields[#responseFields + 1] = responsePrefix[index]
        end
        responseFields[#responseFields + 1] = chunk
        for index = 1, #responseSuffix do
          responseFields[#responseFields + 1] = responseSuffix[index]
        end
        if #BuildPayload("PSUBPATCH_STATE", unpack(responseFields)) > COMM_SAFE_PAYLOAD_LIMIT then
          responseSafe = false
        end
      end
      addCheck("protocol precise response chunks preserve escaped payload limit", true, responseSafe)
    end
  end
  runSnapshotChunkPayloadBoundaryValidation()
  local recordOutboundPayloadReject = INTERNAL_API.LIDCOUNCIL_RecordOutboundPayloadReject_Impl
  local recordOutboundFailureDiagnostic = INTERNAL_API.LIDCOUNCIL_RecordOutboundFailureDiagnostic_Impl
  local recordOutboundDiagnosticResolved = INTERNAL_API.LIDCOUNCIL_RecordOutboundDiagnosticResolved_Impl
  local getOutboundIssueDiagnosticsForSession = INTERNAL_API.LIDCOUNCIL_GetOutboundIssueDiagnosticsForSession_Impl
  local recordOutboundCommOpcodeTelemetry = INTERNAL_API.LIDCOUNCIL_RecordOutboundCommOpcodeTelemetry_Impl
  local getOutboundCommOpcodeTelemetry = INTERNAL_API.LIDCOUNCIL_GetOutboundCommOpcodeTelemetry_Impl
  local getOutboundSessionTelemetry = INTERNAL_API.LIDCOUNCIL_GetOutboundSessionTelemetry_Impl
  addCheck("protocol outbound payload rejection recorder available", true, type(recordOutboundPayloadReject) == "function")
  addCheck("protocol outbound failure diagnostic recorder available", true, type(recordOutboundFailureDiagnostic) == "function")
  addCheck("protocol outbound diagnostic resolution recorder available", true, type(recordOutboundDiagnosticResolved) == "function")
  addCheck("protocol outbound session diagnostics reader available", true, type(getOutboundIssueDiagnosticsForSession) == "function")
  addCheck("protocol outbound opcode telemetry recorder available", true, type(recordOutboundCommOpcodeTelemetry) == "function")
  addCheck("protocol outbound opcode telemetry reader available", true, type(getOutboundCommOpcodeTelemetry) == "function")
  addCheck("protocol outbound session telemetry reader available", true, type(getOutboundSessionTelemetry) == "function")
  if type(recordOutboundPayloadReject) == "function" and type(recordOutboundFailureDiagnostic) == "function"
    and type(recordOutboundDiagnosticResolved) == "function"
    and type(getOutboundIssueDiagnosticsForSession) == "function"
    and type(recordOutboundCommOpcodeTelemetry) == "function" and type(getOutboundCommOpcodeTelemetry) == "function"
    and type(getOutboundSessionTelemetry) == "function"
  then
    local previousRejectedPayloadTotal = outboundCommStats.rejectedPayloadTotal
    local previousRejectedPayloadKind = outboundCommStats.lastRejectedPayloadKind
    local previousRejectedPayloadReason = outboundCommStats.lastRejectedPayloadReason
    local previousRejectedPayloadBytes = outboundCommStats.lastRejectedPayloadBytes
    local previousRejectedPayloadAt = outboundCommStats.lastRejectedPayloadAt
    local previousPayloadRejectHistory = outboundCommStats.payloadRejectHistory
    local previousApiFailureTotal = outboundCommStats.apiFailureTotal
    local previousThrottleExhaustedTotal = outboundCommStats.throttleExhaustedTotal
    local previousOutboundIssueCategory = outboundCommStats.lastOutboundIssueCategory
    local previousOutboundIssueKind = outboundCommStats.lastOutboundIssueKind
    local previousOutboundIssueReason = outboundCommStats.lastOutboundIssueReason
    local previousOutboundIssueBytes = outboundCommStats.lastOutboundIssueBytes
    local previousOutboundIssueAt = outboundCommStats.lastOutboundIssueAt
    local previousOutboundIssueHistory = outboundCommStats.outboundIssueHistory
    local previousOutboundIssueDiagnosticsByScope = outboundCommStats.outboundIssueDiagnosticsByScope
    local previousOutboundIssueScopeOrder = outboundCommStats.outboundIssueScopeOrder
    local previousOpcodeTelemetry = outboundCommStats.opcodeTelemetry
    local previousSessionTelemetryBaseline = outboundCommStats.sessionTelemetryBaseline
    outboundCommStats.payloadRejectHistory = {}
    outboundCommStats.outboundIssueHistory = {}
    outboundCommStats.outboundIssueDiagnosticsByScope = {}
    outboundCommStats.outboundIssueScopeOrder = {}
    outboundCommStats.opcodeTelemetry = {
      byOpcode = {},
      other = {},
      maxTrackedOpcodes = 48,
    }
    outboundCommStats.sessionTelemetryBaseline = nil
    for index = 1, 9 do
      recordOutboundPayloadReject("PSTATE", "validation_payload_reject_" .. tostring(index), index, {
        sessionId = "validation-session",
        target = "Validation-Realm",
      })
    end
    local latestReject = outboundCommStats.payloadRejectHistory[1]
    addCheck("protocol outbound payload rejection total", math.max(0, tonumber(previousRejectedPayloadTotal) or 0) + 9,
      math.max(0, tonumber(outboundCommStats.rejectedPayloadTotal) or 0))
    addCheck("protocol outbound payload rejection history is bounded", 8, #outboundCommStats.payloadRejectHistory)
    addCheck("protocol outbound payload rejection keeps latest opcode and reason", "PSTATE/validation_payload_reject_9/9",
      table.concat({
        TrimText(type(latestReject) == "table" and latestReject.kind or ""),
        TrimText(type(latestReject) == "table" and latestReject.reason or ""),
        tostring(type(latestReject) == "table" and tonumber(latestReject.bytes) or 0),
      }, "/"))
    recordOutboundFailureDiagnostic("api_failure", "PDELTA", "validation_api_failure", 7, {
      sessionId = "validation-session",
      target = "Validation-Realm",
    })
    recordOutboundFailureDiagnostic("throttle_exhausted", "MEMBER", "validation_throttle_exhausted", 11, {
      sessionId = "validation-session",
      target = "Validation-Realm",
    })
    local latestOutboundIssue = outboundCommStats.outboundIssueHistory[1]
    addCheck("protocol outbound API failure total", math.max(0, tonumber(previousApiFailureTotal) or 0) + 1,
      math.max(0, tonumber(outboundCommStats.apiFailureTotal) or 0))
    addCheck("protocol outbound throttle exhaustion total", math.max(0, tonumber(previousThrottleExhaustedTotal) or 0) + 1,
      math.max(0, tonumber(outboundCommStats.throttleExhaustedTotal) or 0))
    addCheck("protocol outbound issue history is bounded", 8, #outboundCommStats.outboundIssueHistory)
    addCheck("protocol outbound issue keeps latest category and reason", "throttle_exhausted/MEMBER/validation_throttle_exhausted/11",
      table.concat({
        TrimText(type(latestOutboundIssue) == "table" and latestOutboundIssue.category or ""),
        TrimText(type(latestOutboundIssue) == "table" and latestOutboundIssue.kind or ""),
        TrimText(type(latestOutboundIssue) == "table" and latestOutboundIssue.reason or ""),
        tostring(type(latestOutboundIssue) == "table" and tonumber(latestOutboundIssue.bytes) or 0),
      }, "/"))
    local validationSessionDiagnostics = getOutboundIssueDiagnosticsForSession("validation-session")
    local freshSessionDiagnostics = getOutboundIssueDiagnosticsForSession("fresh-session")
    addCheck("protocol outbound issue scopes retain current session totals", "9/1/1/8", table.concat({
      tostring(math.max(0, tonumber(validationSessionDiagnostics.payloadRejectedTotal) or 0)),
      tostring(math.max(0, tonumber(validationSessionDiagnostics.apiFailureTotal) or 0)),
      tostring(math.max(0, tonumber(validationSessionDiagnostics.throttleExhaustedTotal) or 0)),
      tostring(#(type(validationSessionDiagnostics.history) == "table" and validationSessionDiagnostics.history or {})),
    }, "/"))
    addCheck("protocol outbound issue scopes reset for a fresh session", "0/0/0/0", table.concat({
      tostring(math.max(0, tonumber(freshSessionDiagnostics.payloadRejectedTotal) or 0)),
      tostring(math.max(0, tonumber(freshSessionDiagnostics.apiFailureTotal) or 0)),
      tostring(math.max(0, tonumber(freshSessionDiagnostics.throttleExhaustedTotal) or 0)),
      tostring(#(type(freshSessionDiagnostics.history) == "table" and freshSessionDiagnostics.history or {})),
    }, "/"))
    local resolvedWrongTarget = recordOutboundDiagnosticResolved("MEMBER", {
      sessionId = "validation-session",
      target = "Other-Realm",
    })
    local resolvedCorrectTarget = recordOutboundDiagnosticResolved("MEMBER", {
      sessionId = "validation-session",
      target = "Validation-Realm",
    })
    validationSessionDiagnostics = getOutboundIssueDiagnosticsForSession("validation-session")
    addCheck("protocol outbound diagnostic resolution requires the same target", false, resolvedWrongTarget)
    addCheck("protocol outbound diagnostic resolution tracks a later matching send", "MEMBER/Validation-Realm/true",
      table.concat({
        TrimText(validationSessionDiagnostics.lastResolvedKind),
        NormalizeCharacterKey(validationSessionDiagnostics.lastResolvedTarget),
        tostring(resolvedCorrectTarget == true),
      }, "/"))
    local opcodeFixture = {
      kind = "PDELTA",
      payload = "code",
      metadata = {
        sessionId = "validation-session",
      },
    }
    recordOutboundCommOpcodeTelemetry(opcodeFixture, "queued")
    recordOutboundCommOpcodeTelemetry(opcodeFixture, "attempted")
    recordOutboundCommOpcodeTelemetry(opcodeFixture, "sent")
    recordOutboundCommOpcodeTelemetry(opcodeFixture, "throttled")
    recordOutboundCommOpcodeTelemetry(opcodeFixture, "failed")
    local opcodeSnapshot = getOutboundCommOpcodeTelemetry()
    local deltaOpcode = {}
    local stateOpcode = {}
    for _, opcode in ipairs(type(opcodeSnapshot.opcodes) == "table" and opcodeSnapshot.opcodes or {}) do
      if TrimText(type(opcode) == "table" and opcode.kind or "") == "PDELTA" then
        deltaOpcode = opcode
      elseif TrimText(type(opcode) == "table" and opcode.kind or "") == "PSTATE" then
        stateOpcode = opcode
      end
    end
    addCheck("protocol outbound opcode telemetry retains queue and transport events", "1/1/1/1/1/0/4/4/4", table.concat({
      tostring(math.max(0, tonumber(deltaOpcode.queuedTotal) or 0)),
      tostring(math.max(0, tonumber(deltaOpcode.attempted) or 0)),
      tostring(math.max(0, tonumber(deltaOpcode.sent) or 0)),
      tostring(math.max(0, tonumber(deltaOpcode.throttled) or 0)),
      tostring(math.max(0, tonumber(deltaOpcode.failed) or 0)),
      tostring(math.max(0, tonumber(deltaOpcode.payloadRejected) or 0)),
      tostring(math.max(0, tonumber(deltaOpcode.bytesQueued) or 0)),
      tostring(math.max(0, tonumber(deltaOpcode.bytesAttempted) or 0)),
      tostring(math.max(0, tonumber(deltaOpcode.bytesSent) or 0)),
    }, "/"))
    addCheck("protocol outbound opcode telemetry retains payload rejection bytes", "9/45", table.concat({
      tostring(math.max(0, tonumber(stateOpcode.payloadRejected) or 0)),
      tostring(math.max(0, tonumber(stateOpcode.bytesRejected) or 0)),
    }, "/"))
    local validationSessionTelemetry = getOutboundSessionTelemetry("validation-session")
    local sessionOpcodeRows = type(validationSessionTelemetry.outboundOpcodeTelemetry) == "table"
      and validationSessionTelemetry.outboundOpcodeTelemetry.opcodes
      or {}
    local sessionDeltaOpcode = {}
    for _, opcode in ipairs(type(sessionOpcodeRows) == "table" and sessionOpcodeRows or {}) do
      if TrimText(type(opcode) == "table" and opcode.kind or "") == "PDELTA" then
        sessionDeltaOpcode = opcode
        break
      end
    end
    addCheck("protocol outbound opcode telemetry is session-baselined", "1/1/1/1/1/0", table.concat({
      tostring(math.max(0, tonumber(sessionDeltaOpcode.queuedTotal) or 0)),
      tostring(math.max(0, tonumber(sessionDeltaOpcode.attempted) or 0)),
      tostring(math.max(0, tonumber(sessionDeltaOpcode.sent) or 0)),
      tostring(math.max(0, tonumber(sessionDeltaOpcode.throttled) or 0)),
      tostring(math.max(0, tonumber(sessionDeltaOpcode.failed) or 0)),
      tostring(math.max(0, tonumber(sessionDeltaOpcode.payloadRejected) or 0)),
    }, "/"))
    outboundCommStats.rejectedPayloadTotal = previousRejectedPayloadTotal
    outboundCommStats.lastRejectedPayloadKind = previousRejectedPayloadKind
    outboundCommStats.lastRejectedPayloadReason = previousRejectedPayloadReason
    outboundCommStats.lastRejectedPayloadBytes = previousRejectedPayloadBytes
    outboundCommStats.lastRejectedPayloadAt = previousRejectedPayloadAt
    outboundCommStats.payloadRejectHistory = previousPayloadRejectHistory
    outboundCommStats.apiFailureTotal = previousApiFailureTotal
    outboundCommStats.throttleExhaustedTotal = previousThrottleExhaustedTotal
    outboundCommStats.lastOutboundIssueCategory = previousOutboundIssueCategory
    outboundCommStats.lastOutboundIssueKind = previousOutboundIssueKind
    outboundCommStats.lastOutboundIssueReason = previousOutboundIssueReason
    outboundCommStats.lastOutboundIssueBytes = previousOutboundIssueBytes
    outboundCommStats.lastOutboundIssueAt = previousOutboundIssueAt
    outboundCommStats.outboundIssueHistory = previousOutboundIssueHistory
    outboundCommStats.outboundIssueDiagnosticsByScope = previousOutboundIssueDiagnosticsByScope
    outboundCommStats.outboundIssueScopeOrder = previousOutboundIssueScopeOrder
    outboundCommStats.opcodeTelemetry = previousOpcodeTelemetry
    outboundCommStats.sessionTelemetryBaseline = previousSessionTelemetryBaseline
  end
  local buildOutboundOpcodePressure = INTERNAL_API.LIDCOUNCIL_BuildOutboundOpcodePressure_Impl
  addCheck("protocol outbound opcode pressure builder available", true, type(buildOutboundOpcodePressure) == "function")
  if type(buildOutboundOpcodePressure) == "function" then
    local pressureFixture = buildOutboundOpcodePressure({
      { kind = "PSYNC_CHUNK", queuedNow = 12 },
      { kind = "PSTATE", payloadRejected = 1 },
      { kind = "MEMBER", bytesSent = 24576 },
      { kind = "PDELTA", failed = 2 },
    })
    local pressureKinds = {}
    for _, pressure in ipairs(pressureFixture) do
      pressureKinds[#pressureKinds + 1] = TrimText(pressure.kind) .. "/" .. TrimText(pressure.severity)
    end
    addCheck("protocol outbound opcode pressure ranks and bounds alerts", "PDELTA/critical|PSTATE/critical|PSYNC_CHUNK/warning",
      table.concat(pressureKinds, "|"))
    local watchFixture = buildOutboundOpcodePressure({
      { kind = "MEMBER", bytesSent = 24576 },
    })
    addCheck("protocol outbound opcode pressure identifies sustained volume", "MEMBER/watch", table.concat({
      TrimText(type(watchFixture[1]) == "table" and watchFixture[1].kind or ""),
      TrimText(type(watchFixture[1]) == "table" and watchFixture[1].severity or ""),
    }, "/"))
  end
  local buildOutboundLanePressure = INTERNAL_API.LIDCOUNCIL_BuildOutboundLanePressure_Impl
  addCheck("protocol outbound lane pressure builder available", true, type(buildOutboundLanePressure) == "function")
  if type(buildOutboundLanePressure) == "function" then
    local lanePressureFixture = buildOutboundLanePressure({
      live = { queuedNow = 8 },
      archive = { bytesSent = 65536 },
      control = { failed = 2 },
    }, outboundCommStats.lanePressureThresholds)
    local lanePressureKinds = {}
    for _, pressure in ipairs(lanePressureFixture) do
      lanePressureKinds[#lanePressureKinds + 1] = TrimText(pressure.lane) .. "/" .. TrimText(pressure.severity)
    end
    addCheck("protocol outbound lane pressure separates urgency from archive volume", "control/critical|live/warning|archive/watch",
      table.concat(lanePressureKinds, "|"))
    local lowArchivePressure = buildOutboundLanePressure({
      archive = { bytesSent = 32768 },
    }, outboundCommStats.lanePressureThresholds)
    addCheck("protocol outbound lane pressure tolerates normal archive volume", 0, #lowArchivePressure)
  end
  local shouldYieldArchiveForLanePressure = INTERNAL_API.LIDCOUNCIL_ShouldYieldArchiveForLanePressure_Impl
  addCheck("protocol archive yield pressure rule available", true, type(shouldYieldArchiveForLanePressure) == "function")
  if type(shouldYieldArchiveForLanePressure) == "function" then
    local yieldForUrgentLane, yieldLane, yieldSeverity = shouldYieldArchiveForLanePressure({
      { lane = "archive", severity = "critical" },
      { lane = "live", severity = "warning" },
    })
    addCheck("protocol archive yield protects live lane", "true/live/warning", table.concat({
      tostring(yieldForUrgentLane),
      TrimText(yieldLane),
      TrimText(yieldSeverity),
    }, "/"))
    local yieldForArchiveOnly, archiveOnlyLane, archiveOnlySeverity = shouldYieldArchiveForLanePressure({
      { lane = "archive", severity = "critical" },
    })
    addCheck("protocol archive yield ignores archive-only pressure", "false//", table.concat({
      tostring(yieldForArchiveOnly),
      TrimText(archiveOnlyLane),
      TrimText(archiveOnlySeverity),
    }, "/"))
  end
  local createOutboundArchivePressure = INTERNAL_API.LIDCOUNCIL_CreateOutboundArchivePressureHelpers_Impl
  addCheck("protocol archive pressure factory available", true, type(createOutboundArchivePressure) == "function")
  if type(createOutboundArchivePressure) == "function" then
    local archivePressureStats = {
      archiveYieldPressureCacheSeconds = 1,
    }
    local archivePressureBuilds = 0
    local capturedArchivePressureLanes = {}
    local archivePressureHelpers = createOutboundArchivePressure({
      Stats = archivePressureStats,
      TrimText = TrimText,
      GetNow = function()
        return 100
      end,
      GetActiveSessionId = function()
        return "validation-session"
      end,
      GetQueue = function()
        return {
          { lane = "live", metadata = { sessionId = "validation-session" } },
          { lane = "archive", metadata = { sessionId = "validation-session" } },
          { lane = "live", metadata = { sessionId = "previous-session" } },
        }
      end,
      ResolveLane = function(item)
        return TrimText(type(item) == "table" and item.lane or "control")
      end,
      ResolveQueueSessionId = function(_, metadata)
        return TrimText(type(metadata) == "table" and metadata.sessionId or "")
      end,
      BuildLanePressure = function(laneTelemetry)
        archivePressureBuilds = archivePressureBuilds + 1
        capturedArchivePressureLanes = laneTelemetry
        return laneTelemetry
      end,
      ShouldYieldArchiveForLanePressure = function(laneTelemetry)
        local live = type(laneTelemetry) == "table" and laneTelemetry.live or {}
        if math.max(0, tonumber(type(live) == "table" and live.queuedNow or 0) or 0) > 0 then
          return true, "live", "warning"
        end
        return false, "", ""
      end,
    })
    addCheck("protocol archive pressure factory creates defer helper", true,
      type(archivePressureHelpers) == "table"
        and type(archivePressureHelpers.ShouldDeferNewArchiveQueueItem) == "function")
    if type(archivePressureHelpers) == "table" then
      local archiveDeferred, pressureLane, pressureSeverity = archivePressureHelpers.ShouldDeferNewArchiveQueueItem({ lane = "archive" })
      addCheck("protocol archive pressure filters session queue and yields", "true/live/warning/1/1", table.concat({
        tostring(archiveDeferred),
        TrimText(pressureLane),
        TrimText(pressureSeverity),
        tostring(math.max(0, tonumber(type(capturedArchivePressureLanes.live) == "table" and capturedArchivePressureLanes.live.queuedNow or 0) or 0)),
        tostring(math.max(0, tonumber(type(capturedArchivePressureLanes.archive) == "table" and capturedArchivePressureLanes.archive.queuedNow or 0) or 0)),
      }, "/"))
      local cachedDeferred, cachedLane, cachedSeverity = archivePressureHelpers.ShouldDeferNewArchiveQueueItem({ lane = "archive" })
      addCheck("protocol archive pressure reuses cached decision", "true/live/warning/1", table.concat({
        tostring(cachedDeferred),
        TrimText(cachedLane),
        TrimText(cachedSeverity),
        tostring(archivePressureBuilds),
      }, "/"))
    end
  end
  addCheck("protocol contract registry version", COMM_PROTOCOL_CONTRACT_VERSION, contractSnapshot.version)
  addCheck("protocol contract registry coverage", true, contractSnapshot.opcodeCount > 0)
  addCheck("protocol handler registry API", true, type(GetCommProtocolHandlerRegistryStatus) == "function")
  addCheck("protocol handler registry available", true, type(handlerStatus) == "table")
  if type(handlerStatus) == "table" then
    addCheck("protocol handler registry ready", true, handlerStatus.ready == true)
    addCheck("protocol handler registry contract count", contractSnapshot.opcodeCount, handlerStatus.contractCount)
    addCheck("protocol handler registry missing handlers", 0, math.max(0, tonumber(handlerStatus.missingCount) or 0))
    addCheck("protocol handler registry owner mismatches", 0, math.max(0, tonumber(handlerStatus.ownerMismatchCount) or 0))
    addCheck("protocol handler registry uncontracted handlers", 0, math.max(0, tonumber(handlerStatus.uncontractedCount) or 0))
  end
  local fixtureOpcode = contractSnapshot.opcodes[1]
  if fixtureOpcode then
    local function runDirectDispatchValidation()
      local initialDispatches = math.max(0, tonumber(dispatchFixtureCalls.total) or 0)
      local knownDispatch, knownDispatchReason = DispatchCommProtocolPayload(fixtureOpcode, { fixtureOpcode }, "Validation-Realm", dispatchFixtureRegistry)
      addCheck("protocol dispatch fixture accepts known opcode", true, knownDispatch)
      addCheck("protocol dispatch fixture known reason", "dispatched", knownDispatchReason)
      addCheck("protocol dispatch fixture invokes one handler", initialDispatches + 1, dispatchFixtureCalls.total)
  
      local unknownDispatch, unknownDispatchReason = DispatchCommProtocolPayload("FUTURE_OPCODE", { "FUTURE_OPCODE" }, "Validation-Realm", dispatchFixtureRegistry)
      addCheck("protocol dispatch fixture rejects unknown opcode", false, unknownDispatch)
      addCheck("protocol dispatch fixture unknown reason", "unknown_opcode", unknownDispatchReason)
      addCheck("protocol dispatch fixture unknown invokes none", initialDispatches + 1, dispatchFixtureCalls.total)
  
      local missingDispatch, missingDispatchReason = DispatchCommProtocolPayload(fixtureOpcode, { fixtureOpcode }, "Validation-Realm", {})
      addCheck("protocol dispatch fixture rejects missing handler", false, missingDispatch)
      addCheck("protocol dispatch fixture missing handler reason", "missing_protocol_handler", missingDispatchReason)
      addCheck("protocol dispatch fixture missing handler invokes none", initialDispatches + 1, dispatchFixtureCalls.total)
  
      local ownerMismatchRegistry = {
        [fixtureOpcode] = {
          owner = "unexpected_owner",
          handler = function()
            dispatchFixtureCalls.total = (tonumber(dispatchFixtureCalls.total) or 0) + 1000
          end,
        },
      }
      local ownerMismatchDispatch, ownerMismatchReason = DispatchCommProtocolPayload(fixtureOpcode, { fixtureOpcode }, "Validation-Realm", ownerMismatchRegistry)
      addCheck("protocol dispatch fixture rejects owner mismatch", false, ownerMismatchDispatch)
      addCheck("protocol dispatch fixture owner mismatch reason", "protocol_handler_owner_mismatch", ownerMismatchReason)
      addCheck("protocol dispatch fixture owner mismatch invokes none", initialDispatches + 1, dispatchFixtureCalls.total)

      local handlerErrorRegistry = {
        [fixtureOpcode] = {
          owner = contractSnapshot.contracts[fixtureOpcode].owner,
          handler = function()
            error("validation_handler_failure")
          end,
        },
      }
      local handlerErrorDispatch, handlerErrorReason, handlerErrorDetail = DispatchCommProtocolPayload(
        fixtureOpcode,
        { fixtureOpcode },
        "Validation-Realm",
        handlerErrorRegistry
      )
      addCheck("protocol dispatch contains handler error", false, handlerErrorDispatch)
      addCheck("protocol dispatch handler error reason", "protocol_handler_error", handlerErrorReason)
      addCheck(
        "protocol dispatch handler error detail",
        true,
        string.find(tostring(handlerErrorDetail), "validation_handler_failure", 1, true) ~= nil
      )
  
      local initialDeltaDispatches = math.max(0, tonumber(dispatchFixtureCalls.PDELTA) or 0)
      local staleInboundDispatch, staleInboundReason = DispatchCommProtocolPayload(
        "PDELTA",
        { "PDELTA", "previous-session" },
        "Validation-Realm",
        dispatchFixtureRegistry,
        "validation-session"
      )
      addCheck("protocol dispatch rejects stale inbound session packet", false, staleInboundDispatch)
      addCheck("protocol dispatch stale inbound reason", "stale_session_bound_message", staleInboundReason)
      addCheck("protocol dispatch stale inbound invokes no handler", initialDeltaDispatches, dispatchFixtureCalls.PDELTA)
  
      local initialLifecycleDispatches = math.max(0, tonumber(dispatchFixtureCalls.START) or 0)
      local lifecycleDispatch, lifecycleReason = DispatchCommProtocolPayload(
        "START",
        { "START", "previous-session" },
        "Validation-Realm",
        dispatchFixtureRegistry,
        "validation-session"
      )
      addCheck("protocol dispatch preserves lifecycle packet", true, lifecycleDispatch)
      addCheck("protocol dispatch lifecycle reason", "dispatched", lifecycleReason)
      addCheck("protocol dispatch lifecycle invokes handler", initialLifecycleDispatches + 1, dispatchFixtureCalls.START)
  
    end
    runDirectDispatchValidation()

    local processInboundAddonMessage = INTERNAL_API.LIDCOUNCIL_ProcessInboundAddonMessage_Impl
    local function buildInboundFixtureTelemetry()
      local telemetry = {
        received = 0,
        rejected = 0,
        dispatched = 0,
        unknown = 0,
        contractRejected = 0,
        handlerErrors = 0,
        lastRejectedReason = "",
        lastHandlerErrorKind = "",
        lastHandlerErrorSender = "",
        lastHandlerErrorDetail = "",
      }
      return telemetry, {
        record = function()
          telemetry.received = telemetry.received + 1
        end,
        recordRejected = function(_, _, reason)
          telemetry.rejected = telemetry.rejected + 1
          telemetry.lastRejectedReason = TrimText(reason)
        end,
        recordDispatched = function()
          telemetry.dispatched = telemetry.dispatched + 1
        end,
        recordUnknownOpcode = function()
          telemetry.unknown = telemetry.unknown + 1
        end,
        recordContractRejected = function()
          telemetry.contractRejected = telemetry.contractRejected + 1
        end,
        recordHandlerError = function(kind, sender, detail)
          telemetry.handlerErrors = telemetry.handlerErrors + 1
          telemetry.lastHandlerErrorKind = TrimText(kind)
          telemetry.lastHandlerErrorSender = TrimText(sender)
          telemetry.lastHandlerErrorDetail = TrimText(detail)
        end,
      }
    end
    local staleInboundArgs = { "previous-session" }
    for index = 2, 15 do
      staleInboundArgs[index] = "field" .. tostring(index)
    end
    local staleInboundTelemetry, staleInboundOps = buildInboundFixtureTelemetry()
    local staleInboundHandlerCalls = math.max(0, tonumber(dispatchFixtureCalls.PDELTA) or 0)
    local staleInboundProcessed, staleInboundProcessReason = false, "processor_unavailable"
    if type(processInboundAddonMessage) == "function" then
      staleInboundProcessed, staleInboundProcessReason = processInboundAddonMessage(
        COMM_PREFIX,
        BuildPayload("PDELTA", unpack(staleInboundArgs)),
        "Validation-Realm",
        {
          handlerRegistry = dispatchFixtureRegistry,
          activeSessionIdOverride = "validation-session",
          inboundOps = staleInboundOps,
        }
      )
    end
    addCheck("protocol inbound processor available", true, type(processInboundAddonMessage) == "function")
    addCheck("protocol inbound processor rejects stale session packet", false, staleInboundProcessed)
    addCheck("protocol inbound processor stale session reason", "stale_session_bound_message", staleInboundProcessReason)
    addCheck("protocol inbound processor records stale rejection", "1/1/0/stale_session_bound_message", table.concat({
      tostring(staleInboundTelemetry.received),
      tostring(staleInboundTelemetry.rejected),
      tostring(math.max(0, tonumber(dispatchFixtureCalls.PDELTA) or 0) - staleInboundHandlerCalls),
      staleInboundTelemetry.lastRejectedReason,
    }, "/"))

    local currentInboundArgs = { "validation-session" }
    for index = 2, 15 do
      currentInboundArgs[index] = "field" .. tostring(index)
    end
    local currentInboundTelemetry, currentInboundOps = buildInboundFixtureTelemetry()
    local currentInboundHandlerCalls = math.max(0, tonumber(dispatchFixtureCalls.PDELTA) or 0)
    local currentInboundProcessed, currentInboundProcessReason = false, "processor_unavailable"
    if type(processInboundAddonMessage) == "function" then
      currentInboundProcessed, currentInboundProcessReason = processInboundAddonMessage(
        COMM_PREFIX,
        BuildPayload("PDELTA", unpack(currentInboundArgs)),
        "Validation-Realm",
        {
          handlerRegistry = dispatchFixtureRegistry,
          activeSessionIdOverride = "validation-session",
          inboundOps = currentInboundOps,
        }
      )
    end
    addCheck("protocol inbound processor accepts current session after stale rejection", "true/dispatched/1/0/1", table.concat({
      tostring(currentInboundProcessed),
      tostring(currentInboundProcessReason),
      tostring(currentInboundTelemetry.received),
      tostring(currentInboundTelemetry.rejected),
      tostring(math.max(0, tonumber(dispatchFixtureCalls.PDELTA) or 0) - currentInboundHandlerCalls),
    }, "/"))

    local handlerErrorInboundTelemetry, handlerErrorInboundOps = buildInboundFixtureTelemetry()
    local handlerErrorInboundProcessed, handlerErrorInboundReason = false, "processor_unavailable"
    if type(processInboundAddonMessage) == "function" then
      handlerErrorInboundProcessed, handlerErrorInboundReason = processInboundAddonMessage(
        COMM_PREFIX,
        BuildPayload("START", "validation-session", "profile", "profile-id", "host", "host", "0"),
        "Validation-Realm",
        {
          handlerRegistry = {
            START = {
              owner = "session_flow",
              handler = function()
                error("validation_inbound_handler_failure")
              end,
            },
          },
          activeSessionIdOverride = "validation-session",
          inboundOps = handlerErrorInboundOps,
        }
      )
    end
    addCheck("protocol inbound processor contains handler error", false, handlerErrorInboundProcessed)
    addCheck("protocol inbound processor handler error reason", "protocol_handler_error", handlerErrorInboundReason)
    addCheck("protocol inbound processor records handler error", "1/1/0/protocol_handler_error", table.concat({
      tostring(handlerErrorInboundTelemetry.received),
      tostring(handlerErrorInboundTelemetry.rejected),
      tostring(handlerErrorInboundTelemetry.dispatched),
      handlerErrorInboundTelemetry.lastRejectedReason,
    }, "/"))
    addCheck("protocol inbound processor records dedicated handler diagnostics", "1/START/Validation-Realm/true", table.concat({
      tostring(handlerErrorInboundTelemetry.handlerErrors),
      handlerErrorInboundTelemetry.lastHandlerErrorKind,
      handlerErrorInboundTelemetry.lastHandlerErrorSender,
      tostring(string.find(
        handlerErrorInboundTelemetry.lastHandlerErrorDetail,
        "validation_inbound_handler_failure",
        1,
        true
      ) ~= nil),
    }, "/"))

    local rateLimitInboundTelemetry, rateLimitInboundOps = buildInboundFixtureTelemetry()
    local rateLimitInboundProcessed, rateLimitInboundReason = false, "processor_unavailable"
    if type(processInboundAddonMessage) == "function" then
      rateLimitInboundProcessed, rateLimitInboundReason = processInboundAddonMessage(
        COMM_PREFIX,
        BuildPayload("START", "validation-session", "profile", "profile-id", "host", "host", "0"),
        "Validation-Realm",
        {
          handlerRegistry = dispatchFixtureRegistry,
          inboundOps = rateLimitInboundOps,
          inboundRateLimiter = {
            Check = function()
              return false, "incoming_rate_limited_control"
            end,
          },
        }
      )
    end
    addCheck("protocol inbound processor applies sender burst limit", false, rateLimitInboundProcessed)
    addCheck("protocol inbound processor records sender burst limit", "incoming_rate_limited_control/1/1/0", table.concat({
      tostring(rateLimitInboundReason),
      tostring(rateLimitInboundTelemetry.received),
      tostring(rateLimitInboundTelemetry.rejected),
      tostring(rateLimitInboundTelemetry.dispatched),
    }, "/"))

    local failOpenTelemetry, failOpenOps = buildInboundFixtureTelemetry()
    local failOpenHandlerCalls = math.max(0, tonumber(dispatchFixtureCalls.START) or 0)
    local failOpenProcessed, failOpenReason = false, "processor_unavailable"
    if type(processInboundAddonMessage) == "function" then
      failOpenProcessed, failOpenReason = processInboundAddonMessage(
        COMM_PREFIX,
        BuildPayload("START", "validation-session", "profile", "profile-id", "host", "host", "0"),
        "Validation-Realm",
        {
          handlerRegistry = dispatchFixtureRegistry,
          inboundOps = failOpenOps,
          inboundRateLimiter = {
            Check = function()
              error("validation_rate_limiter_failure")
            end,
          },
        }
      )
    end
    addCheck("protocol inbound processor fails open on limiter error", "true/dispatched/1/0/1", table.concat({
      tostring(failOpenProcessed),
      tostring(failOpenReason),
      tostring(failOpenTelemetry.received),
      tostring(failOpenTelemetry.rejected),
      tostring(math.max(0, tonumber(dispatchFixtureCalls.START) or 0) - failOpenHandlerCalls),
    }, "/"))

    local lifecycleInboundTelemetry, lifecycleInboundOps = buildInboundFixtureTelemetry()
    local lifecycleInboundHandlerCalls = math.max(0, tonumber(dispatchFixtureCalls.START) or 0)
    local lifecycleInboundProcessed, lifecycleInboundProcessReason = false, "processor_unavailable"
    if type(processInboundAddonMessage) == "function" then
      lifecycleInboundProcessed, lifecycleInboundProcessReason = processInboundAddonMessage(
        COMM_PREFIX,
        BuildPayload("START", "previous-session", "profile", "profile-id", "host", "host", "0"),
        "Validation-Realm",
        {
          handlerRegistry = dispatchFixtureRegistry,
          activeSessionIdOverride = "validation-session",
          inboundOps = lifecycleInboundOps,
        }
      )
    end
    addCheck("protocol inbound processor preserves lifecycle packet", "true/dispatched/1/0/1", table.concat({
      tostring(lifecycleInboundProcessed),
      tostring(lifecycleInboundProcessReason),
      tostring(lifecycleInboundTelemetry.received),
      tostring(lifecycleInboundTelemetry.rejected),
      tostring(math.max(0, tonumber(dispatchFixtureCalls.START) or 0) - lifecycleInboundHandlerCalls),
    }, "/"))

    local function runInboundSnapshotLifecycleValidation()
      local finalizeIncomingProfileSyncSessionState = INTERNAL_API.LIDCOUNCIL_FinalizeIncomingProfileSyncSessionState_Impl
      local resolveIncomingProfileSyncTransfer = INTERNAL_API.LIDCOUNCIL_ResolveIncomingProfileSyncTransfer_Impl
      local applyIncomingProfileSyncChunk = INTERNAL_API.LIDCOUNCIL_ApplyIncomingProfileSyncChunk_Impl
      local recordIncomingSnapshotReject = INTERNAL_API.LIDCOUNCIL_RecordIncomingSnapshotReject_Impl
      local beginIncomingSnapshotDiagnosticsForSession = INTERNAL_API.LIDCOUNCIL_BeginIncomingSnapshotDiagnosticsForSession_Impl
      local snapshotLifecycleState = {
        pendingProfileSyncs = {
          ["retained-transfer-id"] = { sessionId = "retained-session", receivedChunkCount = 1 },
        },
        incomingSnapshotCleanupHistory = {
          { sessionId = "current-session", count = 1, at = 1 },
          { sessionId = "retained-session", count = 1, at = 2 },
        },
        maxIncomingSnapshotCleanupHistory = 2,
        incomingSnapshotRejectHistory = {},
        maxIncomingSnapshotRejectHistory = 4,
        maxIncomingSnapshotRejectReasons = 4,
      }
      local function beginSnapshotDiagnostics(sessionId)
        if type(beginIncomingSnapshotDiagnosticsForSession) == "function" then
          beginIncomingSnapshotDiagnosticsForSession(snapshotLifecycleState, sessionId, 1234, TrimText)
        end
      end
      local function recordSnapshotReject(opcode, sender, fields, reason)
        if type(recordIncomingSnapshotReject) == "function" then
          recordIncomingSnapshotReject(snapshotLifecycleState, opcode, sender, fields, reason, 1234, TrimText)
        end
      end
      local snapshotLifecycleRegistry = {
        PSYNC_START = {
          owner = "profile_sync",
          handler = function(fields, sender)
            beginSnapshotDiagnostics(TrimText(fields[3]))
            snapshotLifecycleState.pendingProfileSyncs[TrimText(fields[2])] = {
              sessionId = TrimText(fields[3]),
              sender = TrimText(sender),
              chunkCount = math.max(0, tonumber(fields[6]) or 0),
              chunks = {},
              receivedBytes = 0,
              receivedChunkCount = 0,
            }
          end,
        },
        PSYNC_CHUNK = {
          owner = "profile_sync",
          handler = function(fields, sender)
            if type(resolveIncomingProfileSyncTransfer) ~= "function" then
              return
            end
            local syncState, transferReason = resolveIncomingProfileSyncTransfer(
              snapshotLifecycleState.pendingProfileSyncs,
              fields[2],
              sender,
              TrimText
            )
            if type(syncState) == "table" then
              local accepted, chunkReason = false, "profile_sync_chunk_helper_unavailable"
              if type(applyIncomingProfileSyncChunk) == "function" then
                accepted, chunkReason = applyIncomingProfileSyncChunk(syncState, fields[3], fields[4], 64, 20, 1234)
              end
              if not accepted then
                snapshotLifecycleState.pendingProfileSyncs[TrimText(fields[2])] = nil
                snapshotLifecycleState.lastChunkFailure = chunkReason
                recordSnapshotReject("PSYNC_CHUNK", sender, fields, chunkReason)
              end
            elseif transferReason == "sender_mismatch" then
              recordSnapshotReject("PSYNC_CHUNK", sender, fields, "profile_sync_sender_mismatch")
            end
          end,
        },
        PSYNC_END = {
          owner = "profile_sync",
          handler = function(fields, sender)
            if type(resolveIncomingProfileSyncTransfer) ~= "function" then
              return
            end
            local syncState, transferReason = resolveIncomingProfileSyncTransfer(
              snapshotLifecycleState.pendingProfileSyncs,
              fields[2],
              sender,
              TrimText
            )
            if type(syncState) == "table" then
              snapshotLifecycleState.pendingProfileSyncs[TrimText(fields[2])] = nil
            elseif transferReason == "sender_mismatch" then
              recordSnapshotReject("PSYNC_END", sender, fields, "profile_sync_sender_mismatch")
            end
          end,
        },
        STOP = {
          owner = "session_flow",
          handler = function(fields)
            if type(finalizeIncomingProfileSyncSessionState) == "function" then
              finalizeIncomingProfileSyncSessionState(snapshotLifecycleState, fields[2], 1234, TrimText)
            end
          end,
        },
      }
      local staleSnapshotStartTelemetry, staleSnapshotStartOps = buildInboundFixtureTelemetry()
      local staleSnapshotStartProcessed, staleSnapshotStartReason = false, "processor_unavailable"
      if type(processInboundAddonMessage) == "function" then
        staleSnapshotStartProcessed, staleSnapshotStartReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("PSYNC_START", "stale-transfer-id", "previous-session", "profile", "profile-id", "1"),
          "Validation-Realm",
          {
            handlerRegistry = snapshotLifecycleRegistry,
            activeSessionIdOverride = "current-session",
            inboundOps = staleSnapshotStartOps,
          }
        )
      end
      addCheck("protocol inbound processor rejects stale snapshot start", "false/stale_session_bound_message/1/1/0", table.concat({
        tostring(staleSnapshotStartProcessed),
        tostring(staleSnapshotStartReason),
        tostring(staleSnapshotStartTelemetry.received),
        tostring(staleSnapshotStartTelemetry.rejected),
        tostring(snapshotLifecycleState.pendingProfileSyncs["stale-transfer-id"] == nil and 0 or 1),
      }, "/"))
  
      local snapshotStartTelemetry, snapshotStartOps = buildInboundFixtureTelemetry()
      local snapshotStartProcessed, snapshotStartReason = false, "processor_unavailable"
      if type(processInboundAddonMessage) == "function" then
        snapshotStartProcessed, snapshotStartReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("PSYNC_START", "transfer-id", "current-session", "profile", "profile-id", "1"),
          "Validation-Realm",
          {
            handlerRegistry = snapshotLifecycleRegistry,
            activeSessionIdOverride = "current-session",
            inboundOps = snapshotStartOps,
          }
        )
      end
      addCheck("protocol inbound snapshot lifecycle finalizer available", true, type(finalizeIncomingProfileSyncSessionState) == "function")
      addCheck("protocol inbound snapshot transfer resolver available", true, type(resolveIncomingProfileSyncTransfer) == "function")
      addCheck("protocol inbound snapshot chunk helper available", true, type(applyIncomingProfileSyncChunk) == "function")
      addCheck("protocol inbound snapshot reject telemetry helper available", true, type(recordIncomingSnapshotReject) == "function")
      addCheck("protocol inbound snapshot diagnostics rollover helper available", true, type(beginIncomingSnapshotDiagnosticsForSession) == "function")
      addCheck("protocol inbound processor stages snapshot before stop", "true/dispatched/1/0/1", table.concat({
        tostring(snapshotStartProcessed),
        tostring(snapshotStartReason),
        tostring(snapshotStartTelemetry.received),
        tostring(snapshotStartTelemetry.rejected),
        tostring(snapshotLifecycleState.pendingProfileSyncs["transfer-id"] ~= nil and 1 or 0),
      }, "/"))
  
      local snapshotStopTelemetry, snapshotStopOps = buildInboundFixtureTelemetry()
      local snapshotStopProcessed, snapshotStopReason = false, "processor_unavailable"
      if type(processInboundAddonMessage) == "function" then
        snapshotStopProcessed, snapshotStopReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("STOP", "current-session", "profile", "host", "0"),
          "Validation-Realm",
          {
            handlerRegistry = snapshotLifecycleRegistry,
            activeSessionIdOverride = "current-session",
            inboundOps = snapshotStopOps,
          }
        )
      end
      local latestSnapshotCleanup = snapshotLifecycleState.incomingSnapshotCleanupHistory[1] or {}
      local matchingSnapshotCleanupEntries = 0
      for _, cleanup in ipairs(snapshotLifecycleState.incomingSnapshotCleanupHistory) do
        if TrimText(type(cleanup) == "table" and cleanup.sessionId or "") == "current-session" then
          matchingSnapshotCleanupEntries = matchingSnapshotCleanupEntries + 1
        end
      end
      addCheck("protocol inbound processor finalizes partial snapshot on stop", "true/dispatched/0/1/1/2/current-session/1/1", table.concat({
        tostring(snapshotStopProcessed),
        tostring(snapshotStopReason),
        tostring(snapshotLifecycleState.pendingProfileSyncs["transfer-id"] == nil and 0 or 1),
        tostring(snapshotLifecycleState.incomingSnapshotCleanupTotal),
        tostring(snapshotLifecycleState.lastIncomingSnapshotCleanupCount),
        tostring(#snapshotLifecycleState.incomingSnapshotCleanupHistory),
        TrimText(latestSnapshotCleanup.sessionId),
        tostring(matchingSnapshotCleanupEntries),
        tostring(snapshotLifecycleState.pendingProfileSyncs["retained-transfer-id"] ~= nil and 1 or 0),
      }, "/"))
  
      local delayedSnapshotTelemetry, delayedSnapshotOps = buildInboundFixtureTelemetry()
      local delayedChunkProcessed, delayedChunkReason = false, "processor_unavailable"
      local delayedEndProcessed, delayedEndReason = false, "processor_unavailable"
      if type(processInboundAddonMessage) == "function" then
        delayedChunkProcessed, delayedChunkReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("PSYNC_CHUNK", "transfer-id", "1", "late-data"),
          "Validation-Realm",
          { handlerRegistry = snapshotLifecycleRegistry, inboundOps = delayedSnapshotOps }
        )
        delayedEndProcessed, delayedEndReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("PSYNC_END", "transfer-id"),
          "Validation-Realm",
          { handlerRegistry = snapshotLifecycleRegistry, inboundOps = delayedSnapshotOps }
        )
      end
      addCheck("protocol inbound processor ignores delayed snapshot chunk and end after stop", "true/dispatched/true/dispatched/2/0/2/0/1", table.concat({
        tostring(delayedChunkProcessed),
        tostring(delayedChunkReason),
        tostring(delayedEndProcessed),
        tostring(delayedEndReason),
        tostring(delayedSnapshotTelemetry.received),
        tostring(delayedSnapshotTelemetry.rejected),
        tostring(delayedSnapshotTelemetry.dispatched),
        tostring(snapshotLifecycleState.pendingProfileSyncs["transfer-id"] == nil and 0 or 1),
        tostring(snapshotLifecycleState.pendingProfileSyncs["retained-transfer-id"] ~= nil and 1 or 0),
      }, "/"))
  
      local repeatedSnapshotStopTelemetry, repeatedSnapshotStopOps = buildInboundFixtureTelemetry()
      local repeatedSnapshotStopProcessed, repeatedSnapshotStopReason = false, "processor_unavailable"
      if type(processInboundAddonMessage) == "function" then
        repeatedSnapshotStopProcessed, repeatedSnapshotStopReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("STOP", "current-session", "profile", "host", "0"),
          "Validation-Realm",
          {
            handlerRegistry = snapshotLifecycleRegistry,
            activeSessionIdOverride = "current-session",
            inboundOps = repeatedSnapshotStopOps,
          }
        )
      end
      addCheck("protocol inbound processor repeats snapshot stop without duplicate cleanup", "true/dispatched/0/1/1/2/current-session/1/1", table.concat({
        tostring(repeatedSnapshotStopProcessed),
        tostring(repeatedSnapshotStopReason),
        tostring(snapshotLifecycleState.pendingProfileSyncs["transfer-id"] == nil and 0 or 1),
        tostring(snapshotLifecycleState.incomingSnapshotCleanupTotal),
        tostring(snapshotLifecycleState.lastIncomingSnapshotCleanupCount),
        tostring(#snapshotLifecycleState.incomingSnapshotCleanupHistory),
        TrimText(latestSnapshotCleanup.sessionId),
        tostring(matchingSnapshotCleanupEntries),
        tostring(snapshotLifecycleState.pendingProfileSyncs["retained-transfer-id"] ~= nil and 1 or 0),
      }, "/"))
  
      local nextSnapshotStartTelemetry, nextSnapshotStartOps = buildInboundFixtureTelemetry()
      local nextSnapshotStartProcessed, nextSnapshotStartReason = false, "processor_unavailable"
      if type(processInboundAddonMessage) == "function" then
        nextSnapshotStartProcessed, nextSnapshotStartReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("PSYNC_START", "next-transfer-id", "next-session", "profile", "profile-id", "1"),
          "Validation-Realm",
          {
            handlerRegistry = snapshotLifecycleRegistry,
            activeSessionIdOverride = "next-session",
            inboundOps = nextSnapshotStartOps,
          }
        )
      end
      addCheck("protocol inbound processor stages next session snapshot after stop", "true/dispatched/1/0/1/1", table.concat({
        tostring(nextSnapshotStartProcessed),
        tostring(nextSnapshotStartReason),
        tostring(nextSnapshotStartTelemetry.received),
        tostring(nextSnapshotStartTelemetry.rejected),
        tostring(snapshotLifecycleState.pendingProfileSyncs["next-transfer-id"] ~= nil and 1 or 0),
        tostring(snapshotLifecycleState.pendingProfileSyncs["retained-transfer-id"] ~= nil and 1 or 0),
      }, "/"))
  
      local foreignSnapshotTelemetry, foreignSnapshotOps = buildInboundFixtureTelemetry()
      local foreignChunkProcessed, foreignChunkReason = false, "processor_unavailable"
      local foreignEndProcessed, foreignEndReason = false, "processor_unavailable"
      if type(processInboundAddonMessage) == "function" then
        foreignChunkProcessed, foreignChunkReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("PSYNC_CHUNK", "next-transfer-id", "1", "foreign-data"),
          "Other-Realm",
          { handlerRegistry = snapshotLifecycleRegistry, inboundOps = foreignSnapshotOps }
        )
        foreignEndProcessed, foreignEndReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("PSYNC_END", "next-transfer-id"),
          "Other-Realm",
          { handlerRegistry = snapshotLifecycleRegistry, inboundOps = foreignSnapshotOps }
        )
      end
      addCheck("protocol inbound processor ignores foreign snapshot chunk and end", "true/dispatched/true/dispatched/2/0/2/0/1/2/profile_sync_sender_mismatch/2", table.concat({
        tostring(foreignChunkProcessed),
        tostring(foreignChunkReason),
        tostring(foreignEndProcessed),
        tostring(foreignEndReason),
        tostring(foreignSnapshotTelemetry.received),
        tostring(foreignSnapshotTelemetry.rejected),
        tostring(foreignSnapshotTelemetry.dispatched),
        tostring(math.max(0, tonumber(type(snapshotLifecycleState.pendingProfileSyncs["next-transfer-id"]) == "table"
          and snapshotLifecycleState.pendingProfileSyncs["next-transfer-id"].receivedChunkCount or 0) or 0)),
        tostring(snapshotLifecycleState.pendingProfileSyncs["next-transfer-id"] ~= nil and 1 or 0),
        tostring(math.max(0, tonumber(snapshotLifecycleState.incomingSnapshotRejectTotal) or 0)),
        TrimText(snapshotLifecycleState.lastIncomingSnapshotRejectReason),
        tostring(math.max(0, tonumber(snapshotLifecycleState.incomingSnapshotRejectCounts.profile_sync_sender_mismatch) or 0)),
      }, "/"))
  
      local completedSnapshotTelemetry, completedSnapshotOps = buildInboundFixtureTelemetry()
      local completedStartProcessed, completedStartReason = false, "processor_unavailable"
      local completedChunkProcessed, completedChunkReason = false, "processor_unavailable"
      local completedEndProcessed, completedEndReason = false, "processor_unavailable"
      if type(processInboundAddonMessage) == "function" then
        completedStartProcessed, completedStartReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("PSYNC_START", "completed-transfer-id", "next-session", "profile", "profile-id", "1"),
          "Validation-Realm",
          {
            handlerRegistry = snapshotLifecycleRegistry,
            activeSessionIdOverride = "next-session",
            inboundOps = completedSnapshotOps,
          }
        )
        completedChunkProcessed, completedChunkReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("PSYNC_CHUNK", "completed-transfer-id", "1", "accepted-data"),
          "Validation-Realm",
          { handlerRegistry = snapshotLifecycleRegistry, inboundOps = completedSnapshotOps }
        )
        completedEndProcessed, completedEndReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("PSYNC_END", "completed-transfer-id"),
          "Validation-Realm",
          { handlerRegistry = snapshotLifecycleRegistry, inboundOps = completedSnapshotOps }
        )
      end
      addCheck("protocol inbound processor completes valid snapshot without affecting concurrent transfer", "true/dispatched/true/dispatched/true/dispatched/3/0/3/0/1", table.concat({
        tostring(completedStartProcessed),
        tostring(completedStartReason),
        tostring(completedChunkProcessed),
        tostring(completedChunkReason),
        tostring(completedEndProcessed),
        tostring(completedEndReason),
        tostring(completedSnapshotTelemetry.received),
        tostring(completedSnapshotTelemetry.rejected),
        tostring(completedSnapshotTelemetry.dispatched),
        tostring(snapshotLifecycleState.pendingProfileSyncs["completed-transfer-id"] == nil and 0 or 1),
        tostring(snapshotLifecycleState.pendingProfileSyncs["next-transfer-id"] ~= nil and 1 or 0),
      }, "/"))

      local duplicateSnapshotTelemetry, duplicateSnapshotOps = buildInboundFixtureTelemetry()
      local duplicateStartProcessed, duplicateStartReason = false, "processor_unavailable"
      local duplicateFirstChunkProcessed, duplicateFirstChunkReason = false, "processor_unavailable"
      local duplicateReplacementChunkProcessed, duplicateReplacementChunkReason = false, "processor_unavailable"
      local duplicateEndProcessed, duplicateEndReason = false, "processor_unavailable"
      if type(processInboundAddonMessage) == "function" then
        duplicateStartProcessed, duplicateStartReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("PSYNC_START", "duplicate-transfer-id", "next-session", "profile", "profile-id", "1"),
          "Validation-Realm",
          {
            handlerRegistry = snapshotLifecycleRegistry,
            activeSessionIdOverride = "next-session",
            inboundOps = duplicateSnapshotOps,
          }
        )
        duplicateFirstChunkProcessed, duplicateFirstChunkReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("PSYNC_CHUNK", "duplicate-transfer-id", "1", "first"),
          "Validation-Realm",
          { handlerRegistry = snapshotLifecycleRegistry, inboundOps = duplicateSnapshotOps }
        )
        duplicateReplacementChunkProcessed, duplicateReplacementChunkReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("PSYNC_CHUNK", "duplicate-transfer-id", "1", "replacement"),
          "Validation-Realm",
          { handlerRegistry = snapshotLifecycleRegistry, inboundOps = duplicateSnapshotOps }
        )
      end
      local duplicateSyncState = snapshotLifecycleState.pendingProfileSyncs["duplicate-transfer-id"] or {}
      addCheck("protocol inbound processor replaces duplicate snapshot chunk without double counting", "true/dispatched/true/dispatched/true/dispatched/3/0/3/1/11", table.concat({
        tostring(duplicateStartProcessed),
        tostring(duplicateStartReason),
        tostring(duplicateFirstChunkProcessed),
        tostring(duplicateFirstChunkReason),
        tostring(duplicateReplacementChunkProcessed),
        tostring(duplicateReplacementChunkReason),
        tostring(duplicateSnapshotTelemetry.received),
        tostring(duplicateSnapshotTelemetry.rejected),
        tostring(duplicateSnapshotTelemetry.dispatched),
        tostring(math.max(0, tonumber(duplicateSyncState.receivedChunkCount) or 0)),
        tostring(math.max(0, tonumber(duplicateSyncState.receivedBytes) or 0)),
      }, "/"))
      if type(processInboundAddonMessage) == "function" then
        duplicateEndProcessed, duplicateEndReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("PSYNC_END", "duplicate-transfer-id"),
          "Validation-Realm",
          { handlerRegistry = snapshotLifecycleRegistry, inboundOps = duplicateSnapshotOps }
        )
      end
      addCheck("protocol inbound processor completes replacement snapshot without affecting concurrent transfer", "true/dispatched/4/0/4/0/1", table.concat({
        tostring(duplicateEndProcessed),
        tostring(duplicateEndReason),
        tostring(duplicateSnapshotTelemetry.received),
        tostring(duplicateSnapshotTelemetry.rejected),
        tostring(duplicateSnapshotTelemetry.dispatched),
        tostring(snapshotLifecycleState.pendingProfileSyncs["duplicate-transfer-id"] == nil and 0 or 1),
        tostring(snapshotLifecycleState.pendingProfileSyncs["next-transfer-id"] ~= nil and 1 or 0),
      }, "/"))

      local rangeSnapshotTelemetry, rangeSnapshotOps = buildInboundFixtureTelemetry()
      local rangeStartProcessed, rangeStartReason = false, "processor_unavailable"
      local rangeChunkProcessed, rangeChunkReason = false, "processor_unavailable"
      if type(processInboundAddonMessage) == "function" then
        rangeStartProcessed, rangeStartReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("PSYNC_START", "range-transfer-id", "next-session", "profile", "profile-id", "1"),
          "Validation-Realm",
          {
            handlerRegistry = snapshotLifecycleRegistry,
            activeSessionIdOverride = "next-session",
            inboundOps = rangeSnapshotOps,
          }
        )
        rangeChunkProcessed, rangeChunkReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("PSYNC_CHUNK", "range-transfer-id", "2", "outside"),
          "Validation-Realm",
          { handlerRegistry = snapshotLifecycleRegistry, inboundOps = rangeSnapshotOps }
        )
      end
      addCheck("protocol inbound processor clears out-of-range snapshot chunk", "true/dispatched/true/dispatched/2/0/2/0/profile_sync_chunk_index_exceeds_declared_count/3/1", table.concat({
        tostring(rangeStartProcessed),
        tostring(rangeStartReason),
        tostring(rangeChunkProcessed),
        tostring(rangeChunkReason),
        tostring(rangeSnapshotTelemetry.received),
        tostring(rangeSnapshotTelemetry.rejected),
        tostring(rangeSnapshotTelemetry.dispatched),
        tostring(snapshotLifecycleState.pendingProfileSyncs["range-transfer-id"] == nil and 0 or 1),
        TrimText(snapshotLifecycleState.lastChunkFailure),
        tostring(math.max(0, tonumber(snapshotLifecycleState.incomingSnapshotRejectTotal) or 0)),
        tostring(math.max(0, tonumber(snapshotLifecycleState.incomingSnapshotRejectCounts.profile_sync_chunk_index_exceeds_declared_count) or 0)),
      }, "/"))

      local byteSnapshotTelemetry, byteSnapshotOps = buildInboundFixtureTelemetry()
      local byteStartProcessed, byteStartReason = false, "processor_unavailable"
      local byteFirstChunkProcessed, byteFirstChunkReason = false, "processor_unavailable"
      local byteOverflowChunkProcessed, byteOverflowChunkReason = false, "processor_unavailable"
      if type(processInboundAddonMessage) == "function" then
        byteStartProcessed, byteStartReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("PSYNC_START", "byte-transfer-id", "next-session", "profile", "profile-id", "2"),
          "Validation-Realm",
          {
            handlerRegistry = snapshotLifecycleRegistry,
            activeSessionIdOverride = "next-session",
            inboundOps = byteSnapshotOps,
          }
        )
        byteFirstChunkProcessed, byteFirstChunkReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("PSYNC_CHUNK", "byte-transfer-id", "1", "abcdefghijkl"),
          "Validation-Realm",
          { handlerRegistry = snapshotLifecycleRegistry, inboundOps = byteSnapshotOps }
        )
        byteOverflowChunkProcessed, byteOverflowChunkReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("PSYNC_CHUNK", "byte-transfer-id", "2", "mnopqrstuvwx"),
          "Validation-Realm",
          { handlerRegistry = snapshotLifecycleRegistry, inboundOps = byteSnapshotOps }
        )
      end
      addCheck("protocol inbound processor clears snapshot above cumulative byte limit", "true/dispatched/true/dispatched/true/dispatched/3/0/3/0/profile_sync_transfer_bytes_exceed_limit/4/1", table.concat({
        tostring(byteStartProcessed),
        tostring(byteStartReason),
        tostring(byteFirstChunkProcessed),
        tostring(byteFirstChunkReason),
        tostring(byteOverflowChunkProcessed),
        tostring(byteOverflowChunkReason),
        tostring(byteSnapshotTelemetry.received),
        tostring(byteSnapshotTelemetry.rejected),
        tostring(byteSnapshotTelemetry.dispatched),
        tostring(snapshotLifecycleState.pendingProfileSyncs["byte-transfer-id"] == nil and 0 or 1),
        TrimText(snapshotLifecycleState.lastChunkFailure),
        tostring(math.max(0, tonumber(snapshotLifecycleState.incomingSnapshotRejectTotal) or 0)),
        tostring(math.max(0, tonumber(snapshotLifecycleState.incomingSnapshotRejectCounts.profile_sync_transfer_bytes_exceed_limit) or 0)),
      }, "/"))

      local diagnosticsPreviousSessionId = TrimText(snapshotLifecycleState.incomingSnapshotDiagnosticsSessionId)
      local diagnosticsRolloverChanged = false
      if type(beginIncomingSnapshotDiagnosticsForSession) == "function" then
        diagnosticsRolloverChanged = beginIncomingSnapshotDiagnosticsForSession(
          snapshotLifecycleState,
          "final-session",
          2000,
          TrimText
        )
      end
      addCheck("protocol inbound snapshot diagnostics rollover clears rejects but retains cleanup telemetry", "true/next-session/final-session/2000/0/0/0/1", table.concat({
        tostring(diagnosticsRolloverChanged),
        diagnosticsPreviousSessionId,
        TrimText(snapshotLifecycleState.incomingSnapshotDiagnosticsSessionId),
        tostring(math.max(0, tonumber(snapshotLifecycleState.incomingSnapshotDiagnosticsStartedAt) or 0)),
        tostring(math.max(0, tonumber(snapshotLifecycleState.incomingSnapshotRejectTotal) or 0)),
        tostring(#snapshotLifecycleState.incomingSnapshotRejectHistory),
        tostring(next(snapshotLifecycleState.incomingSnapshotRejectCounts) == nil and 0 or 1),
        tostring(math.max(0, tonumber(snapshotLifecycleState.incomingSnapshotCleanupTotal) or 0)),
      }, "/"))

      local nextSnapshotStopTelemetry, nextSnapshotStopOps = buildInboundFixtureTelemetry()
      local nextSnapshotStopProcessed, nextSnapshotStopReason = false, "processor_unavailable"
      if type(processInboundAddonMessage) == "function" then
        nextSnapshotStopProcessed, nextSnapshotStopReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("STOP", "next-session", "profile", "host", "0"),
          "Validation-Realm",
          {
            handlerRegistry = snapshotLifecycleRegistry,
            activeSessionIdOverride = "next-session",
            inboundOps = nextSnapshotStopOps,
          }
        )
      end
      local latestNextSnapshotCleanup = snapshotLifecycleState.incomingSnapshotCleanupHistory[1] or {}
      local matchingNextSnapshotCleanupEntries = 0
      for _, cleanup in ipairs(snapshotLifecycleState.incomingSnapshotCleanupHistory) do
        if TrimText(type(cleanup) == "table" and cleanup.sessionId or "") == "next-session" then
          matchingNextSnapshotCleanupEntries = matchingNextSnapshotCleanupEntries + 1
        end
      end
      addCheck("protocol inbound processor finalizes next snapshot without clearing retained transfer", "true/dispatched/0/2/1/2/next-session/1/1", table.concat({
        tostring(nextSnapshotStopProcessed),
        tostring(nextSnapshotStopReason),
        tostring(snapshotLifecycleState.pendingProfileSyncs["next-transfer-id"] == nil and 0 or 1),
        tostring(snapshotLifecycleState.incomingSnapshotCleanupTotal),
        tostring(snapshotLifecycleState.lastIncomingSnapshotCleanupCount),
        tostring(#snapshotLifecycleState.incomingSnapshotCleanupHistory),
        TrimText(latestNextSnapshotCleanup.sessionId),
        tostring(matchingNextSnapshotCleanupEntries),
        tostring(snapshotLifecycleState.pendingProfileSyncs["retained-transfer-id"] ~= nil and 1 or 0),
      }, "/"))
  
    end
    runInboundSnapshotLifecycleValidation()

    local function runInboundAdmissionValidation()
      local admissionTelemetry, admissionOps = buildInboundFixtureTelemetry()
      local admissionHandlerCalls = 0
      local admissionRegistry = {
        START = {
          owner = "session_flow",
          handler = function()
            admissionHandlerCalls = admissionHandlerCalls + 1
          end,
        },
      }
      local ignoredPrefixProcessed, ignoredPrefixReason = false, "processor_unavailable"
      local missingSenderProcessed, missingSenderReason = false, "processor_unavailable"
      local oversizedProcessed, oversizedReason = false, "processor_unavailable"
      local truncatedProcessed, truncatedReason = false, "processor_unavailable"
      local unknownProcessed, unknownReason = false, "processor_unavailable"
      local fieldOverflowProcessed, fieldOverflowReason = false, "processor_unavailable"
      local missingOpcodeProcessed, missingOpcodeReason = false, "processor_unavailable"
      local recoveryProcessed, recoveryReason = false, "processor_unavailable"
      local ignoredPrefixTelemetry = ""
      local missingSenderTelemetry = ""
      local oversizedTelemetry = ""
      local truncatedTelemetry = ""
      local unknownTelemetry = ""
      local fieldOverflowTelemetry = ""
      local missingOpcodeTelemetry = ""
      local recoveryTelemetry = ""
      if type(processInboundAddonMessage) == "function" then
        ignoredPrefixProcessed, ignoredPrefixReason = processInboundAddonMessage(
          "OTHER_PREFIX",
          BuildPayload("START", "session", "profile", "profile-id", "host", "host", "0"),
          "Validation-Realm",
          { handlerRegistry = admissionRegistry, inboundOps = admissionOps }
        )
        ignoredPrefixTelemetry = table.concat({
          tostring(admissionTelemetry.received),
          tostring(admissionTelemetry.rejected),
          tostring(admissionHandlerCalls),
        }, "/")
        missingSenderProcessed, missingSenderReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("START", "session", "profile", "profile-id", "host", "host", "0"),
          "",
          { handlerRegistry = admissionRegistry, inboundOps = admissionOps }
        )
        missingSenderTelemetry = table.concat({
          tostring(admissionTelemetry.received),
          tostring(admissionTelemetry.rejected),
          tostring(admissionHandlerCalls),
        }, "/")
        oversizedProcessed, oversizedReason = processInboundAddonMessage(
          COMM_PREFIX,
          string.rep("x", math.max(1, tonumber(inboundCommTelemetry.maxPayloadBytes) or 1024) + 1),
          "Validation-Realm",
          { handlerRegistry = admissionRegistry, inboundOps = admissionOps }
        )
        oversizedTelemetry = table.concat({
          tostring(admissionTelemetry.received),
          tostring(admissionTelemetry.rejected),
          tostring(admissionHandlerCalls),
        }, "/")
        truncatedProcessed, truncatedReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("START", "session"),
          "Validation-Realm",
          { handlerRegistry = admissionRegistry, inboundOps = admissionOps }
        )
        truncatedTelemetry = table.concat({
          tostring(admissionTelemetry.received),
          tostring(admissionTelemetry.rejected),
          tostring(admissionTelemetry.contractRejected),
          tostring(admissionHandlerCalls),
        }, "/")
        unknownProcessed, unknownReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("FUTURE_OPCODE", "value"),
          "Validation-Realm",
          { handlerRegistry = admissionRegistry, inboundOps = admissionOps }
        )
        unknownTelemetry = table.concat({
          tostring(admissionTelemetry.received),
          tostring(admissionTelemetry.rejected),
          tostring(admissionTelemetry.unknown),
          tostring(admissionHandlerCalls),
        }, "/")
        fieldOverflowProcessed, fieldOverflowReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("START", unpack(overflowArgs)),
          "Validation-Realm",
          { handlerRegistry = admissionRegistry, inboundOps = admissionOps }
        )
        fieldOverflowTelemetry = table.concat({
          tostring(admissionTelemetry.received),
          tostring(admissionTelemetry.rejected),
          tostring(admissionTelemetry.unknown),
          tostring(admissionTelemetry.contractRejected),
          tostring(admissionHandlerCalls),
        }, "/")
        missingOpcodeProcessed, missingOpcodeReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("", "value"),
          "Validation-Realm",
          { handlerRegistry = admissionRegistry, inboundOps = admissionOps }
        )
        missingOpcodeTelemetry = table.concat({
          tostring(admissionTelemetry.received),
          tostring(admissionTelemetry.rejected),
          tostring(admissionTelemetry.unknown),
          tostring(admissionTelemetry.contractRejected),
          tostring(admissionHandlerCalls),
        }, "/")
        recoveryProcessed, recoveryReason = processInboundAddonMessage(
          COMM_PREFIX,
          BuildPayload("START", "session", "profile", "profile-id", "host", "host", "0"),
          "Validation-Realm",
          { handlerRegistry = admissionRegistry, inboundOps = admissionOps }
        )
        recoveryTelemetry = table.concat({
          tostring(admissionTelemetry.received),
          tostring(admissionTelemetry.rejected),
          tostring(admissionTelemetry.dispatched),
          tostring(admissionTelemetry.unknown),
          tostring(admissionTelemetry.contractRejected),
          tostring(admissionHandlerCalls),
        }, "/")
      end
      addCheck("protocol inbound processor ignores foreign prefix without telemetry", "false/ignored_prefix/0/0/0", table.concat({
        tostring(ignoredPrefixProcessed),
        tostring(ignoredPrefixReason),
        ignoredPrefixTelemetry,
      }, "/"))
      addCheck("protocol inbound processor rejects anonymous sender", "false/missing_incoming_sender/1/1/0", table.concat({
        tostring(missingSenderProcessed),
        tostring(missingSenderReason),
        missingSenderTelemetry,
      }, "/"))
      addCheck("protocol inbound processor rejects oversized and truncated payloads", "false/incoming_payload_exceeds_limit/false/incoming_payload_below_opcode_minimum/2/2/0/3/3/1/0", table.concat({
        tostring(oversizedProcessed),
        tostring(oversizedReason),
        tostring(truncatedProcessed),
        tostring(truncatedReason),
        oversizedTelemetry,
        truncatedTelemetry,
      }, "/"))
      addCheck("protocol inbound processor records unknown opcode without dispatch", "false/unknown_opcode/4/4/1/0", table.concat({
        tostring(unknownProcessed),
        tostring(unknownReason),
        unknownTelemetry,
      }, "/"))
      addCheck("protocol inbound processor rejects field-count overflow without dispatch", "false/incoming_payload_field_count_exceeds_limit/5/5/1/1/0", table.concat({
        tostring(fieldOverflowProcessed),
        tostring(fieldOverflowReason),
        fieldOverflowTelemetry,
      }, "/"))
      addCheck("protocol inbound processor rejects missing opcode without dispatch", "false/missing_incoming_opcode/6/6/1/1/0", table.concat({
        tostring(missingOpcodeProcessed),
        tostring(missingOpcodeReason),
        missingOpcodeTelemetry,
      }, "/"))
      addCheck("protocol inbound processor dispatches valid packet after rejections", "true/dispatched/7/6/1/1/1/1", table.concat({
        tostring(recoveryProcessed),
        tostring(recoveryReason),
        recoveryTelemetry,
      }, "/"))
    end
    runInboundAdmissionValidation()
  end
  local function runSessionRosterRefreshPolicyValidation()
    local getRosterRefreshPolicy = INTERNAL_API.LIDCOUNCIL_GetSessionMemberRosterRefreshPolicy_Impl
    local appendRosterEvent = INTERNAL_API.LIDCOUNCIL_AppendProfileSyncRosterEvent_Impl
    addCheck("session roster refresh policy helper available", true, type(getRosterRefreshPolicy) == "function")
    addCheck("session roster timeline helper available", true, type(appendRosterEvent) == "function")
    if type(getRosterRefreshPolicy) == "function" then
      local joinPolicy = getRosterRefreshPolicy(nil, { status = "JOINED" })
      local metadataPolicy = getRosterRefreshPolicy({ status = "JOINED" }, { status = "JOINED" })
      local leavePolicy = getRosterRefreshPolicy({ status = "JOINED" }, { status = "LEFT" })
      addCheck("session roster join forces immediate refresh", "true/true/true", table.concat({
        tostring(joinPolicy.rosterMembershipChanged == true),
        tostring(joinPolicy.forceImmediate == true),
        tostring(joinPolicy.defer == false),
      }, "/"))
      addCheck("session roster metadata keeps refresh coalesced", "false/false/nil", table.concat({
        tostring(metadataPolicy.rosterMembershipChanged == true),
        tostring(metadataPolicy.forceImmediate == true),
        tostring(metadataPolicy.defer),
      }, "/"))
      addCheck("session roster leave forces immediate refresh", "true/true/true", table.concat({
        tostring(leavePolicy.rosterMembershipChanged == true),
        tostring(leavePolicy.forceImmediate == true),
        tostring(leavePolicy.defer == false),
      }, "/"))
    end
    if type(appendRosterEvent) == "function" then
      local rosterEvents = appendRosterEvent({}, { action = "joined", memberKey = "First-Realm" }, 100, 2)
      rosterEvents = appendRosterEvent(rosterEvents, { action = "left", memberKey = "First-Realm" }, 200, 2)
      rosterEvents = appendRosterEvent(rosterEvents, { action = "joined", memberKey = "Second-Realm" }, 300, 2)
      addCheck("session roster timeline keeps latest transition first", "2/joined/300/left/200", table.concat({
        tostring(#rosterEvents),
        tostring(type(rosterEvents[1]) == "table" and rosterEvents[1].action or ""),
        tostring(type(rosterEvents[1]) == "table" and rosterEvents[1].at or ""),
        tostring(type(rosterEvents[2]) == "table" and rosterEvents[2].action or ""),
        tostring(type(rosterEvents[2]) == "table" and rosterEvents[2].at or ""),
      }, "/"))
      local invalidEventResult = appendRosterEvent(rosterEvents, { action = "unknown", memberKey = "Third-Realm" }, 400, 2)
      addCheck("session roster timeline ignores unknown event", "2/joined/300", table.concat({
        tostring(#invalidEventResult),
        tostring(type(invalidEventResult[1]) == "table" and invalidEventResult[1].action or ""),
        tostring(type(invalidEventResult[1]) == "table" and invalidEventResult[1].at or ""),
      }, "/"))
    end
  end
  runSessionRosterRefreshPolicyValidation()

  do
    local buildJoinRosterPlan = INTERNAL_API.LIDCOUNCIL_BuildJoinRosterDeliveryPlan_Impl
    local storeDeferredRoster = INTERNAL_API.LIDCOUNCIL_StoreDeferredJoinMemberRows
    local resolveBackgroundDelay = INTERNAL_API.LIDCOUNCIL_ResolveMemberBackgroundSyncBurstDelay_Impl
    local resolveSnapshotAdmission = INTERNAL_API.LIDCOUNCIL_ResolveSnapshotBatchAdmission_Impl
    addCheck("raid join roster delivery planner available", true, type(buildJoinRosterPlan) == "function")
    addCheck("raid join deferred roster store available", true, type(storeDeferredRoster) == "function")
    addCheck("raid join background stagger helper available", true, type(resolveBackgroundDelay) == "function")
    addCheck("raid join snapshot admission helper available", true, type(resolveSnapshotAdmission) == "function")

    if type(buildJoinRosterPlan) == "function" then
      local raidSession = {
        id = "SESSION-RAID-JOIN-STORM",
        host = "Host-Realm",
        members = {
          ["Host-Realm"] = { name = "Host-Realm", status = "JOINED" },
        },
      }
      for index = 1, 19 do
        local memberKey = string.format("Member%02d-Realm", index)
        raidSession.members[memberKey] = { name = memberKey, status = "JOINED" }
      end
      local immediateKeys, deferredKeys = buildJoinRosterPlan(raidSession, "Member01-Realm")
      local immediateSet = {}
      local deferredSet = {}
      for _, memberKey in ipairs(immediateKeys) do
        immediateSet[memberKey] = true
      end
      for _, memberKey in ipairs(deferredKeys) do
        deferredSet[memberKey] = true
      end
      addCheck("raid join sends only host and joiner rows immediately", "2/true/true", table.concat({
        tostring(#immediateKeys),
        tostring(immediateSet["Host-Realm"] == true),
        tostring(immediateSet["Member01-Realm"] == true),
      }, "/"))
      addCheck("raid join defers the remaining visible roster", "18/false/false", table.concat({
        tostring(#deferredKeys),
        tostring(deferredSet["Host-Realm"] == true),
        tostring(deferredSet["Member01-Realm"] == true),
      }, "/"))
      local immediateFanout = 0
      for index = 1, 19 do
        local memberKey = string.format("Member%02d-Realm", index)
        local plannedImmediateKeys = select(1, buildJoinRosterPlan(raidSession, memberKey))
        immediateFanout = immediateFanout + #plannedImmediateKeys
      end
      addCheck("raid join immediate roster fanout stays linear", 38, immediateFanout)
    end

    if type(resolveBackgroundDelay) == "function" then
      local delayOverrides = {
        baseDelaySeconds = 0.35,
        staggerSeconds = 0.25,
        maxStaggerSeconds = 5.0,
      }
      addCheck("raid join proof prewarm timers are staggered and capped", "0.35/1.35/5.35", table.concat({
        string.format("%.2f", resolveBackgroundDelay(0, delayOverrides)),
        string.format("%.2f", resolveBackgroundDelay(4, delayOverrides)),
        string.format("%.2f", resolveBackgroundDelay(99, delayOverrides)),
      }, "/"))
    end

    if type(resolveSnapshotAdmission) == "function" then
      local admissionOverrides = {
        maxActiveTransfers = 2,
        maxActiveTransfersWhileThrottled = 1,
        maxBackgroundActiveTransfers = 1,
        maxQueuedMessages = 96,
        maxQueuedMessagesWhileThrottled = 48,
        pollSeconds = 0.50,
      }
      local admitted = resolveSnapshotAdmission({ pending = 0, profileTransferStatus = { active = 0 } }, 6, admissionOverrides)
      local activeHeld = resolveSnapshotAdmission({ pending = 0, profileTransferStatus = { active = 2 } }, 6, admissionOverrides)
      local throttleHeld = resolveSnapshotAdmission({
        pending = 0,
        currentThrottleActive = true,
        profileTransferStatus = { active = 1 },
      }, 6, admissionOverrides)
      local queueHeld = resolveSnapshotAdmission({ pending = 96, profileTransferStatus = { active = 0 } }, 6, admissionOverrides)
      local projectedQueueHeld = resolveSnapshotAdmission({ pending = 70, profileTransferStatus = { active = 0 } }, 6, {
        maxActiveTransfers = 2,
        maxQueuedMessages = 96,
        additionalMessages = 35,
      })
      local backgroundHeld = resolveSnapshotAdmission({ pending = 0, profileTransferStatus = { active = 1 } }, 28, admissionOverrides)
      local lockdownHeld = resolveSnapshotAdmission({
        pending = 18,
        chatLockdownActive = true,
        profileTransferStatus = { active = 0 },
      }, 6, admissionOverrides)
      local throttleCooldownHeld = resolveSnapshotAdmission({
        pending = 18,
        globalThrottleCooldownRemaining = 2.75,
        profileTransferStatus = { active = 0 },
      }, 6, admissionOverrides)
      local acknowledgementWaitAdmitted = resolveSnapshotAdmission({
        pending = 0,
        profileTransferStatus = { active = 2 },
        profileTransfers = {
          { state = "waiting_ack" },
          { state = "waiting_apply" },
        },
      }, 6, admissionOverrides)
      addCheck("raid join snapshot admission bounds expanded transfers", "true/active_transfer_limit/throttled_active_transfer_limit/queue_limit/active_transfer_limit", table.concat({
        tostring(admitted.admit == true),
        tostring(activeHeld.reason),
        tostring(throttleHeld.reason),
        tostring(queueHeld.reason),
        tostring(backgroundHeld.reason),
      }, "/"))
      addCheck("raid join snapshot admission does not let ACK waits block later members", true,
        acknowledgementWaitAdmitted.admit == true)
      addCheck("raid join snapshot admission reserves room for the next transfer", "projected_queue_limit",
        tostring(projectedQueueHeld.reason))
      addCheck("raid join snapshot admission parks work during chat lockdown", "false/chat_lockdown/true", table.concat({
        tostring(lockdownHeld.admit == true),
        tostring(lockdownHeld.reason),
        tostring((tonumber(lockdownHeld.delaySeconds) or 0) >= 1),
      }, "/"))
      addCheck("raid join snapshot admission parks work during shared throttle cooldown", "false/global_throttle_cooldown/2.75", table.concat({
        tostring(throttleCooldownHeld.admit == true),
        tostring(throttleCooldownHeld.reason),
        string.format("%.2f", tonumber(throttleCooldownHeld.delaySeconds) or 0),
      }, "/"))
    end
  end

  local function runPerOpcodeContractValidation()
    for _, opcode in ipairs(contractSnapshot.opcodes) do
      local contract = contractSnapshot.contracts[opcode] or {}
      local minimumFields = math.max(1, tonumber(contract.minimumFields) or 1)
      local maximumFields = math.max(1, tonumber(contract.maximumFields) or fieldLimit)
      local minimumArgs = {}
      for index = 1, minimumFields - 1 do
        minimumArgs[index] = "f" .. tostring(index)
      end
      local truncatedArgs = {}
      for index = 1, math.max(0, minimumFields - 2) do
        truncatedArgs[index] = "f" .. tostring(index)
      end
      local minimumPayloadFields = ParsePayload(BuildPayload(opcode, unpack(minimumArgs)))
      local truncatedPayloadFields = ParsePayload(BuildPayload(opcode, unpack(truncatedArgs)))
      local minimumAccepted, minimumReason = ValidateCommProtocolFieldCount(opcode, #minimumPayloadFields)
      local truncatedAccepted, truncatedReason = ValidateCommProtocolFieldCount(opcode, #truncatedPayloadFields)
      local priorOpcodeDispatches = math.max(0, tonumber(dispatchFixtureCalls[opcode]) or 0)
      local priorDispatches = math.max(0, tonumber(dispatchFixtureCalls.total) or 0)
      local dispatched, dispatchReason = DispatchCommProtocolPayload(opcode, minimumPayloadFields, "Validation-Realm", dispatchFixtureRegistry)
      addCheck("protocol " .. opcode .. " minimum fields", minimumFields, #minimumPayloadFields)
      addCheck("protocol " .. opcode .. " rejects truncation", true, #truncatedPayloadFields < minimumFields)
      addCheck("protocol " .. opcode .. " validator accepts minimum", true, minimumAccepted)
      addCheck("protocol " .. opcode .. " validator minimum reason", "accepted", minimumReason)
      addCheck("protocol " .. opcode .. " validator rejects truncation", false, truncatedAccepted)
      addCheck("protocol " .. opcode .. " validator truncation reason", "below_opcode_minimum", truncatedReason)
      addCheck("protocol " .. opcode .. " has a valid field range", true, minimumFields <= maximumFields)
      addCheck("protocol " .. opcode .. " category", true, TrimText(contract.category) ~= "")
      addCheck("protocol " .. opcode .. " owner", true, TrimText(contract.owner) ~= "")
      addCheck("protocol " .. opcode .. " handler available", true,
        type(handlerStatus) == "table" and type(handlerStatus.handlerAvailability) == "table"
          and handlerStatus.handlerAvailability[opcode] == true)
      addCheck("protocol " .. opcode .. " dispatches fixture handler", true, dispatched)
      addCheck("protocol " .. opcode .. " dispatch reason", "dispatched", dispatchReason)
      addCheck("protocol " .. opcode .. " dispatch increments target once", priorOpcodeDispatches + 1, dispatchFixtureCalls[opcode])
      addCheck("protocol " .. opcode .. " dispatch invokes only one handler", priorDispatches + 1, dispatchFixtureCalls.total)
    end
  
  end
  runPerOpcodeContractValidation()
  INTERNAL_API.LIDCOUNCIL_AppendPrefixRegistrationValidationChecks_Impl(addCheck)
  INTERNAL_API.LIDCOUNCIL_AppendInboundRejectClassificationValidationChecks_Impl(addCheck)
  INTERNAL_API.LIDCOUNCIL_AppendOutboundDiagnosticStateValidationChecks_Impl(addCheck)

  return passedCount == #checks, {
    suite = "comm_protocol",
    version = 50,
    contractVersion = contractSnapshot.version,
    contractCount = contractSnapshot.opcodeCount,
    total = #checks,
    passed = passedCount,
    failed = #checks - passedCount,
    checks = checks,
  }
end

INTERNAL_API.LIDCOUNCIL_AppendThirtyPlayerTransportCapacityValidationChecks_Impl = function(addCheck, makeItem, queueKinds)
  if type(addCheck) ~= "function" or type(makeItem) ~= "function" or type(queueKinds) ~= "function" then
    return
  end

  local raidSize = 30
  local remoteRecipients = raidSize - 1
  local itemCount = 5
  local councilVoters = 5
  local remoteCouncilVoters = councilVoters - 1
  local itemOpenRetryAttempts = 4
  local choiceReceiptAttempts = 4
  local councilMirrorTargetedRetries = 2
  local maxMissingRowsPerReceipt = 48
  local queueDepth = math.max(1, tonumber(outboundCommStats.maxQueueDepth) or 6000)
  local criticalOverflow = math.max(0, tonumber(outboundCommStats.maxCriticalQueueOverflow) or 0)

  local logicalChoices = raidSize * itemCount
  local remoteItemAcks = remoteRecipients * itemCount
  local remoteChoiceSubmissions = remoteRecipients * itemCount
  local maximumChoiceAttempts = remoteChoiceSubmissions * choiceReceiptAttempts
  local initialItemOpenMessages = itemCount
  local maximumTargetedItemRetries = remoteItemAcks * itemOpenRetryAttempts
  local directChoiceReceipts = maximumChoiceAttempts
  local authoritativeChoiceMirrors = logicalChoices
  local councilChoiceReceipts = logicalChoices * remoteCouncilVoters
  local maximumTargetedCouncilMirrorRetries = councilChoiceReceipts * councilMirrorTargetedRetries
  local maximumLiveOutbound = initialItemOpenMessages
    + maximumTargetedItemRetries
    + directChoiceReceipts
    + authoritativeChoiceMirrors
  local maximumReliableLiveOutbound = maximumLiveOutbound + maximumTargetedCouncilMirrorRetries

  local selectionRowsPerTarget = logicalChoices
  local voteRowsPerTarget = councilVoters * itemCount
  local boardMessagesPerTarget = 1 + itemCount + selectionRowsPerTarget + 1
  local boardMessagesPerTargetWithVotes = boardMessagesPerTarget + voteRowsPerTarget
  local boardMessages = remoteRecipients * boardMessagesPerTarget
  local boardMessagesWithVotes = remoteRecipients * boardMessagesPerTargetWithVotes
  local boardAndLiveMessages = boardMessages + maximumLiveOutbound
  local populatedBoardAndLiveMessages = boardMessagesWithVotes + maximumLiveOutbound
  local boardAndReliableLiveMessages = boardMessages + maximumReliableLiveOutbound
  local selectiveRepairMessages = remoteRecipients * maxMissingRowsPerReceipt

  addCheck("transport capacity raid members", 30, raidSize)
  addCheck("transport capacity remote recipients", 29, remoteRecipients)
  addCheck("transport capacity raid items", 5, itemCount)
  addCheck("transport capacity logical choices", 150, logicalChoices)
  addCheck("transport capacity remote ITEM_ACK messages", 145, remoteItemAcks)
  addCheck("transport capacity remote CHOICE messages per attempt", 145, remoteChoiceSubmissions)
  addCheck("transport capacity bounded CHOICE attempts", 580, maximumChoiceAttempts)
  addCheck("transport capacity bounded targeted ITEM_OPEN retries", 580, maximumTargetedItemRetries)
  addCheck("transport capacity direct RCHOICE receipts", 580, directChoiceReceipts)
  addCheck("transport capacity authoritative RCHOICE mirrors", 150, authoritativeChoiceMirrors)
  addCheck("transport capacity remote council RCHOICE_ACK receipts", 600, councilChoiceReceipts)
  addCheck("transport capacity bounded targeted council mirror retries", 1200, maximumTargetedCouncilMirrorRetries)
  addCheck("transport capacity maximum live outbound burst", 1315, maximumLiveOutbound)
  addCheck("transport capacity maximum receipt-repaired live burst", 2515, maximumReliableLiveOutbound)
  addCheck("transport capacity BSYNC selection rows per target", 150, selectionRowsPerTarget)
  addCheck("transport capacity BSYNC vote rows per target", 25, voteRowsPerTarget)
  addCheck("transport capacity BSYNC messages per target", 157, boardMessagesPerTarget)
  addCheck("transport capacity populated BSYNC messages per target", 182, boardMessagesPerTargetWithVotes)
  addCheck("transport capacity full BSYNC messages", 4553, boardMessages)
  addCheck("transport capacity populated full BSYNC messages", 5278, boardMessagesWithVotes)
  addCheck("transport capacity normal queue depth", 6000, queueDepth)
  addCheck("transport capacity critical overflow reserve", 64, criticalOverflow)
  addCheck("transport capacity board fits normal queue", true, boardMessages <= queueDepth)
  addCheck("transport capacity board plus bounded live burst", 5868, boardAndLiveMessages)
  addCheck("transport capacity board plus live retains critical reserve", true,
    (queueDepth - boardAndLiveMessages) >= criticalOverflow)
  addCheck("transport capacity populated board plus live pressure", 6593, populatedBoardAndLiveMessages)
  addCheck("transport capacity detects unstaged populated-board overflow", true,
    populatedBoardAndLiveMessages > (queueDepth + criticalOverflow))
  addCheck("transport capacity detects full council-repair overlap", true,
    boardAndReliableLiveMessages > (queueDepth + criticalOverflow))
  addCheck("transport capacity one selective repair round", 1392, selectiveRepairMessages)
  addCheck("transport capacity detects overlapping selective-repair overflow", true,
    (boardMessages + maximumLiveOutbound + selectiveRepairMessages) > (queueDepth + criticalOverflow))

  local priorityQueue = {}
  outboundQueueSelection.InsertOutboundCommQueueItem(makeItem("BSYNC_SEL", "Member-Realm"), false, priorityQueue)
  outboundQueueSelection.InsertOutboundCommQueueItem(makeItem("RCHOICE_ACK", "Member-Realm"), false, priorityQueue)
  outboundQueueSelection.InsertOutboundCommQueueItem(makeItem("RCHOICE", "Member-Realm"), false, priorityQueue)
  outboundQueueSelection.InsertOutboundCommQueueItem(makeItem("ITEM_OPEN", "Member-Realm"), false, priorityQueue)
  outboundQueueSelection.InsertOutboundCommQueueItem(makeItem("MEMBER", "Member-Realm"), false, priorityQueue)
  addCheck("transport capacity production priority values", "1/2/2/2/7", table.concat({
    tostring(GetOutboundCommPriority("MEMBER")),
    tostring(GetOutboundCommPriority("ITEM_OPEN")),
    tostring(GetOutboundCommPriority("RCHOICE")),
    tostring(GetOutboundCommPriority("RCHOICE_ACK")),
    tostring(GetOutboundCommPriority("BSYNC_SEL")),
  }, "/"))
  addCheck("transport capacity live traffic preempts BSYNC", "MEMBER/RCHOICE_ACK/RCHOICE/ITEM_OPEN/BSYNC_SEL", queueKinds(priorityQueue))
  addCheck("transport capacity session control preempts live traffic", true,
    GetOutboundCommPriority("MEMBER") < GetOutboundCommPriority("ITEM_OPEN"))
  addCheck("transport capacity receipt traffic preempts BSYNC", true,
    GetOutboundCommPriority("RCHOICE") < GetOutboundCommPriority("BSYNC_SEL")
      and GetOutboundCommPriority("RCHOICE_ACK") < GetOutboundCommPriority("BSYNC_SEL"))
  addCheck("transport capacity critical admission ceiling", 6064, queueDepth + criticalOverflow)
end

INTERNAL_API.LIDCOUNCIL_RunCommOutboundTransportValidation_Impl = function()
  local checks = {}
  local passedCount = 0
  local function addCheck(name, expected, actual)
    local passed = expected == actual
    checks[#checks + 1] = {
      name = name,
      passed = passed,
      expected = tostring(expected),
      actual = tostring(actual),
    }
    if passed then
      passedCount = passedCount + 1
    end
  end
  local function makeItem(kind, targetName, metadata, payload)
    return {
      kind = kind,
      distribution = "WHISPER",
      targetName = targetName or "Member-Realm",
      payload = payload or kind,
      metadata = type(metadata) == "table" and metadata or {},
      priority = GetOutboundCommPriority(kind, metadata),
    }
  end
  local function queueKinds(queue)
    local kinds = {}
    for _, item in ipairs(queue) do
      kinds[#kinds + 1] = TrimText(type(item) == "table" and item.kind or "")
    end
    return table.concat(kinds, "/")
  end

  local createOutboundRetryHelpers = INTERNAL_API.LIDCOUNCIL_CreateOutboundRetryHelpers_Impl
  addCheck("transport outbound retry helper factory available", true, type(createOutboundRetryHelpers) == "function")
  if type(createOutboundRetryHelpers) == "function" then
    local retryHelpers = createOutboundRetryHelpers({ TrimText = TrimText })
    addCheck("transport outbound retry helper factory creates required functions", true,
      type(retryHelpers) == "table"
        and type(retryHelpers.GetSendAddonResultState) == "function"
        and type(retryHelpers.FormatSendAddonResult) == "function"
        and type(retryHelpers.ResolveOutboundCommRetryDecision) == "function"
        and type(retryHelpers.ResolveGlobalThrottleCooldownSeconds) == "function"
        and type(retryHelpers.ResolveGlobalThrottleRecoveryIntervalSeconds) == "function")
    if type(retryHelpers) == "table"
      and type(retryHelpers.GetSendAddonResultState) == "function"
      and type(retryHelpers.FormatSendAddonResult) == "function"
      and type(retryHelpers.ResolveOutboundCommRetryDecision) == "function"
      and type(retryHelpers.ResolveGlobalThrottleCooldownSeconds) == "function"
      and type(retryHelpers.ResolveGlobalThrottleRecoveryIntervalSeconds) == "function"
    then
      addCheck("transport outbound retry classifies send results", "success/throttle/lockdown/failed", table.concat({
        retryHelpers.GetSendAddonResultState(nil),
        retryHelpers.GetSendAddonResultState("AddonMessageThrottle"),
        retryHelpers.GetSendAddonResultState(11),
        retryHelpers.GetSendAddonResultState("unknown_error"),
      }, "/"))
      addCheck("transport outbound retry formats nil result", "nil", retryHelpers.FormatSendAddonResult(nil))
      local retryItem = {}
      local firstThrottle = retryHelpers.ResolveOutboundCommRetryDecision(retryItem, "throttled", {
        maxThrottleRetries = 1,
      })
      local exhaustedThrottle = retryHelpers.ResolveOutboundCommRetryDecision(retryItem, "throttled", {
        maxThrottleRetries = 1,
      })
      addCheck("transport outbound retry enforces throttle budget", "retry_throttled/true/failed_throttled/false", table.concat({
        tostring(type(firstThrottle) == "table" and firstThrottle.outcome or ""),
        tostring(type(firstThrottle) == "table" and firstThrottle.retry == true),
        tostring(type(exhaustedThrottle) == "table" and exhaustedThrottle.outcome or ""),
        tostring(type(exhaustedThrottle) == "table" and exhaustedThrottle.retry == true),
      }, "/"))
      local lockdownItem = { throttleCount = 2, failureRetryCount = 1 }
      local lockdownDecision = retryHelpers.ResolveOutboundCommRetryDecision(lockdownItem, "lockdown", {
        maxThrottleRetries = 1,
        maxFailureRetries = 0,
      })
      addCheck("transport chat lockdown defers without spending retry budgets", "deferred_lockdown/true/2/1", table.concat({
        tostring(type(lockdownDecision) == "table" and lockdownDecision.outcome or ""),
        tostring(type(lockdownDecision) == "table" and lockdownDecision.retry == true),
        tostring(lockdownItem.throttleCount),
        tostring(lockdownItem.failureRetryCount),
      }, "/"))
      addCheck("transport shared throttle cooldown grows and caps", "1.05/1.75/6.00", table.concat({
        string.format("%.2f", retryHelpers.ResolveGlobalThrottleCooldownSeconds(1, 1.05, 6)),
        string.format("%.2f", retryHelpers.ResolveGlobalThrottleCooldownSeconds(3, 1.05, 6)),
        string.format("%.2f", retryHelpers.ResolveGlobalThrottleCooldownSeconds(99, 1.05, 6)),
      }, "/"))
      addCheck("transport throttle recovery remains paced after the first success", "0.45/0.65/1.25", table.concat({
        string.format("%.2f", retryHelpers.ResolveGlobalThrottleRecoveryIntervalSeconds(1)),
        string.format("%.2f", retryHelpers.ResolveGlobalThrottleRecoveryIntervalSeconds(3)),
        string.format("%.2f", retryHelpers.ResolveGlobalThrottleRecoveryIntervalSeconds(99)),
      }, "/"))
    end
  end

  do
    local resolveJoinDelay = INTERNAL_API.LIDCOUNCIL_ResolveJoinAckRetryDelay_Impl
    local armJoinTimer = INTERNAL_API.LIDCOUNCIL_ArmJoinAckRetryTimer_Impl
    local consumeJoinTimer = INTERNAL_API.LIDCOUNCIL_ConsumeJoinAckRetryTimer_Impl
    local invalidateJoinTimer = INTERNAL_API.LIDCOUNCIL_InvalidateJoinAckRetryTimer_Impl
    local updateJoinBlockedDeadline = INTERNAL_API.LIDCOUNCIL_UpdateJoinAckBlockedDeadline_Impl
    local resolveJoinAction = INTERNAL_API.LIDCOUNCIL_ResolvePendingJoinRetryAction_Impl
    local joinHelpersAvailable = type(resolveJoinDelay) == "function"
      and type(armJoinTimer) == "function"
      and type(consumeJoinTimer) == "function"
      and type(invalidateJoinTimer) == "function"
      and type(updateJoinBlockedDeadline) == "function"
      and type(resolveJoinAction) == "function"
    addCheck("transport member JOIN retry helpers available", true, joinHelpersAvailable)
    addCheck("transport member JOIN successful-send hook available", true,
      type(INTERNAL_API.LIDCOUNCIL_HandleOutboundJoinSent_Impl) == "function")
    addCheck("transport host START successful-send hook available", true,
      type(INTERNAL_API.LIDCOUNCIL_HandleOutboundStartSent_Impl) == "function")
    local resolveInviteReceiptAction = INTERNAL_API.LIDCOUNCIL_ResolveInviteReceiptAction_Impl
    addCheck("transport host START receipt resolver available", true,
      type(resolveInviteReceiptAction) == "function")
    addCheck("transport host accepted JOIN worker available", true,
      type(INTERNAL_API.LIDCOUNCIL_QueueAcceptedJoinFollowup_Impl) == "function"
        and type(INTERNAL_API.LIDCOUNCIL_GetAcceptedJoinBurstStatus_Impl) == "function")
    local getRaidTraceContract = INTERNAL_API.LIDCOUNCIL_GetRaidTestTraceContract_Impl
    local raidTraceContract = type(getRaidTraceContract) == "function" and getRaidTraceContract() or {}
    addCheck("transport raid test flight recorder APIs available", true,
      type(API.LIDCOUNCIL_StartRaidTestTrace) == "function"
        and type(API.LIDCOUNCIL_StopRaidTestTrace) == "function"
        and type(API.LIDCOUNCIL_AddRaidTestTraceMarker) == "function"
        and type(API.LIDCOUNCIL_BuildRaidTestTraceReport) == "function"
        and type(INTERNAL_API.LIDCOUNCIL_RecordRaidTestTraceEvent_Impl) == "function")
    addCheck("transport raid test flight recorder remains bounded and passive", "2/2000/0.25/1.00/10.00/true/false/false", table.concat({
      tostring(math.max(0, tonumber(raidTraceContract.version) or 0)),
      tostring(math.max(0, tonumber(raidTraceContract.capacity) or 0)),
      string.format("%.2f", math.max(0, tonumber(raidTraceContract.frameGapThresholdSeconds) or 0)),
      string.format("%.2f", math.max(0, tonumber(raidTraceContract.sampleIntervalSeconds) or 0)),
      string.format("%.2f", math.max(0, tonumber(raidTraceContract.idleHeartbeatSeconds) or 0)),
      tostring(raidTraceContract.changedTransportSamplesOnly == true),
      tostring(raidTraceContract.uiRefreshPerEvent == true),
      tostring(raidTraceContract.bulkPacketsRecordedIndividually == true),
    }, "/"))
    local joinMetadata = BuildOutboundCommMetadata(
      "JOIN",
      "WHISPER",
      "Host-Realm",
      "validation-session",
      "Validation",
      "Member-Realm"
    )
    addCheck("transport member JOIN metadata retains acknowledgement identity", "validation-session/Member-Realm", table.concat({
      TrimText(type(joinMetadata) == "table" and joinMetadata.sessionId or ""),
      NormalizeCharacterKey(type(joinMetadata) == "table" and joinMetadata.memberKey or ""),
    }, "/"))
    local startMetadata = BuildOutboundCommMetadata(
      "START",
      "WHISPER",
      "Member-Realm",
      "validation-session",
      "Validation"
    )
    addCheck("transport host START metadata retains receipt identity", "validation-session/Member-Realm", table.concat({
      TrimText(type(startMetadata) == "table" and startMetadata.sessionId or ""),
      NormalizeCharacterKey(type(startMetadata) == "table" and startMetadata.memberKey or ""),
    }, "/"))
    if type(resolveInviteReceiptAction) == "function" then
      local inviteOptions = {
        maxAttempts = 2,
        queuePollSeconds = 1,
        blockedPollSeconds = 1,
      }
      addCheck("transport host START receipt waits for sends and restrictions", "wait_blocked/wait_blocked/wait_queued/timeout/queue_retry", table.concat({
        resolveInviteReceiptAction({ state = "QUEUED", attempts = 0 }, { chatLockdownActive = true }, inviteOptions).action,
        resolveInviteReceiptAction({ state = "AWAITING_RECEIPT", attempts = 2 }, { globalThrottleCooldownRemaining = 4 }, inviteOptions).action,
        resolveInviteReceiptAction({ state = "QUEUED", attempts = 0 }, { byKind = { START = 1 } }, inviteOptions).action,
        resolveInviteReceiptAction({ state = "AWAITING_RECEIPT", attempts = 2 }, {}, inviteOptions).action,
        resolveInviteReceiptAction({ state = "AWAITING_RECEIPT", attempts = 1 }, {}, inviteOptions).action,
      }, "/"))
    end
    if joinHelpersAvailable then
      local joinOptions = {
        maxAttempts = 5,
        retryDelaysSeconds = { 8, 12, 18, 25 },
        finalWaitSeconds = 12,
        fallbackDelaySeconds = 10,
        queuePollSeconds = 1,
        blockedPollSeconds = 1,
      }
      addCheck("transport member JOIN retry uses paced seventy-five-second schedule", "8/12/18/25/12", table.concat({
        tostring(resolveJoinDelay(1, joinOptions)),
        tostring(resolveJoinDelay(2, joinOptions)),
        tostring(resolveJoinDelay(3, joinOptions)),
        tostring(resolveJoinDelay(4, joinOptions)),
        tostring(resolveJoinDelay(5, joinOptions)),
      }, "/"))

      local timerState = {}
      local firstArmed, firstToken, firstDueAt = armJoinTimer(timerState, 100, 8, false)
      local overlapArmed, overlapToken, overlapDueAt = armJoinTimer(timerState, 101, 1, false)
      local wrongTimerConsumed = consumeJoinTimer(timerState, firstToken + 1)
      local firstTimerConsumed = consumeJoinTimer(timerState, firstToken)
      local secondArmed, secondToken = armJoinTimer(timerState, 110, 12, false)
      addCheck("transport member JOIN owns one retry timer", "true/false/1/108/1/108/false/true/true/2", table.concat({
        tostring(firstArmed),
        tostring(overlapArmed),
        tostring(firstToken),
        tostring(firstDueAt),
        tostring(overlapToken),
        tostring(overlapDueAt),
        tostring(wrongTimerConsumed),
        tostring(firstTimerConsumed),
        tostring(secondArmed),
        tostring(secondToken),
      }, "/"))
      addCheck("transport member JOIN invalidates stale timer", "3/false/0", table.concat({
        tostring(invalidateJoinTimer(timerState)),
        tostring(timerState.retryTimerArmed == true),
        tostring(timerState.retryTimerDueAt),
      }, "/"))

      local blockedState = { hardDeadlineAt = 190 }
      updateJoinBlockedDeadline(blockedState, 100, true)
      local pausedSeconds = updateJoinBlockedDeadline(blockedState, 112, false)
      addCheck("transport member JOIN timeout pauses during transport restriction", "12/12/202", table.concat({
        tostring(pausedSeconds),
        tostring(blockedState.retryBlockedSeconds),
        tostring(blockedState.hardDeadlineAt),
      }, "/"))

      addCheck("transport member JOIN retry gates queue lockdown timeout and late ACK", "wait_blocked/wait_blocked/wait_queued/wait_queued/timeout/timeout/late_ack_grace/stop/queue_retry", table.concat({
        resolveJoinAction({ attempts = 1 }, { chatLockdownActive = true }, 100, joinOptions).action,
        resolveJoinAction({ attempts = 1 }, { globalThrottleCooldownRemaining = 4 }, 100, joinOptions).action,
        resolveJoinAction({ attempts = 1 }, { byKind = { JOIN = 1 } }, 100, joinOptions).action,
        resolveJoinAction({ attempts = 1, hardDeadlineAt = 99 }, { byKind = { JOIN = 1 } }, 100, joinOptions).action,
        resolveJoinAction({ attempts = 1, hardDeadlineAt = 99 }, {}, 100, joinOptions).action,
        resolveJoinAction({ attempts = 5 }, {}, 100, joinOptions).action,
        resolveJoinAction({ state = "TIMED_OUT" }, {}, 100, joinOptions).action,
        resolveJoinAction({ confirmed = true }, {}, 100, joinOptions).action,
        resolveJoinAction({ attempts = 1 }, {}, 100, joinOptions).action,
      }, "/"))
    end
  end

  local priorityQueue = {}
  outboundQueueSelection.InsertOutboundCommQueueItem(makeItem("PSYNC_CHUNK", "Member-Realm", {
    mode = "BACKGROUND",
    lane = "archive",
    transferKind = "DOMAINS",
  }), false, priorityQueue)
  outboundQueueSelection.InsertOutboundCommQueueItem(makeItem("PDELTA", "Member-Realm"), false, priorityQueue)
  outboundQueueSelection.InsertOutboundCommQueueItem(makeItem("START", "Member-Realm"), false, priorityQueue)
  addCheck("transport priority keeps session control first", "START/PDELTA/PSYNC_CHUNK", queueKinds(priorityQueue))
  addCheck("transport priority preserves PDELTA before bulk sync", "PDELTA", TrimText(type(priorityQueue[2]) == "table" and priorityQueue[2].kind or ""))
  local queuedReceipt = makeItem("RCHOICE", "Member-Realm", { sessionId = "SESSION-live" }, "same-payload")
  addCheck("transport coalesces only identical queued live receipts", "true/false/false", table.concat({
    tostring(INTERNAL_API.LIDCOUNCIL_IsQueuedLiveReceiptDuplicate_Impl(
      makeItem("RCHOICE", "Member-Realm", { sessionId = "SESSION-live" }, "same-payload"),
      { queuedReceipt }
    )),
    tostring(INTERNAL_API.LIDCOUNCIL_IsQueuedLiveReceiptDuplicate_Impl(
      makeItem("RCHOICE", "Member-Realm", { sessionId = "SESSION-live" }, "newer-payload"),
      { queuedReceipt }
    )),
    tostring(INTERNAL_API.LIDCOUNCIL_IsQueuedLiveReceiptDuplicate_Impl(
      makeItem("ITEM_OPEN", "Member-Realm", { sessionId = "SESSION-live" }, "same-payload"),
      { queuedReceipt }
    )),
  }, "/"))
  addCheck("transport live receipt creates a bounded post-live quiet window", "0.75/0.2/0.2", table.concat({
    tostring(INTERNAL_API.LIDCOUNCIL_GetPostLiveTrafficQueueDelay_Impl(
      makeItem("VOTE", "Member-Realm", { sessionId = "SESSION-live" }),
      0.2,
      { makeItem("PSYNC_CHUNK", "Member-Realm", { lane = "archive" }) }
    )),
    tostring(INTERNAL_API.LIDCOUNCIL_GetPostLiveTrafficQueueDelay_Impl(
      makeItem("PDELTA", "Member-Realm", { sessionId = "SESSION-live" }),
      0.2
    )),
    tostring(INTERNAL_API.LIDCOUNCIL_GetPostLiveTrafficQueueDelay_Impl(
      makeItem("VOTE", "Member-Realm", { sessionId = "SESSION-live" }),
      0.2,
      { makeItem("RCHOICE", "Member-Realm", { sessionId = "SESSION-live" }) }
    )),
  }, "/"))
  INTERNAL_API.LIDCOUNCIL_AppendThirtyPlayerTransportCapacityValidationChecks_Impl(addCheck, makeItem, queueKinds)

  local createOutboundFlushPolicy = INTERNAL_API.LIDCOUNCIL_CreateOutboundFlushPolicyHelpers_Impl
  addCheck("transport flush policy factory available", true, type(createOutboundFlushPolicy) == "function")
  if type(createOutboundFlushPolicy) == "function" then
    local flushPolicyQueue = {
      {
        kind = "PSYNC_CHUNK",
        priority = 60,
        metadata = { lane = "archive" },
        throttleCount = 1,
      },
    }
    local flushPolicyHelpers = createOutboundFlushPolicy({
      GetQueue = function()
        return flushPolicyQueue
      end,
      GetIntervalSeconds = function()
        return 0.2
      end,
      GetQueueItemPriority = function(item)
        return math.max(0, tonumber(type(item) == "table" and item.priority or 10) or 10)
      end,
      ResolveProfileSyncTransferLane = function(metadata)
        return TrimText(type(metadata) == "table" and metadata.lane or "")
      end,
      IsChunkedProfileSyncKind = function(kind)
        return TrimText(kind) == "PSYNC_CHUNK"
      end,
      ProfileSyncIdleIntervalSeconds = 1,
    })
    addCheck("transport flush policy factory creates required functions", true,
      type(flushPolicyHelpers) == "table"
        and type(flushPolicyHelpers.GetQueuedOutboundCommDelay) == "function"
        and type(flushPolicyHelpers.ResolveOutboundCommFlushSchedule) == "function")
    if type(flushPolicyHelpers) == "table" then
      local archiveIdleDelay = flushPolicyHelpers.GetQueuedOutboundCommDelay(nil, false, false)
      local archiveRetryDelay = flushPolicyHelpers.GetQueuedOutboundCommDelay(flushPolicyQueue[1], true, false)
      local shouldReschedule, shouldClear, dueAt = flushPolicyHelpers.ResolveOutboundCommFlushSchedule(1, 100, 0.5, 100.25)
      local emptyShouldSchedule, emptyShouldClear, emptyDueAt = flushPolicyHelpers.ResolveOutboundCommFlushSchedule(0, 100, 0.5, 0)
      addCheck("transport flush policy applies pacing and scheduling guards", "1.8/2.5/false/false/100.5/false/true/0", table.concat({
        tostring(archiveIdleDelay),
        tostring(archiveRetryDelay),
        tostring(shouldReschedule),
        tostring(shouldClear),
        tostring(dueAt),
        tostring(emptyShouldSchedule),
        tostring(emptyShouldClear),
        tostring(emptyDueAt),
      }, "/"))
    end
  end

  local createOutboundFlushTimerState = INTERNAL_API.LIDCOUNCIL_CreateOutboundFlushTimerStateHelpers_Impl
  addCheck("transport flush timer state factory available", true, type(createOutboundFlushTimerState) == "function")
  if type(createOutboundFlushTimerState) == "function" then
    local flushTimerState = {}
    local flushTimerOps = createOutboundFlushTimerState()
    addCheck("transport flush timer state factory creates required functions", true,
      type(flushTimerOps) == "table"
        and type(flushTimerOps.ClearOutboundCommFlushSchedule) == "function"
        and type(flushTimerOps.BeginOutboundCommFlushSchedule) == "function"
        and type(flushTimerOps.ConsumeOutboundCommFlushSchedule) == "function"
        and type(flushTimerOps.GetOutboundCommFlushNextAt) == "function")
    if type(flushTimerOps) == "table" then
      local firstToken = flushTimerOps.BeginOutboundCommFlushSchedule(flushTimerState, 10)
      local firstDueAt = flushTimerOps.GetOutboundCommFlushNextAt(flushTimerState)
      local clearToken = flushTimerOps.ClearOutboundCommFlushSchedule(flushTimerState)
      local staleConsumed = flushTimerOps.ConsumeOutboundCommFlushSchedule(flushTimerState, firstToken)
      local clearedDueAt = flushTimerOps.GetOutboundCommFlushNextAt(flushTimerState)
      local activeToken = flushTimerOps.BeginOutboundCommFlushSchedule(flushTimerState, 20)
      local activeConsumed = flushTimerOps.ConsumeOutboundCommFlushSchedule(flushTimerState, activeToken)
      local consumedDueAt = flushTimerOps.GetOutboundCommFlushNextAt(flushTimerState)
      addCheck("transport flush timer state invalidates stale callbacks", "1/10/2/false/0/3/true/0", table.concat({
        tostring(firstToken),
        tostring(firstDueAt),
        tostring(clearToken),
        tostring(staleConsumed),
        tostring(clearedDueAt),
        tostring(activeToken),
        tostring(activeConsumed),
        tostring(consumedDueAt),
      }, "/"))
    end
  end

  addCheck("transport watchdog rearms a running queue with no timer", "true/false/true", table.concat({
    tostring(INTERNAL_API.LIDCOUNCIL_ShouldArmOutboundFlushWatchdog_Impl(true, 0)),
    tostring(INTERNAL_API.LIDCOUNCIL_ShouldArmOutboundFlushWatchdog_Impl(true, 20)),
    tostring(INTERNAL_API.LIDCOUNCIL_ShouldArmOutboundFlushWatchdog_Impl(false, 20)),
  }, "/"))
  addCheck("transport editor refresh cadence preserves a final bounded flush", "0.65/0.05", table.concat({
    string.format("%.2f", INTERNAL_API.LIDCOUNCIL_ResolveDeferredEditorRefreshDelay_Impl(0.05, 100, 100.1, 0.75)),
    string.format("%.2f", INTERNAL_API.LIDCOUNCIL_ResolveDeferredEditorRefreshDelay_Impl(0.05, 100, 101, 0.75)),
  }, "/"))

  local createOutboundTimerAdapter = INTERNAL_API.LIDCOUNCIL_CreateOutboundTimerAdapterHelpers_Impl
  addCheck("transport timer adapter factory available", true, type(createOutboundTimerAdapter) == "function")
  if type(createOutboundTimerAdapter) == "function" then
    local capturedTimerDelay = 0
    local capturedTimerCallback = nil
    local callbackCalls = 0
    local timerAdapterHelpers = createOutboundTimerAdapter({
      GetTimerAfter = function()
        return function(delay, callback)
          capturedTimerDelay = delay
          capturedTimerCallback = callback
        end
      end,
      TrimText = TrimText,
    })
    addCheck("transport timer adapter factory creates scheduling helper", true,
      type(timerAdapterHelpers) == "table"
        and type(timerAdapterHelpers.ScheduleTimer) == "function"
        and type(timerAdapterHelpers.ScheduleOutboundFlushTimer) == "function"
        and type(timerAdapterHelpers.BuildSessionTimerFallbackStatus) == "function")
    local scheduled, scheduledReason = false, ""
    if type(timerAdapterHelpers) == "table" then
      scheduled, scheduledReason = timerAdapterHelpers.ScheduleTimer(0.5, function()
        callbackCalls = callbackCalls + 1
      end)
      if type(capturedTimerCallback) == "function" then
        capturedTimerCallback()
      end
    end
    local failingTimerAdapter = createOutboundTimerAdapter({
      GetTimerAfter = function()
        return function()
          error("validation timer failure")
        end
      end,
    })
    local failedSchedule, failedReason = false, ""
    if type(failingTimerAdapter) == "table" then
      failedSchedule, failedReason = failingTimerAdapter.ScheduleTimer(0.5, function()
      end)
    end
    local unavailableTimerAdapter = createOutboundTimerAdapter()
    local unavailableSchedule, unavailableReason = false, ""
    if type(unavailableTimerAdapter) == "table" then
      unavailableSchedule, unavailableReason = unavailableTimerAdapter.ScheduleTimer(0.5, function()
      end)
    end
    addCheck("transport timer adapter guards API failures", "true/scheduled/0.5/1/false/error/false/unavailable", table.concat({
      tostring(scheduled),
      TrimText(scheduledReason),
      tostring(capturedTimerDelay),
      tostring(callbackCalls),
      tostring(failedSchedule),
      TrimText(failedReason),
      tostring(unavailableSchedule),
      TrimText(unavailableReason),
    }, "/"))
    do
      local compatibilityTimerAdapter = createOutboundTimerAdapter({
        GetTimerAfter = function()
          return function()
            return true, "frame_fallback"
          end
        end,
        TrimText = TrimText,
      })
      local compatibilityScheduled, compatibilityReason = false, "adapter_unavailable"
      if type(compatibilityTimerAdapter) == "table"
        and type(compatibilityTimerAdapter.ScheduleTimer) == "function"
      then
        compatibilityScheduled, compatibilityReason = compatibilityTimerAdapter.ScheduleTimer(0.5, function()
        end)
      end
      addCheck("transport timer adapter preserves compatibility scheduler status",
        "true/frame_fallback",
        tostring(compatibilityScheduled) .. "/" .. TrimText(compatibilityReason))
    end
    do
      local rejectingTimerAdapter = createOutboundTimerAdapter({
        GetTimerAfter = function()
          return function()
            return false, "compatibility_rejected"
          end
        end,
        TrimText = TrimText,
      })
      local rejectedSchedule, rejectedReason = false, "adapter_unavailable"
      if type(rejectingTimerAdapter) == "table"
        and type(rejectingTimerAdapter.ScheduleTimer) == "function"
      then
        rejectedSchedule, rejectedReason = rejectingTimerAdapter.ScheduleTimer(0.5, function()
        end)
      end
      addCheck("transport timer adapter preserves compatibility scheduler rejection",
        "false/compatibility_rejected",
        tostring(rejectedSchedule) .. "/" .. TrimText(rejectedReason))
    end
    if type(timerAdapterHelpers) == "table" and type(timerAdapterHelpers.BuildSessionTimerFallbackStatus) == "function" then
      local activeFallbackStatus = timerAdapterHelpers.BuildSessionTimerFallbackStatus(2, 5, 42, " unavailable ")
      local priorSessionFallbackStatus = timerAdapterHelpers.BuildSessionTimerFallbackStatus(0, 5, 42, " unavailable ")
      addCheck("transport timer fallback formatter scopes latest details", "2/5/42/unavailable/0/5/0/", table.concat({
        tostring(activeFallbackStatus.sessionTotal),
        tostring(activeFallbackStatus.runtimeTotal),
        tostring(activeFallbackStatus.lastAt),
        activeFallbackStatus.lastReason,
        tostring(priorSessionFallbackStatus.sessionTotal),
        tostring(priorSessionFallbackStatus.runtimeTotal),
        tostring(priorSessionFallbackStatus.lastAt),
        priorSessionFallbackStatus.lastReason,
      }, "/"))
    end
  end

  local createOutboundSessionTelemetry = INTERNAL_API.LIDCOUNCIL_CreateOutboundSessionTelemetryHelpers_Impl
  addCheck("transport session timer telemetry factory available", true, type(createOutboundSessionTelemetry) == "function")
  if type(createOutboundSessionTelemetry) == "function" then
    local timerTelemetryStats = {
      timerFallbackTotal = 10,
      profileAckTimeoutTimerFallbackTotal = 20,
    }
    local timerTelemetrySessionId = "timer-session-one"
    local deferredTimerFallbackTotal = 30
    local timerTelemetryHelpers = createOutboundSessionTelemetry({
      Stats = timerTelemetryStats,
      TrimText = TrimText,
      GetNow = function()
        return 100
      end,
      GetActiveSessionId = function()
        return timerTelemetrySessionId
      end,
      GetDeferredEditorRefreshTimerFallbackTotal = function()
        return deferredTimerFallbackTotal
      end,
    })
    addCheck("transport session timer telemetry factory creates reader", true,
      type(timerTelemetryHelpers) == "table" and type(timerTelemetryHelpers.GetOutboundSessionTelemetry) == "function")
    if type(timerTelemetryHelpers) == "table" and type(timerTelemetryHelpers.GetOutboundSessionTelemetry) == "function" then
      local firstTimerTelemetry = timerTelemetryHelpers.GetOutboundSessionTelemetry()
      timerTelemetryStats.timerFallbackTotal = 13
      timerTelemetryStats.profileAckTimeoutTimerFallbackTotal = 22
      deferredTimerFallbackTotal = 34
      local scopedTimerTelemetry = timerTelemetryHelpers.GetOutboundSessionTelemetry()
      timerTelemetrySessionId = "timer-session-two"
      local resetTimerTelemetry = timerTelemetryHelpers.GetOutboundSessionTelemetry()
      addCheck("transport session timer telemetry resets at session boundary", "3/2/4/0/0/0", table.concat({
        tostring(scopedTimerTelemetry.timerFallbackTotal),
        tostring(scopedTimerTelemetry.profileAckTimeoutTimerFallbackTotal),
        tostring(scopedTimerTelemetry.deferredEditorRefreshTimerFallbackTotal),
        tostring(resetTimerTelemetry.timerFallbackTotal),
        tostring(resetTimerTelemetry.profileAckTimeoutTimerFallbackTotal),
        tostring(resetTimerTelemetry.deferredEditorRefreshTimerFallbackTotal),
      }, "/"))
      addCheck("transport session timer telemetry initializes cleanly", "0/0/0", table.concat({
        tostring(firstTimerTelemetry.timerFallbackTotal),
        tostring(firstTimerTelemetry.profileAckTimeoutTimerFallbackTotal),
        tostring(firstTimerTelemetry.deferredEditorRefreshTimerFallbackTotal),
      }, "/"))
    end
  end

  local timerFallbackStatus = GetSessionCommQueueStatus()
  addCheck("transport timer fallback status exposes session and runtime fields", "number/string/number/string/number/string/number/number/number", table.concat({
    type(timerFallbackStatus.timerFallbackTotal),
    type(timerFallbackStatus.lastTimerFallbackReason),
    type(timerFallbackStatus.profileAckTimeoutTimerFallbackTotal),
    type(timerFallbackStatus.lastProfileAckTimeoutTimerFallbackReason),
    type(timerFallbackStatus.deferredEditorRefreshTimerFallbackTotal),
    type(timerFallbackStatus.lastDeferredEditorRefreshTimerFallbackReason),
    type(timerFallbackStatus.totalTimerFallbackTotal),
    type(timerFallbackStatus.totalProfileAckTimeoutTimerFallbackTotal),
    type(timerFallbackStatus.totalDeferredEditorRefreshTimerFallbackTotal),
  }, "/"))
  addCheck("transport timer fallback status keeps counters non-negative", true,
    math.max(0, tonumber(timerFallbackStatus.timerFallbackTotal) or 0) == timerFallbackStatus.timerFallbackTotal
      and math.max(0, tonumber(timerFallbackStatus.profileAckTimeoutTimerFallbackTotal) or 0)
        == timerFallbackStatus.profileAckTimeoutTimerFallbackTotal
      and math.max(0, tonumber(timerFallbackStatus.deferredEditorRefreshTimerFallbackTotal) or 0)
        == timerFallbackStatus.deferredEditorRefreshTimerFallbackTotal
      and math.max(0, tonumber(timerFallbackStatus.totalTimerFallbackTotal) or 0)
        == timerFallbackStatus.totalTimerFallbackTotal
      and math.max(0, tonumber(timerFallbackStatus.totalProfileAckTimeoutTimerFallbackTotal) or 0)
        == timerFallbackStatus.totalProfileAckTimeoutTimerFallbackTotal
      and math.max(0, tonumber(timerFallbackStatus.totalDeferredEditorRefreshTimerFallbackTotal) or 0)
        == timerFallbackStatus.totalDeferredEditorRefreshTimerFallbackTotal)
  do
    local compatStatus = type(timerFallbackStatus.compatTimerStatus) == "table"
      and timerFallbackStatus.compatTimerStatus
      or {}
    addCheck("transport compatibility timer status exposes bounded diagnostics",
      "number/number/number/number/number/string/string",
      table.concat({
        type(compatStatus.attemptsTotal),
        type(compatStatus.nativeScheduledTotal),
        type(compatStatus.fallbackTotal),
        type(compatStatus.frameFallbackTotal),
        type(compatStatus.immediateFallbackTotal),
        type(compatStatus.lastFallbackReason),
        type(compatStatus.lastNativeError),
      }, "/"))
    addCheck("transport compatibility timer status remains consistent", true,
      math.max(0, tonumber(compatStatus.fallbackTotal) or 0)
        == math.max(0, tonumber(compatStatus.frameFallbackTotal) or 0)
          + math.max(0, tonumber(compatStatus.immediateFallbackTotal) or 0)
        and #TrimText(compatStatus.lastFallbackReason) <= 96
        and #TrimText(compatStatus.lastNativeError) <= 160)
  end
  addCheck("transport inbound rate-limit status is exposed", true,
    type(timerFallbackStatus.inboundRateLimitStatus) == "table"
      and type(timerFallbackStatus.inboundRateLimitStatus.rateLimitedTotal) == "number"
      and type(timerFallbackStatus.inboundRateLimitStatus.laneLimits) == "table"
      and type(timerFallbackStatus.inboundRateLimitStatus.laneLimits.control) == "table"
      and type(timerFallbackStatus.inboundRateLimitStatus.laneLimits.bulk) == "table"
      and type(timerFallbackStatus.inboundRateLimitStatus.laneLimits.board) == "table")

  local getOutboundProfileTransferAckTimerStatus = INTERNAL_API.LIDCOUNCIL_GetOutboundProfileTransferAckTimerStatus_Impl
  addCheck("transport transfer ACK timer status helper available", true,
    type(getOutboundProfileTransferAckTimerStatus) == "function")
  if type(getOutboundProfileTransferAckTimerStatus) == "function" then
    local defaultAckTimerStatus = getOutboundProfileTransferAckTimerStatus()
    local fallbackAckTimerStatus = getOutboundProfileTransferAckTimerStatus({
      ackTimeoutTimerScheduled = true,
      ackTimeoutTimerFallbackAt = 42,
      ackTimeoutTimerFallbackReason = " unavailable ",
    })
    addCheck("transport transfer ACK timer status normalizes fallback snapshot", "false/0//true/42/unavailable", table.concat({
      tostring(defaultAckTimerStatus.scheduled),
      tostring(defaultAckTimerStatus.fallbackAt),
      defaultAckTimerStatus.fallbackReason,
      tostring(fallbackAckTimerStatus.scheduled),
      tostring(fallbackAckTimerStatus.fallbackAt),
      fallbackAckTimerStatus.fallbackReason,
    }, "/"))
  end

  local selectReadyOutboundQueueIndex = INTERNAL_API.LIDCOUNCIL_SelectReadyOutboundCommQueueIndex_Impl
  addCheck("transport deferred queue selector available", true, type(selectReadyOutboundQueueIndex) == "function")
  if type(selectReadyOutboundQueueIndex) == "function" then
    local deferredArchiveQueue = {
      { kind = "PSYNC_CHUNK", notBeforeAt = 75 },
      { kind = "PDELTA", notBeforeAt = 0 },
    }
    local readyIndex, nextDeferredAt = selectReadyOutboundQueueIndex(deferredArchiveQueue, 50)
    addCheck("transport deferred archive yields to ready live packet", "2/75", table.concat({
      tostring(readyIndex),
      tostring(nextDeferredAt),
    }, "/"))
    local deferredIndex, deferredOnlyAt = selectReadyOutboundQueueIndex({
      { kind = "PSYNC_CHUNK", notBeforeAt = 75 },
    }, 50)
    addCheck("transport deferred archive waits for its due time", "nil/75", table.concat({
      tostring(deferredIndex),
      tostring(deferredOnlyAt),
    }, "/"))
    local archivePacingQueue = {
      {
        kind = "PSYNC_CHUNK",
        priority = 60,
        targetName = "Alpha-Realm",
        metadata = { lane = "archive", target = "Alpha-Realm", transferId = "alpha-transfer" },
      },
      {
        kind = "PSYNC_START",
        priority = 60,
        targetName = "Bravo-Realm",
        metadata = { lane = "archive", target = "Bravo-Realm", transferId = "bravo-transfer" },
      },
    }
    local pacedIndex, pacedDeferredAt, wasPaced = selectReadyOutboundQueueIndex(archivePacingQueue, 50, {
      lastTarget = "Alpha-Realm",
      consecutiveChunks = 2,
      burstLimit = 2,
    })
    addCheck("transport archive pacing alternates eligible targets", "2/0/true", table.concat({
      tostring(pacedIndex),
      tostring(pacedDeferredAt),
      tostring(wasPaced),
    }, "/"))
    archivePacingQueue[2].notBeforeAt = 75
    local preservedIndex, preservedDeferredAt, wasPreservedPaced = selectReadyOutboundQueueIndex(archivePacingQueue, 50, {
      lastTarget = "Alpha-Realm",
      consecutiveChunks = 2,
      burstLimit = 2,
    })
    addCheck("transport archive pacing preserves deferred transfer order", "1/75/false", table.concat({
      tostring(preservedIndex),
      tostring(preservedDeferredAt),
      tostring(wasPreservedPaced),
    }, "/"))
    archivePacingQueue[2].notBeforeAt = 0
    archivePacingQueue[2].priority = 61
    local priorityIndex, priorityDeferredAt, wasPriorityPaced = selectReadyOutboundQueueIndex(archivePacingQueue, 50, {
      lastTarget = "Alpha-Realm",
      consecutiveChunks = 2,
      burstLimit = 2,
    })
    addCheck("transport archive pacing preserves priority bands", "1/0/false", table.concat({
      tostring(priorityIndex),
      tostring(priorityDeferredAt),
      tostring(wasPriorityPaced),
    }, "/"))

    local singleTargetPacing = {
      lastTarget = "Alpha-Realm",
      consecutiveChunks = 2,
      burstLimit = 2,
    }
    local singleTargetQueue = {
      {
        kind = "PSYNC_CHUNK",
        priority = 60,
        targetName = "Alpha-Realm",
        metadata = { lane = "archive", target = "Alpha-Realm", transferId = "alpha-transfer" },
      },
      {
        kind = "PSYNC_CHUNK",
        priority = 60,
        targetName = "Alpha-Realm",
        metadata = { lane = "archive", target = "Alpha-Realm", transferId = "alpha-transfer" },
      },
    }
    local singleTargetIndex = selectReadyOutboundQueueIndex(singleTargetQueue, 50, singleTargetPacing, {
      fastReadyHead = true,
    })
    addCheck("transport queue selector caches single-target archive head", "1/Alpha-Realm/60", table.concat({
      tostring(singleTargetIndex),
      tostring(singleTargetPacing.singleTarget),
      tostring(singleTargetPacing.singleTargetPriority),
    }, "/"))
  end

  local stablePriorityQueue = {
    { kind = "FIRST", priority = 20 },
    { kind = "SECOND", priority = 20 },
  }
  outboundQueueSelection.InsertOutboundCommQueueItem({ kind = "THIRD", priority = 20 }, false, stablePriorityQueue)
  outboundQueueSelection.InsertOutboundCommQueueItem({ kind = "URGENT", priority = 5 }, false, stablePriorityQueue)
  addCheck("transport fast insertion preserves stable priority order", "URGENT/FIRST/SECOND/THIRD", queueKinds(stablePriorityQueue))

  local shouldPruneQueuedProfileTransfer = INTERNAL_API.LIDCOUNCIL_ShouldPruneQueuedOutboundProfileTransfer_Impl
  addCheck("transport obsolete profile queue prune rule available", true, type(shouldPruneQueuedProfileTransfer) == "function")
  if type(shouldPruneQueuedProfileTransfer) == "function" then
    local obsoletePruned, obsoleteReason = shouldPruneQueuedProfileTransfer({ kind = "PSYNC_CHUNK" }, {
      obsolete = true,
      state = "superseded_sending",
    })
    addCheck("transport obsolete profile transfer is pruned", "true/superseded_transfer", table.concat({
      tostring(obsoletePruned),
      tostring(obsoleteReason),
    }, "/"))
    local activePruned, activeReason = shouldPruneQueuedProfileTransfer({ kind = "PSYNC_CHUNK" }, {
      state = "sending",
    })
    addCheck("transport active profile transfer remains queued", "false/active_transfer", table.concat({
      tostring(activePruned),
      tostring(activeReason),
    }, "/"))
  end

  local matchesArchiveInFlightTransfer = INTERNAL_API.LIDCOUNCIL_IsMatchingArchiveInFlightProfileTransfer_Impl
  addCheck("transport archive in-flight coalescing rule available", true, type(matchesArchiveInFlightTransfer) == "function")
  if type(matchesArchiveInFlightTransfer) == "function" then
    local archiveIncoming = {
      preparedSnapshot = {
        profileName = "Validation",
        transferKind = "DOMAINS",
        domains = { "loot" },
        subdomains = {},
      },
      sessionId = "validation-session",
      target = "Member-Realm",
      opts = {
        mode = "BACKGROUND",
        reason = "archive_repair",
      },
    }
    local activeArchiveTransfer = {
      target = "Member-Realm",
      sessionId = "validation-session",
      profileName = "Validation",
      mode = "BACKGROUND",
      reason = "archive_repair",
      transferKind = "DOMAINS",
      scopeDomains = { "loot" },
      scopeSubdomains = {},
      lane = "archive",
      state = "sending",
    }
    addCheck("transport archive in-flight coalesces identical scope", true,
      matchesArchiveInFlightTransfer(archiveIncoming, activeArchiveTransfer))
    activeArchiveTransfer.scopeDomains = { "session" }
    addCheck("transport archive in-flight retains changed scope", false,
      matchesArchiveInFlightTransfer(archiveIncoming, activeArchiveTransfer))
    activeArchiveTransfer.scopeDomains = { "loot" }
    activeArchiveTransfer.state = "waiting_ack"
    addCheck("transport archive in-flight does not suppress acknowledgement recovery", false,
      matchesArchiveInFlightTransfer(archiveIncoming, activeArchiveTransfer))
  end

  local shouldReuseArchiveRepairPreparation = INTERNAL_API.LIDCOUNCIL_ShouldReuseArchiveRepairPreparation_Impl
  addCheck("transport archive preparation cache rule available", true, type(shouldReuseArchiveRepairPreparation) == "function")
  if type(shouldReuseArchiveRepairPreparation) == "function" then
    local cachedArchiveRepair = {
      signature = "archive-repair-signature",
      revisionSignature = "revision-one",
      expiresAt = 125,
      transfers = { { transferKind = "SUBDOMAINS" } },
    }
    addCheck("transport archive preparation cache reuses exact revision", true,
      shouldReuseArchiveRepairPreparation(cachedArchiveRepair, "archive-repair-signature", "revision-one", 124))
    addCheck("transport archive preparation cache rejects changed revision", false,
      shouldReuseArchiveRepairPreparation(cachedArchiveRepair, "archive-repair-signature", "revision-two", 124))
    addCheck("transport archive preparation cache expires safely", false,
      shouldReuseArchiveRepairPreparation(cachedArchiveRepair, "archive-repair-signature", "revision-one", 125))
  end

  local createIdentityHelpers = INTERNAL_API.LIDCOUNCIL_CreateLootSessionIdentityHelpers_Impl
  addCheck("transport identity helper factory available", true, type(createIdentityHelpers) == "function")
  if type(createIdentityHelpers) == "function" then
    local identityHelpers = createIdentityHelpers({
      TrimText = TrimText,
      NormalizeCharacterKey = NormalizeCharacterKey,
    })
    addCheck("transport identity helper factory creates required functions", true,
      type(identityHelpers) == "table"
        and type(identityHelpers.IsClaimedActorSenderMatch) == "function"
        and type(identityHelpers.IsJoinedSessionCharacter) == "function"
        and type(identityHelpers.DoesActiveSessionMatch) == "function")
    if type(identityHelpers) == "table" then
      addCheck("transport identity accepts normalized claimed sender", true,
        identityHelpers.IsClaimedActorSenderMatch("Member-Realm", "member-realm"))
      addCheck("transport identity recognizes joined member by canonical key", true,
        identityHelpers.IsJoinedSessionCharacter({
          host = "Host-Realm",
          members = {
            ["Member-Realm"] = { status = "JOINED" },
          },
        }, "member-realm"))
      addCheck("transport identity rejects non-joined member", false,
        identityHelpers.IsJoinedSessionCharacter({
          host = "Host-Realm",
          members = {
            ["Member-Realm"] = { status = "LEFT" },
          },
        }, "member-realm"))
      addCheck("transport identity matches active remote profile", true,
        identityHelpers.DoesActiveSessionMatch({
          id = "validation-session",
          remoteProfileName = "Validation",
        }, "", "validation-session", "Validation"))
    end
  end

  local stateQueue = {
    makeItem("PSTATE", "Member-Realm", {
      sessionId = "validation-session",
      profileName = "Validation",
      actor = "Actor-Realm",
    }, "old"),
  }
  local replacementState = makeItem("PSTATE", "Member-Realm", {
    sessionId = "validation-session",
    profileName = "Validation",
    actor = "Actor-Realm",
  }, "new")
  local stateReplacementIndexes = outboundQueueCoalescing.ResolveQueuedOutboundStatePacketReplacement(replacementState, stateQueue)
  addCheck("transport state replacement finds stale packet", 1, #stateReplacementIndexes)
  addCheck("transport state replacement removes stale packet", 1,
    outboundQueueCoalescing.RemoveQueuedOutboundRequestsByIndexes(stateReplacementIndexes, stateQueue))
  outboundQueueSelection.InsertOutboundCommQueueItem(replacementState, false, stateQueue)
  addCheck("transport state replacement keeps latest packet", "new", tostring(type(stateQueue[1]) == "table" and stateQueue[1].payload or ""))

  do
    -- Keep these validation locals scoped so the large transport validator
    -- remains below WoW Lua's per-function active-local limit.
    local readinessControlQueue = {
      makeItem("IACK", "Host-Realm", {
        sessionId = "validation-session",
        profileName = "Validation",
        memberKey = "Member-Realm",
      }, "older-receipt"),
    }
    local latestReadinessControl = makeItem("IACK", "Host-Realm", {
      sessionId = "validation-session",
      profileName = "Validation",
      memberKey = "Member-Realm",
    }, "latest-receipt")
    local readinessReplacementIndexes = outboundQueueCoalescing.ResolveQueuedOutboundStatePacketReplacement(
      latestReadinessControl,
      readinessControlQueue
    )
    addCheck("transport readiness control coalesces repeated member receipt", 1, #readinessReplacementIndexes)
    outboundQueueCoalescing.RemoveQueuedOutboundRequestsByIndexes(readinessReplacementIndexes, readinessControlQueue)
    outboundQueueSelection.InsertOutboundCommQueueItem(latestReadinessControl, false, readinessControlQueue)
    addCheck("transport readiness control keeps latest receipt", "latest-receipt",
      tostring(type(readinessControlQueue[1]) == "table" and readinessControlQueue[1].payload or ""))
  end

  local coveredRequest = makeItem("PSUB_REQ", "Member-Realm", {
    sessionId = "validation-session",
    profileName = "Validation",
    profileId = "validation-profile",
    requestDomains = "settings,loot",
  })
  local narrowRequest = makeItem("PSUB_REQ", "Member-Realm", {
    sessionId = "validation-session",
    profileName = "Validation",
    profileId = "validation-profile",
    requestDomains = "settings",
  })
  local coverageQueue = { coveredRequest }
  local narrowCovered = outboundQueueCoalescing.ResolveQueuedOutboundRequestCoalescing(narrowRequest, coverageQueue)
  addCheck("transport request coverage suppresses narrower request", true, narrowCovered)
  local wideQueue = { narrowRequest }
  local wideCovered, wideSupersededIndexes = outboundQueueCoalescing.ResolveQueuedOutboundRequestCoalescing(coveredRequest, wideQueue)
  addCheck("transport request coverage accepts wider request", false, wideCovered)
  addCheck("transport request coverage supersedes narrower request", 1, #wideSupersededIndexes)
  addCheck("transport request coverage removes narrower request", 1,
    outboundQueueCoalescing.RemoveQueuedOutboundRequestsByIndexes(wideSupersededIndexes, wideQueue))
  do
    local function ValidatePreciseRequestTokenHandling()
      local checksumRequestMetadata = BuildOutboundCommMetadata(
    "PSUB_REQ",
    "WHISPER",
    "Member-Realm",
    "validation-session",
    "Validation",
    "validation-profile",
    "settings,loot",
    "precise-token-a"
  )
      local patchRequestMetadata = BuildOutboundCommMetadata(
    "PSUBPATCH_REQ",
    "WHISPER",
    "Member-Realm",
    "validation-session",
    "Validation",
    "validation-profile",
    "loot:list,session:history",
    "patch-token-a"
  )
      addCheck("transport precise request metadata retains token", "precise-token-a",
        TrimText(type(checksumRequestMetadata) == "table" and checksumRequestMetadata.requestToken or ""))
      addCheck("transport patch request metadata retains token", "patch-token-a",
        TrimText(type(patchRequestMetadata) == "table" and patchRequestMetadata.requestToken or ""))

      local checksumResponseMetadata = BuildOutboundCommMetadata(
        "PSUB_STATE",
        "WHISPER",
        "Member-Realm",
        "validation-session",
        "Validation",
        "validation-profile",
        "session",
        "session-checksum",
        "encoded-part",
        "response-a",
        "1",
        "35",
        "precise-token-a"
      )
      local patchResponseMetadata = BuildOutboundCommMetadata(
        "PSUBPATCH_STATE",
        "WHISPER",
        "Member-Realm",
        "validation-session",
        "Validation",
        "validation-profile",
        "patch-response-a",
        "1",
        "16",
        "patch-part",
        "patch-token-a"
      )
      addCheck("transport precise response metadata retains request token", "precise-token-a",
        TrimText(type(checksumResponseMetadata) == "table" and checksumResponseMetadata.requestToken or ""))
      addCheck("transport patch response metadata retains request token", "patch-token-a",
        TrimText(type(patchResponseMetadata) == "table" and patchResponseMetadata.requestToken or ""))

      local tokenCoveredRequest = makeItem("PSUB_REQ", "Member-Realm", {
    sessionId = "validation-session",
    profileName = "Validation",
    profileId = "validation-profile",
    requestDomains = "settings,loot",
    requestToken = "precise-token-a",
  })
      local sameTokenNarrowRequest = makeItem("PSUB_REQ", "Member-Realm", {
    sessionId = "validation-session",
    profileName = "Validation",
    profileId = "validation-profile",
    requestDomains = "settings",
    requestToken = "precise-token-a",
  })
      local newTokenNarrowRequest = makeItem("PSUB_REQ", "Member-Realm", {
    sessionId = "validation-session",
    profileName = "Validation",
    profileId = "validation-profile",
    requestDomains = "settings",
    requestToken = "precise-token-b",
  })
      addCheck("transport precise request coverage coalesces matching token", true,
        outboundQueueCoalescing.ResolveQueuedOutboundRequestCoalescing(sameTokenNarrowRequest, { tokenCoveredRequest }))
      local newTokenCovered, newTokenSuperseded = outboundQueueCoalescing.ResolveQueuedOutboundRequestCoalescing(
        newTokenNarrowRequest,
        { tokenCoveredRequest }
      )
      addCheck("transport precise retry is not suppressed by stale token", false, newTokenCovered)
      addCheck("transport precise retry does not supersede stale token", 0, #newTokenSuperseded)

      local oldPatchRequest = makeItem("PSUBPATCH_REQ", "Member-Realm", {
    sessionId = "validation-session",
    profileName = "Validation",
    profileId = "validation-profile",
    requestSubdomains = "loot:list,session:history",
    requestToken = "patch-token-a",
  })
      local newPatchRequest = makeItem("PSUBPATCH_REQ", "Member-Realm", {
    sessionId = "validation-session",
    profileName = "Validation",
    profileId = "validation-profile",
    requestSubdomains = "loot:list",
    requestToken = "patch-token-b",
  })
      local newPatchCovered, newPatchSuperseded = outboundQueueCoalescing.ResolveQueuedOutboundRequestCoalescing(
        newPatchRequest,
        { oldPatchRequest }
      )
      addCheck("transport patch retry is not suppressed by stale token", false, newPatchCovered)
      addCheck("transport patch retry does not supersede stale token", 0, #newPatchSuperseded)

      local queuedPreciseResponse = makeItem("PSUB_STATE", "Member-Realm", checksumResponseMetadata, "old-response")
      local duplicatePreciseResponseMetadata = BuildOutboundCommMetadata(
        "PSUB_STATE",
        "WHISPER",
        "Member-Realm",
        "validation-session",
        "Validation",
        "validation-profile",
        "session",
        "session-checksum",
        "encoded-part",
        "response-b",
        "1",
        "35",
        "precise-token-a"
      )
      local duplicatePreciseResponse = makeItem(
        "PSUB_STATE",
        "Member-Realm",
        duplicatePreciseResponseMetadata,
        "duplicate-response"
      )
      addCheck("transport queued precise response coalesces same request and part", true,
        outboundQueueCoalescing.ResolveQueuedOutboundRequestCoalescing(
          duplicatePreciseResponse,
          { queuedPreciseResponse }
        ))

      duplicatePreciseResponseMetadata.requestToken = "precise-token-b"
      local advancedPreciseResponse = makeItem(
        "PSUB_STATE",
        "Member-Realm",
        duplicatePreciseResponseMetadata,
        "advanced-response"
      )
      addCheck("transport advanced precise response replaces stale queued part", 1,
        #outboundQueueCoalescing.ResolveQueuedOutboundStatePacketReplacement(
          advancedPreciseResponse,
          { queuedPreciseResponse }
        ))

      local queuedPatchResponse = makeItem("PSUBPATCH_STATE", "Member-Realm", patchResponseMetadata, "old-patch-response")
      local advancedPatchResponse = makeItem("PSUBPATCH_STATE", "Member-Realm", {
        sessionId = "validation-session",
        profileName = "Validation",
        profileId = "validation-profile",
        responseToken = "patch-response-b",
        partIndex = 1,
        partCount = 16,
        responsePart = "patch-part",
        requestToken = "patch-token-b",
      }, "advanced-patch-response")
      addCheck("transport advanced patch response replaces stale queued part", 1,
        #outboundQueueCoalescing.ResolveQueuedOutboundStatePacketReplacement(
          advancedPatchResponse,
          { queuedPatchResponse }
        ))

      local olderPreciseSet = {}
      for partIndex = 1, 3 do
        olderPreciseSet[#olderPreciseSet + 1] = makeItem("PSUB_STATE", "Member-Realm", {
          sessionId = "validation-session",
          profileName = "Validation",
          profileId = "validation-profile",
          domain = "session",
          responseToken = "older-response-token",
          partIndex = partIndex,
          partCount = 3,
        })
      end
      addCheck("transport new precise response evicts older multipart tail", 3,
        #outboundQueueCoalescing.ResolveQueuedOutboundStatePacketReplacement(
          makeItem("PSUB_STATE", "Member-Realm", {
            sessionId = "validation-session",
            profileName = "Validation",
            profileId = "validation-profile",
            domain = "session",
            responseToken = "newer-response-token",
            partIndex = 1,
            partCount = 2,
          }),
          olderPreciseSet
        ))

      local boundedPreciseQueue = {}
      for cycle = 1, 40 do
        for partIndex = 1, 35 do
          local responseItem = makeItem("PSUB_STATE", "Member-Realm", {
            sessionId = "validation-session",
            profileName = "Validation",
            profileId = "validation-profile",
            domain = "session",
            domainChecksum = "session-checksum",
            responsePart = "part-" .. tostring(partIndex),
            responseToken = "response-" .. tostring(cycle),
            requestToken = "request-" .. tostring(cycle),
            partIndex = partIndex,
            partCount = 35,
          }, "response-payload")
          local covered = outboundQueueCoalescing.ResolveQueuedOutboundRequestCoalescing(
            responseItem,
            boundedPreciseQueue
          )
          if not covered then
            local replacementIndexes = outboundQueueCoalescing.ResolveQueuedOutboundStatePacketReplacement(
              responseItem,
              boundedPreciseQueue
            )
            outboundQueueCoalescing.RemoveQueuedOutboundRequestsByIndexes(replacementIndexes, boundedPreciseQueue)
            boundedPreciseQueue[#boundedPreciseQueue + 1] = responseItem
          end
        end
      end
      addCheck("transport multipart precise retries remain one response set", 35, #boundedPreciseQueue)

      local shouldSuppressPreciseResponse = INTERNAL_API.LIDCOUNCIL_ShouldSuppressPreciseResponse_Impl
      addCheck("transport precise response dedupe helper available", true, type(shouldSuppressPreciseResponse) == "function")
      if type(shouldSuppressPreciseResponse) == "function" then
        local recentPreciseResponse = {
          signature = "validation-signature",
          requestToken = "precise-token-a",
          sentAt = 100,
        }
        addCheck("transport precise response suppresses matching token duplicate", true,
          shouldSuppressPreciseResponse(recentPreciseResponse, "validation-signature", "precise-token-a", 101, 2))
        addCheck("transport precise response resends for replacement token", false,
          shouldSuppressPreciseResponse(recentPreciseResponse, "validation-signature", "precise-token-b", 101, 2))
        addCheck("transport precise response resends after dedupe window", false,
          shouldSuppressPreciseResponse(recentPreciseResponse, "validation-signature", "precise-token-a", 103, 2))
      end
      local resolvePreciseResponseToken = INTERNAL_API.LIDCOUNCIL_ResolvePreciseResponseToken_Impl
      addCheck("transport precise response token reuse helper available", true,
        type(resolvePreciseResponseToken) == "function")
      if type(resolvePreciseResponseToken) == "function" then
        local recentTokenState = {
          signature = "validation-signature",
          requestToken = "precise-token-a",
          responseTokens = {
            session = "stable-response-token",
          },
        }
        local reusedToken, reused = resolvePreciseResponseToken(
          recentTokenState,
          "validation-signature",
          "precise-token-a",
          "session",
          "new-response-token"
        )
        addCheck("transport precise retry reuses multipart response token", "stable-response-token/true",
          tostring(reusedToken) .. "/" .. tostring(reused))
        local replacementToken, replacementReused = resolvePreciseResponseToken(
          recentTokenState,
          "changed-signature",
          "precise-token-a",
          "session",
          "new-response-token"
        )
        addCheck("transport changed response identity rearms multipart token", "new-response-token/false",
          tostring(replacementToken) .. "/" .. tostring(replacementReused))
      end
    end
    ValidatePreciseRequestTokenHandling()
  end
  local createOutboundQueueCoalescing = INTERNAL_API.LIDCOUNCIL_CreateOutboundQueueCoalescingHelpers_Impl
  addCheck("transport queue coalescing factory available", true, type(createOutboundQueueCoalescing) == "function")
  if type(createOutboundQueueCoalescing) == "function" then
    local defaultCoalescingQueue = {
      {
        kind = "PSTATE",
        distribution = "WHISPER",
        targetName = "Member-Realm",
        metadata = {
          sessionId = "validation-session",
          profileName = "Validation",
          actor = "Actor-Realm",
        },
      },
    }
    local queueCoalescingHelpers = createOutboundQueueCoalescing({
      TrimText = TrimText,
      NormalizeCharacterKey = NormalizeCharacterKey,
      GetQueue = function()
        return defaultCoalescingQueue
      end,
      ReplaceQueue = function(queue)
        defaultCoalescingQueue = queue
      end,
    })
    addCheck("transport queue coalescing factory creates required functions", true,
      type(queueCoalescingHelpers) == "table"
        and type(queueCoalescingHelpers.ResolveQueuedOutboundStatePacketReplacement) == "function"
        and type(queueCoalescingHelpers.RemoveQueuedOutboundRequestsByIndexes) == "function")
    if type(queueCoalescingHelpers) == "table" then
      local replacementIndexes = queueCoalescingHelpers.ResolveQueuedOutboundStatePacketReplacement({
        kind = "PSTATE",
        distribution = "WHISPER",
        targetName = "Member-Realm",
        metadata = {
          sessionId = "validation-session",
          profileName = "Validation",
          actor = "Actor-Realm",
        },
      })
      local removedCount = queueCoalescingHelpers.RemoveQueuedOutboundRequestsByIndexes(replacementIndexes)
      addCheck("transport queue coalescing replaces default queue", "1/0", table.concat({
        tostring(removedCount),
        tostring(#defaultCoalescingQueue),
      }, "/"))
    end
  end

  local getUndispatchedAckTimeoutDomains = type(flowHelpers) == "table"
    and flowHelpers.GetUndispatchedAckTimeoutRevalidationDomains
    or nil
  addCheck("transport ACK timeout scope delta helper available", true, type(getUndispatchedAckTimeoutDomains) == "function")
  local initialAckTimeoutDomains = type(getUndispatchedAckTimeoutDomains) == "function"
    and getUndispatchedAckTimeoutDomains({ "settings", "loot" }, {})
    or {}
  addCheck("transport ACK timeout first scope dispatches all domains", "settings/loot", table.concat(initialAckTimeoutDomains, "/"))
  local expandedAckTimeoutDomains = type(getUndispatchedAckTimeoutDomains) == "function"
    and getUndispatchedAckTimeoutDomains({ "settings", "permissions", "loot" }, { "settings", "loot" })
    or {}
  addCheck("transport ACK timeout expanded scope dispatches only new domain", "permissions", table.concat(expandedAckTimeoutDomains, "/"))
  local coveredAckTimeoutDomains = type(getUndispatchedAckTimeoutDomains) == "function"
    and getUndispatchedAckTimeoutDomains({ "settings" }, { "settings", "loot" })
    or {}
  addCheck("transport ACK timeout covered scope sends no duplicate domains", 0, #coveredAckTimeoutDomains)
  addCheck("transport permission state proof gate available", true,
    type(flowHelpers) == "table"
      and type(flowHelpers.ShouldPublishProfileDeltaStateProof) == "function")
  addCheck("transport permission delta publishes coalesced state proof", true,
    type(flowHelpers) == "table"
      and type(flowHelpers.ShouldPublishProfileDeltaStateProof) == "function"
      and flowHelpers.ShouldPublishProfileDeltaStateProof(" permissions ")
      or false)
  addCheck("transport non-permission delta avoids redundant state proof", false,
    type(flowHelpers) == "table"
      and type(flowHelpers.ShouldPublishProfileDeltaStateProof) == "function"
      and flowHelpers.ShouldPublishProfileDeltaStateProof("settings")
      or false)
  local shouldScheduleAckTimeoutRecovery = type(flowHelpers) == "table"
    and flowHelpers.ShouldScheduleAckTimeoutRevalidationRecovery
    or nil
  addCheck("transport ACK timeout recovery gate helper available", true, type(shouldScheduleAckTimeoutRecovery) == "function")
  local pendingRecoveryState = {}
  addCheck("transport ACK timeout recovery gate schedules first callback", true,
    type(shouldScheduleAckTimeoutRecovery) == "function" and shouldScheduleAckTimeoutRecovery(pendingRecoveryState) or false)
  pendingRecoveryState.recoveryScheduled = true
  addCheck("transport ACK timeout recovery gate coalesces later callback", false,
    type(shouldScheduleAckTimeoutRecovery) ~= "function" or shouldScheduleAckTimeoutRecovery(pendingRecoveryState))
  local getAckTimeoutRevalidationStats = type(flowHelpers) == "table"
    and flowHelpers.GetAckTimeoutRevalidationStats
    or nil
  addCheck("transport ACK timeout telemetry helper available", true, type(getAckTimeoutRevalidationStats) == "function")
  local inactiveAckTimeoutStats = type(getAckTimeoutRevalidationStats) == "function"
    and getAckTimeoutRevalidationStats("__validation_missing_session__")
    or {}
  addCheck("transport ACK timeout telemetry starts empty for other session", "0/0/0", table.concat({
    tostring(math.max(0, tonumber(inactiveAckTimeoutStats.suppressedDomainTotal) or 0)),
    tostring(math.max(0, tonumber(inactiveAckTimeoutStats.coalescedRecoveryCallbackTotal) or 0)),
    tostring(math.max(0, tonumber(inactiveAckTimeoutStats.sharedRecoveryBatchTotal) or 0)),
  }, "/"))
  local resolveOutboundTelemetryLane = INTERNAL_API.LIDCOUNCIL_ResolveOutboundCommTelemetryLane_Impl
  addCheck("transport lane telemetry resolver available", true, type(resolveOutboundTelemetryLane) == "function")
  addCheck("transport lane telemetry classifies bootstrap", "bootstrap", type(resolveOutboundTelemetryLane) == "function"
    and resolveOutboundTelemetryLane(makeItem("PSYNC_START", "Member-Realm", { reason = "missing_member_bootstrap" })) or "")
  addCheck("transport lane telemetry classifies archive", "archive", type(resolveOutboundTelemetryLane) == "function"
    and resolveOutboundTelemetryLane(makeItem("PSYNC_CHUNK", "Member-Realm", { lane = "archive" })) or "")
  addCheck("transport lane telemetry classifies live", "live", type(resolveOutboundTelemetryLane) == "function"
    and resolveOutboundTelemetryLane(makeItem("PDELTA", "Member-Realm")) or "")
  addCheck("transport lane telemetry classifies stats", "stats", type(resolveOutboundTelemetryLane) == "function"
    and resolveOutboundTelemetryLane(makeItem("PSYNC_START", "Member-Realm", { lane = "stats" })) or "")
  addCheck("transport lane telemetry classifies control", "control", type(resolveOutboundTelemetryLane) == "function"
    and resolveOutboundTelemetryLane(makeItem("START", "Member-Realm")) or "")
  local resolveOutboundTelemetryTarget = INTERNAL_API.LIDCOUNCIL_ResolveOutboundCommTelemetryTarget_Impl
  addCheck("transport member telemetry resolver available", true, type(resolveOutboundTelemetryTarget) == "function")
  addCheck("transport member telemetry normalizes target", "Member-Realm", type(resolveOutboundTelemetryTarget) == "function"
    and resolveOutboundTelemetryTarget(makeItem("PDELTA", " Member-Realm ")) or "")
  addCheck("transport member telemetry groups non-whisper traffic", "", type(resolveOutboundTelemetryTarget) == "function"
    and resolveOutboundTelemetryTarget({ kind = "START", distribution = "RAID", targetName = "Member-Realm", payload = "START" }) or "")
  local selectOutboundTelemetryMemberBucket = INTERNAL_API.LIDCOUNCIL_SelectOutboundCommTelemetryMemberBucket_Impl
  addCheck("transport member telemetry bucket helper available", true, type(selectOutboundTelemetryMemberBucket) == "function")
  local retainedMemberBucket, retainedMemberOverflowed = "", true
  if type(selectOutboundTelemetryMemberBucket) == "function" then
    retainedMemberBucket, retainedMemberOverflowed = selectOutboundTelemetryMemberBucket("Member-A", { ["Member-A"] = {} }, 1)
  end
  addCheck("transport member telemetry retains known member", "Member-A/false", tostring(retainedMemberBucket) .. "/" .. tostring(retainedMemberOverflowed))
  local overflowMemberBucket, overflowMemberOverflowed = "", false
  if type(selectOutboundTelemetryMemberBucket) == "function" then
    overflowMemberBucket, overflowMemberOverflowed = selectOutboundTelemetryMemberBucket("Member-B", { ["Member-A"] = {} }, 1)
  end
  addCheck("transport member telemetry bounds additional members", "__other__/true", tostring(overflowMemberBucket) .. "/" .. tostring(overflowMemberOverflowed))
  local createOutboundEndpointTelemetry = INTERNAL_API.LIDCOUNCIL_CreateOutboundEndpointTelemetryHelpers_Impl
  addCheck("transport endpoint telemetry factory available", true, type(createOutboundEndpointTelemetry) == "function")
  if type(createOutboundEndpointTelemetry) == "function" then
    local endpointValidationStats = {}
    local endpointHelpers = createOutboundEndpointTelemetry({
      Stats = endpointValidationStats,
      TrimText = TrimText,
      NormalizeCharacterKey = NormalizeCharacterKey,
      ResolveProfileSyncTransferReason = function(metadata)
        return TrimText(type(metadata) == "table" and metadata.reason or "")
      end,
      ResolveProfileSyncTransferLane = function(metadata)
        return TrimText(type(metadata) == "table" and metadata.lane or "live")
      end,
    })
    addCheck("transport endpoint telemetry factory creates required functions", true,
      type(endpointHelpers) == "table"
        and type(endpointHelpers.RecordOutboundCommLaneTelemetry) == "function"
        and type(endpointHelpers.GetOutboundCommLaneTelemetry) == "function"
        and type(endpointHelpers.RecordOutboundCommMemberTelemetry) == "function"
        and type(endpointHelpers.GetOutboundCommMemberTelemetry) == "function")
    if type(endpointHelpers) == "table" then
      local endpointItem = {
        kind = "PDELTA",
        distribution = "WHISPER",
        targetName = "Member-Realm",
        payload = "abc",
        metadata = { lane = "stats" },
      }
      endpointHelpers.RecordOutboundCommLaneTelemetry(endpointItem, "attempted")
      endpointHelpers.RecordOutboundCommLaneTelemetry(endpointItem, "sent")
      endpointHelpers.RecordOutboundCommMemberTelemetry(endpointItem, "attempted")
      endpointHelpers.RecordOutboundCommMemberTelemetry(endpointItem, "sent")
      local laneSnapshot = endpointHelpers.GetOutboundCommLaneTelemetry()
      local memberSnapshot = endpointHelpers.GetOutboundCommMemberTelemetry()
      local statsLane = type(laneSnapshot) == "table" and laneSnapshot.stats or {}
      local member = type(memberSnapshot) == "table" and memberSnapshot.members and memberSnapshot.members[1] or {}
      addCheck("transport endpoint telemetry records lane counters", "1/1/3/3", table.concat({
        tostring(math.max(0, tonumber(type(statsLane) == "table" and statsLane.attempted or 0) or 0)),
        tostring(math.max(0, tonumber(type(statsLane) == "table" and statsLane.sent or 0) or 0)),
        tostring(math.max(0, tonumber(type(statsLane) == "table" and statsLane.bytesAttempted or 0) or 0)),
        tostring(math.max(0, tonumber(type(statsLane) == "table" and statsLane.bytesSent or 0) or 0)),
      }, "/"))
      addCheck("transport endpoint telemetry records member counters", "Member-Realm/1/1/3/3", table.concat({
        NormalizeCharacterKey(type(member) == "table" and member.member or ""),
        tostring(math.max(0, tonumber(type(member) == "table" and member.attempted or 0) or 0)),
        tostring(math.max(0, tonumber(type(member) == "table" and member.sent or 0) or 0)),
        tostring(math.max(0, tonumber(type(member) == "table" and member.bytesAttempted or 0) or 0)),
        tostring(math.max(0, tonumber(type(member) == "table" and member.bytesSent or 0) or 0)),
      }, "/"))
    end
  end
  local isOutboundProfileTransferTelemetryItem = INTERNAL_API.LIDCOUNCIL_IsOutboundProfileTransferTelemetryItem_Impl
  local classifiedProfileChunk = false
  local classifiedDelta = true
  if type(isOutboundProfileTransferTelemetryItem) == "function" then
    classifiedProfileChunk = isOutboundProfileTransferTelemetryItem(makeItem("PSYNC_CHUNK", "Member-Realm"))
    classifiedDelta = isOutboundProfileTransferTelemetryItem(makeItem("PDELTA", "Member-Realm"))
  end
  addCheck("transport transfer telemetry classifier available", true, type(isOutboundProfileTransferTelemetryItem) == "function")
  addCheck("transport transfer telemetry classifies profile chunk", true, classifiedProfileChunk)
  addCheck("transport transfer telemetry excludes live delta", false, classifiedDelta)
  local createOutboundProfileTransferTelemetry = INTERNAL_API.LIDCOUNCIL_CreateOutboundProfileTransferTelemetryHelpers_Impl
  addCheck("transport profile transfer telemetry factory available", true, type(createOutboundProfileTransferTelemetry) == "function")
  if type(createOutboundProfileTransferTelemetry) == "function" then
    local transferTelemetryRecord = {}
    local profileTransferTelemetryHelpers = createOutboundProfileTransferTelemetry({
      TrimText = TrimText,
      EnsureOutboundProfileTransfer = function(transferId)
        return TrimText(transferId) == "validation-transfer" and transferTelemetryRecord or nil
      end,
    })
    addCheck("transport profile transfer telemetry factory creates required functions", true,
      type(profileTransferTelemetryHelpers) == "table"
        and type(profileTransferTelemetryHelpers.IsOutboundProfileTransferTelemetryItem) == "function"
        and type(profileTransferTelemetryHelpers.RecordOutboundProfileTransferTelemetry) == "function")
    if type(profileTransferTelemetryHelpers) == "table" then
      local profileTransferItem = {
        kind = "PSYNC_CHUNK",
        payload = "abc",
        metadata = { transferId = "validation-transfer" },
      }
      profileTransferTelemetryHelpers.RecordOutboundProfileTransferTelemetry(profileTransferItem, "attempted")
      profileTransferTelemetryHelpers.RecordOutboundProfileTransferTelemetry(profileTransferItem, "sent")
      profileTransferTelemetryHelpers.RecordOutboundProfileTransferTelemetry(profileTransferItem, "throttled")
      profileTransferTelemetryHelpers.RecordOutboundProfileTransferTelemetry(profileTransferItem, "failed")
      addCheck("transport profile transfer telemetry records counters", "1/1/1/1/3/3", table.concat({
        tostring(math.max(0, tonumber(transferTelemetryRecord.attemptedMessages) or 0)),
        tostring(math.max(0, tonumber(transferTelemetryRecord.sentMessages) or 0)),
        tostring(math.max(0, tonumber(transferTelemetryRecord.throttledMessages) or 0)),
        tostring(math.max(0, tonumber(transferTelemetryRecord.failedMessages) or 0)),
        tostring(math.max(0, tonumber(transferTelemetryRecord.bytesAttempted) or 0)),
        tostring(math.max(0, tonumber(transferTelemetryRecord.bytesSent) or 0)),
      }, "/"))
    end
  end
  addCheck("transport session telemetry helper available", true, type(INTERNAL_API.LIDCOUNCIL_GetOutboundSessionTelemetry_Impl) == "function")
  local lifecycleTelemetryMetadata = BuildOutboundCommMetadata("START", "RAID", nil, "validation-session", "Validation")
  addCheck("transport lifecycle metadata retains session scope", "validation-session/Validation", table.concat({
    TrimText(type(lifecycleTelemetryMetadata) == "table" and lifecycleTelemetryMetadata.sessionId or ""),
    TrimText(type(lifecycleTelemetryMetadata) == "table" and lifecycleTelemetryMetadata.profileName or ""),
  }, "/"))
  lifecycleTelemetryMetadata = BuildOutboundCommMetadata(
    "BSYNC_END",
    "WHISPER",
    "Receiver-Realm",
    "validation-session",
    "Validation",
    "validation-board",
    "validation-item",
    "validation-token"
  )
  addCheck("transport board END metadata retains receipt identity",
    "validation-session/Validation/validation-board/validation-item/validation-token/Receiver-Realm",
    table.concat({
      TrimText(type(lifecycleTelemetryMetadata) == "table" and lifecycleTelemetryMetadata.sessionId or ""),
      TrimText(type(lifecycleTelemetryMetadata) == "table" and lifecycleTelemetryMetadata.profileName or ""),
      TrimText(type(lifecycleTelemetryMetadata) == "table" and lifecycleTelemetryMetadata.boardId or ""),
      TrimText(type(lifecycleTelemetryMetadata) == "table" and lifecycleTelemetryMetadata.selectedItemKey or ""),
      TrimText(type(lifecycleTelemetryMetadata) == "table" and lifecycleTelemetryMetadata.token or ""),
      TrimText(type(lifecycleTelemetryMetadata) == "table" and lifecycleTelemetryMetadata.target or ""),
    }, "/"))
  local isOutboundProfileTransferForSession = INTERNAL_API.LIDCOUNCIL_IsOutboundProfileTransferForSession_Impl
  local matchingTransferSession = false
  local staleTransferSession = true
  if type(isOutboundProfileTransferForSession) == "function" then
    matchingTransferSession = isOutboundProfileTransferForSession({ sessionId = "validation-session" }, "validation-session")
    staleTransferSession = isOutboundProfileTransferForSession({ sessionId = "previous-session" }, "validation-session")
  end
  addCheck("transport transfer session helper available", true, type(isOutboundProfileTransferForSession) == "function")
  addCheck("transport transfer session helper accepts matching session", true, matchingTransferSession)
  addCheck("transport transfer session helper rejects stale session", false, staleTransferSession)
  local shouldRejectStaleProfileSync = INTERNAL_API.LIDCOUNCIL_ShouldRejectOutboundProfileSyncForActiveSession_Impl
  local rejectsStaleProfileSync = false
  local permitsCurrentProfileSync = true
  if type(shouldRejectStaleProfileSync) == "function" then
    rejectsStaleProfileSync = shouldRejectStaleProfileSync("PSYNC_CHUNK", "previous-session", "validation-session")
    permitsCurrentProfileSync = shouldRejectStaleProfileSync("PSYNC_CHUNK", "validation-session", "validation-session")
  end
  addCheck("transport stale profile sync gate available", true, type(shouldRejectStaleProfileSync) == "function")
  addCheck("transport stale profile sync gate rejects previous session", true, rejectsStaleProfileSync)
  addCheck("transport stale profile sync gate keeps active session", false, permitsCurrentProfileSync)
  local shouldRejectSessionBoundMessage = INTERNAL_API.LIDCOUNCIL_ShouldRejectOutboundSessionBoundMessage_Impl
  local rejectsStaleDelta = false
  local permitsCurrentProfileState = true
  if type(shouldRejectSessionBoundMessage) == "function" then
    rejectsStaleDelta = shouldRejectSessionBoundMessage("PDELTA", "previous-session", "validation-session")
    permitsCurrentProfileState = shouldRejectSessionBoundMessage("PSTATE", "validation-session", "validation-session")
  end
  addCheck("transport session-bound update gate available", true, type(shouldRejectSessionBoundMessage) == "function")
  addCheck("transport session-bound update gate rejects stale delta", true, rejectsStaleDelta)
  addCheck("transport session-bound update gate keeps current profile state", false, permitsCurrentProfileState)
  local isOutboundProfileRepairResponse = INTERNAL_API.LIDCOUNCIL_IsOutboundSessionBoundProfileRepairResponse_Impl
  local rejectsStaleRepairResponse = false
  local permitsCurrentRepairResponse = true
  if type(shouldRejectSessionBoundMessage) == "function" then
    rejectsStaleRepairResponse = shouldRejectSessionBoundMessage("PSUB_STATE", "previous-session", "validation-session")
    permitsCurrentRepairResponse = shouldRejectSessionBoundMessage("PSYNC_ACK", "validation-session", "validation-session")
  end
  addCheck("transport repair response classifier available", true, type(isOutboundProfileRepairResponse) == "function")
  addCheck("transport session-bound gate rejects stale repair response", true, rejectsStaleRepairResponse)
  addCheck("transport session-bound gate keeps current repair response", false, permitsCurrentRepairResponse)
  local isOutboundProfileRepairRequest = INTERNAL_API.LIDCOUNCIL_IsOutboundSessionBoundProfileRepairRequest_Impl
  local rejectsStaleRepairRequest = false
  local permitsCurrentRepairRequest = true
  if type(shouldRejectSessionBoundMessage) == "function" then
    rejectsStaleRepairRequest = shouldRejectSessionBoundMessage("PSUB_REQ", "previous-session", "validation-session")
    permitsCurrentRepairRequest = shouldRejectSessionBoundMessage("PSUBPATCH_REQ", "validation-session", "validation-session")
  end
  addCheck("transport repair request classifier available", true, type(isOutboundProfileRepairRequest) == "function")
  addCheck("transport session-bound gate rejects stale repair request", true, rejectsStaleRepairRequest)
  addCheck("transport session-bound gate keeps current repair request", false, permitsCurrentRepairRequest)
  local resolveSessionBoundQueueSessionId = INTERNAL_API.LIDCOUNCIL_ResolveOutboundSessionBoundQueueSessionId_Impl
  local resolvedQueuedDeltaSessionId = ""
  local resolvedQueuedLifecycleSessionId = "unexpected"
  if type(resolveSessionBoundQueueSessionId) == "function" then
    resolvedQueuedDeltaSessionId = resolveSessionBoundQueueSessionId("PDELTA", { sessionId = "validation-session" })
    resolvedQueuedLifecycleSessionId = resolveSessionBoundQueueSessionId("START", { sessionId = "validation-session" })
  end
  addCheck("transport session-bound queue resolver available", true, type(resolveSessionBoundQueueSessionId) == "function")
  addCheck("transport session-bound queue resolver keeps delta session", "validation-session", resolvedQueuedDeltaSessionId)
  addCheck("transport session-bound queue resolver preserves lifecycle control", "", resolvedQueuedLifecycleSessionId)
  local isInboundSessionBoundProfileMessage = INTERNAL_API.LIDCOUNCIL_IsInboundSessionBoundProfileMessage_Impl
  addCheck("transport inbound session-bound classifier available", true, type(isInboundSessionBoundProfileMessage) == "function")
  addCheck("transport inbound session-bound classifier covers live delta", true,
    type(isInboundSessionBoundProfileMessage) == "function" and isInboundSessionBoundProfileMessage("PDELTA") or false)
  addCheck("transport inbound session-bound classifier covers snapshot start", true,
    type(isInboundSessionBoundProfileMessage) == "function" and isInboundSessionBoundProfileMessage("PSYNC_START") or false)
  addCheck("transport inbound session-bound classifier preserves lifecycle", false,
    type(isInboundSessionBoundProfileMessage) == "function" and isInboundSessionBoundProfileMessage("START") == true)
  local resolveInboundSessionBoundSessionId = INTERNAL_API.LIDCOUNCIL_ResolveInboundSessionBoundMessageSessionId_Impl
  addCheck("transport inbound session-bound resolver available", true, type(resolveInboundSessionBoundSessionId) == "function")
  addCheck("transport inbound resolver reads delta session", "validation-session", type(resolveInboundSessionBoundSessionId) == "function"
    and resolveInboundSessionBoundSessionId("PDELTA", { "PDELTA", "validation-session" }) or "")
  addCheck("transport inbound resolver reads snapshot session", "validation-session", type(resolveInboundSessionBoundSessionId) == "function"
    and resolveInboundSessionBoundSessionId("PSYNC_ACK", { "PSYNC_ACK", "transfer", "validation-session" }) or "")
  local shouldRejectInboundSessionBoundMessage = INTERNAL_API.LIDCOUNCIL_ShouldRejectInboundSessionBoundMessage_Impl
  addCheck("transport inbound session-bound gate available", true, type(shouldRejectInboundSessionBoundMessage) == "function")
  addCheck("transport inbound gate rejects stale live delta", true, type(shouldRejectInboundSessionBoundMessage) == "function"
    and shouldRejectInboundSessionBoundMessage("PDELTA", { "PDELTA", "previous-session" }, "validation-session") or false)
  addCheck("transport inbound gate keeps matching repair response", false, type(shouldRejectInboundSessionBoundMessage) == "function"
    and shouldRejectInboundSessionBoundMessage("PSUB_STATE", { "PSUB_STATE", "validation-session" }, "validation-session") == true)
  addCheck("transport inbound gate rejects stale snapshot start", true, type(shouldRejectInboundSessionBoundMessage) == "function"
    and shouldRejectInboundSessionBoundMessage("PSYNC_START", { "PSYNC_START", "transfer", "previous-session" }, "validation-session") or false)
  addCheck("transport inbound gate preserves lifecycle", false, type(shouldRejectInboundSessionBoundMessage) == "function"
    and shouldRejectInboundSessionBoundMessage("START", { "START", "previous-session" }, "validation-session") == true)
  local runAcceptedJoinFollowup = INTERNAL_API.LIDCOUNCIL_RunAcceptedJoinFollowup_Impl
  addCheck("accepted JOIN follow-up guard available", true, type(runAcceptedJoinFollowup) == "function")
  if type(runAcceptedJoinFollowup) == "function" then
    local validationJoinFollowupOk, validationJoinFollowupResult = runAcceptedJoinFollowup(
      "validation",
      "validation-session",
      "Validation Profile",
      "Member-Realm",
      function()
        return "completed"
      end,
      { suppressDiagnostics = true }
    )
    addCheck("accepted JOIN follow-up guard preserves success", "true/completed",
      tostring(validationJoinFollowupOk == true) .. "/" .. tostring(validationJoinFollowupResult))
    local validationJoinFollowupFailed, validationJoinFollowupError = runAcceptedJoinFollowup(
      "validation",
      "validation-session",
      "Validation Profile",
      "Member-Realm",
      function()
        error("validation returning-member recovery failure")
      end,
      { suppressDiagnostics = true }
    )
    addCheck("accepted JOIN follow-up guard contains optional failure", false, validationJoinFollowupFailed == true)
    addCheck("accepted JOIN follow-up guard preserves failure detail", true,
      string.find(tostring(validationJoinFollowupError), "validation returning-member recovery failure", 1, true) ~= nil)
  end
  local incrementInboundStaleSessionDropTotal = INTERNAL_API.LIDCOUNCIL_IncrementInboundStaleSessionDropTotal_Impl
  local validationInboundTelemetry = {}
  local staleInboundDropTotal = type(incrementInboundStaleSessionDropTotal) == "function"
    and incrementInboundStaleSessionDropTotal(validationInboundTelemetry, "stale_session_bound_message")
    or -1
  local nonStaleInboundDropTotal = type(incrementInboundStaleSessionDropTotal) == "function"
    and incrementInboundStaleSessionDropTotal(validationInboundTelemetry, "unknown_incoming_opcode")
    or -1
  addCheck("transport inbound stale-drop counter available", true, type(incrementInboundStaleSessionDropTotal) == "function")
  addCheck("transport inbound stale-drop counter increments stale packet", 1, staleInboundDropTotal)
  addCheck("transport inbound stale-drop counter ignores other rejection", 1, nonStaleInboundDropTotal)
  local createInboundTelemetryOps = INTERNAL_API.LIDCOUNCIL_CreateInboundTelemetryOps_Impl
  addCheck("transport inbound telemetry factory available", true, type(createInboundTelemetryOps) == "function")
  if type(createInboundTelemetryOps) == "function" then
    local validationTelemetry, validationInboundOps = createInboundTelemetryOps({
      TrimText = TrimText,
      NormalizeCharacterKey = NormalizeCharacterKey,
      GetNow = function()
        return 100
      end,
    })
    addCheck("transport inbound telemetry factory creates required operations", true,
      type(validationTelemetry) == "table"
        and type(validationInboundOps) == "table"
        and type(validationInboundOps.record) == "function"
        and type(validationInboundOps.recordDispatched) == "function"
        and type(validationInboundOps.activitySnapshot) == "function"
        and type(validationInboundOps.recordRejected) == "function"
        and type(validationInboundOps.recordHandlerError) == "function"
        and type(validationInboundOps.snapshot) == "function"
        and type(validationInboundOps.clear) == "function")
    if type(validationInboundOps) == "table"
      and type(validationInboundOps.record) == "function"
      and type(validationInboundOps.recordDispatched) == "function"
      and type(validationInboundOps.activitySnapshot) == "function"
      and type(validationInboundOps.recordRejected) == "function"
      and type(validationInboundOps.recordHandlerError) == "function"
      and type(validationInboundOps.snapshot) == "function"
      and type(validationInboundOps.clear) == "function"
    then
      validationInboundOps.record("PDELTA", "Member-Realm", 10)
      validationInboundOps.recordDispatched("PDELTA", "Member-Realm", 10)
      validationInboundOps.recordHandlerError(
        "PDELTA",
        "Member-Realm",
        "validation_handler_detail" .. string.rep("x", 300)
      )
      validationInboundOps.recordRejected("PDELTA", "Member-Realm", "stale_session_bound_message")
      local telemetrySnapshot = validationInboundOps.snapshot()
      addCheck("transport inbound telemetry records bounded traffic", "1/1/1/10/1/1/1/1/PDELTA/Member-Realm/true/240", table.concat({
        tostring(type(telemetrySnapshot) == "table" and telemetrySnapshot.receivedTotal or 0),
        tostring(type(telemetrySnapshot) == "table" and telemetrySnapshot.rejectedTotal or 0),
        tostring(type(telemetrySnapshot) == "table" and telemetrySnapshot.staleSessionBoundDropTotal or 0),
        tostring(type(telemetrySnapshot) == "table" and telemetrySnapshot.receivedBytes or 0),
        tostring(type(telemetrySnapshot) == "table" and type(telemetrySnapshot.bySender) == "table"
          and type(telemetrySnapshot.bySender["member-realm"]) == "table"
          and telemetrySnapshot.bySender["member-realm"].rejected or 0),
        tostring(type(telemetrySnapshot) == "table" and telemetrySnapshot.handlerErrorTotal or 0),
        tostring(type(telemetrySnapshot) == "table" and type(telemetrySnapshot.handlerErrorByKind) == "table"
          and telemetrySnapshot.handlerErrorByKind.PDELTA or 0),
        tostring(type(telemetrySnapshot) == "table" and type(telemetrySnapshot.bySender) == "table"
          and type(telemetrySnapshot.bySender["member-realm"]) == "table"
          and telemetrySnapshot.bySender["member-realm"].handlerErrors or 0),
        tostring(type(telemetrySnapshot) == "table" and telemetrySnapshot.lastHandlerErrorKind or ""),
        tostring(type(telemetrySnapshot) == "table" and telemetrySnapshot.lastHandlerErrorSender or ""),
        tostring(type(telemetrySnapshot) == "table"
          and string.find(tostring(telemetrySnapshot.lastHandlerErrorDetail), "validation_handler_detail", 1, true) ~= nil),
        tostring(type(telemetrySnapshot) == "table" and #tostring(telemetrySnapshot.lastHandlerErrorDetail) or 0),
      }, "/"))
      telemetrySnapshot.activity = validationInboundOps.activitySnapshot(2)
      addCheck("transport inbound telemetry exposes accepted transfer direction",
        "true/Member-Realm/Member-Realm/true/true/1",
        table.concat({
          tostring(type(telemetrySnapshot.activity) == "table" and telemetrySnapshot.activity.active == true),
          tostring(type(telemetrySnapshot.activity) == "table" and telemetrySnapshot.activity.lastDispatchedSender or ""),
          tostring(type(telemetrySnapshot.activity) == "table" and type(telemetrySnapshot.activity.recentSenders) == "table"
            and telemetrySnapshot.activity.recentSenders[1] or ""),
          tostring(type(telemetrySnapshot.activity) == "table"
            and math.max(0, tonumber(telemetrySnapshot.activity.messageRatePerSecond) or 0) > 0),
          tostring(type(telemetrySnapshot.activity) == "table"
            and math.max(0, tonumber(telemetrySnapshot.activity.byteRatePerSecond) or 0) > 0),
          tostring(type(telemetrySnapshot) == "table" and type(telemetrySnapshot.bySender) == "table"
            and type(telemetrySnapshot.bySender["member-realm"]) == "table"
            and telemetrySnapshot.bySender["member-realm"].dispatched or 0),
        }, "/"))
      validationInboundOps.clear()
      local clearedTelemetrySnapshot = validationInboundOps.snapshot()
      clearedTelemetrySnapshot.activity = validationInboundOps.activitySnapshot(2)
      addCheck("transport inbound telemetry clears counters", "0/0/0/0", table.concat({
        tostring(type(clearedTelemetrySnapshot) == "table" and clearedTelemetrySnapshot.receivedTotal or 0),
        tostring(type(clearedTelemetrySnapshot) == "table" and clearedTelemetrySnapshot.rejectedTotal or 0),
        tostring(type(clearedTelemetrySnapshot) == "table" and clearedTelemetrySnapshot.staleSessionBoundDropTotal or 0),
        tostring(type(clearedTelemetrySnapshot) == "table" and clearedTelemetrySnapshot.handlerErrorTotal or 0),
      }, "/"))
      addCheck("transport inbound telemetry clears transfer direction", "false//0", table.concat({
        tostring(type(clearedTelemetrySnapshot.activity) == "table"
          and clearedTelemetrySnapshot.activity.active == true),
        tostring(type(clearedTelemetrySnapshot.activity) == "table"
          and clearedTelemetrySnapshot.activity.lastDispatchedSender or ""),
        tostring(type(clearedTelemetrySnapshot.activity) == "table"
          and math.max(0, tonumber(clearedTelemetrySnapshot.activity.messageRatePerSecond) or 0) or 0),
      }, "/"))
    end
  end

  do
    local createInboundRateLimit = INTERNAL_API.LIDCOUNCIL_CreateInboundRateLimitHelpers_Impl
    addCheck("transport inbound rate-limit factory available", true, type(createInboundRateLimit) == "function")
    if type(createInboundRateLimit) == "function" then
      local limiterNow = 100
      local validationRateLimiter = createInboundRateLimit({
        TrimText = TrimText,
        NormalizeCharacterKey = NormalizeCharacterKey,
        GetNow = function()
          return limiterNow
        end,
        Limits = {
          control = { windowSeconds = 2, maxMessages = 2, maxBytes = 2048 },
          bulk = { windowSeconds = 5, maxMessages = 3, maxBytes = 2048 },
          board = { windowSeconds = 5, maxMessages = 2, maxBytes = 2048 },
          maxTrackedSenders = 4,
          retentionSeconds = 30,
        },
      })
      addCheck("transport inbound rate-limit factory creates required operations", true,
        type(validationRateLimiter) == "table"
          and type(validationRateLimiter.Check) == "function"
          and type(validationRateLimiter.Snapshot) == "function"
          and type(validationRateLimiter.Clear) == "function"
          and type(validationRateLimiter.ResolveLane) == "function")
      if type(validationRateLimiter) == "table"
        and type(validationRateLimiter.Check) == "function"
        and type(validationRateLimiter.Snapshot) == "function"
        and type(validationRateLimiter.Clear) == "function"
        and type(validationRateLimiter.ResolveLane) == "function"
      then
        addCheck("transport inbound rate limit classifies board snapshots separately",
          "control/bulk/board/board/control",
          table.concat({
            validationRateLimiter.ResolveLane("START"),
            validationRateLimiter.ResolveLane("PSYNC_CHUNK"),
            validationRateLimiter.ResolveLane("BSYNC_START"),
            validationRateLimiter.ResolveLane("BSYNC_END"),
            validationRateLimiter.ResolveLane("ITEM_OPEN"),
          }, "/"))
        local limiterOutcomes = {
          validationRateLimiter.Check("MemberA-Realm", "START", 10),
          validationRateLimiter.Check("MemberA-Realm", "START", 10),
          validationRateLimiter.Check("MemberA-Realm", "START", 10),
          validationRateLimiter.Check("MemberA-Realm", "PSYNC_CHUNK", 10),
          validationRateLimiter.Check("MemberA-Realm", "PSYNC_CHUNK", 10),
          validationRateLimiter.Check("MemberA-Realm", "PSYNC_CHUNK", 10),
          validationRateLimiter.Check("MemberA-Realm", "PSYNC_CHUNK", 10),
          validationRateLimiter.Check("MemberA-Realm", "BSYNC_START", 10),
          validationRateLimiter.Check("MemberA-Realm", "BSYNC_ITEM", 10),
          validationRateLimiter.Check("MemberA-Realm", "BSYNC_SEL", 10),
          (validationRateLimiter.Check("MemberB-Realm", "START", 10)),
        }
        limiterNow = 103
        limiterOutcomes[#limiterOutcomes + 1] = validationRateLimiter.Check("MemberA-Realm", "START", 10)
        limiterNow = 106
        limiterOutcomes[#limiterOutcomes + 1] = validationRateLimiter.Check("MemberA-Realm", "PSYNC_CHUNK", 10)
        limiterOutcomes[#limiterOutcomes + 1] = validationRateLimiter.Check("MemberA-Realm", "BSYNC_END", 10)
        addCheck("transport inbound rate limit separates sender and traffic windows",
          "true/true/false/true/true/true/false/true/true/false/true/true/true/true",
          table.concat({
            tostring(limiterOutcomes[1]),
            tostring(limiterOutcomes[2]),
            tostring(limiterOutcomes[3]),
            tostring(limiterOutcomes[4]),
            tostring(limiterOutcomes[5]),
            tostring(limiterOutcomes[6]),
            tostring(limiterOutcomes[7]),
            tostring(limiterOutcomes[8]),
            tostring(limiterOutcomes[9]),
            tostring(limiterOutcomes[10]),
            tostring(limiterOutcomes[11]),
            tostring(limiterOutcomes[12]),
            tostring(limiterOutcomes[13]),
            tostring(limiterOutcomes[14]),
          }, "/"))
        local limiterStatus = validationRateLimiter.Snapshot()
        addCheck("transport inbound rate limit reports bounded diagnostics",
          "14/11/3/1/1/1/1/1/1/2/membera-realm/BSYNC_SEL/board",
          table.concat({
            tostring(limiterStatus.checkedTotal),
            tostring(limiterStatus.acceptedTotal),
            tostring(limiterStatus.rateLimitedTotal),
            tostring(type(limiterStatus.rateLimitedByLane) == "table" and limiterStatus.rateLimitedByLane.control or 0),
            tostring(type(limiterStatus.rateLimitedByLane) == "table" and limiterStatus.rateLimitedByLane.bulk or 0),
            tostring(type(limiterStatus.rateLimitedByLane) == "table" and limiterStatus.rateLimitedByLane.board or 0),
            tostring(type(limiterStatus.rateLimitedByKind) == "table" and limiterStatus.rateLimitedByKind.START or 0),
            tostring(type(limiterStatus.rateLimitedByKind) == "table" and limiterStatus.rateLimitedByKind.PSYNC_CHUNK or 0),
            tostring(type(limiterStatus.rateLimitedByKind) == "table" and limiterStatus.rateLimitedByKind.BSYNC_SEL or 0),
            tostring(limiterStatus.trackedSenders),
            tostring(limiterStatus.lastRateLimitedSender),
            tostring(limiterStatus.lastRateLimitedKind),
            tostring(limiterStatus.lastRateLimitedLane),
          }, "/"))
        validationRateLimiter.Clear()
        local clearedLimiterStatus = validationRateLimiter.Snapshot()
        addCheck("transport inbound rate limit clears session counters", "0/0/0/0", table.concat({
          tostring(clearedLimiterStatus.checkedTotal),
          tostring(clearedLimiterStatus.acceptedTotal),
          tostring(clearedLimiterStatus.rateLimitedTotal),
          tostring(clearedLimiterStatus.trackedSenders),
        }, "/"))
      end
    end
  end

  local duplicateDelta = makeItem("PDELTA_REQ", "Member-Realm", {
    sessionId = "validation-session",
    profileName = "Validation",
    profileId = "validation-profile",
    changeId = "delta-1",
    actor = "Actor-Realm",
    domain = "loot",
    action = "upsert",
    sequence = 3,
  }, "delta-payload")
  local duplicateCovered = outboundQueueCoalescing.ResolveQueuedOutboundRequestCoalescing(duplicateDelta, { duplicateDelta })
  addCheck("transport duplicate delta request is coalesced", true, duplicateCovered)

  local retryQueue = { makeItem("PDELTA", "Member-Realm") }
  local fakeTransportOutcomes = { "throttled", "failed", "success" }
  local fakeTransportAttempts = 0
  local finalRetryDecision = nil
  while #retryQueue > 0 and fakeTransportAttempts < #fakeTransportOutcomes do
    local item = table.remove(retryQueue, 1)
    fakeTransportAttempts = fakeTransportAttempts + 1
    finalRetryDecision = INTERNAL_API.LIDCOUNCIL_ResolveOutboundCommRetryDecision_Impl(item, fakeTransportOutcomes[fakeTransportAttempts], {
      maxThrottleRetries = 1,
      maxFailureRetries = 1,
    })
    if finalRetryDecision.retry then
      outboundQueueSelection.InsertOutboundCommQueueItem(item, true, retryQueue)
    end
  end
  addCheck("transport fake send retries throttle and failure", 3, fakeTransportAttempts)
  addCheck("transport fake send eventually succeeds", "sent", TrimText(type(finalRetryDecision) == "table" and finalRetryDecision.outcome or ""))
  addCheck("transport fake send drains isolated queue", 0, #retryQueue)
  local terminalFailure = makeItem("PDELTA", "Member-Realm")
  local terminalFailureDecision = INTERNAL_API.LIDCOUNCIL_ResolveOutboundCommRetryDecision_Impl(terminalFailure, "failed", {
    maxFailureRetries = 0,
    maxThrottleRetries = 0,
  })
  addCheck("transport failure retry budget terminates", "failed", terminalFailureDecision.outcome)
  addCheck("transport failure retry count is retained", 1, terminalFailure.failureRetryCount)

  local acknowledgementTransfer = {
    target = "Member-Realm",
    state = "waiting_ack",
    mode = "APPLY",
    sessionId = "validation-session",
    profileName = "Validation",
    profileId = "validation-profile",
    generation = 4,
    totalChunks = 12,
  }
  local acknowledgementAccepted, acknowledgementTimeout, acknowledgementSender = INTERNAL_API.LIDCOUNCIL_ValidateOutboundProfileTransferAcknowledgement_Impl(
    acknowledgementTransfer,
    "Member-Realm",
    "validation-session",
    "Validation",
    4,
    "validation-profile",
    12
  )
  addCheck("transport ACK accepts matching transfer", true, acknowledgementAccepted)
  addCheck("transport ACK normalizes matching sender", "Member-Realm", acknowledgementSender)
  addCheck("transport ACK is not late before timeout", false, acknowledgementTimeout)
  local staleAcknowledgement, staleReason = INTERNAL_API.LIDCOUNCIL_ValidateOutboundProfileTransferAcknowledgement_Impl(
    acknowledgementTransfer,
    "Member-Realm",
    "validation-session",
    "Validation",
    3,
    "validation-profile",
    12
  )
  addCheck("transport ACK rejects stale generation", false, staleAcknowledgement)
  addCheck("transport ACK stale generation reason", "outbound_transfer_generation_stale", staleReason)
  local futureAcknowledgement, futureReason = INTERNAL_API.LIDCOUNCIL_ValidateOutboundProfileTransferAcknowledgement_Impl(
    acknowledgementTransfer,
    "Member-Realm",
    "validation-session",
    "Validation",
    5,
    "validation-profile",
    12
  )
  addCheck("transport ACK rejects future generation", false, futureAcknowledgement)
  addCheck("transport ACK future generation reason", "outbound_transfer_generation_mismatch", futureReason)
  local wrongProfileAcknowledgement, wrongProfileReason = INTERNAL_API.LIDCOUNCIL_ValidateOutboundProfileTransferAcknowledgement_Impl(
    acknowledgementTransfer,
    "Member-Realm",
    "validation-session",
    "Validation",
    4,
    "other-profile",
    12
  )
  addCheck("transport ACK rejects different profile identity", false, wrongProfileAcknowledgement)
  addCheck("transport ACK profile identity reason", "outbound_transfer_profile_id_mismatch", wrongProfileReason)
  local wrongChunkAcknowledgement, wrongChunkReason = INTERNAL_API.LIDCOUNCIL_ValidateOutboundProfileTransferAcknowledgement_Impl(
    acknowledgementTransfer,
    "Member-Realm",
    "validation-session",
    "Validation",
    4,
    "validation-profile",
    11
  )
  addCheck("transport ACK rejects different transaction size", false, wrongChunkAcknowledgement)
  addCheck("transport ACK transaction size reason", "outbound_transfer_chunk_count_mismatch", wrongChunkReason)
  local legacyAcknowledgement = INTERNAL_API.LIDCOUNCIL_ValidateOutboundProfileTransferAcknowledgement_Impl(
    acknowledgementTransfer,
    "Member-Realm",
    "validation-session",
    "Validation",
    0,
    "",
    0
  )
  addCheck("transport ACK accepts legacy empty correlation metadata", true, legacyAcknowledgement)
  local foreignAcknowledgement, foreignReason = INTERNAL_API.LIDCOUNCIL_ValidateOutboundProfileTransferAcknowledgement_Impl(
    acknowledgementTransfer,
    "Other-Realm",
    "validation-session",
    "Validation",
    4,
    "validation-profile",
    12
  )
  addCheck("transport ACK rejects foreign member", false, foreignAcknowledgement)
  addCheck("transport ACK foreign member reason", "outbound_transfer_target_mismatch", foreignReason)

  local timeoutTransfer = {
    state = "waiting_ack",
    completedAt = 100,
  }
  local timeoutEarly, timeoutEarlyReason = INTERNAL_API.LIDCOUNCIL_GetOutboundProfileAckTimeoutTransition_Impl(
    timeoutTransfer,
    timeoutTransfer.completedAt + COMM_LIMITS.PROFILE_ACK_TIMEOUT_SECONDS - 1
  )
  addCheck("transport ACK timeout waits for full deadline", false, timeoutEarly)
  addCheck("transport ACK timeout early reason", "timeout_not_reached", timeoutEarlyReason)
  local timeoutDue, timeoutDueReason = INTERNAL_API.LIDCOUNCIL_GetOutboundProfileAckTimeoutTransition_Impl(
    timeoutTransfer,
    timeoutTransfer.completedAt + COMM_LIMITS.PROFILE_ACK_TIMEOUT_SECONDS
  )
  addCheck("transport ACK timeout fires at deadline", true, timeoutDue)
  addCheck("transport ACK timeout due reason", "ack_timeout_due", timeoutDueReason)
  local missingCompletionTimeout, missingCompletionReason = INTERNAL_API.LIDCOUNCIL_GetOutboundProfileAckTimeoutTransition_Impl({
    state = "waiting_ack",
    completedAt = 0,
  }, 220)
  addCheck("transport ACK timeout requires completed transfer", false, missingCompletionTimeout)
  addCheck("transport ACK timeout missing completion reason", "missing_completed_at", missingCompletionReason)
  local queuedApplyTimeout, queuedApplyTimeoutReason = INTERNAL_API.LIDCOUNCIL_GetOutboundProfileAckTimeoutTransition_Impl({
    state = "waiting_apply",
    completedAt = 100,
  }, 500)
  addCheck("transport queued apply suppresses normal ACK timeout", false, queuedApplyTimeout)
  addCheck("transport queued apply timeout suppression reason", "not_waiting_ack", queuedApplyTimeoutReason)
  addCheck("transport missing ACK phase defaults to applied", "APPLIED",
    INTERNAL_API.LIDCOUNCIL_NormalizeCombatSyncAckPhase_Impl(""))
  addCheck("transport queued ACK alias normalizes", "QUEUED",
    INTERNAL_API.LIDCOUNCIL_NormalizeCombatSyncAckPhase_Impl("received_queued"))
  addCheck("transport invalid ACK phase is rejected", "",
    INTERNAL_API.LIDCOUNCIL_NormalizeCombatSyncAckPhase_Impl("invalid"))

  timeoutTransfer.state = "ack_timeout"
  local reconciliationDue, reconciliationDueReason = INTERNAL_API.LIDCOUNCIL_GetOutboundProfileAckReconciliationDispatch_Impl(timeoutTransfer)
  addCheck("transport ACK timeout dispatches one reconciliation", true, reconciliationDue)
  addCheck("transport ACK timeout reconciliation reason", "reconciliation_due", reconciliationDueReason)
  timeoutTransfer.ackTimeoutRecoveryAttemptedAt = 220
  local repeatReconciliation, repeatReconciliationReason = INTERNAL_API.LIDCOUNCIL_GetOutboundProfileAckReconciliationDispatch_Impl(timeoutTransfer)
  addCheck("transport ACK timeout does not repeat recovery", false, repeatReconciliation)
  addCheck("transport ACK timeout repeated recovery reason", "recovery_already_attempted", repeatReconciliationReason)
  timeoutTransfer.ackTimeoutRecoveryAttemptedAt = nil
  acknowledgementTransfer.state = "ack_timeout"
  local lateAcknowledgement, acknowledgedAfterTimeout = INTERNAL_API.LIDCOUNCIL_ValidateOutboundProfileTransferAcknowledgement_Impl(
    acknowledgementTransfer,
    "Member-Realm",
    "validation-session",
    "Validation",
    4,
    "validation-profile",
    12
  )
  addCheck("transport ACK accepts matching late acknowledgement", true, lateAcknowledgement)
  addCheck("transport ACK marks matching acknowledgement late", true, acknowledgedAfterTimeout)

  return passedCount == #checks, {
    suite = "comm_outbound_transport",
    version = 52,
    total = #checks,
    passed = passedCount,
    failed = #checks - passedCount,
    checks = checks,
  }
end

INTERNAL_API.LIDCOUNCIL_BuildRollOptionFields_Impl = payloadCodec.BuildRollOptionFields
INTERNAL_API.LIDCOUNCIL_ParseRollOptionFields_Impl = payloadCodec.ParseRollOptionFields

local identityHelpers = type(INTERNAL_API.LIDCOUNCIL_CreateLootSessionIdentityHelpers_Impl) == "function"
  and INTERNAL_API.LIDCOUNCIL_CreateLootSessionIdentityHelpers_Impl({
    TrimText = TrimText,
    NormalizeCharacterKey = NormalizeCharacterKey,
  })
  or nil
if type(identityHelpers) ~= "table" then
  error("LidCouncil missing loot session identity helpers.")
end

local outboundDiagnostics = type(INTERNAL_API.LIDCOUNCIL_CreateOutboundDiagnosticsHelpers_Impl) == "function"
  and INTERNAL_API.LIDCOUNCIL_CreateOutboundDiagnosticsHelpers_Impl({
    Stats = outboundCommStats,
    TrimText = TrimText,
    NormalizeCharacterKey = NormalizeCharacterKey,
    GetNow = GetNow,
    GetActiveSessionId = function()
      local activeSession = type(commApi.GetActiveLootSession) == "function" and commApi.GetActiveLootSession() or nil
      return TrimText(type(activeSession) == "table" and activeSession.id or "")
    end,
    RecordOpcodeTelemetry = function(item, event, payloadBytes)
      return INTERNAL_API.LIDCOUNCIL_RecordOutboundCommOpcodeTelemetry_Impl(item, event, payloadBytes)
    end,
  })
  or nil
if type(outboundDiagnostics) ~= "table"
  or type(outboundDiagnostics.GetOutboundIssueDiagnosticsForSession) ~= "function"
  or type(outboundDiagnostics.RecordOutboundFailureDiagnostic) ~= "function"
  or type(outboundDiagnostics.RecordOutboundPayloadReject) ~= "function"
  or type(outboundDiagnostics.RecordOutboundDiagnosticResolved) ~= "function"
then
  error("LidCouncil missing outbound diagnostics helpers.")
end
INTERNAL_API.LIDCOUNCIL_GetOutboundIssueDiagnosticsForSession_Impl = outboundDiagnostics.GetOutboundIssueDiagnosticsForSession
INTERNAL_API.LIDCOUNCIL_RecordOutboundFailureDiagnostic_Impl = outboundDiagnostics.RecordOutboundFailureDiagnostic
INTERNAL_API.LIDCOUNCIL_RecordOutboundPayloadReject_Impl = outboundDiagnostics.RecordOutboundPayloadReject
INTERNAL_API.LIDCOUNCIL_RecordOutboundDiagnosticResolved_Impl = outboundDiagnostics.RecordOutboundDiagnosticResolved

local function SendComm(kind, channel, target, ...)
  local fieldCount = 1 + select("#", ...)
  local fieldAccepted, fieldReason = ValidateCommProtocolFieldCount(kind, fieldCount)
  if not fieldAccepted then
    INTERNAL_API.LIDCOUNCIL_RecordOutboundPayloadReject_Impl(kind, fieldReason, 0)
    if fieldReason == "field_count_exceeds_limit" then
      outboundCommStats.rejectedProtocolFieldTotal = math.max(0, tonumber(outboundCommStats.rejectedProtocolFieldTotal) or 0) + 1
      WarnCommIssue(kind, "Skipped an addon message with too many protocol fields.")
      return false, "Addon message exceeds the supported protocol field count."
    end
    outboundCommStats.rejectedProtocolMinimumTotal = math.max(0, tonumber(outboundCommStats.rejectedProtocolMinimumTotal) or 0) + 1
    outboundCommStats.lastRejectedProtocolMinimumKind = TrimText(kind)
    WarnCommIssue(kind, "Skipped an addon message below the opcode field minimum.")
    return false, "Addon message is missing required protocol fields."
  end
  if not EnsurePrefixRegistered() then
    INTERNAL_API.LIDCOUNCIL_RecordOutboundCommOpcodeTelemetry_Impl({ kind = kind }, "failed", 0)
    INTERNAL_API.LIDCOUNCIL_RecordOutboundFailureDiagnostic_Impl("api_failure", kind, "addon_prefix_not_registered", 0)
    return false, "Addon message prefix is not registered."
  end
  if type(C_ChatInfo) ~= "table" or type(C_ChatInfo.SendAddonMessage) ~= "function" then
    INTERNAL_API.LIDCOUNCIL_RecordOutboundCommOpcodeTelemetry_Impl({ kind = kind }, "failed", 0)
    INTERNAL_API.LIDCOUNCIL_RecordOutboundFailureDiagnostic_Impl("api_failure", kind, "addon_message_api_unavailable", 0)
    return false, "Addon message API is unavailable."
  end

  local distribution = TrimText(channel)
  if distribution == "" then
    return false, "No addon message channel was provided."
  end

  local targetName = nil
  if distribution == "WHISPER" then
    targetName = NormalizeCharacterKey(target)
    if targetName == "" then
      return false, "Whisper target is missing."
    end
  end

  local metadata = BuildOutboundCommMetadata(kind, distribution, targetName, ...)
  if type(metadata) == "table" and TrimText(kind) == "PSYNC_CHUNK" then
    metadata.chunkIndex = tonumber((select(2, ...))) or 0
  end
  local sessionQueueReady, sessionQueueIdOrError = INTERNAL_API.LIDCOUNCIL_PrepareOutboundProfileSyncSessionQueue_Impl(kind, metadata)
  if not sessionQueueReady then
    return false, sessionQueueIdOrError
  end
  INTERNAL_API.LIDCOUNCIL_EnsureOutboundSessionTelemetryBaseline_Impl(sessionQueueIdOrError)
  local payload = BuildPayload(kind, ...)
  if type(metadata) == "table" then
    metadata.payloadBytes = #payload
    metadata.payloadBudget = COMM_SAFE_PAYLOAD_LIMIT
  end
  if #payload > COMM_SAFE_PAYLOAD_LIMIT then
    INTERNAL_API.LIDCOUNCIL_RecordOutboundPayloadReject_Impl(kind, "payload_exceeds_safe_limit", #payload, metadata)
    WarnCommIssue(kind, "Skipped an oversized LidCouncil addon message.")
    return false, "Payload exceeds safe addon message length."
  end

  return QueueAddonPayload(kind, distribution, targetName, payload, metadata)
end

local CreateProfileSyncHelpers = INTERNAL_API.LIDCOUNCIL_CreateLootSessionProfileSyncHelpers_Impl
if type(CreateProfileSyncHelpers) ~= "function" then
  error("LidCouncil missing loot session profile sync helpers.")
end

local CreateProfileSyncStateStore = INTERNAL_API.LIDCOUNCIL_CreateProfileSyncStateStore_Impl
if type(CreateProfileSyncStateStore) ~= "function" then
  error("LidCouncil missing profile sync state store helpers.")
end

local profileSyncStateStore = CreateProfileSyncStateStore({
  RootDB = commApi.RootDB,
  TrimText = TrimText,
  DeepCopy = DeepCopy,
  NormalizeCharacterKey = NormalizeCharacterKey,
  ExportLootProfileSnapshot = commApi.ExportLootProfileSnapshot,
  ImportLootProfileSnapshot = commApi.ImportLootProfileSnapshot,
})

local profileSyncDevHarness = (function()
  local createHarness = INTERNAL_API.LIDCOUNCIL_CreateProfileSyncDevHarness_Impl
  if type(createHarness) ~= "function" then
    error("LidCouncil missing profile sync developer harness helpers.")
  end
  return createHarness({
    RootDB = commApi.RootDB,
    Print = commApi.Print,
    TrimText = TrimText,
    DeepCopy = DeepCopy,
    GetCharacterKey = commApi.GetCharacterKey,
    GetLocalAutoPassEnabled = commApi.GetLocalAutoPassEnabled,
    GetActiveLootSession = commApi.GetActiveLootSession,
    GetLootProfile = commApi.GetLootProfile,
    GetLootProfileId = commApi.GetLootProfileId,
    GetLootProfileRevisionSummary = commApi.GetLootProfileRevisionSummary,
    BuildLootProfileCurrentSessionChecksumSource = commApi.BuildLootProfileCurrentSessionChecksumSource,
    BuildLootProfileLiveBoardSnapshotChecksumSource = commApi.BuildLootProfileLiveBoardSnapshotChecksumSource,
    BuildLootProfileLiveBoardChecksumSource = commApi.BuildLootProfileLiveBoardChecksumSource,
    CalculateStableChecksum = commApi.CalculateStableChecksum,
    ExportLootProfileSnapshot = commApi.ExportLootProfileSnapshot,
    ExportLootProfileDomainSnapshot = commApi.ExportLootProfileDomainSnapshot,
    ExportLootProfileSubdomainSnapshot = commApi.ExportLootProfileSubdomainSnapshot,
    ImportLootProfileSnapshot = commApi.ImportLootProfileSnapshot,
    ImportLootProfileDomainSnapshot = commApi.ImportLootProfileDomainSnapshot,
    ImportLootProfileSubdomainSnapshot = commApi.ImportLootProfileSubdomainSnapshot,
    PreviewLootProfileSnapshot = commApi.PreviewLootProfileSnapshot,
    PreviewLootProfileDomainSnapshot = commApi.PreviewLootProfileDomainSnapshot,
    PreviewLootProfileSubdomainSnapshot = commApi.PreviewLootProfileSubdomainSnapshot,
    BuildLootProfileSnapshotDiff = commApi.BuildLootProfileSnapshotDiff,
    BuildLootProfileDomainSnapshotDiff = commApi.BuildLootProfileDomainSnapshotDiff,
    BuildLootProfileSubdomainSnapshotDiff = commApi.BuildLootProfileSubdomainSnapshotDiff,
    BuildLootProfileTransferConflictPreview = commApi.BuildLootProfileTransferConflictPreview,
    ApplyLootProfileTransferConflictResolution = commApi.ApplyLootProfileTransferConflictResolution,
    GetLootProfileSubchecksumManifest = commApi.GetLootProfileSubchecksumManifest,
    FilterLootProfilePatchCapableSubdomains = commApi.FilterLootProfilePatchCapableSubdomains,
    GetLootProfileSubdomainLabel = commApi.GetLootProfileSubdomainLabel,
    GetLootProfileSubdomainParentDomain = commApi.GetLootProfileSubdomainParentDomain,
    ResolveLootProfileDomainsForSubdomains = commApi.ResolveLootProfileDomainsForSubdomains,
    ValidateSimulationVoteExclusion = commApi.ValidateSimulationVoteExclusion,
    TouchLootProfileDomain = commApi.TouchLootProfileDomain,
    GetProfileSyncEstimate = GetProfileSyncEstimate,
    GetProfileSyncTuning = GetProfileSyncTuning,
    RunCommProtocolValidation = RunCommProtocolValidation,
    RunCommOutboundTransportValidation = INTERNAL_API.LIDCOUNCIL_RunCommOutboundTransportValidation_Impl,
    RunAsymmetricCombatSyncValidation = INTERNAL_API.LIDCOUNCIL_RunAsymmetricCombatSyncValidation_Impl,
    RunCombatSyncInboxValidation = INTERNAL_API.LIDCOUNCIL_RunCombatSyncInboxValidation_Impl,
    ClearIncomingProfileSyncsForSession = INTERNAL_API.LIDCOUNCIL_ClearIncomingProfileSyncsForSession_Impl,
    ResolveIncomingProfileSyncTransfer = INTERNAL_API.LIDCOUNCIL_ResolveIncomingProfileSyncTransfer_Impl,
    FinalizeIncomingProfileSyncSessionState = INTERNAL_API.LIDCOUNCIL_FinalizeIncomingProfileSyncSessionState_Impl,
    GetIncomingProfileSyncHealth = INTERNAL_API.LIDCOUNCIL_GetIncomingProfileSyncHealth_Impl,
    CompareMemberPayloadSyncState = function(...)
      local compare = INTERNAL_API.LIDCOUNCIL_CompareMemberPayloadSyncState
      if type(compare) ~= "function" then
        return nil
      end
      return compare(...)
    end,
    RecordIncomingSnapshotReject = INTERNAL_API.LIDCOUNCIL_RecordIncomingSnapshotReject_Impl,
    BeginIncomingSnapshotDiagnosticsForSession = INTERNAL_API.LIDCOUNCIL_BeginIncomingSnapshotDiagnosticsForSession_Impl,
    ResolvePreciseRequestLifecycle = INTERNAL_API.LIDCOUNCIL_ResolvePreciseRequestLifecycle_Impl,
    BuildAlignedReplicaArchivePlan = INTERNAL_API.LIDCOUNCIL_BuildAlignedReplicaArchivePlan_Impl,
    ResolveAlignedReplicaPreciseProofAction = INTERNAL_API.LIDCOUNCIL_ResolveAlignedReplicaPreciseProofAction_Impl,
    ResolveJoinManifestProofPoll = INTERNAL_API.LIDCOUNCIL_ResolveJoinManifestProofPoll_Impl,
    BuildJoinManifestProofIdentity = INTERNAL_API.LIDCOUNCIL_BuildJoinManifestProofIdentity_Impl,
    ResolveJoinManifestProofRequest = INTERNAL_API.LIDCOUNCIL_ResolveJoinManifestProofRequest_Impl,
    ResolveHostMemberP2ProofDiagnostics = INTERNAL_API.LIDCOUNCIL_ResolveHostMemberP2ProofDiagnostics_Impl,
    ProjectPreciseRequestState = INTERNAL_API.LIDCOUNCIL_ProjectPreciseRequestState_Impl,
    AdvancePreciseRequestProgress = INTERNAL_API.LIDCOUNCIL_AdvancePreciseRequestProgress_Impl,
    RecordPreciseMultipartPart = INTERNAL_API.LIDCOUNCIL_RecordPreciseMultipartPart_Impl,
    IsJoinManifestPreciseProofReady = INTERNAL_API.LIDCOUNCIL_IsJoinManifestPreciseProofReady_Impl,
    ResolveJoinManifestValidationState = INTERNAL_API.LIDCOUNCIL_ResolveJoinManifestValidationState_Impl,
    BuildProfileSyncArchiveScopeChecksums = function(...)
      local build = type(profileSyncHelpers) == "table" and profileSyncHelpers.BuildProfileSyncArchiveScopeChecksums or nil
      if type(build) ~= "function" then
        return {}
      end
      return build(...)
    end,
    BuildItemHistoryDifferenceDiagnostics = function(...)
      local build = type(profileSyncHelpers) == "table" and profileSyncHelpers.BuildItemHistoryDifferenceDiagnostics or nil
      if type(build) ~= "function" then
        return {}
      end
      return build(...)
    end,
    BuildSessionHistoryDifferenceDiagnostics = function(...)
      local build = type(profileSyncHelpers) == "table" and profileSyncHelpers.BuildSessionHistoryDifferenceDiagnostics or nil
      if type(build) ~= "function" then
        return {}
      end
      return build(...)
    end,
    BuildLootListDifferenceDiagnostics = function(...)
      local build = type(profileSyncHelpers) == "table" and profileSyncHelpers.BuildLootListDifferenceDiagnostics or nil
      if type(build) ~= "function" then
        return {}
      end
      return build(...)
    end,
    ApplyJoinManifestValidationToStatusMatrix = INTERNAL_API.LIDCOUNCIL_ApplyJoinManifestValidationToStatusMatrix_Impl,
    ValidateReadinessProofLifecycle = function(...)
      local validate = INTERNAL_API.LIDCOUNCIL_ValidateReadinessProofLifecycle_Impl
      if type(validate) ~= "function" then
        return nil
      end
      return validate(...)
    end,
    ShouldSuppressLocalProfileStateSend = INTERNAL_API.LIDCOUNCIL_ShouldSuppressLocalProfileStateSend_Impl,
    RecordRepairHistory = profileSyncStateStore.RecordRepairHistory,
    PushUndoSnapshot = profileSyncStateStore.PushUndoSnapshot,
    PROFILE_BOOTSTRAP_DOMAINS = { "settings", "permissions" },
    PROFILE_BACKGROUND_SYNC_DOMAINS = { "loot", "session" },
  })
end)()

local commPublicApi = {}

function commPublicApi.GetDeveloperSyntheticHarnessSessionContext()
  if type(profileSyncDevHarness) ~= "table" or type(profileSyncDevHarness.GetSyntheticSessionContext) ~= "function" then
    return nil
  end
  local activeSession = type(commApi.GetActiveLootSession) == "function" and commApi.GetActiveLootSession() or nil
  if type(activeSession) == "table" then
    return nil
  end
  return profileSyncDevHarness.GetSyntheticSessionContext()
end

function commPublicApi.IsDeveloperSyntheticHarnessActive()
  local context = commPublicApi.GetDeveloperSyntheticHarnessSessionContext()
  return type(context) == "table" and context.active == true
end

function commPublicApi.PushActiveProfileSnapshotFlow(targetMemberKey, options)
  if commPublicApi.IsDeveloperSyntheticHarnessActive() and type(profileSyncDevHarness.PushSyntheticRepair) == "function" then
    return profileSyncDevHarness.PushSyntheticRepair(targetMemberKey, options)
  end
  return flowHelpers.PushActiveProfileSnapshotFlow(targetMemberKey, options)
end

function commPublicApi.PushProfileHostOverrideFlow(targetMemberKey, requestedScopes)
  if commPublicApi.IsDeveloperSyntheticHarnessActive() then
    return false, { error = "Host overrides require a real active loot session." }
  end
  return flowHelpers.PushProfileHostOverrideFlow(targetMemberKey, requestedScopes)
end

function commPublicApi.RequestActiveProfileSubchecksumFlow(targetMemberKey)
  if commPublicApi.IsDeveloperSyntheticHarnessActive() and type(profileSyncDevHarness.RequestSyntheticSubchecks) == "function" then
    return profileSyncDevHarness.RequestSyntheticSubchecks(targetMemberKey)
  end
  return flowHelpers.RequestActiveProfileSubchecksumFlow(targetMemberKey)
end

function commPublicApi.RefreshActiveSessionReadinessFlow()
  if commPublicApi.IsDeveloperSyntheticHarnessActive() then
    return false, "Readiness refresh requires a real active loot session."
  end
  return flowHelpers.RefreshActiveSessionReadinessFlow()
end

function commPublicApi.RequestActiveProfileSnapshotFlow(targetMemberKey, options)
  if commPublicApi.IsDeveloperSyntheticHarnessActive() then
    local mode = string.upper(TrimText(type(options) == "table" and options.mode or ""))
    if mode == "PREVIEW" and type(profileSyncDevHarness.RequestSyntheticSnapshot) == "function" then
      return profileSyncDevHarness.RequestSyntheticSnapshot(targetMemberKey, options)
    end
    if type(profileSyncDevHarness.PullSyntheticRepair) == "function" then
      return profileSyncDevHarness.PullSyntheticRepair(targetMemberKey, options)
    end
  end
  return flowHelpers.RequestActiveProfileSnapshotFlow(targetMemberKey, options)
end

function commPublicApi.GetActiveProfileSyncCandidates()
  if commPublicApi.IsDeveloperSyntheticHarnessActive() and type(profileSyncDevHarness.GetSyntheticSyncCandidates) == "function" then
    return profileSyncDevHarness.GetSyntheticSyncCandidates()
  end
  return profileSyncHelpers.GetActiveProfileSyncCandidates()
end

function commPublicApi.GetMemberItemHistoryDifferenceDiagnostics(sessionId, memberKey)
  if type(profileSyncHelpers.GetMemberItemHistoryDifferenceDiagnostics) ~= "function" then
    return nil
  end
  return profileSyncHelpers.GetMemberItemHistoryDifferenceDiagnostics(sessionId, memberKey)
end

function commPublicApi.GetMemberLootListDifferenceDiagnostics(sessionId, memberKey)
  if type(profileSyncHelpers.GetMemberLootListDifferenceDiagnostics) ~= "function" then
    return nil
  end
  return profileSyncHelpers.GetMemberLootListDifferenceDiagnostics(sessionId, memberKey)
end

function commPublicApi.GetMemberSessionHistoryDifferenceDiagnostics(sessionId, memberKey)
  if type(profileSyncHelpers.GetMemberSessionHistoryDifferenceDiagnostics) ~= "function" then
    return nil
  end
  return profileSyncHelpers.GetMemberSessionHistoryDifferenceDiagnostics(sessionId, memberKey)
end

function commPublicApi.GetActiveProfileSyncStatus(precomputedCandidates)
  if commPublicApi.IsDeveloperSyntheticHarnessActive() and type(profileSyncDevHarness.GetSyntheticSyncStatus) == "function" then
    return profileSyncDevHarness.GetSyntheticSyncStatus(precomputedCandidates)
  end
  return profileSyncHelpers.GetActiveProfileSyncStatus(precomputedCandidates)
end

function commPublicApi.GetActiveProfileSyncConflictPreview(memberKey)
  if commPublicApi.IsDeveloperSyntheticHarnessActive() and type(profileSyncDevHarness.GetSyntheticConflictPreview) == "function" then
    return profileSyncDevHarness.GetSyntheticConflictPreview(memberKey)
  end
  return profileSyncHelpers.GetActiveProfileSyncConflictPreview(memberKey)
end

function commPublicApi.ApplyActiveProfilePreviewConflictResolution(memberKey, resolution)
  if commPublicApi.IsDeveloperSyntheticHarnessActive() and type(profileSyncDevHarness.ApplySyntheticConflictResolution) == "function" then
    return profileSyncDevHarness.ApplySyntheticConflictResolution(memberKey, resolution)
  end
  return profileSyncHelpers.ApplyActiveProfilePreviewConflictResolution(memberKey, resolution)
end

profileSyncHelpers = CreateProfileSyncHelpers({
  RootDB = commApi.RootDB,
  Print = commApi.Print,
  DeepCopy = DeepCopy,
  TrimText = TrimText,
  NormalizeCharacterKey = NormalizeCharacterKey,
  FirstNonEmptyText = FirstNonEmptyText,
  CloneProfileSyncDomainList = CloneProfileSyncDomainList,
  RecordProfileSyncDecision = RecordProfileSyncDecision,
  BeginSyncPerformanceSample = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl,
  RecordSyncPerformance = INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl,
  RecordInboundCommReject = inboundCommOps.recordRejected,
  SetProfileSyncRuntimeState = SetProfileSyncRuntimeState,
  profileSyncRuntimeState = profileSyncRuntimeState,
  PROFILE_REVISION_DOMAINS = PROFILE_REVISION_DOMAINS,
  PROFILE_REVISION_DOMAIN_LABELS = PROFILE_REVISION_DOMAIN_LABELS,
  GetCharacterKey = commApi.GetCharacterKey,
  GetActiveLootSession = commApi.GetActiveLootSession,
  GetLootProfileId = commApi.GetLootProfileId,
  FindLootProfileNameById = commApi.FindLootProfileNameById,
  GetLootProfileRevisionSummary = commApi.GetLootProfileRevisionSummary,
  ExportLootProfileSnapshot = commApi.ExportLootProfileSnapshot,
  ExportLootProfileDomainSnapshot = commApi.ExportLootProfileDomainSnapshot,
  ExportLootProfileSubdomainSnapshot = commApi.ExportLootProfileSubdomainSnapshot,
  ExportLootProfileSubdomainPatch = commApi.ExportLootProfileSubdomainPatch,
  ExportLootProfileConflictRowPatch = commApi.ExportLootProfileConflictRowPatch,
  ExportLootProfileSubdomainPatchManifest = commApi.ExportLootProfileSubdomainPatchManifest,
  ImportLootProfileSnapshot = commApi.ImportLootProfileSnapshot,
  ImportLootProfileDomainSnapshot = commApi.ImportLootProfileDomainSnapshot,
  ImportLootProfileSubdomainSnapshot = commApi.ImportLootProfileSubdomainSnapshot,
  ImportLootProfileSubdomainPatch = commApi.ImportLootProfileSubdomainPatch,
  ImportLootProfileConflictRowPatch = commApi.ImportLootProfileConflictRowPatch,
  PreviewLootProfileSnapshot = commApi.PreviewLootProfileSnapshot,
  PreviewLootProfileDomainSnapshot = commApi.PreviewLootProfileDomainSnapshot,
  PreviewLootProfileSubdomainSnapshot = commApi.PreviewLootProfileSubdomainSnapshot,
  PreviewLootProfileSubdomainPatch = commApi.PreviewLootProfileSubdomainPatch,
  PreviewLootProfileConflictRowPatch = commApi.PreviewLootProfileConflictRowPatch,
  PreviewLootProfileSubdomainPatchManifest = commApi.PreviewLootProfileSubdomainPatchManifest,
  BuildLootProfileSnapshotDiff = commApi.BuildLootProfileSnapshotDiff,
  BuildLootProfileDomainSnapshotDiff = commApi.BuildLootProfileDomainSnapshotDiff,
  BuildLootProfileSubdomainSnapshotDiff = commApi.BuildLootProfileSubdomainSnapshotDiff,
  BuildLootProfileSubdomainPatchDiff = commApi.BuildLootProfileSubdomainPatchDiff,
  BuildLootProfileConflictRowPatchDiff = commApi.BuildLootProfileConflictRowPatchDiff,
  BuildLootProfileTransferConflictPreview = commApi.BuildLootProfileTransferConflictPreview,
  ApplyLootProfileTransferConflictResolution = commApi.ApplyLootProfileTransferConflictResolution,
  CalculateStableChecksum = commApi.CalculateStableChecksum,
  GetLootProfileSubchecksumManifest = commApi.GetLootProfileSubchecksumManifest,
  NormalizeLootProfileSubdomainList = commApi.NormalizeLootProfileSubdomainList,
  CloneLootProfileSubdomainList = commApi.CloneLootProfileSubdomainList,
  FilterLootProfilePatchCapableSubdomains = commApi.FilterLootProfilePatchCapableSubdomains,
  GetLootProfileSubdomainKeysForDomain = commApi.GetLootProfileSubdomainKeysForDomain,
  GetLootProfileSubdomainLabel = commApi.GetLootProfileSubdomainLabel,
  GetLootProfileSubdomainParentDomain = commApi.GetLootProfileSubdomainParentDomain,
  ResolveLootProfileDomainsForSubdomains = commApi.ResolveLootProfileDomainsForSubdomains,
  SendComm = SendComm,
  BuildCommProtocolMarker = BuildCommProtocolMarker,
  MarkOutboundProfileTransferAcked = MarkOutboundProfileTransferAcked,
  MarkOutboundProfileTransferQueued = INTERNAL_API.LIDCOUNCIL_MarkOutboundProfileTransferQueued_Impl,
  AnnotateOutboundProfileTransfer = AnnotateOutboundProfileTransfer,
  IsActiveSessionHostSender = identityHelpers.IsActiveSessionHostSender,
  IsJoinedSessionCharacter = identityHelpers.IsJoinedSessionCharacter,
  IsCurrentGroupCharacter = identityHelpers.IsCurrentGroupCharacter,
  DoesActiveSessionMatch = identityHelpers.DoesActiveSessionMatch,
  RefreshEditor = RefreshEditor,
  RequestSessionEditorRefresh = INTERNAL_API.LIDCOUNCIL_RequestSessionEditorRefresh,
  RefreshEditorForCurrentAndSyncSections = INTERNAL_API.LIDCOUNCIL_RefreshEditorForCurrentAndSyncSections,
  RefreshEditorForSyncManagementSection = INTERNAL_API.LIDCOUNCIL_RefreshEditorForSyncManagementSection,
  ResolveOptionalApiFunction = ResolveOptionalApiFunction,
  GetLootProfile = commApi.GetLootProfile,
  GetLootProfileRole = commApi.GetLootProfileRole,
  GetLootProfileMaster = commApi.GetLootProfileMaster,
  NormalizeLootRollOptions = NormalizeLootRollOptions,
  UpsertLootSessionMember = commApi.UpsertLootSessionMember,
  RememberPersistedMemberBaseline = profileSyncStateStore.RememberPersistedMemberBaseline,
  GetPersistedMemberBaseline = profileSyncStateStore.GetPersistedMemberBaseline,
  RecordRepairHistory = profileSyncStateStore.RecordRepairHistory,
  GetRepairHistory = profileSyncStateStore.GetRepairHistory,
  PushUndoSnapshot = profileSyncStateStore.PushUndoSnapshot,
  GetUndoStatus = profileSyncStateStore.GetUndoStatus,
  UndoLastRepair = profileSyncStateStore.UndoLastRepair,
  GetProfileSnapshotChunkSize = GetProfileSnapshotChunkSize,
  SplitProfileSnapshotPayload = INTERNAL_API.LIDCOUNCIL_SplitProfileSnapshotPayload_Impl,
  ValidateProfileSnapshotStartPayload = INTERNAL_API.LIDCOUNCIL_ValidateProfileSnapshotStartPayload_Impl,
  ValidateCommPayload = INTERNAL_API.LIDCOUNCIL_ValidateCommPayload_Impl,
  SplitCommPayloadField = INTERNAL_API.LIDCOUNCIL_SplitCommPayloadField_Impl,
  BuildPayload = BuildPayload,
  RecordOutboundPayloadReject = INTERNAL_API.LIDCOUNCIL_RecordOutboundPayloadReject_Impl,
  PreviewOutboundProfileTransferGeneration = INTERNAL_API.LIDCOUNCIL_PreviewOutboundProfileTransferGeneration_Impl,
  GetCommOutboundIntervalSeconds = GetCommOutboundIntervalSeconds,
  GetCommOutboundQueueStatus = GetSessionCommQueueStatus,
  CancelQueuedProfileTransfersForScope = CancelQueuedProfileTransfersForScope,
})

local CreateFlowHelpers = INTERNAL_API.LIDCOUNCIL_CreateLootSessionFlowHelpers_Impl
if type(CreateFlowHelpers) ~= "function" then
  error("LidCouncil missing loot session flow helpers.")
end

flowHelpers = CreateFlowHelpers({
  Print = commApi.Print,
  TrimText = TrimText,
  NormalizeCharacterKey = NormalizeCharacterKey,
  NormalizeSenderKey = identityHelpers.NormalizeSenderKey,
  NormalizeEnabledFlag = NormalizeEnabledFlag,
  FirstNonEmptyText = FirstNonEmptyText,
  GetCharacterKey = commApi.GetCharacterKey,
  AddCharacterToList = commApi.AddCharacterToList,
  StartLootSession = commApi.StartLootSession,
  ActivateLootSession = commApi.ActivateLootSession,
  GetActiveLootSession = commApi.GetActiveLootSession,
  GetLootProfile = commApi.GetLootProfile,
  StopLootSession = commApi.StopLootSession,
  JoinLootSession = commApi.JoinLootSession,
  UpsertLootSessionMember = commApi.UpsertLootSessionMember,
  RemoveLootSessionMember = commApi.RemoveLootSessionMember,
  FinishLootSession = commApi.FinishLootSession,
  GetLootProfileRole = commApi.GetLootProfileRole,
  GetLootProfileMaster = commApi.GetLootProfileMaster,
  SyncLootProfilePermissionState = commApi.SyncLootProfilePermissionState,
  EnsureLootProfileMemberRole = commApi.EnsureLootProfileMemberRole,
  TouchLootProfileDomain = commApi.TouchLootProfileDomain,
  GetLocalAutoPassEnabled = commApi.GetLocalAutoPassEnabled,
  SetLocalAutoPassEnabled = commApi.SetLocalAutoPassEnabled,
  GetLootProfileId = commApi.GetLootProfileId,
  FindLootProfileNameById = commApi.FindLootProfileNameById,
  GetLootProfileRevisionSummary = commApi.GetLootProfileRevisionSummary,
  GetMemberPayloadDetails = GetMemberPayloadDetails,
  NormalizeLootRollOptions = NormalizeLootRollOptions,
  RefreshEditor = RefreshEditor,
  GetVisibleEditorRefreshContext = GetVisibleEditorRefreshContext,
  ParseRollOptionFields = INTERNAL_API.LIDCOUNCIL_ParseRollOptionFields_Impl,
  BuildRollOptionFields = INTERNAL_API.LIDCOUNCIL_BuildRollOptionFields_Impl,
  GetGroupDistribution = identityHelpers.GetGroupDistribution,
  CollectGroupCharacterKeys = identityHelpers.CollectGroupCharacterKeys,
  IsCurrentGroupCharacter = identityHelpers.IsCurrentGroupCharacter,
  IsClaimedActorSenderMatch = identityHelpers.IsClaimedActorSenderMatch,
  IsActiveSessionHostSender = identityHelpers.IsActiveSessionHostSender,
  IsJoinedSessionCharacter = identityHelpers.IsJoinedSessionCharacter,
  DoesActiveSessionMatch = identityHelpers.DoesActiveSessionMatch,
  SendComm = SendComm,
  GetCommOutboundQueueStatus = GetSessionCommQueueStatus,
  RecordProfileSyncDecision = RecordProfileSyncDecision,
  SetProfileSyncRuntimeState = SetProfileSyncRuntimeState,
  BuildEmptyRevisionSummary = profileSyncHelpers.BuildEmptyRevisionSummary,
  NormalizeRevisionSummary = profileSyncHelpers.NormalizeRevisionSummary,
  CompareProfileRevisionSummaries = profileSyncHelpers.CompareProfileRevisionSummaries,
  FormatProfileRevisionDomains = profileSyncHelpers.FormatProfileRevisionDomains,
  RememberSharedReplicaPlaceholder = profileSyncHelpers.RememberSharedReplicaPlaceholder,
  ResolveLocalSharedProfileName = profileSyncHelpers.ResolveLocalSharedProfileName,
  PrepareProfileSnapshotTransfer = profileSyncHelpers.PrepareProfileSnapshotTransfer,
  BuildPreparedProfileRepairTransfers = profileSyncHelpers.BuildPreparedProfileRepairTransfers,
  HasLoadedPatchManifestSubdomains = profileSyncHelpers.HasLoadedPatchManifestSubdomains,
  FilterLootProfilePatchCapableSubdomains = commApi.FilterLootProfilePatchCapableSubdomains,
  GetLootProfileSubchecksumManifest = commApi.GetLootProfileSubchecksumManifest,
  GetLootProfileSubdomainKeysForDomain = commApi.GetLootProfileSubdomainKeysForDomain,
  GetLootProfileSubdomainParentDomain = commApi.GetLootProfileSubdomainParentDomain,
  CalculateStableChecksum = commApi.CalculateStableChecksum,
  SendProfilePatchManifestRequests = profileSyncHelpers.SendPatchManifestRequests,
  SendProfileSubdomainPatchManifest = profileSyncHelpers.SendProfileSubdomainPatchManifest,
  SendProfileSubchecksumRequests = profileSyncHelpers.SendProfileSubchecksumRequests,
  GetMemberSubchecksumFreshness = profileSyncHelpers.GetMemberSubchecksumFreshness,
  SendPreparedProfileSnapshot = profileSyncHelpers.SendPreparedProfileSnapshot,
  SendProfileSnapshot = profileSyncHelpers.SendProfileSnapshot,
  SendPreparedProfileSnapshotBatch = profileSyncHelpers.SendPreparedProfileSnapshotBatch,
  SendProfileSnapshotBatch = profileSyncHelpers.SendProfileSnapshotBatch,
  SendLocalProfileStateToHost = profileSyncHelpers.SendLocalProfileStateToHost,
  ScheduleDelayedLocalProfileStateSend = profileSyncHelpers.ScheduleDelayedLocalProfileStateSend,
  MarkArchiveTransferState = profileSyncHelpers.MarkArchiveTransferState,
  CanRetryArchiveTransfer = profileSyncHelpers.CanRetryArchiveTransfer,
  ReconcileMemberArchiveTransactions = profileSyncHelpers.ReconcileMemberArchiveTransactions,
  DelayProfileSnapshotBatchForJoins = profileSyncHelpers.DelayProfileSnapshotBatchForJoins,
  ApplyIncomingLootProfileDelta = commApi.ApplyIncomingLootProfileDelta,
  GetActiveProfileSyncCandidates = profileSyncHelpers.GetActiveProfileSyncCandidates,
  ValidateCommPayload = INTERNAL_API.LIDCOUNCIL_ValidateCommPayload_Impl,
  RecordOutboundPayloadReject = INTERNAL_API.LIDCOUNCIL_RecordOutboundPayloadReject_Impl,
  RecordRepairHistory = profileSyncStateStore.RecordRepairHistory,
  ResolveOptionalApiFunction = ResolveOptionalApiFunction,
  COMM_PROTOCOL_VERSION = COMM_PROTOCOL_VERSION,
  BuildCommProtocolMarker = BuildCommProtocolMarker,
  ParseCommProtocolMarker = ParseCommProtocolMarker,
  ParsePayload = ParsePayload,
})

local function HandleLootRuntimeProtocolPayload(fields, sender)
  local handler = INTERNAL_API.LIDCOUNCIL_HandleLootRuntimeSessionComm_Impl
  if type(handler) ~= "function" then
    error("LidCouncil loot runtime protocol handler is unavailable.")
  end
  return handler(fields, sender)
end

commProtocolHandlerRegistry = {
  START = { owner = "session_flow", handler = flowHelpers.HandleStartInvite },
  IACK = { owner = "session_flow", handler = flowHelpers.HandleInviteAck },
  BEGIN = { owner = "session_flow", handler = flowHelpers.HandleBegin },
  JOIN = { owner = "session_flow", handler = flowHelpers.HandleJoin },
  JACK = { owner = "session_flow", handler = flowHelpers.HandleJoinAck },
  MEMBER = { owner = "session_flow", handler = flowHelpers.HandleMember },
  LOCALAP = { owner = "session_flow", handler = flowHelpers.HandleLocalAutoPass },
  APNOTICE = { owner = "session_flow", handler = flowHelpers.HandleAutoPassNotice },
  DECLINE = { owner = "session_flow", handler = flowHelpers.HandleDecline },
  LEAVE = { owner = "session_flow", handler = flowHelpers.HandleLeave },
  PSTATE = { owner = "session_flow", handler = flowHelpers.HandleProfileState },
  PSTATE_PART = { owner = "session_flow", handler = flowHelpers.HandleProfileStatePart },
  STOP = { owner = "session_flow", handler = flowHelpers.HandleStop },
  STOP_ACK = { owner = "session_flow", handler = flowHelpers.HandleStopAck },
  PSYNC_START = { owner = "profile_sync", handler = profileSyncHelpers.HandleProfileSyncStart },
  PSYNC_REQ = { owner = "profile_sync", handler = profileSyncHelpers.HandleProfileSyncRequest },
  PSYNC_CHUNK = { owner = "profile_sync", handler = profileSyncHelpers.HandleProfileSyncChunk },
  PSYNC_END = { owner = "profile_sync", handler = profileSyncHelpers.HandleProfileSyncEnd },
  PSYNC_ACK = { owner = "profile_sync", handler = profileSyncHelpers.HandleProfileSyncAck },
  PSUB_REQ = { owner = "profile_sync", handler = profileSyncHelpers.HandleProfileSubchecksumRequest },
  PSUB_STATE = { owner = "profile_sync", handler = profileSyncHelpers.HandleProfileSubchecksumState },
  PSUBPATCH_REQ = { owner = "profile_sync", handler = profileSyncHelpers.HandleProfileSubdomainPatchManifestRequest },
  PSUBPATCH_STATE = { owner = "profile_sync", handler = profileSyncHelpers.HandleProfileSubdomainPatchManifestState },
  PDELTA_REQ = { owner = "session_flow", handler = flowHelpers.HandleProfileDeltaRequest },
  PDELTA = { owner = "session_flow", handler = flowHelpers.HandleProfileDelta },
  PDELTA_ACK = { owner = "session_flow", handler = flowHelpers.HandleProfileDeltaAck },
  PDELTA_NACK = { owner = "session_flow", handler = flowHelpers.HandleProfileDeltaNack },
  CHOICE = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  RCHOICE = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  RCHOICE_ACK = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  ITEM_REPORT = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  ITEM_OPEN = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  ITEM_ACK = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  AWARD = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  UNASSIGN = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  TRADE = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  VOTE = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  LL_ADD_REQ = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  LL_ADD = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  LL_DEL_REQ = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  LL_DEL = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  LL_MA_REQ = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  LL_MA = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  LL_NOTE_REQ = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  LL_NOTE = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  LL_CHAR_DEL_REQ = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  LL_CHAR_DEL = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  BSYNC_START = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  BSYNC_ITEM = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  BSYNC_SEL = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  BSYNC_VOTE = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  BSYNC_END = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  BSYNC_MISS = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
  BSYNC_ACK = { owner = "loot_runtime", handler = HandleLootRuntimeProtocolPayload },
}

GetCommProtocolHandlerRegistryStatus = function()
  local contractSnapshot = GetCommProtocolContractSnapshot()
  local registry = type(commProtocolHandlerRegistry) == "table" and commProtocolHandlerRegistry or {}
  local missingHandlers = {}
  local ownerMismatches = {}
  local uncontractedHandlers = {}
  local handlerAvailability = {}
  local handlerCount = 0

  for _, opcode in ipairs(contractSnapshot.opcodes) do
    local contract = contractSnapshot.contracts[opcode] or {}
    local entry = registry[opcode]
    local handlerAvailable = type(entry) == "table" and type(entry.handler) == "function"
    handlerAvailability[opcode] = handlerAvailable
    if handlerAvailable then
      handlerCount = handlerCount + 1
      if TrimText(entry.owner) ~= TrimText(contract.owner) then
        ownerMismatches[#ownerMismatches + 1] = opcode
      end
    else
      missingHandlers[#missingHandlers + 1] = opcode
    end
  end

  for opcode in pairs(registry) do
    if type(contractSnapshot.contracts[opcode]) ~= "table" then
      uncontractedHandlers[#uncontractedHandlers + 1] = opcode
    end
  end
  table.sort(uncontractedHandlers)

  return {
    ready = #missingHandlers == 0 and #ownerMismatches == 0 and #uncontractedHandlers == 0,
    contractCount = contractSnapshot.opcodeCount,
    handlerCount = handlerCount,
    missingCount = #missingHandlers,
    missingHandlers = missingHandlers,
    ownerMismatchCount = #ownerMismatches,
    ownerMismatches = ownerMismatches,
    uncontractedCount = #uncontractedHandlers,
    uncontractedHandlers = uncontractedHandlers,
    handlerAvailability = handlerAvailability,
  }
end

local initialProtocolHandlerStatus = GetCommProtocolHandlerRegistryStatus()
if initialProtocolHandlerStatus.ready ~= true then
  local protocolHandlerProblems = {}
  if (tonumber(initialProtocolHandlerStatus.missingCount) or 0) > 0 then
    protocolHandlerProblems[#protocolHandlerProblems + 1] = "missing "
      .. table.concat(initialProtocolHandlerStatus.missingHandlers or {}, ", ")
  end
  if (tonumber(initialProtocolHandlerStatus.ownerMismatchCount) or 0) > 0 then
    protocolHandlerProblems[#protocolHandlerProblems + 1] = "owner mismatch "
      .. table.concat(initialProtocolHandlerStatus.ownerMismatches or {}, ", ")
  end
  if (tonumber(initialProtocolHandlerStatus.uncontractedCount) or 0) > 0 then
    protocolHandlerProblems[#protocolHandlerProblems + 1] = "uncontracted "
      .. table.concat(initialProtocolHandlerStatus.uncontractedHandlers or {}, ", ")
  end
  WarnCommIssue("PROTOCOL", "LidCouncil protocol handler registry is invalid: " .. table.concat(protocolHandlerProblems, "; "))
end

local eventFrame = CreateFrame("Frame")
eventFrame:RegisterEvent("PLAYER_LOGIN")
eventFrame:RegisterEvent("CHAT_MSG_ADDON")
eventFrame:RegisterEvent("GROUP_ROSTER_UPDATE")
eventFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
eventFrame:RegisterEvent("ADDON_RESTRICTION_STATE_CHANGED")
eventFrame:RegisterEvent("PLAYER_REGEN_ENABLED")
eventFrame:RegisterEvent("ENCOUNTER_END")
-- Register immediately for clients that load LidCouncil after PLAYER_LOGIN.
EnsurePrefixRegistered()
eventFrame:SetScript("OnEvent", function(_, event, ...)
  if event == "PLAYER_LOGIN" then
    EnsurePrefixRegistered()
    if type(flowHelpers.EnsureSessionPopup) == "function" then
      flowHelpers.EnsureSessionPopup()
    end
    if type(profileSyncHelpers.EnsureProfileSyncPopup) == "function" then
      profileSyncHelpers.EnsureProfileSyncPopup()
    end
    return
  end

  if event == "ADDON_RESTRICTION_STATE_CHANGED" then
    local restrictionType, restrictionState = ...
    local restrictionTypes = type(Enum) == "table" and Enum.AddOnRestrictionType or nil
    local chatRestrictionType = type(restrictionTypes) == "table" and restrictionTypes.Chat or nil
    local restrictionTypeText = tostring(restrictionType or "")
    local isChatRestriction = restrictionType == chatRestrictionType
      or tonumber(restrictionType) == 5
      or restrictionTypeText:find("Chat", 1, true) ~= nil
    if isChatRestriction then
      local restrictionStateText = tostring(restrictionState or "")
      local inactive = tonumber(restrictionState) == 0
        or restrictionStateText:find("Inactive", 1, true) ~= nil
      INTERNAL_API.LIDCOUNCIL_SetChatMessagingLockdownState_Impl(not inactive)
      if inactive and #outboundCommQueue > 0 then
        ClearScheduledOutboundCommFlush()
        outboundCommQueueRunning = true
        ScheduleOutboundCommQueueFlush(0.01)
      elseif not inactive and #outboundCommQueue > 0 then
        ScheduleOutboundCommQueueFlush(1.0)
      end
    end
    return
  end

  if event == "PLAYER_REGEN_ENABLED" or event == "ENCOUNTER_END" then
    if outboundCommStats.chatLockdownActive == true
      and not INTERNAL_API.LIDCOUNCIL_IsChatMessagingLockdownActive_Impl()
    then
      INTERNAL_API.LIDCOUNCIL_SetChatMessagingLockdownState_Impl(false)
      if #outboundCommQueue > 0 then
        ClearScheduledOutboundCommFlush()
        outboundCommQueueRunning = true
        ScheduleOutboundCommQueueFlush(0.01)
      end
    end
    return
  end

  if event == "GROUP_ROSTER_UPDATE" or event == "PLAYER_ENTERING_WORLD" then
    if event == "PLAYER_ENTERING_WORLD" then
      EnsurePrefixRegistered()
      if not INTERNAL_API.LIDCOUNCIL_IsChatMessagingLockdownActive_Impl() then
        INTERNAL_API.LIDCOUNCIL_SetChatMessagingLockdownState_Impl(false)
      end
    end
    if event == "PLAYER_ENTERING_WORLD"
      and type(INTERNAL_API.LIDCOUNCIL_ClearInactiveCombatDeferredState_Impl) == "function"
    then
      INTERNAL_API.LIDCOUNCIL_ClearInactiveCombatDeferredState_Impl()
    end
    if type(flowHelpers.HandleGroupRosterChanged) == "function" then
      flowHelpers.HandleGroupRosterChanged()
    end
    return
  end

  if event == "CHAT_MSG_ADDON" then
    local prefix, message, _, sender = ...
    INTERNAL_API.LIDCOUNCIL_ProcessInboundAddonMessage_Impl(prefix, message, sender)
    return
  end
end)

INTERNAL_API.LIDCOUNCIL_GetRaidTraceTransportSample_Impl = function()
  local activeSession, activeProfileName = nil, ""
  if type(commApi.GetActiveLootSession) == "function" then
    local ok, session, profileName = pcall(commApi.GetActiveLootSession)
    if ok then
      activeSession = session
      activeProfileName = TrimText(profileName)
    end
  end
  local selfKey = NormalizeCharacterKey(type(commApi.GetCharacterKey) == "function" and commApi.GetCharacterKey() or "")
  local hostKey = NormalizeCharacterKey(type(activeSession) == "table" and activeSession.host or "")
  local role = "NONE"
  if type(activeSession) == "table" then
    role = string.lower(selfKey) == string.lower(hostKey) and "HOST" or "MEMBER"
  end
  local joinStatus = {}
  if type(flowHelpers) == "table" and type(flowHelpers.GetAcceptedJoinBurstStatus) == "function" then
    local ok, status = pcall(flowHelpers.GetAcceptedJoinBurstStatus)
    if ok and type(status) == "table" then
      joinStatus = status
    end
  end
  return {
    queueDepth = #outboundCommQueue,
    queueRunning = outboundCommQueueRunning == true,
    attemptedTotal = math.max(0, tonumber(outboundCommStats.attemptedTotal) or 0),
    sentTotal = math.max(0, tonumber(outboundCommStats.sentTotal) or 0),
    throttledTotal = math.max(0, tonumber(outboundCommStats.throttledTotal) or 0),
    failedTotal = math.max(0, tonumber(outboundCommStats.failedTotal) or 0),
    terminalFailureTotal = math.max(0, tonumber(outboundCommStats.terminalFailureTotal) or 0),
    lockdown = outboundCommStats.chatLockdownActive == true,
    cooldownRemaining = math.max(0,
      math.max(0, tonumber(outboundCommStats.globalThrottleNotBeforeAt) or 0) - GetNow()),
    acceptedJoinPending = math.max(0, tonumber(joinStatus.pending) or 0),
    acceptedJoinTotal = math.max(0, tonumber(joinStatus.acceptedTotal) or 0),
    acceptedJoinProcessed = math.max(0, tonumber(joinStatus.processedTotal) or 0),
    character = selfKey,
    role = role,
    host = hostKey,
    sessionId = TrimText(type(activeSession) == "table" and activeSession.id or ""),
    sessionStatus = TrimText(type(activeSession) == "table" and activeSession.status or ""),
    profileName = FirstNonEmptyText(activeProfileName,
      type(activeSession) == "table" and activeSession.profileName or ""),
  }
end

PublishApi("LIDCOUNCIL_StartLootSessionFlow", flowHelpers.StartLootSessionFlow, { global = false })
PublishApi("LIDCOUNCIL_ActivatePreparedLootSessionFlow", flowHelpers.ActivatePreparedLootSessionFlow, { global = false })
PublishApi("LIDCOUNCIL_StopLootSessionFlow", flowHelpers.StopLootSessionFlow, { global = false })
PublishApi("LIDCOUNCIL_LeaveActiveSessionFlow", flowHelpers.LeaveActiveSessionFlow, { global = false })
PublishApi("LIDCOUNCIL_SendActiveSessionInviteFlow", flowHelpers.SendActiveSessionInviteFlow, { global = false })
PublishApi("LIDCOUNCIL_GetInviteDeliveryStatus", flowHelpers.GetInviteDeliveryStatus, { global = false })
PublishApi("LIDCOUNCIL_GetAcceptedJoinBurstStatus", flowHelpers.GetAcceptedJoinBurstStatus, { global = false })
PublishApi("LIDCOUNCIL_PushActiveProfileSnapshotFlow", commPublicApi.PushActiveProfileSnapshotFlow, { global = false })
PublishApi("LIDCOUNCIL_PushProfileHostOverrideFlow", commPublicApi.PushProfileHostOverrideFlow, { global = false })
PublishApi("LIDCOUNCIL_BroadcastActiveProfileSnapshotFlow", flowHelpers.BroadcastActiveProfileSnapshotFlow, { global = false })
PublishApi("LIDCOUNCIL_BroadcastActiveProfileDeltaFlow", flowHelpers.BroadcastActiveProfileDeltaFlow, { global = false })
PublishApi("LIDCOUNCIL_QueueActiveProfileCheckpointFlow", flowHelpers.QueueActiveProfileCheckpointFlow, { global = false })
PublishApi("LIDCOUNCIL_RequestActiveProfileSubchecksumFlow", commPublicApi.RequestActiveProfileSubchecksumFlow, { global = false })
PublishApi("LIDCOUNCIL_RefreshActiveSessionReadinessFlow", commPublicApi.RefreshActiveSessionReadinessFlow, { global = false })
PublishApi("LIDCOUNCIL_RequestActiveProfileSnapshotFlow", commPublicApi.RequestActiveProfileSnapshotFlow, { global = false })
PublishApi("LIDCOUNCIL_BroadcastSessionMemberUpdate", flowHelpers.BroadcastMember, { global = false })
PublishApi("LIDCOUNCIL_RefreshHostSessionMemberState", flowHelpers.RefreshHostSessionMemberState, { global = false })
PublishApi("LIDCOUNCIL_RemoveActiveSessionMemberFlow", flowHelpers.RemoveActiveSessionMemberFlow, { global = false })
PublishApi("LIDCOUNCIL_GetActiveProfileSyncCandidates", commPublicApi.GetActiveProfileSyncCandidates, { global = false })
PublishApi(
  "LIDCOUNCIL_GetMemberLootListDifferenceDiagnostics",
  commPublicApi.GetMemberLootListDifferenceDiagnostics,
  { global = false }
)
PublishApi(
  "LIDCOUNCIL_GetMemberItemHistoryDifferenceDiagnostics",
  commPublicApi.GetMemberItemHistoryDifferenceDiagnostics,
  { global = false }
)
PublishApi(
  "LIDCOUNCIL_GetMemberSessionHistoryDifferenceDiagnostics",
  commPublicApi.GetMemberSessionHistoryDifferenceDiagnostics,
  { global = false }
)
PublishApi("LIDCOUNCIL_GetActiveProfileSyncStatus", commPublicApi.GetActiveProfileSyncStatus, { global = false })
PublishApi("LIDCOUNCIL_GetActiveProfileSyncConflictPreview", commPublicApi.GetActiveProfileSyncConflictPreview, { global = false })
PublishApi("LIDCOUNCIL_ApplyActiveProfilePreviewConflictResolution", commPublicApi.ApplyActiveProfilePreviewConflictResolution, { global = false })
PublishApi("LIDCOUNCIL_GetProfileRepairHistory", profileSyncStateStore.GetRepairHistory, { global = false })
PublishApi("LIDCOUNCIL_GetProfileUndoStatus", profileSyncStateStore.GetUndoStatus, { global = false })
PublishApi("LIDCOUNCIL_UndoLastProfileRepair", profileSyncStateStore.UndoLastRepair, { global = false })
PublishApi("LIDCOUNCIL_GetSessionCommQueueStatus", GetSessionCommQueueStatus, { global = false })
PublishApi("LIDCOUNCIL_GetCommHeaderActivityStatus", GetCommHeaderActivityStatus, { global = false })
PublishApi("LIDCOUNCIL_GetSessionPresentationStatus", INTERNAL_API.LIDCOUNCIL_GetSessionPresentationStatus_Impl, { global = false })
PublishApi("LIDCOUNCIL_GetProfileSyncDecisionStats", GetProfileSyncDecisionStats, { global = false })
PublishApi("LIDCOUNCIL_ResetProfileSyncDecisionStats", ResetProfileSyncDecisionStats, { global = false })
PublishApi("LIDCOUNCIL_GetProfileSyncEstimate", GetProfileSyncEstimate, { global = false })
PublishApi("LIDCOUNCIL_GetArchiveSyncPaused", GetArchiveSyncPaused)
PublishApi("LIDCOUNCIL_SetArchiveSyncPaused", SetArchiveSyncPaused)
PublishApi("LIDCOUNCIL_RunDeveloperProfileSyncHarness", profileSyncDevHarness.RunHarness, { global = false })
PublishApi("LIDCOUNCIL_RunDeveloperProfileSyncValidation", profileSyncDevHarness.RunAutomatedValidation, { global = false })
PublishApi("LIDCOUNCIL_RunDeveloperCommProtocolValidation", RunCommProtocolValidation, { global = false })
PublishApi("LIDCOUNCIL_RunDeveloperCommOutboundTransportValidation", INTERNAL_API.LIDCOUNCIL_RunCommOutboundTransportValidation_Impl, { global = false })
PublishApi("LIDCOUNCIL_RunDeveloperAsymmetricCombatSyncValidation", INTERNAL_API.LIDCOUNCIL_RunAsymmetricCombatSyncValidation_Impl, { global = false })
PublishApi("LIDCOUNCIL_GetCommProtocolContracts", GetCommProtocolContractSnapshot, { global = false })
PublishApi("LIDCOUNCIL_GetCommProtocolHandlerStatus", GetCommProtocolHandlerRegistryStatus, { global = false })
PublishApi("LIDCOUNCIL_ClearDeveloperProfileSyncHarness", profileSyncDevHarness.ClearHarness, { global = false })
PublishApi("LIDCOUNCIL_GetDeveloperProfileSyncHarnessState", profileSyncDevHarness.GetHarnessState, { global = false })
PublishApi("LIDCOUNCIL_GetDeveloperProfileSyncTransferMatrix", profileSyncDevHarness.GetStatefulTransferMatrix, { global = false })
PublishApi("LIDCOUNCIL_GetDeveloperProfileSyncHarnessSessionContext", commPublicApi.GetDeveloperSyntheticHarnessSessionContext, { global = false })
PublishApi("LIDCOUNCIL_PrepareDeveloperProfileSyncHarnessSession", profileSyncDevHarness.PrepareSyntheticSession, { global = false })
PublishApi("LIDCOUNCIL_ActivateDeveloperProfileSyncHarnessSession", profileSyncDevHarness.ActivateSyntheticSession, { global = false })
PublishApi("LIDCOUNCIL_StopDeveloperProfileSyncHarnessSession", profileSyncDevHarness.StopSyntheticSession, { global = false })
PublishApi("LIDCOUNCIL_GetProfileSyncTuning", GetProfileSyncTuning, { global = false })
PublishApi("LIDCOUNCIL_SetProfileSyncTuning", SetProfileSyncTuning, { global = false })
PublishApi("LIDCOUNCIL_ResetProfileSyncTuning", ResetProfileSyncTuning, { global = false })
PublishApi("LIDCOUNCIL_DelayProfileSnapshotBatchForJoins", profileSyncHelpers.DelayProfileSnapshotBatchForJoins, { global = false })
PublishApi("LIDCOUNCIL_CancelQueuedProfileSyncForSession", CancelQueuedProfileSyncForSession, { global = false })
PublishApi("LIDCOUNCIL_CancelProfileSnapshotBatchForSession", profileSyncHelpers.CancelProfileSnapshotBatchForSession, { global = false })
PublishApi("LIDCOUNCIL_BeginProfileSnapshotDiagnosticsForSession", profileSyncHelpers.BeginProfileSnapshotDiagnosticsForSession, { global = false })
PublishApi("LIDCOUNCIL_BroadcastActiveSessionRoleUpdate", flowHelpers.BroadcastActiveSessionRoleUpdate, { global = false })
PublishApi("LIDCOUNCIL_NotifyLocalAutoPassChanged", flowHelpers.NotifyLocalAutoPassChanged, { global = false })
PublishApi("LIDCOUNCIL_HasJoinedActiveLootSession", flowHelpers.HasJoinedActiveLootSession, { global = false })
PublishApi("LIDCOUNCIL_COMM_PREFIX", COMM_PREFIX, { global = false })
PublishApi("LIDCOUNCIL_SendSessionComm", SendComm, { global = false })
PublishApi("LIDCOUNCIL_ParseSessionComm", ParsePayload, { global = false })
PublishApi("LIDCOUNCIL_NormalizeCharacterKey", NormalizeCharacterKey, { global = false })
