local API = rawget(_G, "LIDCOUNCIL_API")
local INTERNAL_API = type(API) == "table" and type(API.__internal) == "table" and API.__internal or nil
if type(INTERNAL_API) ~= "table" then
  error("LidCouncil missing internal API registry.")
end

INTERNAL_API.LIDCOUNCIL_CreateLootRuntimeCommHelpers_Impl = function(deps)
  deps = type(deps) == "table" and deps or {}

  local Print = deps.Print
  local DeepCopy = deps.DeepCopy
  local TrimText = deps.TrimText
  local ExtractItemID = deps.ExtractItemID
  local NormalizeSelectionNote = deps.NormalizeSelectionNote
  local NormalizeCharacterKey = deps.NormalizeCharacterKey
  local GetActiveLootSession = deps.GetActiveLootSession
  local GetLootProfile = deps.GetLootProfile
  local GetLootProfileRole = deps.GetLootProfileRole
  local GetLootProfileAccessInfo = deps.GetLootProfileAccessInfo
  local IsSelfHost = deps.IsSelfHost
  local EnsureRuntimeSession = deps.EnsureRuntimeSession
  local ResolveRollOption = deps.ResolveRollOption
  local ResolveRollOptions = deps.ResolveRollOptions
  local EnsureLiveEntry = deps.EnsureLiveEntry
  local NextItemKey = deps.NextItemKey
  local QueueContains = deps.QueueContains
  local GetBroadcastDistribution = deps.GetBroadcastDistribution
  local SendSessionComm = deps.SendSessionComm
  local ValidateCommPayload = deps.ValidateCommPayload
  local RefreshBoardAndEditor = deps.RefreshBoardAndEditor
  local RecordChoice = deps.RecordChoice
  local RecordLootVoteStat = deps.RecordLootVoteStat
  local IsRealSimulationItemKey = deps.IsRealSimulationItemKey
  local ClassifyLootRollItem = deps.ClassifyLootRollItem
  local AddLootLedgerEntry = deps.AddLootLedgerEntry
  local RemoveLootLedgerEntry = deps.RemoveLootLedgerEntry
  local NormalizeLootLedgerRoleLocal = deps.NormalizeLootLedgerRoleLocal
  local SetLootLedgerMainAltRole = deps.SetLootLedgerMainAltRole
  local SetLootLedgerCharacterNote = deps.SetLootLedgerCharacterNote
  local SetLootLedgerMainCharacter = deps.SetLootLedgerMainCharacter
  local ClearLootLedgerMainCharacter = deps.ClearLootLedgerMainCharacter
  local DeleteLootLedgerCharacter = deps.DeleteLootLedgerCharacter
  local BuildLootLedgerNavRows = deps.BuildLootLedgerNavRows
  local ApplyAwardMessage = deps.ApplyAwardMessage
  local RemoveAwardFromEntry = deps.RemoveAwardFromEntry
  local NormalizeEntryVotes = deps.NormalizeEntryVotes
  local NormalizeVoteSequence = deps.NormalizeVoteSequence
  local SetEntryVoteTarget = deps.SetEntryVoteTarget
  local PersistRuntimeBoardHistory = deps.PersistRuntimeBoardHistory
  local BuildRuntimeBoardHistorySnapshot = deps.BuildRuntimeBoardHistorySnapshot
  local GetLatestRuntimeBoardSnapshot = deps.GetLatestRuntimeBoardSnapshot
  local RestoreRuntimeBoardSnapshot = deps.RestoreRuntimeBoardSnapshot
  local GetSelfKey = deps.GetSelfKey
  local PrimeSequence = deps.PrimeSequence
  local ClearPreviewState = deps.ClearPreviewState
  local RefreshChoicePopup = deps.RefreshChoicePopup
  local RearmUnconfirmedChoiceReceipts = deps.RearmUnconfirmedChoiceReceipts
  local runtime = deps.runtime

  local function RecordRaidTraceEvent(eventName, detail, fields)
    local recorder = INTERNAL_API.LIDCOUNCIL_RecordRaidTestTraceEvent_Impl
    if type(recorder) == "function" then
      recorder(eventName, detail, fields)
    end
  end

  local incomingBoardSyncs = {}
  local boardSyncTransactions = {
    outgoing = {},
    completedReceipts = {},
    itemOpenOutgoing = {},
    itemOpenByIdentity = {},
    completedItemOpenReceipts = {},
    itemOpenReports = {},
    choiceMirrorOutgoing = {},
    stagedDispatches = {},
    stagedDispatchRequests = 0,
    stagedDispatchCoalesced = 0,
    stagedDispatchReleased = 0,
    nextItemOpenToken = 0,
    itemOpenRetryDelays = { 5, 8, 12, 16 },
    choiceMirrorRetryDelays = { 3, 6, 10 },
    nextToken = 0,
    maxMissingPerReceipt = 48,
    maxSelectiveAttempts = 3,
    maxEndAttempts = 2,
    maxFullRebuilds = 1,
    receiptTimeoutSeconds = 4,
    choiceReceiptAttempts = 4,
    maxActiveTargets = 2,
    getQueueStatus = deps.GetSessionCommQueueStatus,
  }
  local GetBoardSyncToken
  local BuildChoiceMirrorIdentity
  local PrepareItemReportFields
  local GetReportToken
  local ResolveEntrySelection
  local EXPECTED_FIELD_COUNTS = {
    CHOICE = 11,
    RCHOICE = 11,
    RCHOICE_ACK = 7,
    ITEM_REPORT = 12,
    ITEM_OPEN = { 13, 14, 15 },
    ITEM_ACK = 7,
    AWARD = 10,
    UNASSIGN = 5,
    TRADE = 7,
    VOTE = 8,
    LL_ADD_REQ = 9,
    LL_ADD = 10,
    LL_DEL_REQ = 7,
    LL_DEL = 6,
    LL_MA_REQ = 8,
    LL_MA = 8,
    LL_NOTE_REQ = 7,
    LL_NOTE = 7,
    LL_CHAR_DEL_REQ = 6,
    LL_CHAR_DEL = 6,
    BSYNC_START = { 7, 12 },
    BSYNC_ITEM = { 18, 21, 22 },
    BSYNC_SEL = { 17, 18 },
    BSYNC_VOTE = { 8, 9 },
    BSYNC_END = { 5, 6 },
    BSYNC_MISS = 7,
    BSYNC_ACK = 10,
  }
  local MAX_BOARD_SYNC_ITEM_NAME_LENGTH = 80
  local MAX_BOARD_SYNC_LINK_LENGTH = 128
  local MAX_BOARD_SYNC_ICON_LENGTH = 96
  local MAX_BOARD_SYNC_NOTE_LENGTH = 64
  local MAX_BOARD_SYNC_LEDGER_ID_LENGTH = 48
  local MAX_BOARD_SYNC_LABEL_LENGTH = 48
  local MAX_BOARD_SYNC_SOURCE_LENGTH = 24
  local MAX_ITEM_OPEN_NAME_LENGTH = 80
  local MAX_ITEM_OPEN_LINK_LENGTH = 192
  local MAX_ITEM_OPEN_ICON_LENGTH = 96
  local MAX_MANUAL_LEDGER_ID_LENGTH = 24
  local MAX_MANUAL_LEDGER_NAME_LENGTH = 48
  local MAX_MANUAL_LEDGER_NOTE_LENGTH = 24
  local MAX_LOOT_LEDGER_CHARACTER_LENGTH = 64
  local MAX_LOOT_LEDGER_NOTE_LENGTH = 160
  local MANUAL_LEDGER_ICON = "Interface\\Icons\\INV_Misc_Note_06"
  local AUTHORITATIVE_LOOT_ITEM_PREFIX = "LIVE-"

  local function Utf8PrefixByBytes(value, maxBytes)
    local text = tostring(value or "")
    local limit = math.max(0, math.floor(tonumber(maxBytes) or 0))
    if #text <= limit then
      return text
    end
    local index = 1
    local lastComplete = 0
    while index <= #text do
      local firstByte = string.byte(text, index) or 0
      local width = 1
      if firstByte >= 240 and firstByte <= 247 then
        width = 4
      elseif firstByte >= 224 and firstByte <= 239 then
        width = 3
      elseif firstByte >= 194 and firstByte <= 223 then
        width = 2
      end
      if index + width - 1 > limit or index + width - 1 > #text then
        break
      end
      lastComplete = index + width - 1
      index = index + width
    end
    return string.sub(text, 1, lastComplete)
  end

  local function BuildChoicePacketFields(sessionId, profileName, itemKey, memberKey, optionKey, optionLabel, note, rollValue, selectedAt, selectedSeq)
    return {
      TrimText(sessionId),
      TrimText(profileName),
      TrimText(itemKey),
      NormalizeCharacterKey(memberKey),
      TrimText(optionKey),
      TrimText(optionLabel),
      NormalizeSelectionNote(note),
      rollValue or "",
      selectedAt or "",
      selectedSeq or "",
    }
  end

  local function PrepareChoicePacket(kind, sessionId, profileName, itemKey, memberKey, optionKey, optionLabel, note, rollValue, selectedAt, selectedSeq)
    local fields = BuildChoicePacketFields(
      sessionId,
      profileName,
      itemKey,
      memberKey,
      optionKey,
      optionLabel,
      note,
      rollValue,
      selectedAt,
      selectedSeq
    )
    local originalLabel = fields[6]
    local originalNote = fields[7]
    local function Fits(candidate)
      if type(ValidateCommPayload) ~= "function" then
        return true, nil, 0
      end
      return ValidateCommPayload(kind, unpack(candidate))
    end
    local accepted, reason, payloadBytes = Fits(fields)
    if not accepted and fields[6] ~= "" then
      fields[6] = ""
      accepted, reason, payloadBytes = Fits(fields)
    end
    if not accepted and fields[7] ~= "" then
      local low = 0
      local high = #fields[7]
      local best = ""
      while low <= high do
        local middle = math.floor((low + high) / 2)
        local candidateNote = Utf8PrefixByBytes(originalNote, middle)
        fields[7] = candidateNote
        local candidateAccepted = Fits(fields)
        if candidateAccepted then
          best = candidateNote
          low = middle + 1
        else
          high = middle - 1
        end
      end
      fields[7] = best
      accepted, reason, payloadBytes = Fits(fields)
    end
    if not accepted then
      fields[6] = ""
      fields[7] = ""
      accepted, reason, payloadBytes = Fits(fields)
    end
    return accepted == true, fields, {
      reason = TrimText(reason),
      payloadBytes = math.max(0, tonumber(payloadBytes) or 0),
      labelOmitted = originalLabel ~= "" and fields[6] == "",
      noteTruncated = fields[7] ~= originalNote,
      sentNote = fields[7],
    }
  end

  local function SendChoicePacket(kind, distribution, target, sessionId, profileName, itemKey, memberKey, optionKey, optionLabel, note, rollValue, selectedAt, selectedSeq)
    if type(SendSessionComm) ~= "function" then
      return false, "send_unavailable", { reason = "send_unavailable" }
    end
    local accepted, fields, metadata = PrepareChoicePacket(
      kind,
      sessionId,
      profileName,
      itemKey,
      memberKey,
      optionKey,
      optionLabel,
      note,
      rollValue,
      selectedAt,
      selectedSeq
    )
    if not accepted then
      return false, metadata.reason ~= "" and metadata.reason or "payload_exceeds_safe_limit", metadata
    end
    local sent, reason = SendSessionComm(kind, distribution, target, unpack(fields))
    metadata.reason = sent and "" or TrimText(reason)
    return sent == true, reason, metadata
  end

  function boardSyncTransactions.PrepareAwardPacket(sessionId, profileName, itemKey, memberKey, itemName, itemLevel, points, note, changedAt)
    local fields = {
      TrimText(sessionId),
      TrimText(profileName),
      TrimText(itemKey),
      NormalizeCharacterKey(memberKey),
      TrimText(itemName),
      itemLevel or "",
      points or 0,
      TrimText(note),
      changedAt or "",
    }
    local originalItemName = fields[5]
    local originalNote = fields[8]
    local function Fits(candidate)
      if type(ValidateCommPayload) ~= "function" then
        return true, nil, 0
      end
      return ValidateCommPayload("AWARD", unpack(candidate))
    end
    local accepted, reason, payloadBytes = Fits(fields)
    if not accepted and fields[5] ~= "" then
      -- The live-board item already carries the authoritative display name.
      -- Omit that duplicate before sacrificing any user-authored award note.
      fields[5] = ""
      accepted, reason, payloadBytes = Fits(fields)
    end
    if not accepted and fields[8] ~= "" then
      local low = 0
      local high = #originalNote
      local best = ""
      while low <= high do
        local middle = math.floor((low + high) / 2)
        local candidateNote = Utf8PrefixByBytes(originalNote, middle)
        fields[8] = candidateNote
        local candidateAccepted = Fits(fields)
        if candidateAccepted then
          best = candidateNote
          low = middle + 1
        else
          high = middle - 1
        end
      end
      fields[8] = best
      accepted, reason, payloadBytes = Fits(fields)
    end
    if not accepted then
      fields[5] = ""
      fields[8] = ""
      accepted, reason, payloadBytes = Fits(fields)
    end
    return accepted == true, fields, {
      reason = TrimText(reason),
      payloadBytes = math.max(0, tonumber(payloadBytes) or 0),
      itemNameOmitted = originalItemName ~= "" and fields[5] == "",
      noteTruncated = fields[8] ~= originalNote,
      sentNote = fields[8],
    }
  end

  function boardSyncTransactions.SendAwardPacket(distribution, target, sessionId, profileName, itemKey, memberKey, itemName, itemLevel, points, note, changedAt)
    if type(SendSessionComm) ~= "function" then
      return false, "send_unavailable", { reason = "send_unavailable" }
    end
    local accepted, fields, metadata = boardSyncTransactions.PrepareAwardPacket(
      sessionId,
      profileName,
      itemKey,
      memberKey,
      itemName,
      itemLevel,
      points,
      note,
      changedAt
    )
    if not accepted then
      return false, metadata.reason ~= "" and metadata.reason or "payload_exceeds_safe_limit", metadata
    end
    local sent, reason = SendSessionComm("AWARD", distribution, target, unpack(fields))
    metadata.reason = sent and "" or TrimText(reason)
    return sent == true, reason, metadata
  end
  local COMBAT_STAGED_RUNTIME_OPCODES = {
    "LL_ADD_REQ",
    "LL_ADD",
    "LL_DEL_REQ",
    "LL_DEL",
    "LL_MA_REQ",
    "LL_MA",
    "LL_NOTE_REQ",
    "LL_NOTE",
    "LL_CHAR_DEL_REQ",
    "LL_CHAR_DEL",
  }
  local COMBAT_STAGED_RUNTIME_OPCODE_SET = {}
  for _, opcode in ipairs(COMBAT_STAGED_RUNTIME_OPCODES) do
    COMBAT_STAGED_RUNTIME_OPCODE_SET[opcode] = true
  end
  COMBAT_STAGED_RUNTIME_OPCODE_SET.__preparedSession = {
    LL_MA_REQ = true,
    LL_MA = true,
    LL_NOTE_REQ = true,
    LL_NOTE = true,
    LL_CHAR_DEL_REQ = true,
    LL_CHAR_DEL = true,
    BSYNC_START = true,
    BSYNC_ITEM = true,
    BSYNC_SEL = true,
    BSYNC_VOTE = true,
    BSYNC_END = true,
  }

  local function IsCombatLocked()
    return type(InCombatLockdown) == "function" and InCombatLockdown() and true or false
  end

  local function RejectCombatLockedLootEdit(actionLabel)
    if not IsCombatLocked() then
      return false
    end
    local message = tostring(actionLabel or "This Loot List action") .. " is unavailable during combat."
    if type(Print) == "function" then
      Print(message)
    end
    return true, message
  end

  local function QueueRuntimeCombatOp(opcode, fields, sender)
    local queueEntry = INTERNAL_API.LIDCOUNCIL_QueueCombatSyncInboxEntry_Impl
    if type(queueEntry) ~= "function" then
      return false, "combat_inbox_unavailable"
    end
    local resolvedOpcode = string.upper(TrimText(opcode))
    local sessionId = TrimText(type(fields) == "table" and fields[2] or "")
    local profileName = TrimText(type(fields) == "table" and fields[3] or "")
    local senderKey = string.lower(TrimText(sender))
    local dedupeKey = table.concat({
      string.lower(sessionId),
      string.lower(profileName),
      string.lower(resolvedOpcode),
      senderKey,
      table.concat(type(fields) == "table" and fields or {}, "\30"),
    }, "\31")
    return queueEntry({
      opcode = resolvedOpcode,
      sessionId = sessionId,
      profileName = profileName,
      sender = senderKey,
      dedupeKey = dedupeKey,
      action = "runtime_comm",
      payload = {
        fields = fields,
        sender = sender,
      },
    })
  end

  local function NormalizeDistributionMode(value)
    local mode = string.upper(TrimText(value))
    if mode == "MANUAL_VISIBLE" then
      return "MANUAL_VISIBLE"
    end
    return "COUNCIL"
  end

  local function IsLiveSession(activeSession)
    return type(activeSession) == "table" and string.upper(TrimText(activeSession.status or "ACTIVE")) == "ACTIVE"
  end

  local function DoesRuntimeSessionMatch(activeSession, activeProfileName, sessionId, profileName)
    if type(activeSession) ~= "table" or TrimText(activeSession.id) ~= TrimText(sessionId) then
      return false
    end
    local expectedProfileName = TrimText(profileName)
    if expectedProfileName == "" then
      return true
    end
    return TrimText(activeProfileName) == expectedProfileName
      or TrimText(activeSession.profileName) == expectedProfileName
      or TrimText(activeSession.remoteProfileName) == expectedProfileName
  end

  local function GetSessionCommProfileName(activeSession, fallbackProfileName)
    return TrimText(type(activeSession) == "table" and activeSession.remoteProfileName) ~= ""
      and TrimText(activeSession.remoteProfileName)
      or TrimText(fallbackProfileName)
  end

  local function NormalizeSenderKey(sender)
    return NormalizeCharacterKey(sender)
  end

  local function NormalizeComparableCharacterKey(value)
    return string.lower(NormalizeCharacterKey(value))
  end

  local function SplitCharacterKey(value)
    local normalized = NormalizeComparableCharacterKey(value)
    if normalized == "" then
      return "", ""
    end
    local name, realm = normalized:match("^([^%-]+)%-(.+)$")
    if name and name ~= "" then
      return name, realm or ""
    end
    return normalized, ""
  end

  local function AreCharacterKeysSame(left, right)
    local leftKey = NormalizeComparableCharacterKey(left)
    local rightKey = NormalizeComparableCharacterKey(right)
    if leftKey == "" or rightKey == "" then
      return false
    end
    if leftKey == rightKey then
      return true
    end
    local leftName, leftRealm = SplitCharacterKey(leftKey)
    local rightName, rightRealm = SplitCharacterKey(rightKey)
    return leftName ~= "" and leftName == rightName and (leftRealm == "" or rightRealm == "")
  end

  -- A choice receipt identifies one immutable player decision. The host can
  -- safely receive the same request more than once and confirm this key once.
  local function BuildChoiceReceiptKey(sessionId, itemKey, memberKey, selectedSeq)
    return string.lower(TrimText(sessionId))
      .. "\031" .. string.lower(TrimText(itemKey))
      .. "\031" .. string.lower(TrimText(memberKey))
      .. "\031" .. tostring(math.max(0, math.floor(tonumber(selectedSeq) or 0)))
  end

  function boardSyncTransactions.ShouldAcceptIncomingChoice(currentSeq, currentAt, incomingSeq, incomingAt)
    local resolvedCurrentSeq = math.max(0, math.floor(tonumber(currentSeq) or 0))
    local resolvedCurrentAt = math.max(0, tonumber(currentAt) or 0)
    local resolvedIncomingSeq = math.max(0, math.floor(tonumber(incomingSeq) or 0))
    local resolvedIncomingAt = math.max(0, tonumber(incomingAt) or 0)
    if resolvedIncomingSeq <= 0 or resolvedIncomingAt <= 0 then
      return false
    end
    if resolvedIncomingSeq < resolvedCurrentSeq then
      return false
    end
    if resolvedIncomingSeq == resolvedCurrentSeq and resolvedCurrentSeq > 0 then
      -- A sequence identifies one immutable decision. Its exact replay is
      -- accepted so a lost receipt can be sent again, but a different timestamp
      -- must not mutate that sequence or collide with its receipt identity.
      return resolvedIncomingAt == resolvedCurrentAt
    end
    return true
  end

  function boardSyncTransactions.IsExactChoiceReplay(selection, incomingOptionKey, incomingNote, incomingRollValue, incomingSeq, incomingAt)
    if type(selection) ~= "table" then
      return false
    end
    return math.max(0, math.floor(tonumber(selection.selectedSeq) or 0))
        == math.max(0, math.floor(tonumber(incomingSeq) or 0))
      and math.max(0, tonumber(selection.selectedAt) or 0)
        == math.max(0, tonumber(incomingAt) or 0)
      and string.lower(TrimText(selection.optionKey)) == string.lower(TrimText(incomingOptionKey))
      and NormalizeSelectionNote(selection.note) == NormalizeSelectionNote(incomingNote)
      and tostring(selection.rollValue or "") == tostring(incomingRollValue or "")
  end

  function boardSyncTransactions.RunChoiceBurstValidation(requestedMemberCount, requestedItemCount)
    local memberCount = math.max(1, math.min(40, math.floor(tonumber(requestedMemberCount) or 20)))
    local itemCount = math.max(1, math.min(20, math.floor(tonumber(requestedItemCount) or 5)))
    local scenarioLabel = tostring(memberCount) .. "-member " .. tostring(itemCount) .. "-item"
    local selectedAt = 1000
    local states = {}
    local receiptKeys = {}
    local checks = {}
    local passedCount = 0
    local function addCheck(name, expected, actual)
      local passed = expected == actual
      checks[#checks + 1] = {
        name = name,
        expected = tostring(expected),
        actual = tostring(actual),
        passed = passed,
      }
      if passed then
        passedCount = passedCount + 1
      end
    end
    local function choiceKey(memberIndex, itemIndex)
      return string.format("Member%02d-Realm|ITEM-%02d", memberIndex, itemIndex)
    end
    local function applyChoice(memberIndex, itemIndex, sequence, changedAt)
      local key = choiceKey(memberIndex, itemIndex)
      local current = type(states[key]) == "table" and states[key] or {}
      if not boardSyncTransactions.ShouldAcceptIncomingChoice(
        current.sequence,
        current.changedAt,
        sequence,
        changedAt
      ) then
        return false
      end
      states[key] = {
        sequence = math.max(0, math.floor(tonumber(sequence) or 0)),
        changedAt = math.max(0, tonumber(changedAt) or 0),
      }
      return true
    end

    local initialAccepted = 0
    for memberIndex = 1, memberCount do
      for itemIndex = 1, itemCount do
        if applyChoice(memberIndex, itemIndex, 1, selectedAt) then
          initialAccepted = initialAccepted + 1
        end
        receiptKeys[BuildChoiceReceiptKey(
          "VALIDATION-SESSION",
          string.format("ITEM-%02d", itemIndex),
          string.format("Member%02d-Realm", memberIndex),
          1
        )] = true
      end
    end

    local recoveredReceipts = 0
    local staleTimestampRejects = 0
    for memberIndex = 1, memberCount do
      for itemIndex = 1, itemCount do
        -- The first host mirror is treated as lost. Replaying the immutable
        -- request must remain idempotent and produce another valid receipt.
        if applyChoice(memberIndex, itemIndex, 1, selectedAt) then
          recoveredReceipts = recoveredReceipts + 1
        end
        if not applyChoice(memberIndex, itemIndex, 1, selectedAt - 1) then
          staleTimestampRejects = staleTimestampRejects + 1
        end
      end
    end

    local correctedChoices = 0
    local staleSequenceRejects = 0
    for memberIndex = 1, memberCount do
      local itemIndex = ((memberIndex - 1) % itemCount) + 1
      if applyChoice(memberIndex, itemIndex, 2, selectedAt + 1) then
        correctedChoices = correctedChoices + 1
      end
      if not applyChoice(memberIndex, itemIndex, 1, selectedAt + 2) then
        staleSequenceRejects = staleSequenceRejects + 1
      end
    end

    local storedRows = 0
    local latestRows = 0
    for _, state in pairs(states) do
      storedRows = storedRows + 1
      if tonumber(state.sequence) == 2 then
        latestRows = latestRows + 1
      end
    end
    local uniqueReceiptKeys = 0
    for _ in pairs(receiptKeys) do
      uniqueReceiptKeys = uniqueReceiptKeys + 1
    end

    addCheck(scenarioLabel .. " burst accepts every choice", memberCount * itemCount, initialAccepted)
    addCheck(scenarioLabel .. " receipt identities remain collision-free", memberCount * itemCount, uniqueReceiptKeys)
    addCheck(scenarioLabel .. " lost host receipts recover through idempotent replay", memberCount * itemCount, recoveredReceipts)
    addCheck(scenarioLabel .. " older equal-sequence choices cannot overwrite", memberCount * itemCount, staleTimestampRejects)
    addCheck(scenarioLabel .. " newer timestamps cannot mutate an existing sequence", false,
      boardSyncTransactions.ShouldAcceptIncomingChoice(4, 1200, 4, 1201))
    addCheck(scenarioLabel .. " accepts one newer correction per member", memberCount, correctedChoices)
    addCheck(scenarioLabel .. " rejects older sequences after corrections", memberCount, staleSequenceRejects)
    addCheck(scenarioLabel .. " duplicates never inflate authoritative rows", memberCount * itemCount, storedRows)
    addCheck(scenarioLabel .. " preserves every latest correction", memberCount, latestRows)

    local compactAccepted, compactFields, compactMetadata = PrepareChoicePacket(
      "CHOICE",
      string.rep("S", 40),
      string.rep("P", 48),
      string.rep("I", 36),
      "ValidationMember-Realm",
      "need",
      "Need",
      string.rep("Long choice note ", 14),
      100,
      1234567890,
      27
    )
    local compactPayloadAccepted = compactAccepted == true
    local compactPayloadBytes = tonumber(type(compactMetadata) == "table" and compactMetadata.payloadBytes) or 0
    if compactAccepted and type(ValidateCommPayload) == "function" then
      compactPayloadAccepted, _, compactPayloadBytes = ValidateCommPayload("CHOICE", unpack(compactFields))
    end
    addCheck(scenarioLabel .. " oversized choice compacts inside the safe payload limit", true,
      compactAccepted == true and compactPayloadAccepted == true and compactPayloadBytes <= 240)
    addCheck(scenarioLabel .. " choice compaction preserves option and sequence identity", "need/27",
      tostring(type(compactFields) == "table" and compactFields[5]) .. "/"
        .. tostring(type(compactFields) == "table" and compactFields[10]))
    addCheck(scenarioLabel .. " choice compaction removes only optional presentation data", true,
      type(compactMetadata) == "table"
        and (compactMetadata.noteTruncated == true or compactMetadata.labelOmitted == true))

    local reportAccepted, reportFields, reportMetadata = false, nil, nil
    if type(PrepareItemReportFields) == "function" then
      reportAccepted, reportFields, reportMetadata = PrepareItemReportFields(
        string.rep("S", 40),
        string.rep("P", 48),
        "ValidationMember-Realm",
        "123456789",
        {
          itemID = 999999,
          itemLevel = 344,
          quality = 4,
          icon = string.rep("Interface\\Icons\\LongIcon", 6),
          name = string.rep("Long Item Name ", 10),
          link = string.rep("|Hitem:999999::::::::80:70:::::|h[Long Item]|h", 5),
          createdAt = 1234567890,
        }
      )
    end
    local reportPayloadAccepted = reportAccepted == true
    local reportPayloadBytes = tonumber(type(reportMetadata) == "table" and reportMetadata.payloadBytes) or 0
    if reportAccepted and type(ValidateCommPayload) == "function" then
      reportPayloadAccepted, _, reportPayloadBytes = ValidateCommPayload("ITEM_REPORT", unpack(reportFields))
    end
    addCheck(scenarioLabel .. " oversized item report compacts inside the safe payload limit", true,
      reportAccepted == true and reportPayloadAccepted == true and reportPayloadBytes <= 240)
    addCheck(scenarioLabel .. " item report compaction preserves authoritative item identity", "999999/344",
      tostring(type(reportFields) == "table" and reportFields[5]) .. "/"
        .. tostring(type(reportFields) == "table" and reportFields[6]))

    local replaySelection = {
      optionKey = "need",
      note = "same note",
      rollValue = 77,
      selectedSeq = 4,
      selectedAt = 1200,
    }
    addCheck(scenarioLabel .. " exact choice retry is recognized without another group broadcast", true,
      boardSyncTransactions.IsExactChoiceReplay(replaySelection, "need", "same note", 77, 4, 1200))
    addCheck(scenarioLabel .. " corrected choice is not mistaken for an exact retry", false,
      boardSyncTransactions.IsExactChoiceReplay(replaySelection, "need", "corrected note", 77, 4, 1200))

    local firstReportToken = type(GetReportToken) == "function" and GetReportToken("Member01-Realm", "17", "ITEM:100", 1000) or ""
    local secondReporterToken = type(GetReportToken) == "function" and GetReportToken("Member02-Realm", "17", "ITEM:100", 1000) or ""
    local secondRollToken = type(GetReportToken) == "function" and GetReportToken("Member01-Realm", "18", "ITEM:100", 1000) or ""
    local secondItemToken = type(GetReportToken) == "function" and GetReportToken("Member01-Realm", "17", "ITEM:200", 1000) or ""
    local secondEventToken = type(GetReportToken) == "function" and GetReportToken("Member01-Realm", "17", "ITEM:100", 1001) or ""
    local repeatedReportToken = type(GetReportToken) == "function" and GetReportToken("Member01-Realm", "17", "ITEM:100", 1000) or ""
    addCheck(scenarioLabel .. " item reports namespace local roll IDs by reporter, roll, item, and event", true,
      firstReportToken ~= ""
        and firstReportToken ~= secondReporterToken
        and firstReportToken ~= secondRollToken
        and firstReportToken ~= secondItemToken
        and firstReportToken ~= secondEventToken)
    addCheck(scenarioLabel .. " exact item report retries preserve their identity", firstReportToken, repeatedReportToken)

    local firstMirrorIdentity = type(BuildChoiceMirrorIdentity) == "function"
      and BuildChoiceMirrorIdentity("VALIDATION-SESSION", "ITEM-01", "Member01-Realm", 1, "CouncilA-Realm")
      or ""
    local secondTargetIdentity = type(BuildChoiceMirrorIdentity) == "function"
      and BuildChoiceMirrorIdentity("VALIDATION-SESSION", "ITEM-01", "Member01-Realm", 1, "CouncilB-Realm")
      or ""
    local secondSequenceIdentity = type(BuildChoiceMirrorIdentity) == "function"
      and BuildChoiceMirrorIdentity("VALIDATION-SESSION", "ITEM-01", "Member01-Realm", 2, "CouncilA-Realm")
      or ""
    addCheck(scenarioLabel .. " council receipt identity includes target and sequence", true,
      firstMirrorIdentity ~= ""
        and firstMirrorIdentity ~= secondTargetIdentity
        and firstMirrorIdentity ~= secondSequenceIdentity)

    local receiptReport = { targets = { ["councila-realm"] = { state = "pending", attempts = 2 } } }
    local receiptTransaction = {
      state = "pending",
      reason = "",
      attempts = 2,
      targetKey = "CouncilA-Realm",
      report = receiptReport,
    }
    local firstReceiptApplied = type(boardSyncTransactions.ApplyChoiceMirrorReceipt) == "function"
      and boardSyncTransactions.ApplyChoiceMirrorReceipt(receiptTransaction, "RECEIVED")
      or false
    local duplicateReceiptApplied = type(boardSyncTransactions.ApplyChoiceMirrorReceipt) == "function"
      and boardSyncTransactions.ApplyChoiceMirrorReceipt(receiptTransaction, "RECEIVED")
      or false
    addCheck(scenarioLabel .. " council receipt closes exactly one pending mirror", "true/false/acknowledged",
      table.concat({
        tostring(firstReceiptApplied),
        tostring(duplicateReceiptApplied),
        tostring(receiptReport.targets["councila-realm"].state),
      }, "/"))

    return passedCount == #checks, {
      suite = "loot_choice_burst",
      version = 5,
      memberCount = memberCount,
      itemCount = itemCount,
      total = #checks,
      passed = passedCount,
      failed = #checks - passedCount,
      checks = checks,
    }
  end

  local function ConfirmPendingChoiceReceipt(sessionId, itemKey, memberKey, selectedAt, selectedSeq)
    if type(runtime.pendingChoiceReceipts) ~= "table" then
      return false
    end
    local receiptKey = BuildChoiceReceiptKey(sessionId, itemKey, memberKey, selectedSeq)
    local receipt = runtime.pendingChoiceReceipts[receiptKey]
    if type(receipt) ~= "table" then
      return false
    end
    local expectedAt = tonumber(receipt.selectedAt) or 0
    local confirmedAt = tonumber(selectedAt) or 0
    if expectedAt > 0 and confirmedAt > 0 and expectedAt ~= confirmedAt then
      return false
    end
    runtime.pendingChoiceReceipts[receiptKey] = nil
    local entry = type(runtime.items) == "table" and runtime.items[TrimText(itemKey)] or nil
    local confirmedSelection = ResolveEntrySelection(entry, memberKey)
    if type(confirmedSelection) == "table"
      and math.max(0, math.floor(tonumber(confirmedSelection.selectedSeq) or 0))
        == math.max(0, math.floor(tonumber(selectedSeq) or 0))
    then
      confirmedSelection.receiptState = "confirmed"
      confirmedSelection.receiptRearmCount = math.max(
        math.max(0, math.floor(tonumber(confirmedSelection.receiptRearmCount) or 0)),
        math.max(0, math.floor(tonumber(receipt.rearmCount) or 0))
      )
      if type(PersistRuntimeBoardHistory) == "function" then
        PersistRuntimeBoardHistory({
          itemKey = TrimText(itemKey),
          selectionMemberKey = NormalizeCharacterKey(memberKey),
        })
      end
    end
    runtime.lastChoiceReceipt = {
      sessionId = TrimText(sessionId),
      itemKey = TrimText(itemKey),
      memberKey = NormalizeCharacterKey(memberKey),
      selectedAt = confirmedAt,
      selectedSeq = math.max(0, math.floor(tonumber(selectedSeq) or 0)),
      attempts = math.max(0, tonumber(receipt.attempts) or 0),
      recoveryState = string.lower(TrimText(receipt.state)),
      recoveryReason = TrimText(receipt.queuePressureReason),
      confirmedAt = type(GetServerTime) == "function"
        and math.max(0, tonumber(GetServerTime()) or 0)
        or math.max(0, tonumber(time and time() or 0) or 0),
    }
    runtime.lastChoiceReceiptRecovery = {
      state = "confirmed",
      reason = TrimText(receipt.queuePressureReason),
      sessionId = TrimText(sessionId),
      itemKey = TrimText(itemKey),
      host = TrimText(receipt.host),
      attempts = math.max(0, tonumber(receipt.attempts) or 0),
      graceStartedAt = math.max(0, tonumber(receipt.queueGraceStartedAt) or 0),
      graceExpiresAt = math.max(0, tonumber(receipt.queueGraceExpiresAt) or 0),
      confirmedAfterGrace = string.lower(TrimText(receipt.state)) == "queue_grace",
      updatedAt = type(GetTime) == "function" and math.max(0, tonumber(GetTime()) or 0) or 0,
    }
    if type(RefreshChoicePopup) == "function" then
      RefreshChoicePopup({ reason = "choice_receipt", itemKey = itemKey })
    end
    return true
  end

  local function ClipBoardSyncText(value, limit)
    local text = TrimText(value)
    local maxLength = tonumber(limit) or 0
    if maxLength > 0 and #text > maxLength then
      text = text:sub(1, maxLength)
    end
    return text
  end

  local function IsSessionHostKey(activeSession, characterKey)
    return AreCharacterKeysSame(type(activeSession) == "table" and activeSession.host or "", characterKey)
  end

  local function GetSessionMember(activeSession, characterKey)
    if type(activeSession) ~= "table" or type(activeSession.members) ~= "table" then
      return nil
    end
    local resolvedKey = NormalizeCharacterKey(characterKey)
    if resolvedKey == "" then
      return nil
    end
    local direct = activeSession.members[resolvedKey]
    if type(direct) == "table" then
      return direct, resolvedKey
    end
    for storedKey, member in pairs(activeSession.members) do
      if AreCharacterKeysSame(storedKey, resolvedKey) and type(member) == "table" then
        return member, storedKey
      end
    end
    return nil
  end

  local function IsJoinedSessionCharacter(activeSession, characterKey)
    local resolvedKey = NormalizeCharacterKey(characterKey)
    if resolvedKey == "" then
      return false
    end
    if IsSessionHostKey(activeSession, resolvedKey) then
      return true
    end
    local member = GetSessionMember(activeSession, resolvedKey)
    return type(member) == "table" and string.upper(TrimText(member.status or "JOINED")) == "JOINED"
  end

  local function GetSessionCharacterRole(activeSession, profileName, characterKey)
    local resolvedKey = NormalizeCharacterKey(characterKey)
    if resolvedKey == "" then
      return "RAIDER"
    end
    if IsSessionHostKey(activeSession, resolvedKey) then
      return "MASTER"
    end
    local member = GetSessionMember(activeSession, resolvedKey)
    local memberRole = TrimText(type(member) == "table" and member.role or "")
    if memberRole ~= "" then
      memberRole = string.upper(memberRole)
      if memberRole == "MASTER" or memberRole == "COUNCIL" then
        return memberRole
      end
      return "RAIDER"
    end
    if type(GetLootProfileRole) == "function" then
      local resolvedRole = string.upper(TrimText(GetLootProfileRole(profileName, resolvedKey)))
      if resolvedRole == "MASTER" or resolvedRole == "COUNCIL" then
        return resolvedRole
      end
    end
    return "RAIDER"
  end

  local function CanSessionCharacterVote(activeSession, profileName, characterKey)
    if type(GetLootProfileAccessInfo) == "function" then
      local access = GetLootProfileAccessInfo(profileName, characterKey)
      if type(access) == "table" and access.canVote ~= nil then
        return access.canVote and true or false
      end
    end
    local role = GetSessionCharacterRole(activeSession, profileName, characterKey)
    return role == "MASTER" or role == "COUNCIL"
  end

  local function IsClaimedActorSenderMatch(sender, claimedCharacterKey)
    local senderKey = NormalizeSenderKey(sender)
    local claimedKey = NormalizeCharacterKey(claimedCharacterKey)
    if senderKey == "" or claimedKey == "" then
      return false
    end
    return AreCharacterKeysSame(senderKey, claimedKey)
  end

  local function ResolveConfiguredRollOption(activeSession, profileName, optionKey, optionLabel)
    local keyNeedle = string.lower(TrimText(optionKey))
    local labelNeedle = string.lower(TrimText(optionLabel))
    local options = type(ResolveRollOptions) == "function" and ResolveRollOptions(activeSession, profileName) or nil
    for _, candidate in ipairs(type(options) == "table" and options or {}) do
      local candidateKey = string.lower(TrimText(type(candidate) == "table" and candidate.key or ""))
      local candidateLabel = string.lower(TrimText(type(candidate) == "table" and candidate.label or ""))
      if (keyNeedle ~= "" and candidateKey == keyNeedle)
        or (keyNeedle == "" and labelNeedle ~= "" and candidateLabel == labelNeedle)
      then
        return ResolveRollOption(activeSession, profileName, candidate.key, candidate.label)
      end
    end
    return nil
  end

  ResolveEntrySelection = function(entry, memberKey)
    if type(entry) ~= "table" or type(entry.selections) ~= "table" then
      return nil
    end
    local direct = entry.selections[memberKey]
    if type(direct) == "table" then
      return direct, memberKey
    end
    for selectionKey, selection in pairs(entry.selections) do
      if AreCharacterKeysSame(selectionKey, memberKey) and type(selection) == "table" then
        return selection, selectionKey
      end
    end
    return nil
  end

  local function IsPendingSelection(selection)
    local selectionKey = string.lower(TrimText(type(selection) == "table" and (selection.optionKey or selection.label) or "pending"))
    return selectionKey == "" or selectionKey == "pending"
  end

  local function HasBoardSyncState(sessionId, profileName, sender)
    return type(incomingBoardSyncs[GetBoardSyncToken(sessionId, profileName, sender)]) == "table"
  end

  local function GetIncomingTimestamp(value)
    local timestamp = tonumber(value)
    if not timestamp or timestamp <= 0 then
      return nil
    end
    return timestamp
  end

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

  local function ClipManualLedgerText(value, limit)
    local text = TrimText(value)
    local maxLength = tonumber(limit) or 0
    if maxLength > 0 and #text > maxLength then
      text = text:sub(1, maxLength)
    end
    return text
  end

  local function BuildManualLedgerRequestId(prefix)
    local token = tostring(prefix or "ML") .. "-" .. tostring(GetCurrentTimestamp()) .. "-" .. tostring(math.random(1000, 9999))
    return ClipManualLedgerText(token:gsub("[^%w%-_]", ""), MAX_MANUAL_LEDGER_ID_LENGTH)
  end

  local function FindManualLedgerEntry(profileName, memberKey, entryId, sourceRequestId)
    if type(GetLootProfile) ~= "function" then
      return nil
    end
    local profile = select(1, GetLootProfile(profileName))
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local resolvedEntryId = TrimText(entryId)
    local resolvedRequestId = TrimText(sourceRequestId)
    local ledger = type(profile) == "table" and type(profile.lootLedger) == "table" and profile.lootLedger[resolvedMemberKey] or nil
    local items = type(ledger) == "table" and ledger.items or nil
    if type(items) ~= "table" then
      return nil
    end
    for _, entry in ipairs(items) do
      if type(entry) == "table" then
        if resolvedEntryId ~= "" and TrimText(entry.entryId) == resolvedEntryId then
          return entry
        end
        if resolvedRequestId ~= "" and TrimText(entry.sourceRequestId) == resolvedRequestId then
          return entry
        end
      end
    end
    return nil
  end

  local function CanSessionCharacterEditManualPoints(activeSession, profileName, characterKey)
    local resolvedKey = NormalizeCharacterKey(characterKey)
    if resolvedKey == "" or not IsJoinedSessionCharacter(activeSession, resolvedKey) then
      return false
    end
    if type(GetLootProfileAccessInfo) ~= "function" then
      return false
    end
    local access = GetLootProfileAccessInfo(profileName, resolvedKey)
    return type(access) == "table" and access.canEditManualPoints == true
  end

  local function CanSessionCharacterEditMainAlt(activeSession, profileName, characterKey)
    local resolvedKey = NormalizeCharacterKey(characterKey)
    if resolvedKey == "" or not IsJoinedSessionCharacter(activeSession, resolvedKey) then
      return false
    end
    if type(GetLootProfileAccessInfo) ~= "function" then
      return false
    end
    local access = GetLootProfileAccessInfo(profileName, resolvedKey)
    return type(access) == "table" and access.canEditMainAlt == true
  end

  local function CanSessionCharacterEditNotes(activeSession, profileName, characterKey)
    local resolvedKey = NormalizeCharacterKey(characterKey)
    if resolvedKey == "" or not IsJoinedSessionCharacter(activeSession, resolvedKey) then
      return false
    end
    if type(GetLootProfileAccessInfo) ~= "function" then
      return false
    end
    local access = GetLootProfileAccessInfo(profileName, resolvedKey)
    return type(access) == "table" and access.canEditNotes == true
  end

  local function CanSessionCharacterDeleteLootListCharacter(activeSession, profileName, characterKey)
    local resolvedKey = NormalizeCharacterKey(characterKey)
    if resolvedKey == "" or not IsJoinedSessionCharacter(activeSession, resolvedKey) then
      return false
    end
    if type(GetLootProfileAccessInfo) ~= "function" then
      return false
    end
    local access = GetLootProfileAccessInfo(profileName, resolvedKey)
    return type(access) == "table" and access.canDeleteLootListCharacter == true
  end

  local function RefreshManualLedgerViews()
    RefreshBoardAndEditor({
      reason = "ledger",
      editorRefresh = { refreshPages = { Backgrounds = true, Profiles = true, Panels = true } },
    })
  end

  local function ApplyManualLedgerAdd(profileName, memberKey, itemName, points, note, grantedBy, requestId, entryId, awardedAt, sessionId)
    if type(AddLootLedgerEntry) ~= "function" then
      return false, "Loot list ledger API is unavailable."
    end

    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local resolvedItemName = ClipManualLedgerText(itemName, MAX_MANUAL_LEDGER_NAME_LENGTH)
    local resolvedRequestId = ClipManualLedgerText(requestId, MAX_MANUAL_LEDGER_ID_LENGTH)
    local resolvedEntryId = ClipManualLedgerText(entryId, MAX_MANUAL_LEDGER_ID_LENGTH)
    if resolvedMemberKey == "" then
      return false, "Character-Realm is required."
    end
    if resolvedItemName == "" then
      return false, "Item name is required."
    end

    local existing = FindManualLedgerEntry(profileName, resolvedMemberKey, resolvedEntryId, resolvedRequestId)
    if type(existing) == "table" then
      return true, existing, "DUPLICATE"
    end

    return AddLootLedgerEntry(
      profileName,
      resolvedMemberKey,
      resolvedItemName,
      nil,
      tonumber(points) or 0,
      ClipManualLedgerText(note, MAX_MANUAL_LEDGER_NOTE_LENGTH),
      nil,
      nil,
      MANUAL_LEDGER_ICON,
      nil,
      {
        entryId = resolvedEntryId,
        sourceRequestId = resolvedRequestId,
        awardedAt = tonumber(awardedAt) or GetCurrentTimestamp(),
        grantedBy = NormalizeCharacterKey(grantedBy),
        sessionId = TrimText(sessionId),
        isManual = true,
      }
    )
  end

  local function ApplyManualLedgerDelete(profileName, memberKey, entryId)
    if type(RemoveLootLedgerEntry) ~= "function" then
      return false, "Loot list ledger API is unavailable."
    end
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local resolvedEntryId = ClipManualLedgerText(entryId, MAX_MANUAL_LEDGER_ID_LENGTH)
    if resolvedMemberKey == "" or resolvedEntryId == "" then
      return false, "Manual ledger entry is missing."
    end
    local existing = FindManualLedgerEntry(profileName, resolvedMemberKey, resolvedEntryId, "")
    if type(existing) ~= "table" then
      return false, "Ledger entry not found."
    end
    if existing.isManual ~= true then
      return false, "Only manual point entries can be removed from this control."
    end
    return RemoveLootLedgerEntry(profileName, resolvedMemberKey, resolvedEntryId)
  end

  local function ResolveLootLedgerRole(value)
    if type(NormalizeLootLedgerRoleLocal) == "function" then
      return NormalizeLootLedgerRoleLocal(value)
    end
    return string.upper(TrimText(value)) == "ALT" and "ALT" or "MAIN"
  end

  local function ApplyLootLedgerMainAlt(profileName, characterKey, role, mainCharacter)
    if type(GetLootProfile) ~= "function" then
      return false, "Loot profile API is unavailable."
    end
    if type(SetLootLedgerMainAltRole) ~= "function" or type(SetLootLedgerMainCharacter) ~= "function" or type(ClearLootLedgerMainCharacter) ~= "function" then
      return false, "Main / Alt update API is unavailable."
    end

    local profile = select(1, GetLootProfile(profileName))
    if type(profile) ~= "table" then
      return false, "Profile not found."
    end

    local resolvedCharacter = ClipManualLedgerText(NormalizeCharacterKey(characterKey), MAX_LOOT_LEDGER_CHARACTER_LENGTH)
    if resolvedCharacter == "" then
      return false, "Select a character first."
    end

    local resolvedRole = ResolveLootLedgerRole(role)
    if resolvedRole ~= "ALT" then
      return ClearLootLedgerMainCharacter(profile, resolvedCharacter)
    end

    local ok, result = SetLootLedgerMainAltRole(profile, resolvedCharacter, "ALT")
    if not ok then
      return false, result
    end

    local allCharactersByKey = nil
    if type(BuildLootLedgerNavRows) == "function" then
      local _, byCharacter = BuildLootLedgerNavRows(profile, profileName, "")
      allCharactersByKey = byCharacter
    end
    local resolvedMain = ClipManualLedgerText(NormalizeCharacterKey(mainCharacter), MAX_LOOT_LEDGER_CHARACTER_LENGTH)
    return SetLootLedgerMainCharacter(profile, resolvedCharacter, resolvedMain, allCharactersByKey)
  end

  local function ApplyLootLedgerCharacterNote(profileName, characterKey, noteText)
    if type(GetLootProfile) ~= "function" then
      return false, "Loot profile API is unavailable."
    end
    if type(SetLootLedgerCharacterNote) ~= "function" then
      return false, "Loot List note API is unavailable."
    end

    local profile = select(1, GetLootProfile(profileName))
    if type(profile) ~= "table" then
      return false, "Profile not found."
    end

    local resolvedCharacter = ClipManualLedgerText(NormalizeCharacterKey(characterKey), MAX_LOOT_LEDGER_CHARACTER_LENGTH)
    if resolvedCharacter == "" then
      return false, "Select a character first."
    end

    return SetLootLedgerCharacterNote(profile, resolvedCharacter, ClipManualLedgerText(noteText, MAX_LOOT_LEDGER_NOTE_LENGTH))
  end

  local function ApplyLootLedgerCharacterDelete(profileName, characterKey)
    if type(GetLootProfile) ~= "function" then
      return false, "Loot profile API is unavailable."
    end
    if type(DeleteLootLedgerCharacter) ~= "function" then
      return false, "Loot List character delete API is unavailable."
    end

    local profile = select(1, GetLootProfile(profileName))
    if type(profile) ~= "table" then
      return false, "Profile not found."
    end

    local resolvedCharacter = ClipManualLedgerText(NormalizeCharacterKey(characterKey), MAX_LOOT_LEDGER_CHARACTER_LENGTH)
    if resolvedCharacter == "" then
      return false, "Select a character first."
    end

    return DeleteLootLedgerCharacter(profile, resolvedCharacter)
  end

  local function ResolveOptionalApiFunction(name)
    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 BuildDynamicLootScopeKey(prefix, identity)
    local resolvedPrefix = string.lower(TrimText(prefix))
    local resolvedIdentity = TrimText(identity)
    if resolvedPrefix == "" or resolvedIdentity == "" then
      return ""
    end
    local token = resolvedIdentity:gsub("([^%w%-%_])", function(character)
      return string.format("%%%02x", string.byte(character))
    end)
    if token == "" then
      return ""
    end
    return resolvedPrefix .. ":" .. token
  end

  local function BroadcastProfileLootDelta(profileName, change)
    local broadcastProfileDelta = ResolveOptionalApiFunction("LIDCOUNCIL_BroadcastActiveProfileDeltaFlow")
    if type(broadcastProfileDelta) ~= "function" or type(change) ~= "table" then
      return false, "Profile delta broadcast is unavailable."
    end
    change.domain = "loot"
    return broadcastProfileDelta(profileName, "loot", change)
  end

  local function BroadcastLootChangeWithFallback(profileName, change, legacySender, ...)
    local sent, err = BroadcastProfileLootDelta(profileName, change)
    if sent then
      return true, "delta"
    end
    if type(legacySender) == "function" then
      local legacySent = legacySender(...)
      if legacySent then
        return true, "legacy"
      end
    end
    return false, err or "Could not broadcast live loot change."
  end

  local function QueueScopedLootCheckpoint(profileName, subdomains, reason)
    local queueCheckpoint = ResolveOptionalApiFunction("LIDCOUNCIL_QueueActiveProfileCheckpointFlow")
    if type(queueCheckpoint) ~= "function" then
      return false
    end
    local requestedSubdomains = {}
    for _, subdomain in ipairs(type(subdomains) == "table" and subdomains or {}) do
      local resolvedSubdomain = TrimText(subdomain)
      if resolvedSubdomain ~= "" then
        requestedSubdomains[#requestedSubdomains + 1] = resolvedSubdomain
      end
    end
    if #requestedSubdomains == 0 then
      return false
    end
    return queueCheckpoint(profileName, {
      reason = TrimText(reason) ~= "" and TrimText(reason) or "loot_checkpoint",
      domains = { "loot" },
      subdomains = requestedSubdomains,
    }) == true
  end

  local function QueueLootLedgerRowCheckpoint(profileName, characterKey, reason)
    local subdomain = BuildDynamicLootScopeKey("llr", NormalizeCharacterKey(characterKey))
    if subdomain == "" then
      return false
    end
    return QueueScopedLootCheckpoint(profileName, { subdomain }, reason)
  end

  local function QueueLootLedgerMetaCheckpoint(profileName, characterKey, reason)
    local subdomain = BuildDynamicLootScopeKey("lmr", NormalizeCharacterKey(characterKey))
    if subdomain == "" then
      return false
    end
    return QueueScopedLootCheckpoint(profileName, { subdomain }, reason)
  end

  local function QueueLootLedgerCharacterCheckpoint(profileName, characterKey, reason)
    local subdomains = {}
    local rowSubdomain = BuildDynamicLootScopeKey("llr", NormalizeCharacterKey(characterKey))
    local metaSubdomain = BuildDynamicLootScopeKey("lmr", NormalizeCharacterKey(characterKey))
    if rowSubdomain ~= "" then
      subdomains[#subdomains + 1] = rowSubdomain
    end
    if metaSubdomain ~= "" then
      subdomains[#subdomains + 1] = metaSubdomain
    end
    return QueueScopedLootCheckpoint(profileName, subdomains, reason)
  end

  local function BuildManualLedgerAddDeltaChange(activeSession, memberKey, entry, grantedBy)
    if type(entry) ~= "table" then
      return nil
    end
    local resolvedGrantedBy = NormalizeCharacterKey(TrimText(grantedBy) ~= "" and grantedBy or entry.grantedBy)
    local resolvedSessionId = TrimText(TrimText(entry.sessionId) ~= "" and entry.sessionId or (type(activeSession) == "table" and activeSession.id or ""))
    return {
      action = "LEDGER_MANUAL_ADD",
      args = {
        NormalizeCharacterKey(memberKey),
        ClipManualLedgerText(entry.entryId, MAX_MANUAL_LEDGER_ID_LENGTH),
        ClipManualLedgerText(entry.itemName, MAX_MANUAL_LEDGER_NAME_LENGTH),
        tostring(tonumber(entry.points) or 0),
        ClipManualLedgerText(entry.note, MAX_MANUAL_LEDGER_NOTE_LENGTH),
        resolvedGrantedBy,
        tostring(tonumber(entry.awardedAt) or GetCurrentTimestamp()),
        resolvedSessionId,
      },
    }
  end

  local function BuildManualLedgerDeleteDeltaChange(memberKey, entryId)
    return {
      action = "LEDGER_MANUAL_DELETE",
      args = {
        NormalizeCharacterKey(memberKey),
        ClipManualLedgerText(entryId, MAX_MANUAL_LEDGER_ID_LENGTH),
      },
    }
  end

  local function BuildLootLedgerMainAltDeltaChange(characterKey, role, mainCharacter)
    return {
      action = "LEDGER_MAIN_ALT_SET",
      args = {
        ClipManualLedgerText(NormalizeCharacterKey(characterKey), MAX_LOOT_LEDGER_CHARACTER_LENGTH),
        ResolveLootLedgerRole(role),
        ClipManualLedgerText(NormalizeCharacterKey(mainCharacter), MAX_LOOT_LEDGER_CHARACTER_LENGTH),
      },
    }
  end

  local function BuildLootLedgerCharacterNoteDeltaChange(characterKey, noteText)
    return {
      action = "LEDGER_NOTE_SET",
      args = {
        ClipManualLedgerText(NormalizeCharacterKey(characterKey), MAX_LOOT_LEDGER_CHARACTER_LENGTH),
        ClipManualLedgerText(noteText, MAX_LOOT_LEDGER_NOTE_LENGTH),
      },
    }
  end

  local function BuildLootLedgerCharacterDeleteDeltaChange(characterKey)
    return {
      action = "LEDGER_CHARACTER_DELETE",
      args = {
        ClipManualLedgerText(NormalizeCharacterKey(characterKey), MAX_LOOT_LEDGER_CHARACTER_LENGTH),
      },
    }
  end

  local function BroadcastManualLedgerAdd(activeSession, profileName, memberKey, entry, grantedBy)
    local distribution = GetBroadcastDistribution()
    if not distribution or type(SendSessionComm) ~= "function" or type(entry) ~= "table" then
      return false
    end
    return SendSessionComm(
      "LL_ADD",
      distribution,
      nil,
      tostring(activeSession.id or ""),
      GetSessionCommProfileName(activeSession, profileName),
      ClipManualLedgerText(entry.entryId, MAX_MANUAL_LEDGER_ID_LENGTH),
      NormalizeCharacterKey(memberKey),
      ClipManualLedgerText(entry.itemName, MAX_MANUAL_LEDGER_NAME_LENGTH),
      tostring(tonumber(entry.points) or 0),
      ClipManualLedgerText(entry.note, MAX_MANUAL_LEDGER_NOTE_LENGTH),
      tostring(tonumber(entry.awardedAt) or GetCurrentTimestamp()),
      NormalizeCharacterKey(grantedBy)
    )
  end

  local function BroadcastManualLedgerDelete(activeSession, profileName, memberKey, entryId, changedAt)
    local distribution = GetBroadcastDistribution()
    if not distribution or type(SendSessionComm) ~= "function" then
      return false
    end
    return SendSessionComm(
      "LL_DEL",
      distribution,
      nil,
      tostring(activeSession.id or ""),
      GetSessionCommProfileName(activeSession, profileName),
      ClipManualLedgerText(entryId, MAX_MANUAL_LEDGER_ID_LENGTH),
      NormalizeCharacterKey(memberKey),
      tostring(tonumber(changedAt) or GetCurrentTimestamp())
    )
  end

  local function BroadcastLootLedgerMainAlt(activeSession, profileName, characterKey, role, mainCharacter, changedAt, changedBy)
    local distribution = GetBroadcastDistribution()
    if not distribution or type(SendSessionComm) ~= "function" then
      return false
    end
    return SendSessionComm(
      "LL_MA",
      distribution,
      nil,
      tostring(activeSession.id or ""),
      GetSessionCommProfileName(activeSession, profileName),
      ClipManualLedgerText(NormalizeCharacterKey(characterKey), MAX_LOOT_LEDGER_CHARACTER_LENGTH),
      ResolveLootLedgerRole(role),
      ClipManualLedgerText(NormalizeCharacterKey(mainCharacter), MAX_LOOT_LEDGER_CHARACTER_LENGTH),
      tostring(tonumber(changedAt) or GetCurrentTimestamp()),
      NormalizeCharacterKey(changedBy)
    )
  end

  local function BroadcastLootLedgerCharacterNote(activeSession, profileName, characterKey, noteText, changedAt, changedBy)
    local distribution = GetBroadcastDistribution()
    if not distribution or type(SendSessionComm) ~= "function" then
      return false
    end
    return SendSessionComm(
      "LL_NOTE",
      distribution,
      nil,
      tostring(activeSession.id or ""),
      GetSessionCommProfileName(activeSession, profileName),
      ClipManualLedgerText(NormalizeCharacterKey(characterKey), MAX_LOOT_LEDGER_CHARACTER_LENGTH),
      ClipManualLedgerText(noteText, MAX_LOOT_LEDGER_NOTE_LENGTH),
      tostring(tonumber(changedAt) or GetCurrentTimestamp()),
      NormalizeCharacterKey(changedBy)
    )
  end

  local function BroadcastLootLedgerCharacterDelete(activeSession, profileName, characterKey, changedAt, changedBy)
    local distribution = GetBroadcastDistribution()
    if not distribution or type(SendSessionComm) ~= "function" then
      return false
    end
    return SendSessionComm(
      "LL_CHAR_DEL",
      distribution,
      nil,
      tostring(activeSession.id or ""),
      GetSessionCommProfileName(activeSession, profileName),
      ClipManualLedgerText(NormalizeCharacterKey(characterKey), MAX_LOOT_LEDGER_CHARACTER_LENGTH),
      tostring(tonumber(changedAt) or GetCurrentTimestamp()),
      NormalizeCharacterKey(changedBy)
    )
  end

  local function EnsureRuntimeAuthorityMaps()
    runtime.localRollItemKeys = type(runtime.localRollItemKeys) == "table" and runtime.localRollItemKeys or {}
    runtime.hostRollItemKeys = type(runtime.hostRollItemKeys) == "table" and runtime.hostRollItemKeys or {}
    runtime.hostReportItemKeys = type(runtime.hostReportItemKeys) == "table" and runtime.hostReportItemKeys or {}
  end

  local function ClipItemOpenText(value, limit)
    local text = TrimText(value)
    local maxLength = tonumber(limit) or 0
    if maxLength > 0 and #text > maxLength then
      return ""
    end
    return text
  end

  local function BuildCompactItemDescriptor(value, limit)
    local link = TrimText(value)
    if link == "" then
      return ""
    end

    -- GameTooltip accepts the internal item: descriptor directly.  Removing
    -- the colour wrapper and localized display name preserves the item variant
    -- (including its context and bonus IDs) while avoiding repeated text in
    -- ITEM_OPEN and ITEM_REPORT packets.
    local descriptor = link:match("|H(item:[^|]+)|h")
    if not descriptor then
      descriptor = link:match("^(item:[^|]+)$")
    end
    if not descriptor then
      descriptor = link
    end
    return ClipItemOpenText(descriptor, limit)
  end

  local function NormalizeLootItemName(value)
    local text = TrimText(value)
    text = text:gsub("[%c#\t]+", " ")
    text = text:gsub("%s+", " ")
    return TrimText(text)
  end

  local function BuildLootItemBaseKey(payload)
    local itemID = tonumber(type(payload) == "table" and payload.itemID) or ExtractItemID(type(payload) == "table" and payload.link or nil)
    if itemID then
      return "ITEM-" .. tostring(math.floor(itemID))
    end

    local name = NormalizeLootItemName(type(payload) == "table" and payload.name or "")
    if name ~= "" then
      if #name > 40 then
        name = name:sub(1, 40)
      end
      return "NAME-" .. name
    end
    return "UNKNOWN"
  end

  local function BuildLootItemSignature(payload)
    local itemID = tonumber(type(payload) == "table" and payload.itemID) or ExtractItemID(type(payload) == "table" and payload.link or nil)
    if itemID then
      return "ITEM:" .. tostring(math.floor(itemID))
    end
    local name = NormalizeLootItemName(type(payload) == "table" and payload.name or "")
    if name ~= "" then
      return "NAME:" .. string.lower(name)
    end
    return "UNKNOWN"
  end

  local function GetCurrentInstanceDifficultyInfo()
    if type(GetInstanceInfo) ~= "function" then
      return nil, ""
    end
    local _, _, difficultyID, difficultyName = GetInstanceInfo()
    return tonumber(difficultyID) or nil, TrimText(difficultyName)
  end

  local function ResolveDetailedItemLevel(link)
    local itemLink = TrimText(link)
    if itemLink == "" then
      return nil
    end
    if type(C_Item) == "table" and type(C_Item.GetDetailedItemLevelInfo) == "function" then
      local ok, itemLevel = pcall(C_Item.GetDetailedItemLevelInfo, itemLink)
      if ok and tonumber(itemLevel) and tonumber(itemLevel) > 0 then
        return tonumber(itemLevel)
      end
    end
    if type(GetDetailedItemLevelInfo) == "function" then
      local ok, itemLevel = pcall(GetDetailedItemLevelInfo, itemLink)
      if ok and tonumber(itemLevel) and tonumber(itemLevel) > 0 then
        return tonumber(itemLevel)
      end
    end
    return nil
  end

  local function NormalizeLootItemPayload(payload)
    payload = type(payload) == "table" and payload or {}
    local itemID = tonumber(payload.itemID) or ExtractItemID(payload.link)
    local name = NormalizeLootItemName(payload.name)
    if #name > MAX_ITEM_OPEN_NAME_LENGTH then
      name = name:sub(1, MAX_ITEM_OPEN_NAME_LENGTH)
    end
    local icon = ClipItemOpenText(payload.icon, MAX_ITEM_OPEN_ICON_LENGTH)
    local numericIcon = tonumber(icon)
    if numericIcon then
      icon = math.floor(numericIcon)
    end
    local difficultyID = tonumber(payload.difficultyID or payload.lootDifficultyID or payload.difficulty) or nil
    local difficultyName = TrimText(payload.difficultyName)
    if not difficultyID then
      difficultyID, difficultyName = GetCurrentInstanceDifficultyInfo()
    end
    -- Runtime state uses the same canonical descriptor that crosses the wire.
    -- Keeping the host and receiver representations identical prevents a
    -- cosmetic display-link wrapper from becoming an archive checksum diff.
    local link = BuildCompactItemDescriptor(payload.link, MAX_ITEM_OPEN_LINK_LENGTH)
    -- The sender resolved this value in the loot/Encounter Journal context that
    -- created the item. A receiver may only have the base item cached (for
    -- example level 44), so its local hyperlink result must remain a fallback.
    local itemLevel = tonumber(payload.itemLevel)
    if not itemLevel or itemLevel <= 0 then
      itemLevel = ResolveDetailedItemLevel(link)
    end
    return {
      rollID = tonumber(payload.rollID) or nil,
      itemID = itemID and math.floor(itemID) or nil,
      itemLevel = itemLevel,
      quality = tonumber(payload.quality) or nil,
      icon = icon,
      name = name,
      link = link,
      difficultyID = difficultyID,
      difficultyName = difficultyName,
      createdAt = tonumber(payload.createdAt) or ((type(GetServerTime) == "function" and GetServerTime()) or (time and time() or 0)),
      distributionMode = NormalizeDistributionMode(payload.distributionMode),
      collectibleKind = TrimText(payload.collectibleKind),
    }
  end

  PrepareItemReportFields = function(sessionId, profileName, reporterKey, rollID, payload)
    local normalizedPayload = NormalizeLootItemPayload(payload)
    local function BuildFields(linkValue, nameValue, iconValue)
      return {
        TrimText(sessionId),
        TrimText(profileName),
        NormalizeCharacterKey(reporterKey),
        TrimText(rollID),
        normalizedPayload.itemID or "",
        normalizedPayload.itemLevel or "",
        normalizedPayload.quality or "",
        iconValue or "",
        nameValue or "",
        BuildCompactItemDescriptor(linkValue, MAX_ITEM_OPEN_LINK_LENGTH),
        normalizedPayload.createdAt or "",
      }
    end
    local function Fits(fields)
      if type(ValidateCommPayload) ~= "function" then
        return true, nil, 0
      end
      return ValidateCommPayload("ITEM_REPORT", unpack(fields))
    end
    local candidates = {
      BuildFields(normalizedPayload.link, normalizedPayload.name, normalizedPayload.icon),
      BuildFields("", normalizedPayload.name, normalizedPayload.icon),
      BuildFields("", normalizedPayload.name, ""),
    }
    local lastReason = "payload_exceeds_safe_limit"
    for _, fields in ipairs(candidates) do
      local accepted, reason, payloadBytes = Fits(fields)
      if accepted then
        return true, fields, {
          reason = "",
          payloadBytes = math.max(0, tonumber(payloadBytes) or 0),
          compacted = fields[8] ~= tostring(normalizedPayload.icon or "")
            or fields[9] ~= tostring(normalizedPayload.name or "")
            or fields[10] ~= tostring(normalizedPayload.link or ""),
        }
      end
      lastReason = TrimText(reason) ~= "" and TrimText(reason) or lastReason
    end
    local fields = BuildFields("", "", "")
    local originalName = TrimText(normalizedPayload.name)
    local low = 0
    local high = #originalName
    local bestName = ""
    while low <= high do
      local middle = math.floor((low + high) / 2)
      fields[9] = Utf8PrefixByBytes(originalName, middle)
      local accepted = Fits(fields)
      if accepted then
        bestName = fields[9]
        low = middle + 1
      else
        high = middle - 1
      end
    end
    fields[9] = bestName
    local accepted, reason, payloadBytes = Fits(fields)
    return accepted == true, fields, {
      reason = TrimText(reason) ~= "" and TrimText(reason) or lastReason,
      payloadBytes = math.max(0, tonumber(payloadBytes) or 0),
      compacted = true,
    }
  end

  local function SendItemReportPacket(activeSession, profileName, reporterKey, rollID, payload)
    if type(SendSessionComm) ~= "function" or type(activeSession) ~= "table" then
      return false, "send_unavailable"
    end
    local accepted, fields, metadata = PrepareItemReportFields(
      activeSession.id,
      profileName,
      reporterKey,
      rollID,
      payload
    )
    if not accepted then
      return false, type(metadata) == "table" and metadata.reason or "payload_exceeds_safe_limit"
    end
    return SendSessionComm("ITEM_REPORT", "WHISPER", activeSession.host, unpack(fields))
  end

  GetReportToken = function(memberKey, rollID, itemSignature, eventCreatedAt)
    local reporter = NormalizeCharacterKey(memberKey)
    local localRollId = TrimText(rollID)
    if reporter == "" or localRollId == "" then
      return ""
    end
    local signature = TrimText(itemSignature)
    local eventTime = math.max(0, math.floor(tonumber(eventCreatedAt) or 0))
    local identity = reporter .. ":" .. localRollId
    if signature ~= "" then
      identity = identity .. "\031" .. string.lower(signature)
    end
    if eventTime > 0 then
      identity = identity .. "\031" .. tostring(eventTime)
    end
    return identity
  end

  function boardSyncTransactions.EnsurePendingSelectionForMember(entry, memberKey)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if type(entry) ~= "table" or resolvedMemberKey == "" then
      return false, "missing_entry_or_member", nil
    end
    entry.selections = type(entry.selections) == "table" and entry.selections or {}
    local selection = ResolveEntrySelection(entry, resolvedMemberKey)
    if type(selection) == "table" then
      if IsPendingSelection(selection) then
        selection.optionKey = "pending"
        if TrimText(selection.label) == "" then
          selection.label = "Pending"
        end
        return true, "pending_selection_present", selection
      end
      return false, "choice_already_committed", selection
    end
    selection = {
      optionKey = "pending",
      label = "Pending",
      color = { 0.72, 0.72, 0.76 },
      selectedAt = nil,
      source = "RUNTIME_RECEIVER",
    }
    entry.selections[resolvedMemberKey] = selection
    return true, "pending_selection_created", selection
  end

  local function QueueLocalChoiceForItem(activeSession, itemKey)
    local selfKey = GetSelfKey()
    local acceptedBySelf = type(activeSession) == "table" and activeSession.acceptedBySelf == true
    if selfKey == "" or (not IsJoinedSessionCharacter(activeSession, selfKey) and not acceptedBySelf) then
      return false, "local_member_not_joined"
    end
    local entry = type(runtime.items) == "table" and runtime.items[itemKey] or nil
    if type(entry) ~= "table" then
      return false, "item_not_admitted"
    end
    if NormalizeDistributionMode(entry.distributionMode) == "MANUAL_VISIBLE" then
      return false, "manual_distribution"
    end
    local _, localMemberKey = GetSessionMember(activeSession, selfKey)
    local choiceMemberKey = localMemberKey or (IsSessionHostKey(activeSession, selfKey) and TrimText(activeSession.host) or selfKey)
    local pendingReady, pendingReason = boardSyncTransactions.EnsurePendingSelectionForMember(entry, choiceMemberKey)
    if not pendingReady then
      return false, pendingReason
    end
    if type(QueueContains) == "function" and QueueContains(itemKey) then
      return true, "already_queued"
    end
    runtime.popupQueue = type(runtime.popupQueue) == "table" and runtime.popupQueue or {}
    runtime.popupQueue[#runtime.popupQueue + 1] = itemKey
    return true, pendingReason
  end

  local function BroadcastOfficialLootItem(activeSession, profileName, itemKey, entry, sourceMemberKey, sourceRollID, targetMemberKey, receiptToken)
    local targetKey = NormalizeCharacterKey(targetMemberKey)
    local distribution = targetKey ~= "" and "WHISPER" or GetBroadcastDistribution()
    if not distribution or type(SendSessionComm) ~= "function" then
      return false
    end
    local payload = NormalizeLootItemPayload(entry)
    local function BuildFields(linkValue, nameValue, iconValue)
      local token = TrimText(receiptToken)
      if token ~= "" then
        return {
          tostring(activeSession.id or ""),
          profileName,
          itemKey,
          payload.itemID or "",
          payload.itemLevel or "",
          payload.quality or "",
          iconValue or "",
          nameValue or "",
          BuildCompactItemDescriptor(linkValue, MAX_ITEM_OPEN_LINK_LENGTH),
          payload.createdAt or "",
          NormalizeCharacterKey(sourceMemberKey),
          TrimText(sourceRollID),
          NormalizeDistributionMode(payload.distributionMode),
          token
        }
      end
      return {
        tostring(activeSession.id or ""),
        profileName,
        itemKey,
        payload.itemID or "",
        payload.itemLevel or "",
        payload.quality or "",
        iconValue or "",
        nameValue or "",
        BuildCompactItemDescriptor(linkValue, MAX_ITEM_OPEN_LINK_LENGTH),
        payload.createdAt or "",
        NormalizeCharacterKey(sourceMemberKey),
        TrimText(sourceRollID),
        NormalizeDistributionMode(payload.distributionMode)
      }
    end
    local function TryFields(fields)
      if type(ValidateCommPayload) == "function" then
        local accepted, reason = ValidateCommPayload("ITEM_OPEN", unpack(fields))
        if not accepted then
          return false, reason, false
        end
      end
      local sent, reason = SendSessionComm(
        "ITEM_OPEN",
        distribution,
        targetKey ~= "" and targetKey or nil,
        unpack(fields)
      )
      return sent == true, reason, true
    end
    local candidates = {
      BuildFields(payload.link or "", payload.name or "", payload.icon or ""),
      BuildFields("", payload.name or "", payload.icon or ""),
      BuildFields("", payload.name or "", ""),
    }
    local lastReason = "payload_exceeds_safe_limit"
    for _, fields in ipairs(candidates) do
      local sent, reason, attempted = TryFields(fields)
      if attempted then
        return sent, reason
      end
      lastReason = TrimText(reason) ~= "" and TrimText(reason) or lastReason
    end
    local baseFields = BuildFields("", "", "")
    local originalName = TrimText(payload.name)
    local low = 0
    local high = #originalName
    local bestName = ""
    while low <= high do
      local middle = math.floor((low + high) / 2)
      baseFields[8] = Utf8PrefixByBytes(originalName, middle)
      local accepted = type(ValidateCommPayload) ~= "function"
        or ValidateCommPayload("ITEM_OPEN", unpack(baseFields)) == true
      if accepted then
        bestName = baseFields[8]
        low = middle + 1
      else
        high = middle - 1
      end
    end
    baseFields[8] = bestName
    local sent, reason, attempted = TryFields(baseFields)
    if attempted then
      return sent, reason
    end
    return false, TrimText(reason) ~= "" and reason or lastReason
  end

  function boardSyncTransactions.GetItemOpenIdentity(sessionId, itemKey, targetKey)
    return string.lower(TrimText(sessionId))
      .. "\031" .. string.lower(TrimText(itemKey))
      .. "\031" .. string.lower(NormalizeCharacterKey(targetKey))
  end

  function boardSyncTransactions.GetItemOpenReceiptKey(token, targetKey)
    return TrimText(token) .. "\031" .. string.lower(NormalizeCharacterKey(targetKey))
  end

  function boardSyncTransactions.RecordItemOpenReceiverReplay(
    receiverState,
    sessionId,
    itemKey,
    receiptToken,
    choiceState,
    updatedAt
  )
    if type(receiverState) ~= "table" or TrimText(sessionId) == "" or TrimText(itemKey) == "" then
      return false, nil, false
    end
    if TrimText(receiverState.sessionId) ~= TrimText(sessionId) then
      receiverState.sessionId = TrimText(sessionId)
      receiverState.items = {}
      receiverState.order = {}
      receiverState.admissionCount = 0
      receiverState.duplicateCount = 0
      receiverState.ackIntentCount = 0
    end
    receiverState.items = type(receiverState.items) == "table" and receiverState.items or {}
    receiverState.order = type(receiverState.order) == "table" and receiverState.order or {}
    local identity = string.lower(TrimText(itemKey))
    local token = TrimText(receiptToken)
    local record = receiverState.items[identity]
    local duplicate = type(record) == "table" and TrimText(record.receiptToken) == token
    if type(record) ~= "table" then
      record = {
        itemKey = TrimText(itemKey),
        receiptToken = token,
        deliveryCount = 0,
        ackIntentCount = 0,
        generation = 1,
      }
      receiverState.items[identity] = record
      receiverState.order[#receiverState.order + 1] = identity
      receiverState.admissionCount = (tonumber(receiverState.admissionCount) or 0) + 1
      while #receiverState.order > 64 do
        local expiredIdentity = table.remove(receiverState.order, 1)
        receiverState.items[expiredIdentity] = nil
      end
    elseif not duplicate then
      record.receiptToken = token
      record.generation = (tonumber(record.generation) or 1) + 1
    else
      receiverState.duplicateCount = (tonumber(receiverState.duplicateCount) or 0) + 1
    end
    if TrimText(choiceState) ~= "" then
      record.choiceState = TrimText(choiceState)
    end
    record.deliveryCount = (tonumber(record.deliveryCount) or 0) + 1
    record.ackIntentCount = (tonumber(record.ackIntentCount) or 0) + 1
    record.state = duplicate and "duplicate_replay"
      or ((tonumber(record.generation) or 1) > 1 and "replay_generation" or "admitted")
    record.updatedAt = math.max(0, tonumber(updatedAt) or 0)
    receiverState.ackIntentCount = (tonumber(receiverState.ackIntentCount) or 0) + 1
    receiverState.updatedAt = record.updatedAt
    return true, record, duplicate
  end

  function boardSyncTransactions.RunItemOpenReplayValidation()
    local checks = {}
    local function addReplayCheck(name, expected, actual)
      checks[#checks + 1] = {
        name = name,
        expected = tostring(expected),
        actual = tostring(actual),
      }
    end
    local receiverState = {}
    local accepted, receiverRecord, duplicate = boardSyncTransactions.RecordItemOpenReceiverReplay(
      receiverState,
      "REPLAY-SESSION",
      "REPLAY-ITEM",
      "REPLAY-TOKEN-A",
      "pending",
      100
    )
    addReplayCheck("ITEM_OPEN first delivery admits one item and one ACK intent", "true/admitted/1/1/false",
      table.concat({
        tostring(accepted),
        tostring(receiverRecord and receiverRecord.state),
        tostring(receiverState.admissionCount),
        tostring(receiverState.ackIntentCount),
        tostring(duplicate),
      }, "/"))
    if type(receiverRecord) == "table" then
      receiverRecord.choiceState = "bis"
    end
    local savedDispatch = runtime.lastItemOpenDispatch
    local hostReport = {
      sessionId = "REPLAY-SESSION",
      profileName = "Replay Profile",
      itemKey = "REPLAY-ITEM",
      targets = {
        ["member-realm"] = {
          targetKey = "Member-Realm",
          token = "REPLAY-TOKEN-A",
          state = "pending",
          attempts = 1,
        },
      },
    }
    boardSyncTransactions.RefreshItemOpenReport(hostReport)
    addReplayCheck("ITEM_OPEN lost first ACK leaves only its recipient pending", "0/1/awaiting_receipts",
      table.concat({
        tostring(hostReport.acknowledgedCount),
        tostring(hostReport.pendingReceiptCount),
        tostring(hostReport.state),
      }, "/"))
    local replayAccepted, replayRecord, wasDuplicate = boardSyncTransactions.RecordItemOpenReceiverReplay(
      receiverState,
      "REPLAY-SESSION",
      "REPLAY-ITEM",
      "REPLAY-TOKEN-A",
      "",
      101
    )
    addReplayCheck("ITEM_OPEN retry is classified as duplicate delivery", "true/true/duplicate_replay",
      table.concat({
        tostring(replayAccepted),
        tostring(wasDuplicate),
        tostring(replayRecord and replayRecord.state),
      }, "/"))
    addReplayCheck("ITEM_OPEN duplicate preserves the submitted choice", "bis",
      replayRecord and replayRecord.choiceState)
    addReplayCheck("ITEM_OPEN duplicate creates a second ACK intent without readmission", "1/2/2",
      table.concat({
        tostring(receiverState.admissionCount),
        tostring(receiverState.ackIntentCount),
        tostring(replayRecord and replayRecord.ackIntentCount),
      }, "/"))
    addReplayCheck("ITEM_OPEN repeated ACK closes the original host transaction", true,
      boardSyncTransactions.ApplyItemOpenDispatchState(
        hostReport,
        {
          sessionId = "REPLAY-SESSION",
          profileName = "Replay Profile",
          itemKey = "REPLAY-ITEM",
          targetKey = "Member-Realm",
          token = "REPLAY-TOKEN-A",
          attempts = 2,
        },
        "acknowledged",
        "duplicate_replay",
        102
      ))
    addReplayCheck("ITEM_OPEN repeated ACK converges the host transaction", "1/0/acknowledged",
      table.concat({
        tostring(hostReport.acknowledgedCount),
        tostring(hostReport.pendingReceiptCount),
        tostring(hostReport.state),
      }, "/"))
    local _, nextGenerationRecord, nextGenerationDuplicate = boardSyncTransactions.RecordItemOpenReceiverReplay(
      receiverState,
      "REPLAY-SESSION",
      "REPLAY-ITEM",
      "REPLAY-TOKEN-B",
      "",
      103
    )
    addReplayCheck("ITEM_OPEN new dispatch generation preserves one item and its choice", "false/replay_generation/1/bis/3",
      table.concat({
        tostring(nextGenerationDuplicate),
        tostring(nextGenerationRecord and nextGenerationRecord.state),
        tostring(receiverState.admissionCount),
        tostring(nextGenerationRecord and nextGenerationRecord.choiceState),
        tostring(receiverState.ackIntentCount),
      }, "/"))
    for index = 2, 70 do
      boardSyncTransactions.RecordItemOpenReceiverReplay(
        receiverState,
        "REPLAY-SESSION",
        "REPLAY-ITEM-" .. tostring(index),
        "REPLAY-TOKEN-" .. tostring(index),
        "pending",
        103 + index
      )
    end
    local retainedCount = 0
    for _ in pairs(receiverState.items) do
      retainedCount = retainedCount + 1
    end
    addReplayCheck("ITEM_OPEN receiver replay cache is bounded", "64/64/false",
      table.concat({
        tostring(#receiverState.order),
        tostring(retainedCount),
        tostring(receiverState.items["replay-item"] ~= nil),
      }, "/"))
    local pendingEntry = { selections = {} }
    local pendingReady, pendingReason, pendingSelection = boardSyncTransactions.EnsurePendingSelectionForMember(
      pendingEntry,
      "Member-Realm"
    )
    addReplayCheck("ITEM_OPEN receiver creates a missing local pending choice", "true/pending_selection_created/pending",
      table.concat({
        tostring(pendingReady),
        tostring(pendingReason),
        tostring(type(pendingSelection) == "table" and pendingSelection.optionKey or ""),
      }, "/"))
    pendingEntry.selections = {
      ["member-realm"] = {
        optionKey = "",
        label = "",
      },
    }
    local normalizedReady, normalizedReason, normalizedSelection = boardSyncTransactions.EnsurePendingSelectionForMember(
      pendingEntry,
      "member-realm"
    )
    addReplayCheck("ITEM_OPEN receiver normalizes an empty pending choice before popup gating", "true/pending_selection_present/pending/Pending",
      table.concat({
        tostring(normalizedReady),
        tostring(normalizedReason),
        tostring(type(normalizedSelection) == "table" and normalizedSelection.optionKey or ""),
        tostring(type(normalizedSelection) == "table" and normalizedSelection.label or ""),
      }, "/"))
    if type(normalizedSelection) == "table" then
      normalizedSelection.optionKey = "bis"
    else
      pendingEntry.selections["member-realm"] = { optionKey = "bis" }
    end
    local committedReady, committedReason, committedSelection = boardSyncTransactions.EnsurePendingSelectionForMember(
      pendingEntry,
      "member-realm"
    )
    addReplayCheck("ITEM_OPEN receiver never overwrites a committed local choice", "false/choice_already_committed/bis",
      table.concat({
        tostring(committedReady),
        tostring(committedReason),
        tostring(type(committedSelection) == "table" and committedSelection.optionKey or ""),
      }, "/"))
    runtime.lastItemOpenDispatch = savedDispatch
    return checks
  end

  function boardSyncTransactions.RefreshItemOpenReport(report)
    if type(report) ~= "table" then
      return nil
    end
    local acknowledged = 0
    local pending = 0
    local failed = 0
    for _, target in pairs(type(report.targets) == "table" and report.targets or {}) do
      local state = string.lower(TrimText(type(target) == "table" and target.state or "pending"))
      if state == "acknowledged" then
        acknowledged = acknowledged + 1
      elseif state == "failed" then
        failed = failed + 1
      else
        pending = pending + 1
      end
    end
    report.acknowledgedCount = acknowledged
    report.pendingReceiptCount = pending
    report.failedTargetCount = failed
    report.expectedCount = acknowledged + pending + failed
    report.state = failed > 0 and "failed" or (pending > 0 and "awaiting_receipts" or "acknowledged")
    report.updatedAt = (type(GetServerTime) == "function" and GetServerTime()) or (time and time() or 0)
    runtime.lastItemOpenDispatch = report
    local transportTest = type(runtime.lastLiveTransportTest) == "table" and runtime.lastLiveTransportTest or nil
    if type(transportTest) == "table" and TrimText(transportTest.itemKey) == TrimText(report.itemKey) then
      transportTest.acknowledgedCount = acknowledged
      transportTest.pendingReceiptCount = pending
      transportTest.failedTargetCount = failed
      transportTest.dispatchState = report.state
      transportTest.deliveryOk = report.state == "acknowledged"
      transportTest.ok = report.state ~= "failed"
      transportTest.code = report.state == "acknowledged" and "ACKNOWLEDGED"
        or (report.state == "failed" and "RECEIPT_FAILED" or "AWAITING_RECEIPTS")
      transportTest.message = report.state == "acknowledged"
        and ("Live ITEM_OPEN delivery confirmed by " .. tostring(acknowledged) .. "/" .. tostring(report.expectedCount) .. " member(s).")
        or (report.state == "failed"
          and ("Live ITEM_OPEN delivery failed for " .. tostring(failed) .. " member(s).")
          or ("Live ITEM_OPEN delivery awaiting " .. tostring(pending) .. " receipt(s)."))
      transportTest.updatedAt = report.updatedAt
    end
    return report
  end

  function boardSyncTransactions.ApplyItemOpenDispatchState(report, transaction, state, reason, updatedAt)
    if type(report) ~= "table" or type(transaction) ~= "table" then
      return false
    end
    if TrimText(report.sessionId) ~= TrimText(transaction.sessionId)
      or TrimText(report.profileName) ~= TrimText(transaction.profileName)
      or TrimText(report.itemKey) ~= TrimText(transaction.itemKey)
    then
      return false
    end
    local targetKey = NormalizeCharacterKey(transaction.targetKey)
    local target = type(report.targets) == "table" and report.targets[string.lower(targetKey)] or nil
    if type(target) ~= "table" or TrimText(target.token) ~= TrimText(transaction.token) then
      return false
    end
    local resolvedState = string.lower(TrimText(state))
    if resolvedState ~= "acknowledged" and resolvedState ~= "failed" and resolvedState ~= "pending" then
      return false
    end
    target.state = resolvedState
    target.reason = TrimText(reason)
    target.attempts = math.max(0, tonumber(transaction.attempts) or tonumber(target.attempts) or 0)
    target.updatedAt = math.max(0, tonumber(updatedAt) or 0)
    transaction.state = resolvedState
    transaction.reason = target.reason
    transaction.updatedAt = target.updatedAt
    boardSyncTransactions.RefreshItemOpenReport(report)
    return true
  end

  function boardSyncTransactions.FailItemOpenTransaction(transaction, reason)
    if type(transaction) ~= "table" or transaction.state ~= "pending" then
      return false
    end
    local report = boardSyncTransactions.itemOpenReports[TrimText(transaction.reportKey)]
    if not boardSyncTransactions.ApplyItemOpenDispatchState(
      report,
      transaction,
      "failed",
      TrimText(reason) ~= "" and TrimText(reason) or "receipt_timeout",
      (type(GetServerTime) == "function" and GetServerTime()) or (time and time() or 0)
    ) then
      return false
    end
    boardSyncTransactions.itemOpenOutgoing[TrimText(transaction.key)] = nil
    boardSyncTransactions.completedItemOpenReceipts[TrimText(transaction.key)] = transaction
    return true
  end

  function boardSyncTransactions.ScheduleItemOpenRetry(transaction, delayIndex)
    local delay = boardSyncTransactions.itemOpenRetryDelays[math.max(1, tonumber(delayIndex) or 1)]
    if not delay or type(C_Timer) ~= "table" or type(C_Timer.After) ~= "function" then
      return boardSyncTransactions.FailItemOpenTransaction(transaction, "receipt_timeout")
    end
    transaction.retryWatch = math.max(0, tonumber(transaction.retryWatch) or 0) + 1
    local retryWatch = transaction.retryWatch
    C_Timer.After(delay, function()
      if boardSyncTransactions.itemOpenOutgoing[TrimText(transaction.key)] ~= transaction
        or transaction.retryWatch ~= retryWatch
        or transaction.state ~= "pending"
      then
        return
      end
      if transaction.attempts >= #boardSyncTransactions.itemOpenRetryDelays then
        boardSyncTransactions.FailItemOpenTransaction(transaction, "receipt_timeout")
      else
        boardSyncTransactions.SendItemOpenAttempt(transaction)
      end
    end)
    return true
  end

  function boardSyncTransactions.SendItemOpenAttempt(transaction)
    if type(transaction) ~= "table" or transaction.state ~= "pending" then
      return false
    end
    local activeSession, activeProfileName = GetActiveLootSession()
    if not DoesRuntimeSessionMatch(activeSession, activeProfileName, transaction.sessionId, transaction.profileName)
      or not IsSelfHost(activeSession)
    then
      return boardSyncTransactions.FailItemOpenTransaction(transaction, "session_changed")
    end
    if not IsJoinedSessionCharacter(activeSession, transaction.targetKey) then
      return boardSyncTransactions.FailItemOpenTransaction(transaction, "target_left_session")
    end
    local entry = type(runtime.items) == "table" and runtime.items[transaction.itemKey] or nil
    if type(entry) ~= "table" then
      return boardSyncTransactions.FailItemOpenTransaction(transaction, "item_unavailable")
    end
    transaction.attempts = math.max(0, tonumber(transaction.attempts) or 0) + 1
    transaction.lastSendAccepted, transaction.lastSendReason = BroadcastOfficialLootItem(
      activeSession,
      transaction.profileName,
      transaction.itemKey,
      entry,
      transaction.sourceMemberKey,
      transaction.sourceRollID,
      transaction.targetKey,
      transaction.token
    )
    transaction.lastSentAt = (type(GetServerTime) == "function" and GetServerTime()) or (time and time() or 0)
    local report = boardSyncTransactions.itemOpenReports[TrimText(transaction.reportKey)]
    local target = type(report) == "table" and type(report.targets) == "table"
      and report.targets[string.lower(NormalizeCharacterKey(transaction.targetKey))]
      or nil
    if type(target) == "table" then
      target.attempts = transaction.attempts
      target.sendAccepted = transaction.lastSendAccepted == true
      target.reason = transaction.lastSendAccepted == true and "" or TrimText(transaction.lastSendReason)
      target.updatedAt = transaction.lastSentAt
      boardSyncTransactions.RefreshItemOpenReport(report)
    end
    boardSyncTransactions.ScheduleItemOpenRetry(transaction, transaction.attempts)
    return transaction.lastSendAccepted == true
  end

  function boardSyncTransactions.DispatchOfficialLootItem(activeSession, profileName, itemKey, entry, sourceMemberKey, sourceRollID, onlyTargetKey)
    if type(activeSession) ~= "table" or not IsSelfHost(activeSession) then
      return false, nil
    end
    local reportKey = string.lower(TrimText(activeSession.id)) .. "\031" .. string.lower(TrimText(itemKey))
    local report = boardSyncTransactions.itemOpenReports[reportKey]
    if type(report) ~= "table" then
      boardSyncTransactions.nextItemOpenToken = boardSyncTransactions.nextItemOpenToken + 1
      local now = (type(GetServerTime) == "function" and GetServerTime()) or (time and time() or 0)
      report = {
        sessionId = TrimText(activeSession.id),
        profileName = TrimText(profileName),
        itemKey = TrimText(itemKey),
        token = "IOA-" .. tostring(now) .. "-" .. tostring(boardSyncTransactions.nextItemOpenToken),
        sourceMemberKey = NormalizeCharacterKey(sourceMemberKey),
        sourceRollID = TrimText(sourceRollID),
        targets = {},
        state = "pending",
      }
      boardSyncTransactions.itemOpenReports[reportKey] = report
    end
    local targets = {}
    local onlyTarget = NormalizeCharacterKey(onlyTargetKey)
    if onlyTarget ~= "" then
      if IsJoinedSessionCharacter(activeSession, onlyTarget) and not IsSessionHostKey(activeSession, onlyTarget) then
        targets[1] = onlyTarget
      end
    else
      for memberKey, member in pairs(type(activeSession.members) == "table" and activeSession.members or {}) do
        local targetKey = NormalizeCharacterKey(memberKey)
        if targetKey ~= ""
          and string.upper(TrimText(type(member) == "table" and member.status or "JOINED")) == "JOINED"
          and not IsSessionHostKey(activeSession, targetKey)
        then
          targets[#targets + 1] = targetKey
        end
      end
      table.sort(targets)
    end
    local allAccepted = true
    for _, targetKey in ipairs(targets) do
      local identity = boardSyncTransactions.GetItemOpenIdentity(activeSession.id, itemKey, targetKey)
      local transaction = boardSyncTransactions.itemOpenByIdentity[identity]
      if type(transaction) ~= "table" then
        transaction = {
          token = report.token,
          reportKey = reportKey,
          sessionId = report.sessionId,
          profileName = report.profileName,
          itemKey = report.itemKey,
          targetKey = targetKey,
          sourceMemberKey = report.sourceMemberKey,
          sourceRollID = report.sourceRollID,
          state = "pending",
          attempts = 0,
        }
        transaction.key = boardSyncTransactions.GetItemOpenReceiptKey(transaction.token, targetKey)
        boardSyncTransactions.itemOpenByIdentity[identity] = transaction
        boardSyncTransactions.itemOpenOutgoing[transaction.key] = transaction
        report.targets[string.lower(targetKey)] = {
          targetKey = targetKey,
          token = transaction.token,
          state = "pending",
          attempts = 0,
        }
      end
      if onlyTarget ~= "" and transaction.state == "pending" then
        allAccepted = boardSyncTransactions.SendItemOpenAttempt(transaction) and allAccepted
      elseif onlyTarget ~= "" then
        allAccepted = BroadcastOfficialLootItem(
          activeSession, profileName, itemKey, entry, sourceMemberKey, sourceRollID, targetKey, transaction.token
        ) and allAccepted
      end
    end
    if onlyTarget == "" and #targets > 0 and report.initialDispatched ~= true then
      report.initialDispatched = true
      report.initialSendAccepted, report.initialSendReason = BroadcastOfficialLootItem(
        activeSession, profileName, itemKey, entry, sourceMemberKey, sourceRollID, nil, report.token
      )
      report.initialSentAt = (type(GetServerTime) == "function" and GetServerTime()) or (time and time() or 0)
      allAccepted = report.initialSendAccepted == true
      for _, targetKey in ipairs(targets) do
        local transaction = boardSyncTransactions.itemOpenByIdentity[
          boardSyncTransactions.GetItemOpenIdentity(activeSession.id, itemKey, targetKey)
        ]
        if type(transaction) == "table" and transaction.state == "pending" then
          transaction.attempts = 1
          transaction.lastSendAccepted = report.initialSendAccepted == true
          transaction.lastSendReason = TrimText(report.initialSendReason)
          transaction.lastSentAt = report.initialSentAt
          local target = report.targets[string.lower(targetKey)]
          if type(target) == "table" then
            target.attempts = 1
            target.sendAccepted = report.initialSendAccepted == true
            target.reason = report.initialSendAccepted == true and "" or TrimText(report.initialSendReason)
            target.updatedAt = report.initialSentAt
          end
          boardSyncTransactions.ScheduleItemOpenRetry(transaction, 1)
        end
      end
    end
    boardSyncTransactions.RefreshItemOpenReport(report)
    return allAccepted, report
  end

  BuildChoiceMirrorIdentity = function(sessionId, itemKey, memberKey, selectedSeq, targetKey)
    return string.lower(table.concat({
      TrimText(sessionId),
      TrimText(itemKey),
      NormalizeCharacterKey(memberKey),
      tostring(math.max(0, math.floor(tonumber(selectedSeq) or 0))),
      NormalizeCharacterKey(targetKey),
    }, "\031"))
  end

  function boardSyncTransactions.ApplyChoiceMirrorReceipt(transaction, reason)
    if type(transaction) ~= "table" or transaction.state ~= "pending" then
      return false
    end
    transaction.state = "acknowledged"
    transaction.reason = string.lower(TrimText(reason))
    transaction.retryWatch = math.max(0, tonumber(transaction.retryWatch) or 0) + 1
    local target = transaction.report and transaction.report.targets
      and transaction.report.targets[string.lower(NormalizeCharacterKey(transaction.targetKey))]
      or nil
    if type(target) == "table" then
      target.state = "acknowledged"
      target.reason = transaction.reason
      target.attempts = transaction.attempts
    end
    return true
  end

  local function RefreshChoiceMirrorDispatch(report)
    if type(report) ~= "table" then
      return nil
    end
    local acknowledged = 0
    local pending = 0
    local failed = 0
    for _, target in pairs(type(report.targets) == "table" and report.targets or {}) do
      local state = string.lower(TrimText(type(target) == "table" and target.state or "pending"))
      if state == "acknowledged" then
        acknowledged = acknowledged + 1
      elseif state == "failed" then
        failed = failed + 1
      else
        pending = pending + 1
      end
    end
    report.acknowledgedCount = acknowledged
    report.pendingReceiptCount = pending
    report.failedTargetCount = failed
    report.expectedCount = acknowledged + pending + failed
    report.state = failed > 0 and "failed" or (pending > 0 and "awaiting_receipts" or "acknowledged")
    report.updatedAt = (type(GetServerTime) == "function" and GetServerTime()) or (time and time() or 0)
    runtime.lastChoiceMirrorDispatch = report
    return report
  end

  local SendChoiceMirrorAttempt
  local function FailChoiceMirrorTransaction(transaction, reason)
    if type(transaction) ~= "table" or transaction.state ~= "pending" then
      return false
    end
    transaction.state = "failed"
    transaction.reason = TrimText(reason) ~= "" and TrimText(reason) or "receipt_timeout"
    transaction.retryWatch = math.max(0, tonumber(transaction.retryWatch) or 0) + 1
    local target = transaction.report and transaction.report.targets
      and transaction.report.targets[string.lower(transaction.targetKey)]
      or nil
    if type(target) == "table" then
      target.state = "failed"
      target.reason = transaction.reason
      target.attempts = transaction.attempts
    end
    boardSyncTransactions.choiceMirrorOutgoing[transaction.identity] = nil
    RefreshChoiceMirrorDispatch(transaction.report)
    return true
  end

  local function ScheduleChoiceMirrorRetry(transaction, delayIndex)
    local delay = boardSyncTransactions.choiceMirrorRetryDelays[math.max(1, tonumber(delayIndex) or 1)]
    if not delay or type(C_Timer) ~= "table" or type(C_Timer.After) ~= "function" then
      return FailChoiceMirrorTransaction(transaction, "receipt_timeout")
    end
    transaction.retryWatch = math.max(0, tonumber(transaction.retryWatch) or 0) + 1
    local retryWatch = transaction.retryWatch
    C_Timer.After(delay, function()
      if boardSyncTransactions.choiceMirrorOutgoing[transaction.identity] ~= transaction
        or transaction.retryWatch ~= retryWatch
        or transaction.state ~= "pending"
      then
        return
      end
      if transaction.attempts >= #boardSyncTransactions.choiceMirrorRetryDelays then
        FailChoiceMirrorTransaction(transaction, "receipt_timeout")
      else
        SendChoiceMirrorAttempt(transaction)
      end
    end)
    return true
  end

  SendChoiceMirrorAttempt = function(transaction)
    if type(transaction) ~= "table" or transaction.state ~= "pending" then
      return false
    end
    local activeSession, activeProfileName = GetActiveLootSession()
    if not DoesRuntimeSessionMatch(activeSession, activeProfileName, transaction.sessionId, transaction.profileName)
      or not IsSelfHost(activeSession)
      or not IsJoinedSessionCharacter(activeSession, transaction.targetKey)
      or not CanSessionCharacterVote(activeSession, activeProfileName, transaction.targetKey)
    then
      return FailChoiceMirrorTransaction(transaction, "session_or_target_changed")
    end
    transaction.attempts = math.max(0, tonumber(transaction.attempts) or 0) + 1
    transaction.lastSendAccepted, transaction.lastSendReason = SendChoicePacket(
      "RCHOICE",
      "WHISPER",
      transaction.targetKey,
      transaction.sessionId,
      transaction.profileName,
      transaction.itemKey,
      transaction.memberKey,
      transaction.optionKey,
      transaction.optionLabel,
      transaction.note,
      transaction.rollValue,
      transaction.selectedAt,
      transaction.selectedSeq
    )
    local target = transaction.report and transaction.report.targets
      and transaction.report.targets[string.lower(transaction.targetKey)]
      or nil
    if type(target) == "table" then
      target.attempts = transaction.attempts
      target.sendAccepted = transaction.lastSendAccepted == true
      target.reason = transaction.lastSendAccepted and "" or TrimText(transaction.lastSendReason)
    end
    ScheduleChoiceMirrorRetry(transaction, transaction.attempts)
    RefreshChoiceMirrorDispatch(transaction.report)
    return transaction.lastSendAccepted == true
  end

  local function TrackCouncilChoiceMirrors(activeSession, profileName, packet, initialAccepted)
    local report = {
      sessionId = TrimText(activeSession.id),
      profileName = TrimText(profileName),
      itemKey = TrimText(packet.itemKey),
      memberKey = NormalizeCharacterKey(packet.memberKey),
      selectedSeq = math.max(0, math.floor(tonumber(packet.selectedSeq) or 0)),
      initialSendAccepted = initialAccepted == true,
      targets = {},
      state = "acknowledged",
    }
    for memberKey, member in pairs(type(activeSession.members) == "table" and activeSession.members or {}) do
      local targetKey = NormalizeCharacterKey(memberKey)
      if targetKey ~= ""
        and string.upper(TrimText(type(member) == "table" and member.status or "JOINED")) == "JOINED"
        and not IsSessionHostKey(activeSession, targetKey)
        and CanSessionCharacterVote(activeSession, profileName, targetKey)
      then
        local identity = BuildChoiceMirrorIdentity(
          activeSession.id, packet.itemKey, packet.memberKey, packet.selectedSeq, targetKey
        )
        local transaction = {
          identity = identity,
          sessionId = TrimText(activeSession.id),
          profileName = TrimText(profileName),
          itemKey = TrimText(packet.itemKey),
          memberKey = NormalizeCharacterKey(packet.memberKey),
          optionKey = TrimText(packet.optionKey),
          optionLabel = TrimText(packet.optionLabel),
          note = NormalizeSelectionNote(packet.note),
          rollValue = packet.rollValue or "",
          selectedAt = packet.selectedAt,
          selectedSeq = packet.selectedSeq,
          targetKey = targetKey,
          attempts = 1,
          state = "pending",
          report = report,
        }
        boardSyncTransactions.choiceMirrorOutgoing[identity] = transaction
        report.targets[string.lower(targetKey)] = {
          targetKey = targetKey,
          state = "pending",
          attempts = 1,
          sendAccepted = initialAccepted == true,
        }
        ScheduleChoiceMirrorRetry(transaction, 1)
      end
    end
    return RefreshChoiceMirrorDispatch(report)
  end

  local function BroadcastAuthoritativeChoice(activeSession, profileName, itemKey, memberKey, optionKey, optionLabel, note, rollValue, selectedAt, selectedSeq, directTarget)
    if type(activeSession) ~= "table" or not IsSelfHost(activeSession) then
      return false, "not_session_host"
    end
    local packet = {
      itemKey = TrimText(itemKey),
      memberKey = NormalizeCharacterKey(memberKey),
      optionKey = TrimText(optionKey),
      optionLabel = TrimText(optionLabel),
      note = NormalizeSelectionNote(note),
      rollValue = rollValue or "",
      selectedAt = selectedAt or "",
      selectedSeq = selectedSeq or "",
    }
    local commProfileName = GetSessionCommProfileName(activeSession, profileName)
    local resolvedDirectTarget = NormalizeCharacterKey(directTarget)
    if resolvedDirectTarget ~= "" then
      SendChoicePacket(
        "RCHOICE", "WHISPER", resolvedDirectTarget, activeSession.id, commProfileName,
        packet.itemKey, packet.memberKey, packet.optionKey, packet.optionLabel, packet.note,
        packet.rollValue, packet.selectedAt, packet.selectedSeq
      )
    end
    local distribution = GetBroadcastDistribution()
    if not distribution then
      return false, "broadcast_unavailable"
    end
    local sent, reason = SendChoicePacket(
      "RCHOICE", distribution, nil, activeSession.id, commProfileName,
      packet.itemKey, packet.memberKey, packet.optionKey, packet.optionLabel, packet.note,
      packet.rollValue, packet.selectedAt, packet.selectedSeq
    )
    TrackCouncilChoiceMirrors(activeSession, commProfileName, packet, sent)
    return sent == true, reason
  end

  local function OpenAuthoritativeLootItem(activeSession, profileName, payload, sourceMemberKey, sourceRollID)
    if type(activeSession) ~= "table" or TrimText(profileName) == "" or not IsSelfHost(activeSession) then
      return false, "Only the active session host can open official loot items."
    end
    if not EnsureRuntimeSession(activeSession, profileName) then
      return false, "Could not prepare the active session runtime."
    end

    EnsureRuntimeAuthorityMaps()
    local normalizedPayload = NormalizeLootItemPayload(payload)
    if type(ClassifyLootRollItem) == "function" then
      local classification = ClassifyLootRollItem(normalizedPayload)
      if type(classification) == "table" then
        normalizedPayload.distributionMode = NormalizeDistributionMode(classification.distributionMode)
        normalizedPayload.collectibleKind = TrimText(classification.collectibleKind ~= "" and classification.collectibleKind or normalizedPayload.collectibleKind)
      end
    end
    local sourceKey = NormalizeCharacterKey(sourceMemberKey ~= nil and sourceMemberKey or GetSelfKey())
    local localSelfKey = GetSelfKey()
    local rollID = TrimText(sourceRollID ~= nil and sourceRollID or normalizedPayload.rollID)
    local signature = BuildLootItemSignature(normalizedPayload)
    local reportToken = GetReportToken(sourceKey, rollID, signature, normalizedPayload.createdAt)
    local rollIdentity = rollID ~= "" and (string.lower(rollID) .. "\031" .. string.lower(signature)) or ""
    local itemKey = reportToken ~= "" and runtime.hostReportItemKeys[reportToken] or nil
    local matchedExactReport = TrimText(itemKey) ~= ""
    if TrimText(itemKey) == "" and rollIdentity ~= "" then
      itemKey = runtime.hostRollItemKeys[rollIdentity]
    end

    local entry = nil
    if TrimText(itemKey) ~= "" then
      entry = runtime.items[itemKey]
      if type(entry) ~= "table" or entry.awardedAt ~= nil or TrimText(entry.awardedTo) ~= "" then
        if matchedExactReport and type(entry) == "table" then
          -- A queued retry for an already-completed event must not reopen the
          -- awarded item as a second live roll.
          return true, itemKey
        end
        itemKey = nil
        entry = nil
      end
    end

    local createdNewEntry = type(entry) ~= "table"
    if TrimText(itemKey) == "" or createdNewEntry then
      local baseKey = AUTHORITATIVE_LOOT_ITEM_PREFIX .. BuildLootItemBaseKey(normalizedPayload)
      if type(NextItemKey) == "function" then
        itemKey = NextItemKey(baseKey)
      else
        itemKey = baseKey .. "#" .. tostring(#(runtime.itemOrder or {}) + 1)
      end
      createdNewEntry = true
    end

    entry = EnsureLiveEntry(activeSession, profileName, itemKey, normalizedPayload)
    entry.__authoritativeLoot = true
    entry.__lootItemSignature = signature
    entry.__lastReportSource = sourceKey
    entry.__lastReportRollID = rollID
    entry.createdAt = tonumber(entry.createdAt) or normalizedPayload.createdAt
    if reportToken ~= "" then
      runtime.hostReportItemKeys[reportToken] = itemKey
    end
    if rollIdentity ~= "" then
      runtime.hostRollItemKeys[rollIdentity] = itemKey
    end
    if AreCharacterKeysSame(sourceKey, localSelfKey) and rollID ~= "" then
      runtime.localRollItemKeys[rollID] = itemKey
    end

    QueueLocalChoiceForItem(activeSession, itemKey)
    if createdNewEntry then
      boardSyncTransactions.DispatchOfficialLootItem(activeSession, profileName, itemKey, entry, sourceKey, rollID)
    elseif not AreCharacterKeysSame(sourceKey, localSelfKey) then
      -- Every remote report receives the authoritative item again. This is the
      -- reporter's receipt when their original ITEM_OPEN was missed.
      boardSyncTransactions.DispatchOfficialLootItem(activeSession, profileName, itemKey, entry, sourceKey, rollID, sourceKey)
    end
    RefreshBoardAndEditor({
      reason = "track",
      itemKey = itemKey,
    })
    if type(RefreshChoicePopup) == "function" then
      RefreshChoicePopup({
        reason = "track",
        itemKey = itemKey,
      })
    end
    return true, itemKey
  end

  function boardSyncTransactions.ClearSimulationRuntimeItems()
    local removeKeys = {}
    for _, itemKey in ipairs(runtime.itemOrder or {}) do
      if IsRealSimulationItemKey(itemKey) then
        removeKeys[itemKey] = true
        runtime.items[itemKey] = nil
      end
    end
    local itemOrder = {}
    for _, itemKey in ipairs(runtime.itemOrder or {}) do
      if not removeKeys[itemKey] and type(runtime.items[itemKey]) == "table" then
        itemOrder[#itemOrder + 1] = itemKey
      end
    end
    runtime.itemOrder = itemOrder
    local popupQueue = {}
    for _, itemKey in ipairs(runtime.popupQueue or {}) do
      if not removeKeys[itemKey] and type(runtime.items[itemKey]) == "table" then
        popupQueue[#popupQueue + 1] = itemKey
      end
    end
    runtime.popupQueue = popupQueue
    if removeKeys[runtime.selectedItemKey] then
      runtime.selectedItemKey = runtime.itemOrder[1]
    end
    if #runtime.itemOrder == 0 then
      runtime.selectedMemberKey = nil
    end
    for token, transaction in pairs(boardSyncTransactions.itemOpenOutgoing) do
      if removeKeys[TrimText(type(transaction) == "table" and transaction.itemKey or "")] then
        boardSyncTransactions.itemOpenOutgoing[token] = nil
      end
    end
    for token, transaction in pairs(boardSyncTransactions.completedItemOpenReceipts) do
      if removeKeys[TrimText(type(transaction) == "table" and transaction.itemKey or "")] then
        boardSyncTransactions.completedItemOpenReceipts[token] = nil
      end
    end
    for identity, transaction in pairs(boardSyncTransactions.itemOpenByIdentity) do
      if removeKeys[TrimText(type(transaction) == "table" and transaction.itemKey or "")] then
        boardSyncTransactions.itemOpenByIdentity[identity] = nil
      end
    end
    for reportKey, report in pairs(boardSyncTransactions.itemOpenReports) do
      if removeKeys[TrimText(type(report) == "table" and report.itemKey or "")] then
        boardSyncTransactions.itemOpenReports[reportKey] = nil
      end
    end
    if removeKeys[TrimText(type(runtime.lastItemOpenDispatch) == "table" and runtime.lastItemOpenDispatch.itemKey or "")] then
      runtime.lastItemOpenDispatch = nil
    end
  end

  function boardSyncTransactions.OpenTransportSimulationItem(activeSession, profileName, payload)
    if type(activeSession) ~= "table" or TrimText(profileName) == "" or not IsSelfHost(activeSession) then
      return false, "", { code = "NOT_SESSION_HOST", message = "Only the active session host can run the live transport test." }
    end
    if string.upper(TrimText(activeSession.status or "")) ~= "ACTIVE" then
      return false, "", { code = "SESSION_NOT_ACTIVE", message = "Start the session before running the live transport test." }
    end
    if not EnsureRuntimeSession(activeSession, profileName) then
      return false, "", { code = "RUNTIME_UNAVAILABLE", message = "Could not prepare the active session runtime." }
    end
    boardSyncTransactions.ClearSimulationRuntimeItems()

    local normalizedPayload = NormalizeLootItemPayload(payload)
    if type(ClassifyLootRollItem) == "function" then
      local classification = ClassifyLootRollItem(normalizedPayload)
      if type(classification) == "table" then
        normalizedPayload.distributionMode = NormalizeDistributionMode(classification.distributionMode)
        normalizedPayload.collectibleKind = TrimText(classification.collectibleKind)
      end
    end
    -- The parity test validates the council-roll route even if its sample item
    -- would normally be handled as a visible manual-distribution item.
    normalizedPayload.distributionMode = "COUNCIL"
    local now = (type(GetServerTime) == "function" and GetServerTime()) or (time and time() or 0)
    local itemKey = NextItemKey("TESTSIM-TRANSPORT-" .. tostring(now))
    local sourceKey = NormalizeCharacterKey(GetSelfKey())
    local entry = EnsureLiveEntry(activeSession, profileName, itemKey, normalizedPayload)
    entry.isSimulation = true
    entry.__transportSimulation = true
    entry.__authoritativeLoot = true
    entry.__lootItemSignature = BuildLootItemSignature(normalizedPayload)
    entry.__lastReportSource = sourceKey
    entry.createdAt = tonumber(entry.createdAt) or now
    local choiceQueued = QueueLocalChoiceForItem(activeSession, itemKey)

    local remoteTargetCount = 0
    for memberKey, member in pairs(type(activeSession.members) == "table" and activeSession.members or {}) do
      if string.upper(TrimText(type(member) == "table" and member.status or "JOINED")) == "JOINED"
        and not AreCharacterKeysSame(memberKey, sourceKey)
      then
        remoteTargetCount = remoteTargetCount + 1
      end
    end
    local sent, dispatchReport = boardSyncTransactions.DispatchOfficialLootItem(
      activeSession, profileName, itemKey, entry, sourceKey, ""
    )
    sent = remoteTargetCount == 0 or sent == true
    RefreshBoardAndEditor({ reason = "track", itemKey = itemKey })
    local popupOpened = type(RefreshChoicePopup) == "function"
      and RefreshChoicePopup({ reason = "track", itemKey = itemKey }) == true
      or false
    local detail = {
      ok = sent,
      code = sent and (remoteTargetCount > 0 and "DISPATCHED" or "LOCAL_ONLY") or "DISPATCH_FAILED",
      message = sent
        and (remoteTargetCount > 0
          and ("Live transport test sent through ITEM_OPEN to " .. tostring(remoteTargetCount) .. " joined member(s).")
          or "Live transport test opened locally; no remote joined members were present.")
        or "Live transport test could not send the ITEM_OPEN packet.",
      sessionId = TrimText(activeSession.id),
      profileName = TrimText(profileName),
      itemKey = itemKey,
      remoteTargetCount = remoteTargetCount,
      acknowledgedCount = type(dispatchReport) == "table" and math.max(0, tonumber(dispatchReport.acknowledgedCount) or 0) or 0,
      pendingReceiptCount = type(dispatchReport) == "table" and math.max(0, tonumber(dispatchReport.pendingReceiptCount) or 0) or 0,
      failedTargetCount = type(dispatchReport) == "table" and math.max(0, tonumber(dispatchReport.failedTargetCount) or 0) or 0,
      dispatchState = type(dispatchReport) == "table" and TrimText(dispatchReport.state) or (remoteTargetCount == 0 and "acknowledged" or "dispatch_failed"),
      transportOpcode = "ITEM_OPEN",
      transportAccepted = sent,
      choiceQueued = choiceQueued == true,
      popupOpened = popupOpened,
      simulationOnly = true,
      updatedAt = now,
    }
    runtime.lastLiveTransportTest = detail
    if type(dispatchReport) == "table" then
      boardSyncTransactions.RefreshItemOpenReport(dispatchReport)
    end
    return sent, itemKey, detail
  end

  local function ReportLootRollToHost(activeSession, profileName, payload)
    if type(activeSession) ~= "table" or TrimText(profileName) == "" then
      return false, "No active session."
    end
    if IsSelfHost(activeSession) then
      return OpenAuthoritativeLootItem(activeSession, profileName, payload, GetSelfKey(), type(payload) == "table" and payload.rollID or nil)
    end
    if type(SendSessionComm) ~= "function" then
      return false, "Session comms are unavailable."
    end

    EnsureRuntimeAuthorityMaps()
    local normalizedPayload = NormalizeLootItemPayload(payload)
    local selfKey = GetSelfKey()
    local rollID = TrimText(normalizedPayload.rollID)
    local commProfileName = GetSessionCommProfileName(activeSession, profileName)
    if rollID ~= "" then
      runtime.localRollItemKeys[rollID] = "REPORTED"
    end
    local sessionId = tostring(activeSession.id or "")
    local reportIdentity = GetReportToken(
      selfKey,
      rollID,
      BuildLootItemSignature(normalizedPayload),
      normalizedPayload.createdAt
    )
    local reportKey = reportIdentity ~= "" and (
      string.lower(sessionId) .. "\031" .. string.lower(reportIdentity)
    ) or ""
    if reportKey == "" then
      return SendItemReportPacket(activeSession, commProfileName, selfKey, rollID, normalizedPayload)
    end

    runtime.pendingItemReports = type(runtime.pendingItemReports) == "table"
      and runtime.pendingItemReports
      or {}
    local existing = runtime.pendingItemReports[reportKey]
    if type(existing) == "table" and existing.state == "waiting" then
      return true, "awaiting_host_receipt"
    end
    if type(existing) == "table" and existing.state == "unconfirmed" then
      return false, "host_receipt_unconfirmed"
    end

    local report = {
      sessionId = sessionId,
      profileName = commProfileName,
      host = NormalizeCharacterKey(activeSession.host),
      reporterKey = NormalizeCharacterKey(selfKey),
      rollID = rollID,
      payload = normalizedPayload,
      attempts = 0,
      state = "waiting",
    }
    runtime.pendingItemReports[reportKey] = report

    local function MarkReportUnconfirmed()
      if runtime.pendingItemReports[reportKey] ~= report or report.state ~= "waiting" then
        return
      end
      report.state = "unconfirmed"
      runtime.lastItemReportReceipt = {
        sessionId = report.sessionId,
        reporterKey = report.reporterKey,
        rollID = report.rollID,
        state = report.state,
        attempts = report.attempts,
      }
      if type(Print) == "function" then
        Print("Loot report was not confirmed by the host. This item is not yet confirmed on the host's live board.")
      end
    end

    local function SendReportAttempt()
      if runtime.pendingItemReports[reportKey] ~= report or report.state ~= "waiting" then
        return false, "superseded"
      end
      local retrySession, retryProfileName = GetActiveLootSession()
      if not DoesRuntimeSessionMatch(retrySession, retryProfileName, report.sessionId, report.profileName)
        or not AreCharacterKeysSame(type(retrySession) == "table" and retrySession.host or "", report.host)
      then
        runtime.pendingItemReports[reportKey] = nil
        return false, "session_changed"
      end

      local ok, reason = SendItemReportPacket(
        retrySession,
        report.profileName,
        report.reporterKey,
        report.rollID,
        report.payload
      )
      report.attempts = math.max(0, tonumber(report.attempts) or 0) + 1
      report.lastError = ok and "" or TrimText(reason)

      local retryDelays = { 1.5, 3, 6, 8 }
      local retryDelay = retryDelays[math.min(#retryDelays, report.attempts)]
      if type(C_Timer) == "table" and type(C_Timer.After) == "function" then
        C_Timer.After(retryDelay, function()
          if runtime.pendingItemReports[reportKey] ~= report or report.state ~= "waiting" then
            return
          end
          if (tonumber(report.attempts) or 0) >= #retryDelays then
            MarkReportUnconfirmed()
          else
            SendReportAttempt()
          end
        end)
      else
        MarkReportUnconfirmed()
      end
      return ok, reason
    end

    return SendReportAttempt()
  end

  local function HasExactFieldCount(fields, opcode)
    local expected = EXPECTED_FIELD_COUNTS[tostring(opcode or "")]
    if expected == nil or type(fields) ~= "table" then
      return false
    end
    if type(expected) == "table" then
      for _, candidate in ipairs(expected) do
        if #fields == candidate then
          return true
        end
      end
      return false
    end
    return #fields == expected
  end

  function boardSyncTransactions.GetOutgoingKey(sessionId, profileName, targetKey, token)
    return string.lower(table.concat({
      TrimText(sessionId),
      TrimText(profileName),
      NormalizeCharacterKey(targetKey),
      TrimText(token),
    }, "|"))
  end

  function boardSyncTransactions.GetCompletedKey(sessionId, profileName, senderKey, token)
    return string.lower(table.concat({
      TrimText(sessionId),
      TrimText(profileName),
      NormalizeCharacterKey(senderKey),
      TrimText(token),
    }, "|"))
  end

  function boardSyncTransactions.BuildRowSignature(kind, rowIndex, itemKey, actorKey, targetKey, sequence)
    return table.concat({
      string.upper(TrimText(kind)),
      tostring(math.max(0, tonumber(rowIndex) or 0)),
      TrimText(itemKey),
      NormalizeCharacterKey(actorKey),
      NormalizeCharacterKey(targetKey),
      tostring(math.max(0, tonumber(sequence) or 0)),
    }, "\31")
  end

  function boardSyncTransactions.CalculateManifestChecksum(itemSignatures, selectionSignatures, voteSignatures, counts)
    counts = type(counts) == "table" and counts or {}
    local parts = {}
    for _, descriptor in ipairs({
      { prefix = "I", rows = itemSignatures, count = math.max(0, tonumber(counts.items) or 0) },
      { prefix = "S", rows = selectionSignatures, count = math.max(0, tonumber(counts.selections) or 0) },
      { prefix = "V", rows = voteSignatures, count = math.max(0, tonumber(counts.votes) or 0) },
    }) do
      parts[#parts + 1] = descriptor.prefix .. ":" .. tostring(descriptor.count)
      for index = 1, descriptor.count do
        parts[#parts + 1] = tostring(type(descriptor.rows) == "table" and descriptor.rows[index] or "")
      end
    end
    local text = table.concat(parts, "\30")
    local a = 1
    local b = 0
    for index = 1, #text do
      a = (a + string.byte(text, index)) % 65521
      b = (b + a) % 65521
    end
    return string.format("%04x%04x", b, a)
  end

  function boardSyncTransactions.CountIndexedRows(rows)
    local count = 0
    for index, signature in pairs(type(rows) == "table" and rows or {}) do
      if (tonumber(index) or 0) > 0 and TrimText(signature) ~= "" then
        count = count + 1
      end
    end
    return count
  end

  function boardSyncTransactions.CollectMissing(syncState)
    local missing = { item = {}, selection = {}, vote = {} }
    local total = 0
    for _, descriptor in ipairs({
      { kind = "item", rows = syncState.itemSignatures, count = tonumber(syncState.expectedItems) or 0 },
      { kind = "selection", rows = syncState.selectionSignatures, count = tonumber(syncState.expectedSelections) or 0 },
      { kind = "vote", rows = syncState.voteSignatures, count = tonumber(syncState.expectedVotes) or 0 },
    }) do
      for index = 1, math.max(0, descriptor.count) do
        if TrimText(type(descriptor.rows) == "table" and descriptor.rows[index] or "") == "" then
          missing[descriptor.kind][#missing[descriptor.kind] + 1] = index
          total = total + 1
        end
      end
    end
    return missing, total
  end

  local function GetSelectionUpdatedAt(entry, memberKey)
    local selection = ResolveEntrySelection(entry, memberKey)
    return tonumber(type(selection) == "table" and selection.selectedAt) or 0
  end

  local function GetSelectionSequence(entry, memberKey)
    local selection = ResolveEntrySelection(entry, memberKey)
    return tonumber(type(selection) == "table" and selection.selectedSeq) or 0
  end

  local function NormalizeVoteUpdatedAt(entry)
    local normalized = {}
    if type(entry) == "table" and type(entry.voteUpdatedAtByVoter) == "table" then
      for voterKey, updatedAt in pairs(entry.voteUpdatedAtByVoter) do
        local normalizedVoterKey = NormalizeCharacterKey(voterKey)
        local normalizedUpdatedAt = tonumber(updatedAt)
        if normalizedVoterKey ~= "" and normalizedUpdatedAt and normalizedUpdatedAt > 0 then
          normalized[normalizedVoterKey] = normalizedUpdatedAt
        end
      end
    end
    if type(entry) == "table" then
      entry.voteUpdatedAtByVoter = normalized
    end
    return normalized
  end

  local function GetVoteUpdatedAt(entry, voterKey)
    local normalizedVoterKey = NormalizeCharacterKey(voterKey)
    if normalizedVoterKey == "" then
      return 0
    end
    local voteUpdatedAtByVoter = NormalizeVoteUpdatedAt(entry)
    return tonumber(voteUpdatedAtByVoter[normalizedVoterKey]) or 0
  end

  local function GetVoteSequence(entry, voterKey)
    local normalizedVoterKey = NormalizeCharacterKey(voterKey)
    if normalizedVoterKey == "" then
      return 0
    end
    local voteSequenceByVoter = type(NormalizeVoteSequence) == "function" and NormalizeVoteSequence(entry) or {}
    return tonumber(voteSequenceByVoter[normalizedVoterKey]) or 0
  end

  local function SetVoteUpdatedAt(entry, voterKey, changedAt)
    if type(entry) ~= "table" then
      return
    end
    local normalizedVoterKey = NormalizeCharacterKey(voterKey)
    local normalizedChangedAt = tonumber(changedAt)
    if normalizedVoterKey == "" or not normalizedChangedAt or normalizedChangedAt <= 0 then
      return
    end
    local voteUpdatedAtByVoter = NormalizeVoteUpdatedAt(entry)
    voteUpdatedAtByVoter[normalizedVoterKey] = normalizedChangedAt
    entry.voteUpdatedAtByVoter = voteUpdatedAtByVoter
  end

  local function SetVoteSequence(entry, voterKey, sequence)
    if type(entry) ~= "table" then
      return
    end
    local normalizedVoterKey = NormalizeCharacterKey(voterKey)
    local normalizedSequence = tonumber(sequence)
    if normalizedVoterKey == "" or not normalizedSequence or normalizedSequence <= 0 then
      return
    end
    local voteSequenceByVoter = type(NormalizeVoteSequence) == "function" and NormalizeVoteSequence(entry) or {}
    voteSequenceByVoter[normalizedVoterKey] = math.floor(normalizedSequence)
    entry.voteSequenceByVoter = voteSequenceByVoter
  end

  local function GetAwardUpdatedAt(entry)
    return tonumber(type(entry) == "table" and (entry.awardUpdatedAt or entry.awardedAt)) or 0
  end

  local function GetTradeUpdatedAt(entry)
    return tonumber(type(entry) == "table" and (entry.tradeUpdatedAt or entry.tradedAt)) or 0
  end

  local function BuildBestRuntimeBoardSyncSnapshot(activeSession, profileName)
    local snapshot = BuildRuntimeBoardHistorySnapshot()
    if type(snapshot) == "table" and type(snapshot.items) == "table" and type(snapshot.itemOrder) == "table" and #snapshot.itemOrder > 0 then
      return snapshot
    end
    if type(activeSession) ~= "table" then
      return nil
    end
    return GetLatestRuntimeBoardSnapshot(profileName, activeSession.id)
  end

  local function RestoreRuntimeBoardFromSyncSnapshot(activeSession, profileName, snapshot)
    if type(activeSession) ~= "table" or TrimText(profileName) == "" or type(snapshot) ~= "table" then
      return false
    end
    runtime.sessionId = tostring(activeSession.id or "")
    runtime.profileName = tostring(profileName or "")
    runtime.host = tostring(activeSession.host or runtime.host or "")
    return RestoreRuntimeBoardSnapshot(activeSession, profileName, snapshot)
  end

  local function CaptureLocalPopupQueue()
    local queue = {}
    for _, itemKey in ipairs(runtime.popupQueue or {}) do
      local resolvedKey = TrimText(itemKey)
      if resolvedKey ~= "" then
        queue[#queue + 1] = resolvedKey
      end
    end
    return queue
  end

  local function RestoreLocalPopupQueue(activeSession, capturedQueue)
    if type(capturedQueue) ~= "table" or #capturedQueue == 0 then
      return
    end

    local selfKey = GetSelfKey()
    if selfKey == "" then
      return
    end

    local _, localMemberKey = GetSessionMember(activeSession, selfKey)
    local choiceMemberKey = localMemberKey or (IsSessionHostKey(activeSession, selfKey) and TrimText(activeSession.host) or selfKey)
    local restoredQueue = {}
    local seen = {}
    for _, itemKey in ipairs(capturedQueue) do
      local entry = type(runtime.items) == "table" and runtime.items[itemKey] or nil
      if type(entry) == "table" and not seen[itemKey] then
        local selection = ResolveEntrySelection(entry, choiceMemberKey)
        if IsPendingSelection(selection) then
          restoredQueue[#restoredQueue + 1] = itemKey
          seen[itemKey] = true
        end
      end
    end
    runtime.popupQueue = restoredQueue
  end

  local function SendBoardSyncStartMessage(targetKey, sessionId, profileName, boardUpdatedAt, boardId, historyProfileName, selectedItemKey, transaction)
    transaction = type(transaction) == "table" and transaction or {}
    local ok = SendSessionComm(
      "BSYNC_START",
      "WHISPER",
      targetKey,
      sessionId,
      profileName,
      boardUpdatedAt,
      boardId,
      historyProfileName,
      selectedItemKey,
      TrimText(transaction.token),
      tostring(math.max(0, tonumber(transaction.itemCount) or 0)),
      tostring(math.max(0, tonumber(transaction.selectionCount) or 0)),
      tostring(math.max(0, tonumber(transaction.voteCount) or 0)),
      TrimText(transaction.checksum)
    )
    if ok then
      return true, false
    end
    ok = SendSessionComm(
      "BSYNC_START",
      "WHISPER",
      targetKey,
      sessionId,
      profileName,
      boardUpdatedAt,
      boardId,
      historyProfileName,
      "",
      TrimText(transaction.token),
      tostring(math.max(0, tonumber(transaction.itemCount) or 0)),
      tostring(math.max(0, tonumber(transaction.selectionCount) or 0)),
      tostring(math.max(0, tonumber(transaction.voteCount) or 0)),
      TrimText(transaction.checksum)
    )
    return ok, true
  end

  local function SendBoardSyncEndMessage(targetKey, sessionId, profileName, boardId, selectedItemKey, token)
    local ok = SendSessionComm("BSYNC_END", "WHISPER", targetKey, sessionId, profileName, boardId, selectedItemKey, TrimText(token))
    if ok then
      return true, false
    end
    ok = SendSessionComm("BSYNC_END", "WHISPER", targetKey, sessionId, profileName, boardId, "", TrimText(token))
    return ok, true
  end

  local function BuildBoardSyncItemArgs(sessionId, profileName, orderIndex, itemKey, fields)
    local args = {
      sessionId,
      profileName,
      tostring(orderIndex),
      TrimText(itemKey),
      TrimText(fields.name),
      fields.link or "",
      fields.icon or "",
      tostring(tonumber(fields.quality) or ""),
      tostring(fields.itemID or ""),
      tostring(tonumber(fields.itemLevel) or ""),
      tostring(tonumber(fields.createdAt) or ""),
      TrimText(fields.awardedTo),
      tostring(tonumber(fields.awardedPoints) or ""),
      TrimText(fields.awardedNote),
      tostring(tonumber(fields.awardedAt) or ""),
      TrimText(fields.ledgerEntryId),
      tostring(tonumber(fields.awardUpdatedAt) or ""),
    }
    if fields.includeTradeState ~= false then
      args[#args + 1] = TrimText(fields.tradeState)
      args[#args + 1] = tostring(tonumber(fields.tradedAt) or "")
      args[#args + 1] = NormalizeCharacterKey(fields.tradedBy)
      args[#args + 1] = NormalizeDistributionMode(fields.distributionMode)
    end
    return args
  end

  local function SendBoardSyncItemMessage(targetKey, sessionId, profileName, orderIndex, itemKey, fields)
    return SendSessionComm("BSYNC_ITEM", "WHISPER", targetKey,
      unpack(BuildBoardSyncItemArgs(sessionId, profileName, orderIndex, itemKey, fields)))
  end

  local function SendBoardSyncItemWithFallback(targetKey, sessionId, profileName, orderIndex, itemKey, entry)
    local attempts = {
      {
        name = ClipBoardSyncText(entry.name, MAX_BOARD_SYNC_ITEM_NAME_LENGTH),
        link = BuildCompactItemDescriptor(entry.link, MAX_BOARD_SYNC_LINK_LENGTH),
        icon = ClipBoardSyncText(entry.icon, MAX_BOARD_SYNC_ICON_LENGTH),
        quality = entry.quality,
        itemID = entry.itemID,
        itemLevel = entry.itemLevel,
        createdAt = entry.createdAt,
        awardedTo = entry.awardedTo,
        awardedPoints = entry.awardedPoints,
        awardedNote = ClipBoardSyncText(entry.awardedNote, MAX_BOARD_SYNC_NOTE_LENGTH),
        awardedAt = entry.awardedAt,
        ledgerEntryId = ClipBoardSyncText(entry.ledgerEntryId, MAX_BOARD_SYNC_LEDGER_ID_LENGTH),
        awardUpdatedAt = entry.awardUpdatedAt,
        tradeState = entry.tradeState,
        tradedAt = entry.tradedAt,
        tradedBy = entry.tradedBy,
        distributionMode = entry.distributionMode,
      },
      {
        name = ClipBoardSyncText(entry.name, 64),
        link = "",
        icon = ClipBoardSyncText(entry.icon, 48),
        quality = entry.quality,
        itemID = entry.itemID,
        itemLevel = entry.itemLevel,
        createdAt = entry.createdAt,
        awardedTo = entry.awardedTo,
        awardedPoints = entry.awardedPoints,
        awardedNote = ClipBoardSyncText(entry.awardedNote, 32),
        awardedAt = entry.awardedAt,
        ledgerEntryId = "",
        awardUpdatedAt = entry.awardUpdatedAt,
        tradeState = entry.tradeState,
        tradedAt = entry.tradedAt,
        tradedBy = entry.tradedBy,
        distributionMode = entry.distributionMode,
      },
      {
        name = ClipBoardSyncText(entry.name, 48),
        link = "",
        icon = "",
        quality = entry.quality,
        itemID = entry.itemID,
        itemLevel = entry.itemLevel,
        createdAt = entry.createdAt,
        awardedTo = entry.awardedTo,
        awardedPoints = entry.awardedPoints,
        awardedNote = "",
        awardedAt = entry.awardedAt,
        ledgerEntryId = "",
        awardUpdatedAt = entry.awardUpdatedAt,
        tradeState = entry.tradeState,
        tradedAt = entry.tradedAt,
        tradedBy = entry.tradedBy,
        distributionMode = entry.distributionMode,
      },
      {
        -- The receiver supports this 18-field core form.  It preserves the item
        -- and award state while omitting trade-only metadata that later TRADE
        -- updates will restore when a full board item cannot fit in one message.
        name = ClipBoardSyncText(entry.name, 32),
        link = "",
        icon = "",
        quality = entry.quality,
        itemID = entry.itemID,
        itemLevel = entry.itemLevel,
        createdAt = entry.createdAt,
        awardedTo = entry.awardedTo,
        awardedPoints = entry.awardedPoints,
        awardedNote = "",
        awardedAt = entry.awardedAt,
        ledgerEntryId = "",
        awardUpdatedAt = entry.awardUpdatedAt,
        includeTradeState = false,
      },
    }

    for attemptIndex, fields in ipairs(attempts) do
      local args = BuildBoardSyncItemArgs(sessionId, profileName, orderIndex, itemKey, fields)
      local payloadSafe = type(ValidateCommPayload) ~= "function"
        or ValidateCommPayload("BSYNC_ITEM", unpack(args))
      local ok = payloadSafe and SendBoardSyncItemMessage(targetKey, sessionId, profileName, orderIndex, itemKey, fields)
      if ok then
        return true, attemptIndex > 1
      end
    end
    return false, false
  end

  local function SendBoardSyncSelectionMessage(targetKey, sessionId, profileName, itemKey, memberKey, fields, rowIndex)
    local color = type(fields.color) == "table" and fields.color or {}
    return SendSessionComm(
      "BSYNC_SEL",
      "WHISPER",
      targetKey,
      sessionId,
      profileName,
      TrimText(itemKey),
      NormalizeCharacterKey(memberKey),
      TrimText(fields.optionKey),
      TrimText(fields.label),
      tostring(tonumber(color[1]) or ""),
      tostring(tonumber(color[2]) or ""),
      tostring(tonumber(color[3]) or ""),
      fields.icon or "",
      NormalizeSelectionNote(fields.note),
      tostring(tonumber(fields.rollValue) or ""),
      TrimText(fields.pointBehavior),
      tostring(tonumber(fields.selectedAt) or ""),
      TrimText(fields.source),
      tostring(tonumber(fields.selectedSeq) or 1),
      tostring(math.max(0, tonumber(rowIndex) or 0))
    )
  end

  local function SendBoardSyncSelectionWithFallback(targetKey, sessionId, profileName, itemKey, memberKey, selection, rowIndex)
    local attempts = {
      {
        optionKey = selection.optionKey,
        label = ClipBoardSyncText(selection.label, MAX_BOARD_SYNC_LABEL_LENGTH),
        color = selection.color,
        icon = ClipBoardSyncText(selection.icon, MAX_BOARD_SYNC_ICON_LENGTH),
        note = ClipBoardSyncText(selection.note, MAX_BOARD_SYNC_NOTE_LENGTH),
        rollValue = selection.rollValue,
        pointBehavior = selection.pointBehavior,
        selectedAt = selection.selectedAt,
        source = ClipBoardSyncText(selection.source, MAX_BOARD_SYNC_SOURCE_LENGTH),
        selectedSeq = selection.selectedSeq,
      },
      {
        optionKey = selection.optionKey,
        label = ClipBoardSyncText(selection.label, 40),
        color = selection.color,
        icon = "",
        note = ClipBoardSyncText(selection.note, 32),
        rollValue = selection.rollValue,
        pointBehavior = selection.pointBehavior,
        selectedAt = selection.selectedAt,
        source = ClipBoardSyncText(selection.source, 16),
        selectedSeq = selection.selectedSeq,
      },
      {
        optionKey = selection.optionKey,
        label = ClipBoardSyncText(selection.label, 32),
        color = selection.color,
        icon = "",
        note = "",
        rollValue = selection.rollValue,
        pointBehavior = selection.pointBehavior,
        selectedAt = selection.selectedAt,
        source = "",
        selectedSeq = selection.selectedSeq,
      },
    }

    for attemptIndex, fields in ipairs(attempts) do
      local ok = SendBoardSyncSelectionMessage(targetKey, sessionId, profileName, itemKey, memberKey, fields, rowIndex)
      if ok then
        return true, attemptIndex > 1
      end
    end
    return false, false
  end

  function boardSyncTransactions.PopulateRows(transaction, snapshot, selectionScopeKey, includeVotes)
    if type(transaction) ~= "table" or type(snapshot) ~= "table" then
      return false
    end
    local resolvedScopeKey = NormalizeCharacterKey(selectionScopeKey)
    transaction.itemRows = {}
    transaction.selectionRows = {}
    transaction.voteRows = {}
    transaction.itemSignatures = {}
    transaction.selectionSignatures = {}
    transaction.voteSignatures = {}
    transaction.missing = { item = {}, selection = {}, vote = {} }
    for orderIndex, itemKey in ipairs(snapshot.itemOrder or {}) do
      local entry = type(snapshot.items) == "table" and snapshot.items[itemKey] or nil
      if type(entry) == "table" then
        local transportIndex = #transaction.itemRows + 1
        transaction.itemRows[#transaction.itemRows + 1] = {
          orderIndex = transportIndex,
          itemKey = itemKey,
          entry = entry,
        }
        transaction.itemSignatures[#transaction.itemRows] = boardSyncTransactions.BuildRowSignature(
          "I", transportIndex, itemKey, "", "", transportIndex
        )

        local selectionKeys = {}
        if resolvedScopeKey ~= "" then
          for memberKey, selection in pairs(entry.selections or {}) do
            local optionKey = string.lower(TrimText(type(selection) == "table" and selection.optionKey or ""))
            if AreCharacterKeysSame(memberKey, resolvedScopeKey) or optionKey ~= "pending" then
              selectionKeys[#selectionKeys + 1] = memberKey
            end
          end
        else
          for memberKey in pairs(entry.selections or {}) do
            selectionKeys[#selectionKeys + 1] = memberKey
          end
        end
        table.sort(selectionKeys, function(left, right)
          return string.lower(tostring(left or "")) < string.lower(tostring(right or ""))
        end)
        for _, memberKey in ipairs(selectionKeys) do
          local selection = entry.selections and entry.selections[memberKey] or nil
          if type(selection) == "table" then
            local transportSelection = {}
            for fieldName, fieldValue in pairs(selection) do
              transportSelection[fieldName] = fieldValue
            end
            -- Pending choices are real BSYNC manifest rows even though no player
            -- has clicked yet. Give them deterministic transport metadata so the
            -- receiver does not reject the row before it can build its popup queue.
            transportSelection.selectedAt = math.max(1,
              tonumber(selection.selectedAt)
                or tonumber(entry.createdAt)
                or tonumber(transaction.boardUpdatedAt)
                or GetCurrentTimestamp())
            transportSelection.selectedSeq = math.max(1, math.floor(tonumber(selection.selectedSeq) or 1))
            transaction.selectionRows[#transaction.selectionRows + 1] = {
              itemKey = itemKey,
              memberKey = memberKey,
              selection = transportSelection,
            }
            local rowIndex = #transaction.selectionRows
            transaction.selectionSignatures[rowIndex] = boardSyncTransactions.BuildRowSignature(
              "S", rowIndex, itemKey, memberKey, "", transportSelection.selectedSeq
            )
          end
        end

        if includeVotes == true or resolvedScopeKey ~= "" then
          local voteKeys = {}
          local votesByVoter = NormalizeEntryVotes(entry)
          for voterKey in pairs(votesByVoter or {}) do
            voteKeys[#voteKeys + 1] = voterKey
          end
          table.sort(voteKeys, function(left, right)
            return string.lower(tostring(left or "")) < string.lower(tostring(right or ""))
          end)
          for _, voterKey in ipairs(voteKeys) do
            local targetMemberKey = NormalizeCharacterKey(votesByVoter[voterKey])
            if targetMemberKey ~= "" then
              transaction.voteRows[#transaction.voteRows + 1] = {
                itemKey = itemKey,
                voterKey = voterKey,
                targetMemberKey = targetMemberKey,
                changedAt = tonumber(type(entry.voteUpdatedAtByVoter) == "table" and entry.voteUpdatedAtByVoter[voterKey]),
                voteSeq = tonumber(type(entry.voteSequenceByVoter) == "table" and entry.voteSequenceByVoter[voterKey]) or 1,
              }
              local rowIndex = #transaction.voteRows
              transaction.voteSignatures[rowIndex] = boardSyncTransactions.BuildRowSignature(
                "V", rowIndex, itemKey, voterKey, targetMemberKey, transaction.voteRows[rowIndex].voteSeq
              )
            end
          end
        end
      end
    end
    transaction.itemCount = #transaction.itemRows
    transaction.selectionCount = #transaction.selectionRows
    transaction.voteCount = #transaction.voteRows
    transaction.checksum = boardSyncTransactions.CalculateManifestChecksum(
      transaction.itemSignatures,
      transaction.selectionSignatures,
      transaction.voteSignatures,
      { items = transaction.itemCount, selections = transaction.selectionCount, votes = transaction.voteCount }
    )
    return true
  end

  function boardSyncTransactions.Build(activeSession, profileName, snapshot, targetKey, recipientScoped)
    boardSyncTransactions.nextToken = math.max(0, tonumber(boardSyncTransactions.nextToken) or 0) + 1
    local transaction = {
      sessionId = TrimText(activeSession.id),
      profileName = TrimText(profileName),
      targetKey = NormalizeCharacterKey(targetKey),
      boardUpdatedAt = tonumber(snapshot.updatedAt) or 0,
      boardId = TrimText(snapshot.boardId),
      historyProfileName = TrimText(snapshot.historyProfileName ~= "" and snapshot.historyProfileName or profileName),
      selectedItemKey = TrimText(snapshot.selectedItemKey),
      token = tostring(math.max(0, tonumber(snapshot.updatedAt) or 0)) .. "-" .. tostring(boardSyncTransactions.nextToken),
      sourceSnapshot = snapshot,
      recipientScoped = recipientScoped == true,
      selectiveAttempts = 0,
      endAttempts = 0,
      fullRebuilds = 0,
      receiptWatch = 0,
    }
    boardSyncTransactions.PopulateRows(
      transaction,
      snapshot,
      transaction.recipientScoped and transaction.targetKey or "",
      transaction.recipientScoped ~= true
    )
    transaction.key = boardSyncTransactions.GetOutgoingKey(
      transaction.sessionId, transaction.profileName, transaction.targetKey, transaction.token
    )
    return transaction
  end

  function boardSyncTransactions.PromoteToFullSnapshot(transaction)
    if type(transaction) ~= "table" or transaction.recipientScoped ~= true
      or type(transaction.sourceSnapshot) ~= "table"
    then
      return false
    end
    if not boardSyncTransactions.PopulateRows(transaction, transaction.sourceSnapshot, "", true) then
      return false
    end
    transaction.recipientScoped = false
    transaction.fullFallbackPromoted = true
    transaction.missing = { item = {}, selection = {}, vote = {} }
    return true
  end

  function boardSyncTransactions.BuildAdmissionPlan(
    targetCount,
    itemCount,
    selectionCount,
    voteCount,
    queueStatus,
    reservedSelectionCount,
    projectedMessagesOverride
  )
    local resolvedTargets = math.max(0, math.floor(tonumber(targetCount) or 0))
    local resolvedItems = math.max(0, math.floor(tonumber(itemCount) or 0))
    local resolvedSelections = math.max(0, math.floor(tonumber(selectionCount) or 0))
    local resolvedVotes = math.max(0, math.floor(tonumber(voteCount) or 0))
    local statusAvailable = type(queueStatus) == "table"
    local currentQueueDepth = math.max(0, math.floor(tonumber(statusAvailable and queueStatus.pending or 0) or 0))
    local maxQueueDepth = math.max(1, math.floor(tonumber(statusAvailable and queueStatus.maxQueueDepth or 6000) or 6000))
    local criticalOverflow = math.max(0,
      math.floor(tonumber(statusAvailable and queueStatus.maxCriticalQueueOverflow or 64) or 64))
    local messagesPerTarget = 2 + resolvedItems + resolvedSelections + resolvedVotes
    local projectedMessages = math.max(0, math.floor(
      tonumber(projectedMessagesOverride) or (resolvedTargets * messagesPerTarget)
    ))
    local remoteChoiceSlots = resolvedTargets * resolvedItems
    local targetedItemRetries = remoteChoiceSlots * #boardSyncTransactions.itemOpenRetryDelays
    local directChoiceReceipts = remoteChoiceSlots * boardSyncTransactions.choiceReceiptAttempts
    local resolvedReservedSelections = math.max(
      resolvedSelections,
      math.max(0, math.floor(tonumber(reservedSelectionCount) or 0))
    )
    local calculatedLiveHeadroom = resolvedItems
      + targetedItemRetries
      + directChoiceReceipts
      + resolvedReservedSelections
    local requiredLiveHeadroom = math.max(criticalOverflow, calculatedLiveHeadroom)
    local normalHeadroomBefore = math.max(0, maxQueueDepth - currentQueueDepth)
    local safeMessageCapacity = math.max(0, normalHeadroomBefore - requiredLiveHeadroom)
    local normalHeadroomAfter = maxQueueDepth - currentQueueDepth - projectedMessages
    local fullAdmissionSafe = projectedMessages <= safeMessageCapacity
    local maxTargetCapacity = messagesPerTarget > 0
      and math.max(0, math.floor(safeMessageCapacity / messagesPerTarget))
      or 0
    local activeTargetLimit = math.min(
      resolvedTargets,
      math.max(1, tonumber(boardSyncTransactions.maxActiveTargets) or 2),
      maxTargetCapacity
    )
    local stagedAdmissionSafe = activeTargetLimit > 0
    local requiresStaging = resolvedTargets > activeTargetLimit or not fullAdmissionSafe
    local admitted = statusAvailable and resolvedTargets > 0 and stagedAdmissionSafe
    local reason = "admitted"
    if not statusAvailable then
      reason = "queue_status_unavailable"
    elseif resolvedTargets <= 0 then
      reason = "no_targets"
    elseif messagesPerTarget > math.max(0, maxQueueDepth - requiredLiveHeadroom) then
      reason = "transaction_exceeds_capacity"
    elseif not stagedAdmissionSafe then
      reason = "queue_headroom_insufficient"
    elseif requiresStaging then
      reason = "admitted_staged"
    end
    return {
      admitted = admitted,
      reason = reason,
      targetCount = resolvedTargets,
      itemCount = resolvedItems,
      selectionCount = resolvedSelections,
      reservedSelectionCount = resolvedReservedSelections,
      voteCount = resolvedVotes,
      messagesPerTarget = messagesPerTarget,
      projectedMessages = projectedMessages,
      currentQueueDepth = currentQueueDepth,
      maxQueueDepth = maxQueueDepth,
      criticalOverflow = criticalOverflow,
      targetedItemRetries = targetedItemRetries,
      directChoiceReceipts = directChoiceReceipts,
      calculatedLiveHeadroom = calculatedLiveHeadroom,
      requiredLiveHeadroom = requiredLiveHeadroom,
      normalHeadroomBefore = normalHeadroomBefore,
      normalHeadroomAfter = normalHeadroomAfter,
      safeMessageCapacity = safeMessageCapacity,
      fullAdmissionSafe = fullAdmissionSafe,
      stagedAdmissionSafe = stagedAdmissionSafe,
      requiresStaging = requiresStaging,
      maxTargetCapacity = maxTargetCapacity,
      activeTargetLimit = activeTargetLimit,
      projectedQueueDepth = currentQueueDepth + projectedMessages,
      criticalAdmissionCeiling = maxQueueDepth + criticalOverflow,
    }
  end

  function boardSyncTransactions.BuildSnapshotAdmissionPlan(
    snapshot,
    targets,
    queueStatus,
    recipientScoped,
    recipientScopeByTarget
  )
    local targetKeys = type(targets) == "table" and targets or nil
    local targetCount = targetKeys and #targetKeys or math.max(0, math.floor(tonumber(targets) or 0))
    local itemCount = 0
    local fullSelectionCount = 0
    local voteCount = 0
    local scopedSelectionsByTarget = {}
    local scopedTargetCount = 0
    local fullTargetCount = 0
    local function targetUsesScopedRows(targetKey)
      if recipientScoped ~= true then
        return false
      end
      if type(recipientScopeByTarget) ~= "table" then
        return true
      end
      return recipientScopeByTarget[string.lower(NormalizeCharacterKey(targetKey))] == true
    end
    for _, targetKey in ipairs(targetKeys or {}) do
      if targetUsesScopedRows(targetKey) then
        scopedTargetCount = scopedTargetCount + 1
      else
        fullTargetCount = fullTargetCount + 1
      end
    end
    for _, itemKey in ipairs(type(snapshot) == "table" and snapshot.itemOrder or {}) do
      local entry = type(snapshot.items) == "table" and snapshot.items[itemKey] or nil
      if type(entry) == "table" then
        itemCount = itemCount + 1
        local resolvedSelectionCount = 0
        for _, selection in pairs(type(entry.selections) == "table" and entry.selections or {}) do
          fullSelectionCount = fullSelectionCount + 1
          if string.lower(TrimText(type(selection) == "table" and selection.optionKey or "")) ~= "pending" then
            resolvedSelectionCount = resolvedSelectionCount + 1
          end
        end
        if recipientScoped == true and targetKeys then
          for _, targetKey in ipairs(targetKeys) do
            if targetUsesScopedRows(targetKey) then
              local targetMapKey = string.lower(NormalizeCharacterKey(targetKey))
              local targetSelectionCount = resolvedSelectionCount
              local targetSelection = ResolveEntrySelection(entry, targetKey)
              if type(targetSelection) == "table"
                and string.lower(TrimText(targetSelection.optionKey)) == "pending"
              then
                targetSelectionCount = targetSelectionCount + 1
              end
              scopedSelectionsByTarget[targetMapKey] = math.max(0,
                tonumber(scopedSelectionsByTarget[targetMapKey]) or 0) + targetSelectionCount
            end
          end
        end
        for _, targetMemberKey in pairs(NormalizeEntryVotes(entry) or {}) do
          if NormalizeCharacterKey(targetMemberKey) ~= "" then
            voteCount = voteCount + 1
          end
        end
      end
    end
    local selectionCount = recipientScoped == true and 0 or fullSelectionCount
    local projectedMessages
    if targetKeys then
      projectedMessages = 0
      for _, targetKey in ipairs(targetKeys) do
        local targetSelectionCount = fullSelectionCount
        if targetUsesScopedRows(targetKey) then
          targetSelectionCount = math.max(0,
            tonumber(scopedSelectionsByTarget[string.lower(NormalizeCharacterKey(targetKey))]) or 0)
        end
        selectionCount = math.max(selectionCount, targetSelectionCount)
        projectedMessages = projectedMessages + 2 + itemCount + targetSelectionCount + voteCount
      end
    elseif recipientScoped == true then
      -- Without recipient identities, retain the full-row estimate rather than
      -- understating capacity for a transaction that cannot be scoped safely.
      selectionCount = fullSelectionCount
      fullTargetCount = targetCount
    end
    local plan = boardSyncTransactions.BuildAdmissionPlan(
      targetCount,
      itemCount,
      selectionCount,
      voteCount,
      queueStatus,
      fullSelectionCount,
      projectedMessages
    )
    plan.scopedTargetCount = scopedTargetCount
    plan.fullTargetCount = fullTargetCount
    return plan
  end

  function boardSyncTransactions.GetQueueStatusForAdmission()
    if type(boardSyncTransactions.getQueueStatus) ~= "function" then
      return nil, "queue_status_unavailable"
    end
    local ok, status = pcall(boardSyncTransactions.getQueueStatus)
    if not ok or type(status) ~= "table" then
      return nil, "queue_status_unavailable"
    end
    return status, "available"
  end

  function boardSyncTransactions.BuildStagedTargetAdmissionPlan(dispatch, queueStatus)
    local admissionPlan = type(dispatch) == "table" and type(dispatch.admissionPlan) == "table"
      and dispatch.admissionPlan
      or {}
    local statusAvailable = type(queueStatus) == "table"
    local currentQueueDepth = math.max(0,
      math.floor(tonumber(statusAvailable and queueStatus.pending or 0) or 0))
    local maxQueueDepth = math.max(1,
      math.floor(tonumber(statusAvailable and queueStatus.maxQueueDepth or admissionPlan.maxQueueDepth or 6000) or 6000))
    local requiredLiveHeadroom = math.max(0,
      math.floor(tonumber(admissionPlan.requiredLiveHeadroom) or 64))
    local messagesPerTarget = math.max(1,
      math.floor(tonumber(admissionPlan.messagesPerTarget) or 1))
    local safeMessageCapacity = math.max(0, maxQueueDepth - currentQueueDepth - requiredLiveHeadroom)
    local admitted = statusAvailable and messagesPerTarget <= safeMessageCapacity
    return {
      admitted = admitted,
      reason = not statusAvailable and "queue_status_unavailable"
        or (admitted and "admitted" or "queue_headroom_insufficient"),
      currentQueueDepth = currentQueueDepth,
      maxQueueDepth = maxQueueDepth,
      requiredLiveHeadroom = requiredLiveHeadroom,
      messagesPerTarget = messagesPerTarget,
      safeMessageCapacity = safeMessageCapacity,
    }
  end

  function boardSyncTransactions.AppendAdmissionPlanValidationChecks(addCheck)
    if type(addCheck) ~= "function" then
      return
    end
    local emptyQueue = {
      pending = 0,
      maxQueueDepth = 6000,
      maxCriticalQueueOverflow = 64,
    }
    local baseline = boardSyncTransactions.BuildAdmissionPlan(29, 5, 150, 0, emptyQueue)
    addCheck("board admission 30-player baseline shape", "157/4553", table.concat({
      tostring(baseline.messagesPerTarget),
      tostring(baseline.projectedMessages),
    }, "/"))
    addCheck("board admission 30-player bounded live headroom", 1315, baseline.requiredLiveHeadroom)
    addCheck("board admission 30-player baseline is safe", true, baseline.admitted)
    addCheck("board admission 30-player baseline remaining headroom", 1447, baseline.normalHeadroomAfter)
    addCheck("board admission preserves critical overflow reserve", 6064, baseline.criticalAdmissionCeiling)
    addCheck("board admission caps active recipient window", "true/2/admitted_staged", table.concat({
      tostring(baseline.requiresStaging),
      tostring(baseline.activeTargetLimit),
      tostring(baseline.reason),
    }, "/"))

    local populated = boardSyncTransactions.BuildAdmissionPlan(29, 5, 150, 25, emptyQueue)
    addCheck("board admission populated 30-player shape", "182/5278/6593", table.concat({
      tostring(populated.messagesPerTarget),
      tostring(populated.projectedMessages),
      tostring(populated.projectedMessages + populated.requiredLiveHeadroom),
    }, "/"))
    addCheck("board admission stages unsafe populated transaction", true, populated.admitted)
    addCheck("board admission populated staging reason", "true/2/admitted_staged", table.concat({
      tostring(populated.requiresStaging),
      tostring(populated.activeTargetLimit),
      tostring(populated.reason),
    }, "/"))

    local busyQueue = boardSyncTransactions.BuildAdmissionPlan(29, 5, 150, 0, {
      pending = 4600,
      maxQueueDepth = 6000,
      maxCriticalQueueOverflow = 64,
    })
    addCheck("board admission defers when existing queue consumes headroom", false, busyQueue.admitted)
    addCheck("board admission busy queue reason", "queue_headroom_insufficient", busyQueue.reason)

    local twentyPlayer = boardSyncTransactions.BuildAdmissionPlan(19, 5, 100, 0, emptyQueue)
    addCheck("board admission 20-player baseline remains safe", "true/2033/865", table.concat({
      tostring(twentyPlayer.admitted),
      tostring(twentyPlayer.projectedMessages),
      tostring(twentyPlayer.requiredLiveHeadroom),
    }, "/"))

    local unavailable = boardSyncTransactions.BuildAdmissionPlan(1, 1, 2, 0, nil)
    addCheck("board admission fails closed without queue status", "false/queue_status_unavailable", table.concat({
      tostring(unavailable.admitted),
      tostring(unavailable.reason),
    }, "/"))

    local stagedBaseline = boardSyncTransactions.BuildStagedTargetAdmissionPlan({ admissionPlan = baseline }, emptyQueue)
    addCheck("staged board target preserves raid-wide live reserve", "true/157/1315/4685", table.concat({
      tostring(stagedBaseline.admitted),
      tostring(stagedBaseline.messagesPerTarget),
      tostring(stagedBaseline.requiredLiveHeadroom),
      tostring(stagedBaseline.safeMessageCapacity),
    }, "/"))

    local stagedPopulated = boardSyncTransactions.BuildStagedTargetAdmissionPlan({ admissionPlan = populated }, emptyQueue)
    addCheck("staged populated target fits one bounded recipient", "true/182/admitted", table.concat({
      tostring(stagedPopulated.admitted),
      tostring(stagedPopulated.messagesPerTarget),
      tostring(stagedPopulated.reason),
    }, "/"))

    local stagedBusy = boardSyncTransactions.BuildStagedTargetAdmissionPlan({ admissionPlan = baseline }, {
      pending = 4600,
      maxQueueDepth = 6000,
      maxCriticalQueueOverflow = 64,
    })
    addCheck("staged target pauses when live reserve is unavailable", "false/85/queue_headroom_insufficient", table.concat({
      tostring(stagedBusy.admitted),
      tostring(stagedBusy.safeMessageCapacity),
      tostring(stagedBusy.reason),
    }, "/"))

    local stagedRecovered = boardSyncTransactions.BuildStagedTargetAdmissionPlan({ admissionPlan = baseline }, {
      pending = 4400,
      maxQueueDepth = 6000,
      maxCriticalQueueOverflow = 64,
    })
    addCheck("staged target resumes after queue headroom recovers", "true/285/admitted", table.concat({
      tostring(stagedRecovered.admitted),
      tostring(stagedRecovered.safeMessageCapacity),
      tostring(stagedRecovered.reason),
    }, "/"))

    local stagedUnavailable = boardSyncTransactions.BuildStagedTargetAdmissionPlan({ admissionPlan = baseline }, nil)
    addCheck("staged target fails closed without current queue status", "false/queue_status_unavailable", table.concat({
      tostring(stagedUnavailable.admitted),
      tostring(stagedUnavailable.reason),
    }, "/"))

    local scopedSnapshot = { itemOrder = {}, items = {} }
    local scopedTargets = {}
    for memberIndex = 1, 29 do
      scopedTargets[memberIndex] = "ScopedMember" .. tostring(memberIndex) .. "-Realm"
    end
    for itemIndex = 1, 5 do
      local itemKey = "SCOPED-ITEM-" .. tostring(itemIndex)
      local entry = { selections = {} }
      entry.selections["Host-Realm"] = { optionKey = "pending" }
      for _, targetKey in ipairs(scopedTargets) do
        entry.selections[targetKey] = { optionKey = "pending" }
      end
      scopedSnapshot.itemOrder[itemIndex] = itemKey
      scopedSnapshot.items[itemKey] = entry
    end
    local scopedPlan = boardSyncTransactions.BuildSnapshotAdmissionPlan(
      scopedSnapshot,
      scopedTargets,
      emptyQueue,
      true
    )
    addCheck("recipient-scoped board plan keeps only target choices", "5/5/0/150", table.concat({
      tostring(scopedPlan.itemCount),
      tostring(scopedPlan.selectionCount),
      tostring(scopedPlan.voteCount),
      tostring(scopedPlan.reservedSelectionCount),
    }, "/"))
    addCheck("recipient-scoped 30-player board load is bounded", "12/348/1315", table.concat({
      tostring(scopedPlan.messagesPerTarget),
      tostring(scopedPlan.projectedMessages),
      tostring(scopedPlan.requiredLiveHeadroom),
    }, "/"))
    addCheck("recipient-scoped board removes redundant fan-out", 4205,
      baseline.projectedMessages - scopedPlan.projectedMessages)

    local mixedScope = {}
    for targetIndex, targetKey in ipairs(scopedTargets) do
      mixedScope[string.lower(NormalizeCharacterKey(targetKey))] = targetIndex ~= 1
    end
    local mixedPlan = boardSyncTransactions.BuildSnapshotAdmissionPlan(
      scopedSnapshot,
      scopedTargets,
      emptyQueue,
      true,
      mixedScope
    )
    addCheck("council recipient keeps full decision matrix", "28/1/157/493", table.concat({
      tostring(mixedPlan.scopedTargetCount),
      tostring(mixedPlan.fullTargetCount),
      tostring(mixedPlan.messagesPerTarget),
      tostring(mixedPlan.projectedMessages),
    }, "/"))

    addCheck("capacity telemetry exposes projected load and live-safe headroom", "348/4685/1315", table.concat({
      tostring(scopedPlan.projectedMessages),
      tostring(scopedPlan.safeMessageCapacity),
      tostring(scopedPlan.requiredLiveHeadroom),
    }, "/"))
    addCheck("capacity telemetry exposes pre-overflow admission block", "false/85/queue_headroom_insufficient", table.concat({
      tostring(busyQueue.admitted),
      tostring(busyQueue.safeMessageCapacity),
      tostring(busyQueue.reason),
    }, "/"))

    local previousStagedTelemetry = runtime.lastBoardSyncStagedDispatch
    boardSyncTransactions.UpdateStagedDispatchRuntime({
      key = "VALIDATION-CAPACITY",
      sessionId = "VALIDATION-SESSION",
      profileName = "Validation Profile",
      boardId = "VALIDATION-BOARD",
      state = "staged",
      targetKeys = scopedTargets,
      activeTargetLimit = 2,
      activeTargetCount = 2,
      dispatchedCount = 2,
      acknowledgedCount = 0,
      failedCount = 0,
      failedBeforeDispatchCount = 0,
      nextTargetIndex = 3,
    })
    local stagedTelemetry = type(runtime.lastBoardSyncStagedDispatch) == "table"
      and runtime.lastBoardSyncStagedDispatch or {}
    addCheck("capacity telemetry exposes active and staged BSYNC targets", "29/2/2/27", table.concat({
      tostring(stagedTelemetry.targetCount),
      tostring(stagedTelemetry.activeTargetLimit),
      tostring(stagedTelemetry.activeTargetCount),
      tostring(stagedTelemetry.stagedCount),
    }, "/"))
    boardSyncTransactions.UpdateStagedDispatchRuntime({
      key = "VALIDATION-CAPACITY",
      sessionId = "VALIDATION-SESSION",
      profileName = "Validation Profile",
      boardId = "VALIDATION-BOARD",
      state = "waiting_capacity",
      targetKeys = scopedTargets,
      activeTargetLimit = 2,
      activeTargetCount = 0,
      dispatchedCount = 2,
      acknowledgedCount = 2,
      failedCount = 0,
      failedBeforeDispatchCount = 0,
      nextTargetIndex = 3,
      lastCapacityReason = "queue_headroom_insufficient",
    })
    stagedTelemetry = type(runtime.lastBoardSyncStagedDispatch) == "table"
      and runtime.lastBoardSyncStagedDispatch or {}
    addCheck("capacity telemetry exposes staged headroom pause", "waiting_capacity/27/queue_headroom_insufficient", table.concat({
      tostring(stagedTelemetry.state),
      tostring(stagedTelemetry.stagedCount),
      tostring(stagedTelemetry.lastCapacityReason),
    }, "/"))
    runtime.lastBoardSyncStagedDispatch = previousStagedTelemetry
  end

  function boardSyncTransactions.SendRows(transaction, onlyMissing)
    local missing = type(onlyMissing) == "table" and onlyMissing or nil
    local droppedRows = 0
    local hadTruncation = false
    for rowIndex, row in ipairs(transaction.itemRows or {}) do
      if not missing or missing.item[rowIndex] then
        local sent, truncated = SendBoardSyncItemWithFallback(
          transaction.targetKey, transaction.sessionId, transaction.profileName, row.orderIndex, row.itemKey, row.entry
        )
        if sent then
          hadTruncation = hadTruncation or truncated
        else
          droppedRows = droppedRows + 1
        end
      end
    end
    for rowIndex, row in ipairs(transaction.selectionRows or {}) do
      if not missing or missing.selection[rowIndex] then
        local sent, truncated = SendBoardSyncSelectionWithFallback(
          transaction.targetKey,
          transaction.sessionId,
          transaction.profileName,
          row.itemKey,
          row.memberKey,
          row.selection,
          rowIndex
        )
        if sent then
          hadTruncation = hadTruncation or truncated
        else
          droppedRows = droppedRows + 1
        end
      end
    end
    for rowIndex, row in ipairs(transaction.voteRows or {}) do
      if not missing or missing.vote[rowIndex] then
        local sent = SendSessionComm(
          "BSYNC_VOTE",
          "WHISPER",
          transaction.targetKey,
          transaction.sessionId,
          transaction.profileName,
          TrimText(row.itemKey),
          NormalizeCharacterKey(row.voterKey),
          row.targetMemberKey,
          tostring(row.changedAt or ""),
          tostring(row.voteSeq or 1),
          tostring(rowIndex)
        )
        if not sent then
          droppedRows = droppedRows + 1
        end
      end
    end
    return droppedRows, hadTruncation
  end

  function boardSyncTransactions.Fail(transaction, reason)
    if type(transaction) ~= "table" then
      return
    end
    transaction.state = "failed"
    transaction.failureReason = TrimText(reason)
    runtime.lastBoardSyncReceiptFailure = {
      target = transaction.targetKey,
      boardId = transaction.boardId,
      token = transaction.token,
      reason = transaction.failureReason,
      at = GetCurrentTimestamp(),
    }
    RecordRaidTraceEvent("BSYNC_TRANSACTION_FAILED", transaction.failureReason, {
      boardId = TrimText(transaction.boardId),
      token = TrimText(transaction.token),
      target = TrimText(transaction.targetKey),
      endAttempts = math.max(0, tonumber(transaction.endAttempts) or 0),
      rebuilds = math.max(0, tonumber(transaction.fullRebuilds) or 0),
    })
    boardSyncTransactions.outgoing[transaction.key] = nil
    boardSyncTransactions.UpdateRealSimulationDispatch(transaction, "failed", transaction.failureReason)
    if type(boardSyncTransactions.OnStagedTransactionTerminal) == "function" then
      boardSyncTransactions.OnStagedTransactionTerminal(transaction, "failed", transaction.failureReason)
    end
  end

  function boardSyncTransactions.BuildRealSimulationDispatchSummary(report)
    report = type(report) == "table" and report or {}
    local acknowledgedCount = 0
    local pendingCount = 0
    local failedCount = 0
    for _, current in pairs(type(report.dispatchTargets) == "table" and report.dispatchTargets or {}) do
      local currentState = TrimText(type(current) == "table" and current.state or "")
      if currentState == "acknowledged" then
        acknowledgedCount = acknowledgedCount + 1
      elseif currentState == "failed" or currentState == "dispatch_failed" then
        failedCount = failedCount + 1
      elseif currentState ~= "" then
        pendingCount = pendingCount + 1
      end
    end
    local dispatchState
    local statusText
    if failedCount > 0 then
      dispatchState = "failed"
      statusText = string.format(
        "Test items: %d created | %d acknowledged | %d failed",
        math.max(0, tonumber(report.itemCount) or 0),
        acknowledgedCount,
        failedCount
      )
    elseif pendingCount > 0 then
      dispatchState = "awaiting_receipts"
      statusText = string.format(
        "Test items: %d created | %d/%d receipts confirmed",
        math.max(0, tonumber(report.itemCount) or 0),
        acknowledgedCount,
        acknowledgedCount + pendingCount
      )
    else
      dispatchState = "acknowledged"
      statusText = string.format(
        "Test items synced | %d/%d receipts confirmed",
        acknowledgedCount,
        acknowledgedCount
      )
    end
    return {
      acknowledgedCount = acknowledgedCount,
      pendingReceiptCount = pendingCount,
      failedTargetCount = failedCount,
      dispatchState = dispatchState,
      statusText = statusText,
    }
  end

  function boardSyncTransactions.ApplyRealSimulationDispatchState(report, transaction, state, reason, updatedAt)
    if type(report) ~= "table"
      or TrimText(report.sessionId) ~= TrimText(type(transaction) == "table" and transaction.sessionId or "")
      or TrimText(report.boardId) ~= TrimText(type(transaction) == "table" and transaction.boardId or "")
    then
      return false
    end

    local targetKey = string.lower(NormalizeCharacterKey(type(transaction) == "table" and transaction.targetKey or ""))
    local target = type(report.dispatchTargets) == "table" and report.dispatchTargets[targetKey] or nil
    if type(target) ~= "table" or TrimText(target.token) ~= TrimText(transaction.token) then
      return false
    end

    target.state = TrimText(state)
    target.reason = TrimText(reason)
    target.updatedAt = math.max(0, tonumber(updatedAt) or 0)
    if target.state == "acknowledged" then
      target.acknowledgedAt = target.updatedAt
    end

    local summary = boardSyncTransactions.BuildRealSimulationDispatchSummary(report)
    report.acknowledgedCount = summary.acknowledgedCount
    report.pendingReceiptCount = summary.pendingReceiptCount
    report.failedTargetCount = summary.failedTargetCount
    report.dispatchState = summary.dispatchState
    report.statusText = summary.statusText
    report.message = summary.statusText
    if summary.dispatchState == "failed" then
      report.ok = false
      report.deliveryOk = false
      report.resultCode = "RECEIPT_FAILED"
    elseif summary.dispatchState == "acknowledged" then
      report.ok = true
      report.deliveryOk = true
      report.resultCode = "ACKNOWLEDGED"
    else
      report.deliveryOk = nil
    end
    report.updatedAt = target.updatedAt
    return true
  end

  function boardSyncTransactions.UpdateRealSimulationDispatch(transaction, state, reason)
    local report = type(runtime) == "table" and runtime.lastRealSimulationRun or nil
    if not boardSyncTransactions.ApplyRealSimulationDispatchState(
      report,
      transaction,
      state,
      reason,
      GetCurrentTimestamp()
    ) then
      return false
    end

    if type(RefreshBoardAndEditor) == "function" then
      RefreshBoardAndEditor({
        reason = "board_sync_receipt",
        editorRefresh = { refreshPages = { LiveBoard = true } },
      })
    end
    return true
  end

  function boardSyncTransactions.AppendChoiceReceiptRecoveryValidationChecks(addCheck)
    addCheck("mirrored choice receipt resolver is bound before live RCHOICE handling", true,
      type(ResolveEntrySelection) == "function")
    local runValidation = INTERNAL_API.LIDCOUNCIL_RunChoiceReceiptQueueRecoveryValidation_Impl
    addCheck("choice receipt queue recovery validation API", true, type(runValidation) == "function")
    if type(runValidation) ~= "function" then
      return
    end
    local executed, validationOk, validationReport = pcall(runValidation)
    addCheck("choice receipt queue recovery validation completed", true, executed and validationOk == true)
    for _, validationCheck in ipairs(type(validationReport) == "table" and validationReport.checks or {}) do
      addCheck(
        "choice receipt queue recovery: " .. tostring(
          type(validationCheck) == "table" and validationCheck.name or "unnamed check"
        ),
        true,
        type(validationCheck) == "table" and validationCheck.passed == true
      )
    end
  end

  function boardSyncTransactions.AppendItemDescriptorValidationChecks(addCheck)
    local validationItemDescriptor = "item:123456:0:0:0:0:0:0:0:80:70:16:1:3524"
    local validationDisplayLink = "|cffa335ee|H" .. validationItemDescriptor .. "|h[Localized Raid Item]|h|r"
    addCheck(
      "ITEM_OPEN compacts a display link without losing its item variant",
      validationItemDescriptor,
      BuildCompactItemDescriptor(validationDisplayLink, MAX_ITEM_OPEN_LINK_LENGTH)
    )
    addCheck(
      "ITEM_OPEN accepts an already compact item descriptor",
      validationItemDescriptor,
      BuildCompactItemDescriptor(validationItemDescriptor, MAX_ITEM_OPEN_LINK_LENGTH)
    )
    addCheck(
      "BSYNC_ITEM carries the same compact item descriptor",
      validationItemDescriptor,
      BuildCompactItemDescriptor(validationDisplayLink, MAX_BOARD_SYNC_LINK_LENGTH)
    )
    addCheck(
      "ITEM_OPEN rejects an item descriptor beyond its wire bound",
      "",
      BuildCompactItemDescriptor("item:" .. string.rep("1", MAX_ITEM_OPEN_LINK_LENGTH), MAX_ITEM_OPEN_LINK_LENGTH)
    )
    local normalizedValidationItem = NormalizeLootItemPayload({
      itemID = 123456,
      itemLevel = 344,
      name = "Localized Raid Item",
      link = validationDisplayLink,
    })
    addCheck(
      "loot runtime canonicalizes host and receiver links to the same descriptor",
      validationItemDescriptor,
      normalizedValidationItem.link
    )
    addCheck(
      "loot runtime keeps the host item level authoritative while compacting",
      344,
      normalizedValidationItem.itemLevel
    )
    local resolveTooltipMode = INTERNAL_API.LIDCOUNCIL_ResolveAuthoritativeItemTooltipMode_Impl
    addCheck("authoritative item tooltip classifier API", true, type(resolveTooltipMode) == "function")
    if type(resolveTooltipMode) == "function" then
      addCheck(
        "authoritative item tooltip uses native details for an exact compact variant",
        "native",
        select(1, resolveTooltipMode(true, 344, 344, true))
      )
      addCheck(
        "authoritative item tooltip rejects a locally resolved wrong variant",
        "authoritative_fallback",
        select(1, resolveTooltipMode(true, 344, 219, true))
      )
      addCheck(
        "authoritative item tooltip does not invent native details without a descriptor",
        "authoritative_fallback",
        select(1, resolveTooltipMode(false, 344, 219, true))
      )
    end
  end

  function boardSyncTransactions.AppendAwardPayloadValidationChecks(addCheck)
    local accepted, fields, metadata = boardSyncTransactions.PrepareAwardPacket(
      "SESSION-VALIDATION-1234567890",
      "Validation Profile With A Long Name",
      "TESTSIM-VALIDATION-AWARD-1",
      "Receiver-Realm",
      "An Extremely Long Validation Item Name That Is Already Present On The Live Board",
      344,
      15,
      string.rep("Long award note ", 18),
      1786812431
    )
    addCheck("AWARD compaction produces a transport-safe packet", true, accepted)
    addCheck("AWARD compaction preserves receipt identity", "TESTSIM-VALIDATION-AWARD-1/Receiver-Realm/1786812431",
      table.concat({
        tostring(type(fields) == "table" and fields[3] or ""),
        tostring(type(fields) == "table" and fields[4] or ""),
        tostring(type(fields) == "table" and fields[9] or ""),
      }, "/"))
    addCheck("AWARD compaction removes only redundant or truncatable text", true,
      type(metadata) == "table" and (metadata.itemNameOmitted == true or metadata.noteTruncated == true))
  end

  function boardSyncTransactions.RunBoardSyncReceiptValidation()
    local checks = {}
    local passedCount = 0
    local function addCheck(name, expected, actual)
      local passed = expected == actual
      checks[#checks + 1] = {
        name = name,
        expected = tostring(expected),
        actual = tostring(actual),
        passed = passed,
      }
      if passed then
        passedCount = passedCount + 1
      end
    end
    boardSyncTransactions.AppendAdmissionPlanValidationChecks(addCheck)
    boardSyncTransactions.AppendChoiceReceiptRecoveryValidationChecks(addCheck)
    boardSyncTransactions.AppendItemDescriptorValidationChecks(addCheck)
    boardSyncTransactions.AppendAwardPayloadValidationChecks(addCheck)
    local runItemPreparationValidation = INTERNAL_API.LIDCOUNCIL_RunRealSimulationItemPreparationValidation_Impl
    addCheck("Test Raid Items preload validation API", true, type(runItemPreparationValidation) == "function")
    if type(runItemPreparationValidation) == "function" then
      local executed, validationOk, validationReport = pcall(runItemPreparationValidation)
      addCheck("Test Raid Items preload validation completed", true, executed and validationOk == true)
      for _, validationCheck in ipairs(type(validationReport) == "table" and validationReport.checks or {}) do
        addCheck(
          "item preload: " .. tostring(type(validationCheck) == "table" and validationCheck.name or "unnamed check"),
          true,
          type(validationCheck) == "table" and validationCheck.passed == true
        )
      end
    end
    local report = {
      sessionId = "VALIDATION-SESSION",
      boardId = "VALIDATION-BOARD",
      itemCount = 5,
      dispatchTargets = {
        ["alpha-realm"] = { token = "TOKEN-A", state = "waiting_receipt" },
        ["beta-realm"] = { token = "TOKEN-B", state = "waiting_receipt" },
        ["gamma-realm"] = { token = "TOKEN-C", state = "waiting_receipt" },
      },
    }
    addCheck("board sync is admitted during session-start transition", true,
      COMBAT_STAGED_RUNTIME_OPCODE_SET.__preparedSession.BSYNC_START == true
        and COMBAT_STAGED_RUNTIME_OPCODE_SET.__preparedSession.BSYNC_ITEM == true
        and COMBAT_STAGED_RUNTIME_OPCODE_SET.__preparedSession.BSYNC_SEL == true
        and COMBAT_STAGED_RUNTIME_OPCODE_SET.__preparedSession.BSYNC_VOTE == true
        and COMBAT_STAGED_RUNTIME_OPCODE_SET.__preparedSession.BSYNC_END == true)
    addCheck("board sync commits and acknowledges during combat", true,
      COMBAT_STAGED_RUNTIME_OPCODE_SET.BSYNC_START ~= true
        and COMBAT_STAGED_RUNTIME_OPCODE_SET.BSYNC_ITEM ~= true
        and COMBAT_STAGED_RUNTIME_OPCODE_SET.BSYNC_SEL ~= true
        and COMBAT_STAGED_RUNTIME_OPCODE_SET.BSYNC_VOTE ~= true
        and COMBAT_STAGED_RUNTIME_OPCODE_SET.BSYNC_END ~= true)
    local pendingTransaction = boardSyncTransactions.Build(
      { id = "VALIDATION-SESSION" },
      "Validation Profile",
      {
        updatedAt = 200,
        boardId = "VALIDATION-BOARD",
        selectedItemKey = "TESTSIM-VALIDATION-1",
        itemOrder = { "TESTSIM-VALIDATION-1" },
        items = {
          ["TESTSIM-VALIDATION-1"] = {
            key = "TESTSIM-VALIDATION-1",
            createdAt = 201,
            selections = {
              ["Receiver-Realm"] = {
                optionKey = "pending",
                label = "Pending",
                pointBehavior = "NONE",
              },
            },
          },
        },
      },
      "Receiver-Realm"
    )
    local pendingTransportSelection = type(pendingTransaction) == "table"
      and type(pendingTransaction.selectionRows) == "table"
      and type(pendingTransaction.selectionRows[1]) == "table"
      and pendingTransaction.selectionRows[1].selection
      or nil
    addCheck("pending board choice carries receiver-valid transport metadata", "pending/201/1",
      table.concat({
        tostring(type(pendingTransportSelection) == "table" and pendingTransportSelection.optionKey),
        tostring(type(pendingTransportSelection) == "table" and pendingTransportSelection.selectedAt),
        tostring(type(pendingTransportSelection) == "table" and pendingTransportSelection.selectedSeq),
      }, "/"))
    local scopedSnapshot = {
      updatedAt = 210,
      boardId = "VALIDATION-SCOPED-BOARD",
      selectedItemKey = "VALIDATION-SCOPED-ITEM",
      itemOrder = { "VALIDATION-SCOPED-ITEM" },
      items = {
        ["VALIDATION-SCOPED-ITEM"] = {
          key = "VALIDATION-SCOPED-ITEM",
          createdAt = 211,
          selections = {
            ["Receiver-Realm"] = { optionKey = "pending", label = "Pending" },
            ["Other-Realm"] = { optionKey = "bis", label = "BiS", selectedAt = 212, selectedSeq = 2 },
            ["PendingOther-Realm"] = { optionKey = "pending", label = "Pending" },
          },
          votesByVoter = { ["Council-Realm"] = "Other-Realm" },
          voteUpdatedAtByVoter = { ["Council-Realm"] = 213 },
          voteSequenceByVoter = { ["Council-Realm"] = 3 },
        },
      },
    }
    local scopedTransaction = boardSyncTransactions.Build(
      { id = "VALIDATION-SESSION" },
      "Validation Profile",
      scopedSnapshot,
      "Receiver-Realm",
      true
    )
    local scopedChecksum = TrimText(type(scopedTransaction) == "table" and scopedTransaction.checksum or "")
    addCheck("recipient transaction keeps own pending row and resolved board state", "1/2/1/true", table.concat({
      tostring(type(scopedTransaction) == "table" and scopedTransaction.itemCount),
      tostring(type(scopedTransaction) == "table" and scopedTransaction.selectionCount),
      tostring(type(scopedTransaction) == "table" and scopedTransaction.voteCount),
      tostring(type(scopedTransaction) == "table" and scopedTransaction.recipientScoped),
    }, "/"))
    addCheck("recipient transaction promotes to full repair snapshot", true,
      boardSyncTransactions.PromoteToFullSnapshot(scopedTransaction))
    addCheck("full repair restores all pending selections", "1/3/1/false/true", table.concat({
      tostring(scopedTransaction.itemCount),
      tostring(scopedTransaction.selectionCount),
      tostring(scopedTransaction.voteCount),
      tostring(scopedTransaction.recipientScoped),
      tostring(scopedTransaction.fullFallbackPromoted),
    }, "/"))
    addCheck("full repair manifest replaces scoped checksum", true,
      scopedChecksum ~= "" and scopedChecksum ~= TrimText(scopedTransaction.checksum))
    local function transaction(target, token, sessionId, boardId)
      return {
        targetKey = target,
        token = token,
        sessionId = sessionId or report.sessionId,
        boardId = boardId or report.boardId,
      }
    end
    addCheck("board receipt rejects another session", false,
      boardSyncTransactions.ApplyRealSimulationDispatchState(
        report, transaction("Alpha-Realm", "TOKEN-A", "OTHER-SESSION"), "acknowledged", "", 100
      ))
    addCheck("board receipt rejects another board", false,
      boardSyncTransactions.ApplyRealSimulationDispatchState(
        report, transaction("Alpha-Realm", "TOKEN-A", nil, "OTHER-BOARD"), "acknowledged", "", 100
      ))
    addCheck("board receipt rejects a stale token", false,
      boardSyncTransactions.ApplyRealSimulationDispatchState(
        report, transaction("Alpha-Realm", "STALE-TOKEN"), "acknowledged", "", 100
      ))
    addCheck("board receipt accepts exact target transaction", true,
      boardSyncTransactions.ApplyRealSimulationDispatchState(
        report, transaction("Alpha-Realm", "TOKEN-A"), "acknowledged", "", 101
      ))
    addCheck("board receipt tracks partial acknowledgement", "1/2/0/awaiting_receipts",
      table.concat({
        tostring(report.acknowledgedCount),
        tostring(report.pendingReceiptCount),
        tostring(report.failedTargetCount),
        tostring(report.dispatchState),
      }, "/"))
    addCheck("board receipt records terminal target failure", true,
      boardSyncTransactions.ApplyRealSimulationDispatchState(
        report, transaction("Beta-Realm", "TOKEN-B"), "failed", "receipt_timeout", 102
      ))
    addCheck("board receipt failure dominates pending targets", "1/1/1/failed",
      table.concat({
        tostring(report.acknowledgedCount),
        tostring(report.pendingReceiptCount),
        tostring(report.failedTargetCount),
        tostring(report.dispatchState),
      }, "/"))
    addCheck("board receipt failure updates public result", "false/false/RECEIPT_FAILED",
      table.concat({
        tostring(report.ok),
        tostring(report.deliveryOk),
        tostring(report.resultCode),
      }, "/"))
    addCheck("board receipt accepts remaining target", true,
      boardSyncTransactions.ApplyRealSimulationDispatchState(
        report, transaction("Gamma-Realm", "TOKEN-C"), "acknowledged", "", 103
      ))
    addCheck("board receipt accepts recovered failed target", true,
      boardSyncTransactions.ApplyRealSimulationDispatchState(
        report, transaction("Beta-Realm", "TOKEN-B"), "acknowledged", "", 104
      ))
    addCheck("board receipt converges all targets", "3/0/0/acknowledged",
      table.concat({
        tostring(report.acknowledgedCount),
        tostring(report.pendingReceiptCount),
        tostring(report.failedTargetCount),
        tostring(report.dispatchState),
      }, "/"))
    addCheck("board receipt completion text is deterministic", "Test items synced | 3/3 receipts confirmed",
      report.statusText)
    addCheck("board receipt completion updates public result", "true/true/ACKNOWLEDGED",
      table.concat({
        tostring(report.ok),
        tostring(report.deliveryOk),
        tostring(report.resultCode),
      }, "/"))
    addCheck("live transport test key remains simulation-only", true,
      IsRealSimulationItemKey("TESTSIM-TRANSPORT-VALIDATION") == true)
    addCheck("real live item key remains persistent", false,
      IsRealSimulationItemKey("LIVE-VALIDATION") == true)
    addCheck("live transport test uses token-compatible ITEM_OPEN schema", "13/14/15",
      table.concat(EXPECTED_FIELD_COUNTS.ITEM_OPEN, "/"))
    addCheck("ITEM_OPEN receipt uses exact compact schema", 7, EXPECTED_FIELD_COUNTS.ITEM_ACK)
    addCheck("ITEM_OPEN commits runtime data during combat", true,
      COMBAT_STAGED_RUNTIME_OPCODE_SET.ITEM_OPEN ~= true)
    addCheck("ITEM_OPEN receipt commits during combat", true,
      COMBAT_STAGED_RUNTIME_OPCODE_SET.ITEM_ACK ~= true)
    addCheck("ITEM_OPEN still requires an active session", false,
      COMBAT_STAGED_RUNTIME_OPCODE_SET.__preparedSession.ITEM_OPEN == true)
    local savedItemDispatch = runtime.lastItemOpenDispatch
    local savedLiveTransportTest = runtime.lastLiveTransportTest
    local itemReport = {
      sessionId = "VALIDATION-ITEM-SESSION",
      profileName = "Validation Profile",
      itemKey = "LIVE-VALIDATION-ITEM",
      targets = {
        ["alpha-realm"] = { targetKey = "Alpha-Realm", token = "ITEM-TOKEN-A", state = "pending" },
        ["beta-realm"] = { targetKey = "Beta-Realm", token = "ITEM-TOKEN-A", state = "pending" },
      },
    }
    local itemTransaction = {
      sessionId = itemReport.sessionId,
      profileName = itemReport.profileName,
      itemKey = itemReport.itemKey,
      targetKey = "Alpha-Realm",
      token = "ITEM-TOKEN-A",
      attempts = 2,
    }
    addCheck("ITEM_OPEN receipt rejects another session", false,
      boardSyncTransactions.ApplyItemOpenDispatchState(
        itemReport,
        {
          sessionId = "OTHER-SESSION",
          profileName = itemTransaction.profileName,
          itemKey = itemTransaction.itemKey,
          targetKey = itemTransaction.targetKey,
          token = itemTransaction.token,
        },
        "acknowledged",
        "",
        100
      ))
    addCheck("ITEM_OPEN receipt rejects stale token", false,
      boardSyncTransactions.ApplyItemOpenDispatchState(
        itemReport,
        {
          sessionId = itemTransaction.sessionId,
          profileName = itemTransaction.profileName,
          itemKey = itemTransaction.itemKey,
          targetKey = itemTransaction.targetKey,
          token = "STALE-TOKEN",
        },
        "acknowledged",
        "",
        100
      ))
    addCheck("ITEM_OPEN receipt accepts exact target token", true,
      boardSyncTransactions.ApplyItemOpenDispatchState(itemReport, itemTransaction, "acknowledged", "item_admitted", 101))
    addCheck("ITEM_OPEN duplicate receipt is idempotent", true,
      boardSyncTransactions.ApplyItemOpenDispatchState(itemReport, itemTransaction, "acknowledged", "item_admitted", 102))
    addCheck("ITEM_OPEN receipt tracks target acknowledgement", "1/1/0/awaiting_receipts",
      table.concat({
        tostring(itemReport.acknowledgedCount),
        tostring(itemReport.pendingReceiptCount),
        tostring(itemReport.failedTargetCount),
        tostring(itemReport.state),
      }, "/"))
    addCheck("ITEM_OPEN terminal failure identifies recipient", true,
      boardSyncTransactions.ApplyItemOpenDispatchState(
        itemReport,
        {
          sessionId = itemReport.sessionId,
          profileName = itemReport.profileName,
          itemKey = itemReport.itemKey,
          targetKey = "Beta-Realm",
          token = "ITEM-TOKEN-A",
          attempts = 4,
        },
        "failed",
        "receipt_timeout",
        103
      ))
    addCheck("ITEM_OPEN failure is visible by target", "failed/receipt_timeout/4",
      table.concat({
        tostring(itemReport.targets["beta-realm"].state),
        tostring(itemReport.targets["beta-realm"].reason),
        tostring(itemReport.targets["beta-realm"].attempts),
      }, "/"))
    addCheck("ITEM_OPEN receipt can recover a terminal target", true,
      boardSyncTransactions.ApplyItemOpenDispatchState(
        itemReport,
        {
          sessionId = itemReport.sessionId,
          profileName = itemReport.profileName,
          itemKey = itemReport.itemKey,
          targetKey = "Beta-Realm",
          token = "ITEM-TOKEN-A",
          attempts = 4,
        },
        "acknowledged",
        "duplicate_replay",
        104
      ))
    addCheck("ITEM_OPEN receipts converge all targets", "2/0/0/acknowledged",
      table.concat({
        tostring(itemReport.acknowledgedCount),
        tostring(itemReport.pendingReceiptCount),
        tostring(itemReport.failedTargetCount),
        tostring(itemReport.state),
      }, "/"))
    addCheck("ITEM_OPEN retry budget is bounded", "4/41",
      tostring(#boardSyncTransactions.itemOpenRetryDelays)
        .. "/" .. tostring(
          (tonumber(boardSyncTransactions.itemOpenRetryDelays[1]) or 0)
          + (tonumber(boardSyncTransactions.itemOpenRetryDelays[2]) or 0)
          + (tonumber(boardSyncTransactions.itemOpenRetryDelays[3]) or 0)
          + (tonumber(boardSyncTransactions.itemOpenRetryDelays[4]) or 0)
        ))
    addCheck("ITEM_OPEN duplicate identity is stable", true,
      boardSyncTransactions.GetItemOpenIdentity("SESSION", "LIVE-ITEM", "Alpha-Realm")
        == boardSyncTransactions.GetItemOpenIdentity("SESSION", "LIVE-ITEM", "alpha-realm"))
    addCheck("ITEM_OPEN group fan-out keeps per-recipient receipt keys", true,
      boardSyncTransactions.GetItemOpenReceiptKey("ITEM-TOKEN-A", "Alpha-Realm")
        ~= boardSyncTransactions.GetItemOpenReceiptKey("ITEM-TOKEN-A", "Beta-Realm"))
    for _, replayCheck in ipairs(boardSyncTransactions.RunItemOpenReplayValidation()) do
      addCheck(replayCheck.name, replayCheck.expected, replayCheck.actual)
    end
    runtime.lastItemOpenDispatch = savedItemDispatch
    runtime.lastLiveTransportTest = savedLiveTransportTest
    local savedReceiver = runtime.lastBoardSyncReceiver
    local receiverFixture = {
      sessionId = "VALIDATION-RECEIVER-SESSION",
      profileName = "Validation Profile",
      boardId = "VALIDATION-RECEIVER-BOARD",
      token = "VALIDATION-RECEIVER-TOKEN",
      expectedItems = 2,
      expectedSelections = 2,
      expectedVotes = 1,
      itemSignatures = {},
      selectionSignatures = {},
      voteSignatures = {},
    }
    boardSyncTransactions.RecordReceiver("start_received", receiverFixture, "Receiver-Realm", "")
    addCheck("board receiver records admitted start", "start_received/2/2/1",
      table.concat({
        tostring(runtime.lastBoardSyncReceiver.state),
        tostring(runtime.lastBoardSyncReceiver.expectedItems),
        tostring(runtime.lastBoardSyncReceiver.expectedSelections),
        tostring(runtime.lastBoardSyncReceiver.expectedVotes),
      }, "/"))
    receiverFixture.itemSignatures[1] = "I1"
    receiverFixture.itemSignatures[2] = "I2"
    receiverFixture.selectionSignatures[1] = "S1"
    receiverFixture.voteSignatures[1] = "V1"
    boardSyncTransactions.RecordReceiver("receiving", receiverFixture, "Receiver-Realm", "")
    addCheck("board receiver records bounded row progress", "2/1/1",
      table.concat({
        tostring(runtime.lastBoardSyncReceiver.receivedItems),
        tostring(runtime.lastBoardSyncReceiver.receivedSelections),
        tostring(runtime.lastBoardSyncReceiver.receivedVotes),
      }, "/"))
    boardSyncTransactions.RecordReceiver("checksum_mismatch", receiverFixture, "Receiver-Realm", "manifest_checksum_mismatch", {
      checksumMatched = false,
      ackStatus = "CHECKSUM",
      ackSent = true,
    })
    addCheck("board receiver records checksum recovery receipt", "checksum_mismatch/CHECKSUM/true/false",
      table.concat({
        tostring(runtime.lastBoardSyncReceiver.state),
        tostring(runtime.lastBoardSyncReceiver.ackStatus),
        tostring(runtime.lastBoardSyncReceiver.ackSent),
        tostring(runtime.lastBoardSyncReceiver.checksumMatched),
      }, "/"))
    receiverFixture.selectionSignatures[2] = "S2"
    boardSyncTransactions.RecordReceiver("complete", receiverFixture, "Receiver-Realm", "", {
      checksumMatched = true,
      ackStatus = "COMPLETE",
      ackSent = true,
      popupQueueCount = 2,
      popupOpened = false,
      popupState = "deferred",
      popupReason = "combat_ui_deferred",
    })
    addCheck("board receiver separates completion from deferred UI", "complete/true/deferred/combat_ui_deferred",
      table.concat({
        tostring(runtime.lastBoardSyncReceiver.state),
        tostring(runtime.lastBoardSyncReceiver.ackSent),
        tostring(runtime.lastBoardSyncReceiver.popupState),
        tostring(runtime.lastBoardSyncReceiver.popupReason),
      }, "/"))
    addCheck("board receiver telemetry remains scalar and bounded", "nil/nil/nil",
      table.concat({
        tostring(runtime.lastBoardSyncReceiver.itemSignatures),
        tostring(runtime.lastBoardSyncReceiver.selectionSignatures),
        tostring(runtime.lastBoardSyncReceiver.voteSignatures),
      }, "/"))
    addCheck("board item receiver admits compact fallback schema", "18/21/22",
      table.concat(EXPECTED_FIELD_COUNTS.BSYNC_ITEM, "/"))
    if type(boardSyncTransactions.AppendStagedDispatchCoalescingValidationChecks) == "function" then
      boardSyncTransactions.AppendStagedDispatchCoalescingValidationChecks(addCheck)
    else
      addCheck("staged board coalescing validation is available", true, false)
    end
    boardSyncTransactions.RunOutboundEndValidation(addCheck)
    runtime.lastBoardSyncReceiver = savedReceiver
    return passedCount == #checks, {
      suite = "board_sync_receipts",
      total = #checks,
      passed = passedCount,
      failed = #checks - passedCount,
      checks = checks,
    }
  end

  function boardSyncTransactions.ScheduleReceiptTimeout(transaction)
    if type(transaction) ~= "table" or transaction.state == "complete" or transaction.state == "failed" then
      return
    end
    transaction.receiptWatch = math.max(0, tonumber(transaction.receiptWatch) or 0) + 1
    local watch = transaction.receiptWatch
    if type(C_Timer) ~= "table" or type(C_Timer.After) ~= "function" then
      return
    end
    C_Timer.After(boardSyncTransactions.receiptTimeoutSeconds, function()
      if boardSyncTransactions.outgoing[transaction.key] ~= transaction
        or transaction.receiptWatch ~= watch
        or transaction.state == "complete"
      then
        return
      end
      RecordRaidTraceEvent("BSYNC_RECEIPT_TIMEOUT", "Board receipt deadline reached.", {
        boardId = TrimText(transaction.boardId),
        token = TrimText(transaction.token),
        target = TrimText(transaction.targetKey),
        endAttempts = math.max(0, tonumber(transaction.endAttempts) or 0),
        rebuilds = math.max(0, tonumber(transaction.fullRebuilds) or 0),
      })
      if (tonumber(transaction.endAttempts) or 0) < boardSyncTransactions.maxEndAttempts then
        transaction.endAttempts = math.max(0, tonumber(transaction.endAttempts) or 0) + 1
        transaction.state = "end_retry_queued"
        local endOk = SendBoardSyncEndMessage(
          transaction.targetKey,
          transaction.sessionId,
          transaction.profileName,
          transaction.boardId,
          transaction.selectedItemKey,
          transaction.token
        )
        if not endOk then
          boardSyncTransactions.SendFullRebuild(transaction, "end_retry_queue_failed")
        end
      elseif (tonumber(transaction.fullRebuilds) or 0) < boardSyncTransactions.maxFullRebuilds then
        boardSyncTransactions.SendFullRebuild(transaction, "receipt_timeout")
      else
        boardSyncTransactions.Fail(transaction, "receipt_timeout")
      end
    end)
  end

  function boardSyncTransactions.ResolveFromOutboundMetadata(metadata)
    metadata = type(metadata) == "table" and metadata or {}
    local key = boardSyncTransactions.GetOutgoingKey(
      metadata.sessionId,
      metadata.profileName,
      metadata.target,
      metadata.token
    )
    local transaction = boardSyncTransactions.outgoing[key]
    if type(transaction) ~= "table"
      or TrimText(metadata.boardId) == ""
      or TrimText(transaction.boardId) ~= TrimText(metadata.boardId)
    then
      return nil
    end
    return transaction
  end

  function boardSyncTransactions.MarkEndSent(metadata, sentAt, skipSchedule)
    local transaction = boardSyncTransactions.ResolveFromOutboundMetadata(metadata)
    if type(transaction) ~= "table" or transaction.state == "complete" or transaction.state == "failed" then
      return false
    end
    transaction.endSentAt = math.max(0, tonumber(sentAt) or GetCurrentTimestamp())
    transaction.endSentCount = math.max(0, tonumber(transaction.endSentCount) or 0) + 1
    transaction.state = "waiting_receipt"
    RecordRaidTraceEvent("BSYNC_END_SENT", "Transaction end reached the WoW API.", {
      boardId = TrimText(transaction.boardId),
      token = TrimText(transaction.token),
      target = TrimText(transaction.targetKey),
      endSentCount = math.max(0, tonumber(transaction.endSentCount) or 0),
    })
    boardSyncTransactions.UpdateRealSimulationDispatch(transaction, "waiting_receipt", "")
    if skipSchedule ~= true then
      boardSyncTransactions.ScheduleReceiptTimeout(transaction)
    end
    return true
  end

  function boardSyncTransactions.MarkEndFailed(metadata, failedAt, reason)
    local transaction = boardSyncTransactions.ResolveFromOutboundMetadata(metadata)
    if type(transaction) ~= "table" or transaction.state == "complete" or transaction.state == "failed" then
      return false
    end
    transaction.endFailedAt = math.max(0, tonumber(failedAt) or GetCurrentTimestamp())
    RecordRaidTraceEvent("BSYNC_END_FAILED", TrimText(reason), {
      boardId = TrimText(transaction.boardId),
      token = TrimText(transaction.token),
      target = TrimText(transaction.targetKey),
    })
    boardSyncTransactions.Fail(transaction, "board_sync_end_send_failed:" .. TrimText(reason))
    return true
  end

  INTERNAL_API.LIDCOUNCIL_NotifyOutboundBoardSyncEnd_Impl = function(event, metadata, eventAt, reason)
    if TrimText(event) == "sent" then
      return boardSyncTransactions.MarkEndSent(metadata, eventAt)
    elseif TrimText(event) == "failed" then
      return boardSyncTransactions.MarkEndFailed(metadata, eventAt, reason)
    end
    return false
  end

  function boardSyncTransactions.RunOutboundEndValidation(addCheck)
    local results = {}
    local sentMetadata = {
      sessionId = "SESSION-END-SENT",
      profileName = "Profile",
      boardId = "BOARD-END-SENT",
      token = "TOKEN-END-SENT",
      target = "Receiver-Realm",
    }
    local sentKey = boardSyncTransactions.GetOutgoingKey(
      sentMetadata.sessionId,
      sentMetadata.profileName,
      sentMetadata.target,
      sentMetadata.token
    )
    local savedSentTransaction = boardSyncTransactions.outgoing[sentKey]
    local sentTransaction = {
      key = sentKey,
      sessionId = sentMetadata.sessionId,
      profileName = sentMetadata.profileName,
      boardId = sentMetadata.boardId,
      token = sentMetadata.token,
      targetKey = sentMetadata.target,
      state = "end_queued",
    }
    boardSyncTransactions.outgoing[sentKey] = sentTransaction
    results[#results + 1] = {
      name = "board receipt remains unarmed while transaction end is queued",
      expected = "end_queued/0",
      actual = tostring(sentTransaction.state) .. "/" .. tostring(tonumber(sentTransaction.endSentCount) or 0),
    }
    boardSyncTransactions.MarkEndSent(sentMetadata, 101, true)
    results[#results + 1] = {
      name = "board receipt begins only after physical transaction end send",
      expected = "waiting_receipt/101/1",
      actual = table.concat({
        tostring(sentTransaction.state),
        tostring(sentTransaction.endSentAt),
        tostring(sentTransaction.endSentCount),
      }, "/"),
    }
    boardSyncTransactions.outgoing[sentKey] = savedSentTransaction

    local failedMetadata = {
      sessionId = "SESSION-END-FAILED",
      profileName = "Profile",
      boardId = "BOARD-END-FAILED",
      token = "TOKEN-END-FAILED",
      target = "Receiver-Realm",
    }
    local failedKey = boardSyncTransactions.GetOutgoingKey(
      failedMetadata.sessionId,
      failedMetadata.profileName,
      failedMetadata.target,
      failedMetadata.token
    )
    local savedFailedTransaction = boardSyncTransactions.outgoing[failedKey]
    local savedReceiptFailure = runtime.lastBoardSyncReceiptFailure
    local failedTransaction = {
      key = failedKey,
      sessionId = failedMetadata.sessionId,
      profileName = failedMetadata.profileName,
      boardId = failedMetadata.boardId,
      token = failedMetadata.token,
      targetKey = failedMetadata.target,
      state = "end_queued",
    }
    boardSyncTransactions.outgoing[failedKey] = failedTransaction
    boardSyncTransactions.MarkEndFailed(failedMetadata, 102, "transport_terminal")
    results[#results + 1] = {
      name = "terminal transaction end send failure closes receipt tracking",
      expected = "failed/true",
      actual = tostring(failedTransaction.state) .. "/"
        .. tostring(boardSyncTransactions.outgoing[failedKey] == nil),
    }
    boardSyncTransactions.outgoing[failedKey] = savedFailedTransaction
    runtime.lastBoardSyncReceiptFailure = savedReceiptFailure
    if type(addCheck) == "function" then
      for _, timingCheck in ipairs(results) do
        addCheck(timingCheck.name, timingCheck.expected, timingCheck.actual)
      end
    end
    return results
  end

  function boardSyncTransactions.SendFullRebuild(transaction, reason)
    if type(transaction) ~= "table" then
      return false
    end
    if (tonumber(transaction.fullRebuilds) or 0) >= boardSyncTransactions.maxFullRebuilds then
      boardSyncTransactions.Fail(transaction, "full_rebuild_exhausted:" .. TrimText(reason))
      return false
    end
    boardSyncTransactions.PromoteToFullSnapshot(transaction)
    transaction.fullRebuilds = math.max(0, tonumber(transaction.fullRebuilds) or 0) + 1
    transaction.endAttempts = 1
    transaction.state = "rebuild_queued"
    transaction.lastRecoveryReason = TrimText(reason)
    RecordRaidTraceEvent("BSYNC_FULL_REBUILD", TrimText(reason), {
      boardId = TrimText(transaction.boardId),
      token = TrimText(transaction.token),
      target = TrimText(transaction.targetKey),
      rebuilds = math.max(0, tonumber(transaction.fullRebuilds) or 0),
    })
    transaction.missing = { item = {}, selection = {}, vote = {} }
    local startOk = SendBoardSyncStartMessage(
      transaction.targetKey,
      transaction.sessionId,
      transaction.profileName,
      transaction.boardUpdatedAt,
      transaction.boardId,
      transaction.historyProfileName,
      transaction.selectedItemKey,
      transaction
    )
    if not startOk then
      boardSyncTransactions.Fail(transaction, "full_rebuild_start_failed")
      return false
    end
    boardSyncTransactions.SendRows(transaction)
    local endOk = SendBoardSyncEndMessage(
      transaction.targetKey,
      transaction.sessionId,
      transaction.profileName,
      transaction.boardId,
      transaction.selectedItemKey,
      transaction.token
    )
    if not endOk then
      boardSyncTransactions.Fail(transaction, "full_rebuild_end_failed")
      return false
    end
    return true
  end

  function boardSyncTransactions.SendSelectiveRepair(transaction)
    if type(transaction) ~= "table" then
      return false
    end
    if (tonumber(transaction.selectiveAttempts) or 0) >= boardSyncTransactions.maxSelectiveAttempts then
      return boardSyncTransactions.SendFullRebuild(transaction, "selective_retry_exhausted")
    end
    transaction.selectiveAttempts = math.max(0, tonumber(transaction.selectiveAttempts) or 0) + 1
    transaction.endAttempts = 1
    transaction.state = "selective_repair_queued"
    RecordRaidTraceEvent("BSYNC_SELECTIVE_REPAIR", "Missing board rows queued again.", {
      boardId = TrimText(transaction.boardId),
      token = TrimText(transaction.token),
      target = TrimText(transaction.targetKey),
      attempt = math.max(0, tonumber(transaction.selectiveAttempts) or 0),
    })
    boardSyncTransactions.SendRows(transaction, transaction.missing)
    transaction.missing = { item = {}, selection = {}, vote = {} }
    local endOk = SendBoardSyncEndMessage(
      transaction.targetKey,
      transaction.sessionId,
      transaction.profileName,
      transaction.boardId,
      transaction.selectedItemKey,
      transaction.token
    )
    if not endOk then
      return boardSyncTransactions.SendFullRebuild(transaction, "selective_end_failed")
    end
    return true
  end

  local function SendBoardSyncSnapshotToTarget(activeSession, profileName, snapshot, targetKey)
    if type(activeSession) ~= "table" or TrimText(profileName) == "" or type(snapshot) ~= "table" then
      return false, { reason = "invalid_board_sync_context" }
    end
    local resolvedTargetKey = NormalizeCharacterKey(targetKey)
    if resolvedTargetKey == "" or type(SendSessionComm) ~= "function" then
      return false, { target = resolvedTargetKey, reason = "invalid_board_sync_target" }
    end
    local recipientScoped = not CanSessionCharacterVote(activeSession, profileName, resolvedTargetKey)
    local transaction = boardSyncTransactions.Build(
      activeSession,
      profileName,
      snapshot,
      resolvedTargetKey,
      recipientScoped
    )
    transaction.endAttempts = 1
    transaction.state = "queued"
    boardSyncTransactions.outgoing[transaction.key] = transaction
    RecordRaidTraceEvent("BSYNC_TRANSACTION_BEGIN", "Full board transaction created.", {
      boardId = TrimText(transaction.boardId),
      token = TrimText(transaction.token),
      target = TrimText(transaction.targetKey),
      items = math.max(0, tonumber(transaction.itemCount) or 0),
      selections = math.max(0, tonumber(transaction.selectionCount) or 0),
      votes = math.max(0, tonumber(transaction.voteCount) or 0),
      recipientScoped = transaction.recipientScoped == true,
    })
    local startOk, startTruncated = SendBoardSyncStartMessage(
      transaction.targetKey,
      transaction.sessionId,
      transaction.profileName,
      transaction.boardUpdatedAt,
      transaction.boardId,
      transaction.historyProfileName,
      transaction.selectedItemKey,
      transaction
    )
    if not startOk then
      boardSyncTransactions.outgoing[transaction.key] = nil
      transaction.state = "failed"
      transaction.failureReason = "board_sync_start_failed"
      RecordRaidTraceEvent("BSYNC_TRANSACTION_FAILED", transaction.failureReason, {
        boardId = TrimText(transaction.boardId),
        token = TrimText(transaction.token),
        target = TrimText(transaction.targetKey),
        phase = "start_queue",
      })
      return false, {
        target = resolvedTargetKey,
        token = transaction.token,
        boardId = transaction.boardId,
        reason = "board_sync_start_failed",
      }
    end
    local droppedRows, rowTruncation = boardSyncTransactions.SendRows(transaction)
    local endOk, endTruncated = SendBoardSyncEndMessage(
      transaction.targetKey,
      transaction.sessionId,
      transaction.profileName,
      transaction.boardId,
      transaction.selectedItemKey,
      transaction.token
    )
    if not endOk then
      boardSyncTransactions.outgoing[transaction.key] = nil
      transaction.state = "failed"
      transaction.failureReason = "board_sync_end_failed"
      RecordRaidTraceEvent("BSYNC_TRANSACTION_FAILED", transaction.failureReason, {
        boardId = TrimText(transaction.boardId),
        token = TrimText(transaction.token),
        target = TrimText(transaction.targetKey),
        phase = "end_queue",
      })
      return false, {
        target = resolvedTargetKey,
        token = transaction.token,
        boardId = transaction.boardId,
        reason = "board_sync_end_failed",
      }
    end
    transaction.state = "end_queued"
    RecordRaidTraceEvent("BSYNC_TRANSACTION_QUEUED", "Full board rows and end marker queued.", {
      boardId = TrimText(transaction.boardId),
      token = TrimText(transaction.token),
      target = TrimText(transaction.targetKey),
      droppedRows = math.max(0, tonumber(droppedRows) or 0),
      truncated = startTruncated or rowTruncation or endTruncated,
    })
    return true, {
      hadTruncation = startTruncated or rowTruncation or endTruncated,
      droppedRows = droppedRows,
      receiptPending = true,
      target = transaction.targetKey,
      token = transaction.token,
      boardId = transaction.boardId,
      itemCount = transaction.itemCount,
      selectionCount = transaction.selectionCount,
      voteCount = transaction.voteCount,
      recipientScoped = transaction.recipientScoped == true,
    }
  end

  function boardSyncTransactions.GetStagedDispatchKey(sessionId, profileName, boardId, updatedAt)
    return table.concat({
      string.lower(TrimText(sessionId)),
      string.lower(TrimText(profileName)),
      string.lower(TrimText(boardId)),
      tostring(math.max(0, tonumber(updatedAt) or 0)),
    }, "|")
  end

  function boardSyncTransactions.UpdateStagedDispatchRuntime(dispatch)
    if type(dispatch) ~= "table" then
      return
    end
    runtime.lastBoardSyncStagedDispatch = {
      key = TrimText(dispatch.key),
      sessionId = TrimText(dispatch.sessionId),
      profileName = TrimText(dispatch.profileName),
      boardId = TrimText(dispatch.boardId),
      state = TrimText(dispatch.state),
      targetCount = #(dispatch.targetKeys or {}),
      activeTargetLimit = math.max(0, tonumber(dispatch.activeTargetLimit) or 0),
      activeTargetCount = math.max(0, tonumber(dispatch.activeTargetCount) or 0),
      dispatchedCount = math.max(0, tonumber(dispatch.dispatchedCount) or 0),
      acknowledgedCount = math.max(0, tonumber(dispatch.acknowledgedCount) or 0),
      failedCount = math.max(0, tonumber(dispatch.failedCount) or 0),
      pendingLatestCount = type(dispatch.pendingLatest) == "table" and 1 or 0,
      coalescedRequestCount = math.max(0, tonumber(dispatch.coalescedRequestCount) or 0),
      totalRequestCount = math.max(0, tonumber(boardSyncTransactions.stagedDispatchRequests) or 0),
      totalCoalescedCount = math.max(0, tonumber(boardSyncTransactions.stagedDispatchCoalesced) or 0),
      totalReleasedCount = math.max(0, tonumber(boardSyncTransactions.stagedDispatchReleased) or 0),
      stagedCount = math.max(0,
        #(dispatch.targetKeys or {})
          - math.max(0, tonumber(dispatch.dispatchedCount) or 0)
          - math.max(0, tonumber(dispatch.failedBeforeDispatchCount) or 0)),
      nextTargetIndex = math.max(0, tonumber(dispatch.nextTargetIndex) or 0),
      lastCapacityReason = TrimText(dispatch.lastCapacityReason),
      updatedAt = GetCurrentTimestamp(),
    }
  end

  function boardSyncTransactions.UpdateStagedReportTarget(dispatch, targetState)
    local report = type(runtime.lastRealSimulationRun) == "table" and runtime.lastRealSimulationRun or nil
    if type(report) ~= "table"
      or TrimText(report.sessionId) ~= TrimText(type(dispatch) == "table" and dispatch.sessionId or "")
      or TrimText(report.boardId) ~= TrimText(type(dispatch) == "table" and dispatch.boardId or "")
    then
      return false
    end
    local targetKey = string.lower(NormalizeCharacterKey(type(targetState) == "table" and targetState.target or ""))
    local reportTarget = type(report.dispatchTargets) == "table" and report.dispatchTargets[targetKey] or nil
    if type(reportTarget) ~= "table" then
      return false
    end
    reportTarget.token = TrimText(targetState.token) ~= "" and TrimText(targetState.token) or TrimText(reportTarget.token)
    reportTarget.state = TrimText(targetState.state)
    reportTarget.reason = TrimText(targetState.reason)
    reportTarget.updatedAt = GetCurrentTimestamp()
    local summary = boardSyncTransactions.BuildRealSimulationDispatchSummary(report)
    report.acknowledgedCount = summary.acknowledgedCount
    report.pendingReceiptCount = summary.pendingReceiptCount
    report.failedTargetCount = summary.failedTargetCount
    report.dispatchState = summary.dispatchState
    report.statusText = summary.statusText
    report.message = summary.statusText
    report.updatedAt = reportTarget.updatedAt
    return true
  end

  function boardSyncTransactions.FindActiveStagedDispatch(sessionId, profileName)
    for _, existing in pairs(boardSyncTransactions.stagedDispatches) do
      if type(existing) == "table"
        and TrimText(existing.sessionId) == TrimText(sessionId)
        and TrimText(existing.profileName) == TrimText(profileName)
        and existing.state ~= "complete"
        and existing.state ~= "complete_with_failures"
        and existing.state ~= "cancelled"
      then
        return existing
      end
    end
    return nil
  end

  function boardSyncTransactions.ActivateStagedDispatch(dispatch)
    if type(dispatch) ~= "table" or TrimText(dispatch.key) == "" then
      return false
    end
    dispatch.state = "staged"
    dispatch.activatedAt = GetCurrentTimestamp()
    boardSyncTransactions.stagedDispatches[dispatch.key] = dispatch
    boardSyncTransactions.UpdateStagedDispatchRuntime(dispatch)
    RecordRaidTraceEvent("BSYNC_DISPATCH_ACTIVATED", "Full board transaction admitted.", {
      boardId = TrimText(dispatch.boardId),
      session = TrimText(dispatch.sessionId),
      targets = #(dispatch.targetKeys or {}),
      coalesced = math.max(0, tonumber(dispatch.coalescedRequestCount) or 0),
    })
    boardSyncTransactions.PumpStagedDispatch(dispatch)
    return true
  end

  function boardSyncTransactions.FinalizeStagedDispatch(dispatch)
    if type(dispatch) ~= "table" then
      return
    end
    dispatch.state = (tonumber(dispatch.failedCount) or 0) > 0 and "complete_with_failures" or "complete"
    dispatch.completedAt = GetCurrentTimestamp()
    local pendingLatest = type(dispatch.pendingLatest) == "table" and dispatch.pendingLatest or nil
    dispatch.pendingLatest = nil
    boardSyncTransactions.UpdateStagedDispatchRuntime(dispatch)
    if boardSyncTransactions.stagedDispatches[dispatch.key] == dispatch then
      boardSyncTransactions.stagedDispatches[dispatch.key] = nil
    end
    RecordRaidTraceEvent("BSYNC_DISPATCH_TERMINAL", TrimText(dispatch.state), {
      boardId = TrimText(dispatch.boardId),
      session = TrimText(dispatch.sessionId),
      acknowledged = math.max(0, tonumber(dispatch.acknowledgedCount) or 0),
      failed = math.max(0, tonumber(dispatch.failedCount) or 0),
      pendingLatest = pendingLatest ~= nil,
    })
    if pendingLatest then
      boardSyncTransactions.stagedDispatchReleased =
        math.max(0, tonumber(boardSyncTransactions.stagedDispatchReleased) or 0) + 1
      pendingLatest.releasedAfterBoardId = TrimText(dispatch.boardId)
      RecordRaidTraceEvent("BSYNC_LATEST_RELEASED", "Newest retained board transaction released.", {
        boardId = TrimText(pendingLatest.boardId),
        previousBoardId = TrimText(dispatch.boardId),
        session = TrimText(pendingLatest.sessionId),
        targets = #(pendingLatest.targetKeys or {}),
      })
      boardSyncTransactions.ActivateStagedDispatch(pendingLatest)
    end
  end

  function boardSyncTransactions.ScheduleStagedDispatchPump(dispatch, delaySeconds)
    if type(dispatch) ~= "table" or boardSyncTransactions.stagedDispatches[dispatch.key] ~= dispatch then
      return false
    end
    if type(C_Timer) ~= "table" or type(C_Timer.After) ~= "function" then
      return false
    end
    dispatch.pumpWatch = math.max(0, tonumber(dispatch.pumpWatch) or 0) + 1
    local watch = dispatch.pumpWatch
    C_Timer.After(math.max(0.1, tonumber(delaySeconds) or 0.5), function()
      if boardSyncTransactions.stagedDispatches[dispatch.key] == dispatch
        and dispatch.pumpWatch == watch
      then
        boardSyncTransactions.PumpStagedDispatch(dispatch)
      end
    end)
    return true
  end

  function boardSyncTransactions.PumpStagedDispatch(dispatch)
    if type(dispatch) ~= "table"
      or boardSyncTransactions.stagedDispatches[dispatch.key] ~= dispatch
      or dispatch.pumping == true
    then
      return false
    end
    local activeSession, activeProfileName = GetActiveLootSession()
    if not DoesRuntimeSessionMatch(activeSession, activeProfileName, dispatch.sessionId, dispatch.profileName)
      or not IsLiveSession(activeSession)
      or not IsSelfHost(activeSession)
    then
      dispatch.state = "cancelled"
      dispatch.lastCapacityReason = "session_no_longer_active"
      boardSyncTransactions.UpdateStagedDispatchRuntime(dispatch)
      boardSyncTransactions.stagedDispatches[dispatch.key] = nil
      return false
    end

    dispatch.pumping = true
    dispatch.state = "dispatching"
    while (tonumber(dispatch.activeTargetCount) or 0) < (tonumber(dispatch.activeTargetLimit) or 1)
      and (tonumber(dispatch.nextTargetIndex) or 1) <= #(dispatch.targetKeys or {})
    do
      local queueStatus = boardSyncTransactions.GetQueueStatusForAdmission()
      local targetAdmission = boardSyncTransactions.BuildStagedTargetAdmissionPlan(dispatch, queueStatus)
      dispatch.lastTargetAdmission = targetAdmission
      if targetAdmission.admitted ~= true then
        dispatch.state = "waiting_capacity"
        dispatch.lastCapacityReason = TrimText(targetAdmission.reason)
        boardSyncTransactions.ScheduleStagedDispatchPump(dispatch, 0.5)
        break
      end

      local targetIndex = math.max(1, tonumber(dispatch.nextTargetIndex) or 1)
      local targetKey = dispatch.targetKeys[targetIndex]
      dispatch.nextTargetIndex = targetIndex + 1
      local targetState = dispatch.targetStates[string.lower(NormalizeCharacterKey(targetKey))]
      if type(targetState) ~= "table" then
        targetState = { target = NormalizeCharacterKey(targetKey), state = "staged" }
        dispatch.targetStates[string.lower(NormalizeCharacterKey(targetKey))] = targetState
        dispatch.targetResults[#dispatch.targetResults + 1] = targetState
      end
      targetState.state = "dispatching"
      targetState.updatedAt = GetCurrentTimestamp()
      local sentOk, syncMeta = SendBoardSyncSnapshotToTarget(
        activeSession,
        dispatch.profileName,
        dispatch.snapshot,
        targetKey
      )
      syncMeta = type(syncMeta) == "table" and syncMeta or {}
      targetState.token = TrimText(syncMeta.token)
      targetState.boardId = TrimText(syncMeta.boardId) ~= "" and TrimText(syncMeta.boardId) or dispatch.boardId
      targetState.hadTruncation = syncMeta.hadTruncation == true
      targetState.droppedRows = math.max(0, tonumber(syncMeta.droppedRows) or 0)
      targetState.recipientScoped = syncMeta.recipientScoped == true
      dispatch.hadTruncation = dispatch.hadTruncation == true or targetState.hadTruncation
      dispatch.droppedRows = math.max(0, tonumber(dispatch.droppedRows) or 0) + targetState.droppedRows
      if sentOk then
        targetState.state = "queued"
        targetState.reason = ""
        dispatch.activeTargetCount = math.max(0, tonumber(dispatch.activeTargetCount) or 0) + 1
        dispatch.dispatchedCount = math.max(0, tonumber(dispatch.dispatchedCount) or 0) + 1
        dispatch.activeTargets[string.lower(NormalizeCharacterKey(targetKey))] = true
        local transaction = boardSyncTransactions.outgoing[
          boardSyncTransactions.GetOutgoingKey(
            dispatch.sessionId,
            dispatch.profileName,
            targetKey,
            targetState.token
          )
        ]
        if type(transaction) == "table" then
          transaction.stagedDispatchKey = dispatch.key
        end
      else
        targetState.state = "dispatch_failed"
        targetState.reason = TrimText(syncMeta.reason)
        dispatch.failedCount = math.max(0, tonumber(dispatch.failedCount) or 0) + 1
        dispatch.failedBeforeDispatchCount = math.max(0,
          tonumber(dispatch.failedBeforeDispatchCount) or 0) + 1
      end
      targetState.updatedAt = GetCurrentTimestamp()
      boardSyncTransactions.UpdateStagedReportTarget(dispatch, targetState)
    end
    dispatch.pumping = false
    boardSyncTransactions.UpdateStagedDispatchRuntime(dispatch)
    if (tonumber(dispatch.activeTargetCount) or 0) <= 0
      and (tonumber(dispatch.nextTargetIndex) or 1) > #(dispatch.targetKeys or {})
    then
      boardSyncTransactions.FinalizeStagedDispatch(dispatch)
    end
    return true
  end

  function boardSyncTransactions.OnStagedTransactionTerminal(transaction, terminalState, reason)
    if type(transaction) ~= "table" or transaction.stagedTerminalNotified == true then
      return false
    end
    transaction.stagedTerminalNotified = true
    local dispatch = boardSyncTransactions.stagedDispatches[TrimText(transaction.stagedDispatchKey)]
    if type(dispatch) ~= "table" then
      return false
    end
    local targetKey = string.lower(NormalizeCharacterKey(transaction.targetKey))
    if dispatch.activeTargets[targetKey] then
      dispatch.activeTargets[targetKey] = nil
      dispatch.activeTargetCount = math.max(0, (tonumber(dispatch.activeTargetCount) or 0) - 1)
    end
    local targetState = dispatch.targetStates[targetKey]
    if type(targetState) == "table" then
      targetState.state = TrimText(terminalState)
      targetState.reason = TrimText(reason)
      targetState.updatedAt = GetCurrentTimestamp()
    end
    if TrimText(terminalState) == "acknowledged" then
      dispatch.acknowledgedCount = math.max(0, tonumber(dispatch.acknowledgedCount) or 0) + 1
    else
      dispatch.failedCount = math.max(0, tonumber(dispatch.failedCount) or 0) + 1
    end
    boardSyncTransactions.UpdateStagedDispatchRuntime(dispatch)
    if (tonumber(dispatch.activeTargetCount) or 0) <= 0
      and (tonumber(dispatch.nextTargetIndex) or 1) > #(dispatch.targetKeys or {})
    then
      boardSyncTransactions.FinalizeStagedDispatch(dispatch)
    else
      boardSyncTransactions.PumpStagedDispatch(dispatch)
    end
    return true
  end

  function boardSyncTransactions.StartStagedDispatch(activeSession, profileName, snapshot, targetKeys, admissionPlan, performancePrefix)
    performancePrefix = TrimText(performancePrefix)
    local beginPerformance = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl
    local recordPerformance = INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl
    local targetPlanStartedAt = performancePrefix ~= "" and type(beginPerformance) == "function"
      and beginPerformance(performancePrefix .. "_target_plan", 1)
      or nil
    local key = boardSyncTransactions.GetStagedDispatchKey(
      type(activeSession) == "table" and activeSession.id or "",
      profileName,
      type(snapshot) == "table" and snapshot.boardId or "",
      type(snapshot) == "table" and snapshot.updatedAt or 0
    )
    boardSyncTransactions.stagedDispatchRequests =
      math.max(0, tonumber(boardSyncTransactions.stagedDispatchRequests) or 0) + 1
    local dispatch = {
      key = key,
      sessionId = TrimText(type(activeSession) == "table" and activeSession.id or ""),
      profileName = TrimText(profileName),
      boardId = TrimText(type(snapshot) == "table" and snapshot.boardId or ""),
      snapshot = snapshot,
      admissionPlan = admissionPlan,
      targetKeys = targetKeys,
      targetStates = {},
      targetResults = {},
      activeTargets = {},
      activeTargetLimit = math.max(1, math.min(
        math.max(1, tonumber(boardSyncTransactions.maxActiveTargets) or 2),
        math.max(1, tonumber(type(admissionPlan) == "table" and admissionPlan.activeTargetLimit or 1) or 1)
      )),
      nextTargetIndex = 1,
      activeTargetCount = 0,
      dispatchedCount = 0,
      acknowledgedCount = 0,
      failedCount = 0,
      failedBeforeDispatchCount = 0,
      droppedRows = 0,
      state = "staged",
      createdAt = GetCurrentTimestamp(),
    }
    for index, targetKey in ipairs(targetKeys or {}) do
      local targetState = {
        target = NormalizeCharacterKey(targetKey),
        boardId = dispatch.boardId,
        state = "staged",
        reason = "",
        stagedIndex = index,
        updatedAt = dispatch.createdAt,
      }
      dispatch.targetStates[string.lower(targetState.target)] = targetState
      dispatch.targetResults[#dispatch.targetResults + 1] = targetState
    end
    if performancePrefix ~= "" and type(recordPerformance) == "function" then
      recordPerformance(performancePrefix .. "_target_plan", targetPlanStartedAt, {
        context = "staged_target_plan",
        chunkCount = #(targetKeys or {}),
      })
    end

    local receiptStartedAt = performancePrefix ~= "" and type(beginPerformance) == "function"
      and beginPerformance(performancePrefix .. "_receipts", 1)
      or nil
    local existing = boardSyncTransactions.FindActiveStagedDispatch(dispatch.sessionId, dispatch.profileName)
    if type(existing) == "table" then
      if type(existing.pendingLatest) == "table" then
        existing.pendingLatest.state = "superseded_before_dispatch"
        RecordRaidTraceEvent("BSYNC_PENDING_SUPERSEDED", "An older retained board snapshot was replaced.", {
          boardId = TrimText(existing.pendingLatest.boardId),
          replacementBoardId = TrimText(dispatch.boardId),
          session = TrimText(dispatch.sessionId),
        })
      end
      dispatch.state = "coalesced_latest"
      for _, targetState in ipairs(dispatch.targetResults or {}) do
        targetState.state = "coalesced_latest"
      end
      existing.pendingLatest = dispatch
      existing.coalescedRequestCount = math.max(0, tonumber(existing.coalescedRequestCount) or 0) + 1
      boardSyncTransactions.stagedDispatchCoalesced =
        math.max(0, tonumber(boardSyncTransactions.stagedDispatchCoalesced) or 0) + 1
      boardSyncTransactions.UpdateStagedDispatchRuntime(existing)
      RecordRaidTraceEvent("BSYNC_REQUEST_COALESCED", "Newest board snapshot retained behind the active transaction.", {
        activeBoardId = TrimText(existing.boardId),
        boardId = TrimText(dispatch.boardId),
        session = TrimText(dispatch.sessionId),
        targets = #(dispatch.targetKeys or {}),
        coalesced = math.max(0, tonumber(existing.coalescedRequestCount) or 0),
      })
    else
      boardSyncTransactions.ActivateStagedDispatch(dispatch)
    end
    if performancePrefix ~= "" and type(recordPerformance) == "function" then
      recordPerformance(performancePrefix .. "_receipts", receiptStartedAt, {
        context = existing and "coalesced_latest" or "staged_receipt_state",
        chunkCount = #(targetKeys or {}),
      })
    end

    local enqueueStartedAt = performancePrefix ~= "" and type(beginPerformance) == "function"
      and beginPerformance(performancePrefix .. "_enqueue", 1)
      or nil
    if performancePrefix ~= "" and type(recordPerformance) == "function" then
      recordPerformance(performancePrefix .. "_enqueue", enqueueStartedAt, {
        context = existing and "retained_latest" or "initial_queue_enqueue",
        chunkCount = math.max(0, tonumber(dispatch.dispatchedCount) or 0),
      })
    end
    return dispatch
  end

  function boardSyncTransactions.AppendStagedDispatchCoalescingValidationChecks(addCheck)
    if type(addCheck) ~= "function" then
      return
    end
    local savedDispatches = boardSyncTransactions.stagedDispatches
    local savedRequests = boardSyncTransactions.stagedDispatchRequests
    local savedCoalesced = boardSyncTransactions.stagedDispatchCoalesced
    local savedReleased = boardSyncTransactions.stagedDispatchReleased
    local savedPump = boardSyncTransactions.PumpStagedDispatch
    local savedTelemetry = runtime.lastBoardSyncStagedDispatch
    local savedTraceRecorder = INTERNAL_API.LIDCOUNCIL_RecordRaidTestTraceEvent_Impl
    local results = {}
    local succeeded, failure = pcall(function()
      INTERNAL_API.LIDCOUNCIL_RecordRaidTestTraceEvent_Impl = nil
      boardSyncTransactions.stagedDispatches = {}
      boardSyncTransactions.stagedDispatchRequests = 0
      boardSyncTransactions.stagedDispatchCoalesced = 0
      boardSyncTransactions.stagedDispatchReleased = 0
      local active = {
        key = "VALIDATION-STAGED-ACTIVE",
        sessionId = "VALIDATION-STAGED-SESSION",
        profileName = "Validation Profile",
        boardId = "VALIDATION-BOARD-A",
        state = "waiting_receipt",
        targetKeys = { "Alpha-Realm" },
        targetStates = {},
        targetResults = {},
        activeTargets = { ["alpha-realm"] = true },
        activeTargetLimit = 1,
        activeTargetCount = 1,
        dispatchedCount = 1,
        acknowledgedCount = 0,
        failedCount = 0,
        failedBeforeDispatchCount = 0,
        nextTargetIndex = 2,
      }
      boardSyncTransactions.stagedDispatches[active.key] = active
      local sessionFixture = { id = active.sessionId }
      local admissionFixture = { activeTargetLimit = 1 }
      local firstRetained = boardSyncTransactions.StartStagedDispatch(
        sessionFixture,
        active.profileName,
        { boardId = "VALIDATION-BOARD-B", updatedAt = 2 },
        { "Alpha-Realm" },
        admissionFixture,
        ""
      )
      local newestRetained = boardSyncTransactions.StartStagedDispatch(
        sessionFixture,
        active.profileName,
        { boardId = "VALIDATION-BOARD-C", updatedAt = 3 },
        { "Alpha-Realm" },
        admissionFixture,
        ""
      )
      local stagedCount = 0
      for _ in pairs(boardSyncTransactions.stagedDispatches) do
        stagedCount = stagedCount + 1
      end
      results.activeState = active.state
      results.retainedState = type(firstRetained) == "table" and firstRetained.state or "missing"
      results.latestState = type(newestRetained) == "table" and newestRetained.state or "missing"
      results.latestBoard = type(active.pendingLatest) == "table" and active.pendingLatest.boardId or "missing"
      results.stagedCount = stagedCount
      results.counts = tostring(boardSyncTransactions.stagedDispatchRequests)
        .. "/" .. tostring(boardSyncTransactions.stagedDispatchCoalesced)

      boardSyncTransactions.PumpStagedDispatch = function(dispatch)
        dispatch.__validationPumped = true
        return true
      end
      active.activeTargetCount = 0
      boardSyncTransactions.FinalizeStagedDispatch(active)
      local released = boardSyncTransactions.stagedDispatches[newestRetained.key]
      results.released = type(released) == "table"
        and released == newestRetained
        and released.state == "staged"
        and released.__validationPumped == true
      results.releaseCount = boardSyncTransactions.stagedDispatchReleased
    end)
    boardSyncTransactions.stagedDispatches = savedDispatches
    boardSyncTransactions.stagedDispatchRequests = savedRequests
    boardSyncTransactions.stagedDispatchCoalesced = savedCoalesced
    boardSyncTransactions.stagedDispatchReleased = savedReleased
    boardSyncTransactions.PumpStagedDispatch = savedPump
    runtime.lastBoardSyncStagedDispatch = savedTelemetry
    INTERNAL_API.LIDCOUNCIL_RecordRaidTestTraceEvent_Impl = savedTraceRecorder

    addCheck("staged board coalescing validation executes safely", true, succeeded)
    if not succeeded then
      addCheck("staged board coalescing validation failure", "none", TrimText(failure))
      return
    end
    addCheck("active board transaction is never superseded", "waiting_receipt/1",
      tostring(results.activeState) .. "/" .. tostring(results.stagedCount))
    addCheck("only the newest waiting board snapshot is retained", "superseded_before_dispatch/coalesced_latest/VALIDATION-BOARD-C",
      tostring(results.retainedState) .. "/" .. tostring(results.latestState) .. "/" .. tostring(results.latestBoard))
    addCheck("repeated board snapshots increment bounded coalescing telemetry", "2/2", results.counts)
    addCheck("newest waiting board releases after active transaction", true, results.released == true)
    addCheck("released board telemetry increments once", 1, results.releaseCount)
  end

  local function SendActiveLiveBoardSyncFlow(options)
    options = type(options) == "table" and options or {}
    local performancePrefix = TrimText(options.performancePrefix)
    local beginPerformance = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl
    local recordPerformance = INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or TrimText(profileName) == "" then
      if type(Print) == "function" then
        Print("No active loot session.")
      end
      return false, "No active session."
    end
    if not IsLiveSession(activeSession) then
      if type(Print) == "function" then
        Print("Start the prepared session before sending a Live Board sync.")
      end
      return false, "Session is not active."
    end

    local selfKey = GetSelfKey()
    if not IsSessionHostKey(activeSession, selfKey) then
      if type(Print) == "function" then
        Print("Only the loot session host can send a Live Board sync.")
      end
      return false, "Only the host can send a Live Board sync."
    end

    if type(InCombatLockdown) == "function" and InCombatLockdown() then
      if type(Print) == "function" then
        Print("Send Board Sync is unavailable during combat.")
      end
      return false, "Send Board Sync is unavailable during combat."
    end

    local serializationStartedAt = performancePrefix ~= "" and type(beginPerformance) == "function"
      and beginPerformance(performancePrefix .. "_serialization", 1)
      or nil
    local snapshot = BuildBestRuntimeBoardSyncSnapshot(activeSession, profileName)
    if performancePrefix ~= "" and type(recordPerformance) == "function" then
      recordPerformance(performancePrefix .. "_serialization", serializationStartedAt, {
        context = "board_snapshot",
        chunkCount = type(snapshot) == "table" and #(snapshot.itemOrder or {}) or 0,
      })
    end
    if type(snapshot) ~= "table" or type(snapshot.itemOrder) ~= "table" or #snapshot.itemOrder == 0 then
      if type(Print) == "function" then
        Print("No Live Board state is available to sync.")
      end
      return false, "No Live Board state is available."
    end

    local recipientsStartedAt = performancePrefix ~= "" and type(beginPerformance) == "function"
      and beginPerformance(performancePrefix .. "_recipients", 1)
      or nil
    local targetKeys = {}
    for memberKey, member in pairs(activeSession.members or {}) do
      if not AreCharacterKeysSame(memberKey, selfKey)
        and string.upper(TrimText(type(member) == "table" and member.status or "JOINED")) == "JOINED"
      then
        targetKeys[#targetKeys + 1] = NormalizeCharacterKey(memberKey)
      end
    end
    table.sort(targetKeys, function(left, right)
      return string.lower(tostring(left or "")) < string.lower(tostring(right or ""))
    end)
    if #targetKeys == 0 then
      if performancePrefix ~= "" and type(recordPerformance) == "function" then
        recordPerformance(performancePrefix .. "_recipients", recipientsStartedAt, {
          context = "recipient_selection",
          chunkCount = 0,
        })
      end
      if type(Print) == "function" then
        Print("No joined session members were available for a Live Board sync.")
      end
      return false, 0, {
        attemptedCount = 0,
        sentCount = 0,
        failedCount = 0,
        receiptPendingCount = 0,
        reason = "no_targets",
        targets = {},
      }
    end

    local recipientScopeByTarget = {}
    for _, targetKey in ipairs(targetKeys) do
      recipientScopeByTarget[string.lower(NormalizeCharacterKey(targetKey))] =
        not CanSessionCharacterVote(activeSession, profileName, targetKey)
    end
    if performancePrefix ~= "" and type(recordPerformance) == "function" then
      recordPerformance(performancePrefix .. "_recipients", recipientsStartedAt, {
        context = "recipient_selection",
        chunkCount = #targetKeys,
      })
    end

    local admissionStartedAt = performancePrefix ~= "" and type(beginPerformance) == "function"
      and beginPerformance(performancePrefix .. "_admission", 1)
      or nil
    local queueStatus = boardSyncTransactions.GetQueueStatusForAdmission()
    local admissionPlan = boardSyncTransactions.BuildSnapshotAdmissionPlan(
      snapshot,
      targetKeys,
      queueStatus,
      true,
      recipientScopeByTarget
    )
    admissionPlan.sessionId = TrimText(activeSession.id)
    admissionPlan.profileName = TrimText(profileName)
    admissionPlan.boardId = TrimText(snapshot.boardId)
    admissionPlan.updatedAt = GetCurrentTimestamp()
    runtime.lastBoardSyncAdmissionPlan = admissionPlan
    if performancePrefix ~= "" and type(recordPerformance) == "function" then
      recordPerformance(performancePrefix .. "_admission", admissionStartedAt, {
        context = TrimText(admissionPlan.reason),
        chunkCount = math.max(0, tonumber(admissionPlan.projectedMessages) or 0),
      })
    end
    if admissionPlan.admitted ~= true then
      runtime.lastBoardSyncAdmissionFailure = admissionPlan
      if type(Print) == "function" then
        Print(string.format(
          "Live Board sync deferred: %d projected messages exceed the %d safe slots available after reserving %d live-traffic slots (%s).",
          math.max(0, tonumber(admissionPlan.projectedMessages) or 0),
          math.max(0, tonumber(admissionPlan.safeMessageCapacity) or 0),
          math.max(0, tonumber(admissionPlan.requiredLiveHeadroom) or 0),
          TrimText(admissionPlan.reason)
        ))
      end
      return false, 0, {
        attemptedCount = #targetKeys,
        sentCount = 0,
        failedCount = 0,
        receiptPendingCount = 0,
        reason = "capacity_deferred",
        admissionPlan = admissionPlan,
        targets = {},
      }
    end
    runtime.lastBoardSyncAdmissionFailure = nil

    local localStateStartedAt = performancePrefix ~= "" and type(beginPerformance) == "function"
      and beginPerformance(performancePrefix .. "_local_state", 1)
      or nil
    local reuseCurrentLocalBoard = options.reuseCurrentLocalBoard == true
      and TrimText(runtime.sessionId) == TrimText(activeSession.id)
      and TrimText(runtime.profileName) == TrimText(profileName)
      and TrimText(runtime.boardId) ~= ""
      and TrimText(runtime.boardId) == TrimText(snapshot.boardId)
      and (tonumber(runtime.boardUpdatedAt) or 0) > 0
      and tonumber(runtime.boardUpdatedAt) == tonumber(snapshot.updatedAt)
      and #(runtime.itemOrder or {}) == #snapshot.itemOrder
    if reuseCurrentLocalBoard then
      for index, itemKey in ipairs(snapshot.itemOrder) do
        if TrimText(runtime.itemOrder[index]) ~= TrimText(itemKey) then
          reuseCurrentLocalBoard = false
          break
        end
      end
    end
    if not reuseCurrentLocalBoard then
      local capturedPopupQueue = CaptureLocalPopupQueue()
      RestoreRuntimeBoardFromSyncSnapshot(activeSession, profileName, snapshot)
      RestoreLocalPopupQueue(activeSession, capturedPopupQueue)
      PersistRuntimeBoardHistory()
      RefreshBoardAndEditor({
        reason = "sync",
        editorRefresh = { refreshPages = { Panels = true, LiveBoard = true, Backgrounds = true } },
      })
    end
    if performancePrefix ~= "" and type(recordPerformance) == "function" then
      recordPerformance(performancePrefix .. "_local_state", localStateStartedAt, {
        context = reuseCurrentLocalBoard and "current_local_board_reused" or "local_board_restore_persist_refresh",
        chunkCount = #snapshot.itemOrder,
      })
    end

    RecordRaidTraceEvent("BSYNC_SNAPSHOT_READY", "Full board snapshot admitted for staged delivery.", {
      boardId = TrimText(snapshot.boardId),
      session = TrimText(activeSession.id),
      targets = #targetKeys,
      projected = math.max(0, tonumber(admissionPlan.projectedMessages) or 0),
      items = #(snapshot.itemOrder or {}),
    })
    local stagedDispatch = boardSyncTransactions.StartStagedDispatch(
      activeSession,
      profileName,
      snapshot,
      targetKeys,
      admissionPlan,
      performancePrefix
    )
    local failedCount = math.max(0,
      tonumber(type(stagedDispatch) == "table" and stagedDispatch.failedBeforeDispatchCount or 0) or 0)
    local acceptedCount = math.max(0, #targetKeys - failedCount)
    local initiallyQueuedCount = math.max(0,
      tonumber(type(stagedDispatch) == "table" and stagedDispatch.dispatchedCount or 0) or 0)
    local stagedCount = math.max(0, acceptedCount - initiallyQueuedCount)
    local coalescedLatest = type(stagedDispatch) == "table"
      and TrimText(stagedDispatch.state) == "coalesced_latest"
    if type(Print) == "function" then
      local summary
      if coalescedLatest then
        summary = string.format(
          "Live Board sync already active; retained the newest board for %d joined member%s.",
          acceptedCount,
          acceptedCount == 1 and "" or "s"
        )
      else
        summary = string.format(
          "Staged Live Board sync for %d joined member%s: %d active now, %d waiting.",
          acceptedCount,
          acceptedCount == 1 and "" or "s",
          initiallyQueuedCount,
          stagedCount
        )
      end
      if type(stagedDispatch) == "table" and stagedDispatch.hadTruncation == true then
        summary = summary .. " Some long fields were compacted for transport."
      end
      if failedCount > 0 then
        summary = summary .. " " .. tostring(failedCount) .. " target" .. (failedCount == 1 and "" or "s") .. " failed before dispatch."
      end
      Print(summary)
    end
    return acceptedCount > 0, acceptedCount, {
      attemptedCount = #targetKeys,
      acceptedCount = acceptedCount,
      sentCount = acceptedCount,
      initiallyQueuedCount = initiallyQueuedCount,
      stagedCount = stagedCount,
      failedCount = failedCount,
      receiptPendingCount = acceptedCount,
      coalescedLatest = coalescedLatest == true,
      hadTruncation = type(stagedDispatch) == "table" and stagedDispatch.hadTruncation == true,
      droppedRows = math.max(0, tonumber(type(stagedDispatch) == "table" and stagedDispatch.droppedRows or 0) or 0),
      boardId = TrimText(snapshot.boardId),
      sessionId = TrimText(activeSession.id),
      profileName = TrimText(profileName),
      admissionPlan = admissionPlan,
      stagedDispatchKey = TrimText(type(stagedDispatch) == "table" and stagedDispatch.key or ""),
      targets = type(stagedDispatch) == "table" and stagedDispatch.targetResults or {},
    }
  end

  local function RequestManualLootLedgerEntryFlow(profileName, memberKey, itemName, points, note)
    local activeSession, activeProfileName = GetActiveLootSession()
    local resolvedProfileName = TrimText(profileName)
    if resolvedProfileName == "" then
      resolvedProfileName = TrimText(activeProfileName)
    end
    if resolvedProfileName == "" then
      return false, "No profile is active."
    end
    local blocked, blockedMessage = RejectCombatLockedLootEdit("Add Manual Points")
    if blocked then
      return false, blockedMessage
    end

    local selfKey = GetSelfKey()
    local access = type(GetLootProfileAccessInfo) == "function" and GetLootProfileAccessInfo(resolvedProfileName, selfKey) or nil
    if not (type(access) == "table" and access.canEditManualPoints) then
      return false, "Your current role cannot add manual points."
    end

    local requestId = BuildManualLedgerRequestId("MLA")
    local liveSession = type(activeSession) == "table"
      and IsLiveSession(activeSession)
      and DoesRuntimeSessionMatch(activeSession, activeProfileName, TrimText(activeSession.id), resolvedProfileName)

    if liveSession then
      if not IsJoinedSessionCharacter(activeSession, selfKey) then
        return false, "You are not joined to the active session."
      end
      if IsSelfHost(activeSession) then
        local ok, entry, ledgerRow = ApplyManualLedgerAdd(resolvedProfileName, memberKey, itemName, points, note, selfKey, requestId, "", GetCurrentTimestamp(), activeSession.id)
        if ok and type(entry) == "table" then
          local broadcastOk, broadcastMode = BroadcastLootChangeWithFallback(
            resolvedProfileName,
            BuildManualLedgerAddDeltaChange(activeSession, memberKey, entry, selfKey),
            BroadcastManualLedgerAdd,
            activeSession,
            resolvedProfileName,
            memberKey,
            entry,
            selfKey
          )
          if broadcastOk and broadcastMode == "legacy" then
            QueueLootLedgerRowCheckpoint(resolvedProfileName, memberKey, "manual_ledger_checkpoint")
          end
          RefreshManualLedgerViews()
        end
        return ok, entry or ledgerRow, "BROADCAST"
      end

      if type(SendSessionComm) ~= "function" then
        return false, "Session comms are unavailable."
      end
      local sent = SendSessionComm(
        "LL_ADD_REQ",
        "WHISPER",
        activeSession.host,
        tostring(activeSession.id or ""),
        GetSessionCommProfileName(activeSession, resolvedProfileName),
        requestId,
        NormalizeCharacterKey(memberKey),
        ClipManualLedgerText(itemName, MAX_MANUAL_LEDGER_NAME_LENGTH),
        tostring(tonumber(points) or 0),
        ClipManualLedgerText(note, MAX_MANUAL_LEDGER_NOTE_LENGTH),
        tostring(GetCurrentTimestamp())
      )
      if sent then
        return true, "Manual point request sent to the session host.", "REQUEST_SENT"
      end
      return false, "Could not send manual point request to the session host."
    end

    local ok, entry = ApplyManualLedgerAdd(resolvedProfileName, memberKey, itemName, points, note, selfKey, requestId, "", GetCurrentTimestamp(), "")
    if ok then
      RefreshManualLedgerViews()
    end
    return ok, entry, "LOCAL"
  end

  local function RequestManualLootLedgerDeleteFlow(profileName, memberKey, entryId)
    local activeSession, activeProfileName = GetActiveLootSession()
    local resolvedProfileName = TrimText(profileName)
    if resolvedProfileName == "" then
      resolvedProfileName = TrimText(activeProfileName)
    end
    if resolvedProfileName == "" then
      return false, "No profile is active."
    end
    local blocked, blockedMessage = RejectCombatLockedLootEdit("Delete Manual Points")
    if blocked then
      return false, blockedMessage
    end

    local selfKey = GetSelfKey()
    local access = type(GetLootProfileAccessInfo) == "function" and GetLootProfileAccessInfo(resolvedProfileName, selfKey) or nil
    if not (type(access) == "table" and access.canEditManualPoints) then
      return false, "Your current role cannot delete manual points."
    end

    local requestId = BuildManualLedgerRequestId("MLD")
    local liveSession = type(activeSession) == "table"
      and IsLiveSession(activeSession)
      and DoesRuntimeSessionMatch(activeSession, activeProfileName, TrimText(activeSession.id), resolvedProfileName)

    if liveSession then
      if not IsJoinedSessionCharacter(activeSession, selfKey) then
        return false, "You are not joined to the active session."
      end
      if IsSelfHost(activeSession) then
        local ok, result = ApplyManualLedgerDelete(resolvedProfileName, memberKey, entryId)
        if ok then
          local broadcastOk, broadcastMode = BroadcastLootChangeWithFallback(
            resolvedProfileName,
            BuildManualLedgerDeleteDeltaChange(memberKey, entryId),
            BroadcastManualLedgerDelete,
            activeSession,
            resolvedProfileName,
            memberKey,
            entryId,
            GetCurrentTimestamp()
          )
          if broadcastOk and broadcastMode == "legacy" then
            QueueLootLedgerRowCheckpoint(resolvedProfileName, memberKey, "manual_ledger_checkpoint")
          end
          RefreshManualLedgerViews()
        end
        return ok, result, "BROADCAST"
      end

      if type(SendSessionComm) ~= "function" then
        return false, "Session comms are unavailable."
      end
      local sent = SendSessionComm(
        "LL_DEL_REQ",
        "WHISPER",
        activeSession.host,
        tostring(activeSession.id or ""),
        GetSessionCommProfileName(activeSession, resolvedProfileName),
        requestId,
        NormalizeCharacterKey(memberKey),
        ClipManualLedgerText(entryId, MAX_MANUAL_LEDGER_ID_LENGTH),
        tostring(GetCurrentTimestamp())
      )
      if sent then
        return true, "Manual point delete request sent to the session host.", "REQUEST_SENT"
      end
      return false, "Could not send manual point delete request to the session host."
    end

    local ok, result = ApplyManualLedgerDelete(resolvedProfileName, memberKey, entryId)
    if ok then
      RefreshManualLedgerViews()
    end
    return ok, result, "LOCAL"
  end

  local function RequestLootLedgerMainAltFlow(profileName, characterKey, role, mainCharacter)
    local activeSession, activeProfileName = GetActiveLootSession()
    local resolvedProfileName = TrimText(profileName)
    if resolvedProfileName == "" then
      resolvedProfileName = TrimText(activeProfileName)
    end
    if resolvedProfileName == "" then
      return false, "No profile is active."
    end
    local blocked, blockedMessage = RejectCombatLockedLootEdit("Change Main / Alt Links")
    if blocked then
      return false, blockedMessage
    end

    local selfKey = GetSelfKey()
    local access = type(GetLootProfileAccessInfo) == "function" and GetLootProfileAccessInfo(resolvedProfileName, selfKey) or nil
    if not (type(access) == "table" and access.canEditMainAlt) then
      return false, "Your current role cannot change Main / Alt links."
    end

    local resolvedRole = ResolveLootLedgerRole(role)
    local requestId = BuildManualLedgerRequestId("MAL")
    local changedAt = GetCurrentTimestamp()
    local openSession = type(activeSession) == "table"
      and DoesRuntimeSessionMatch(activeSession, activeProfileName, TrimText(activeSession.id), resolvedProfileName)

    if openSession then
      if not IsJoinedSessionCharacter(activeSession, selfKey) then
        return false, "You are not joined to the active session."
      end
      if IsSelfHost(activeSession) then
        local ok, result = ApplyLootLedgerMainAlt(resolvedProfileName, characterKey, resolvedRole, mainCharacter)
        if ok then
          local broadcastOk, broadcastMode = BroadcastLootChangeWithFallback(
            resolvedProfileName,
            BuildLootLedgerMainAltDeltaChange(characterKey, resolvedRole, mainCharacter),
            BroadcastLootLedgerMainAlt,
            activeSession,
            resolvedProfileName,
            characterKey,
            resolvedRole,
            mainCharacter,
            changedAt,
            selfKey
          )
          if broadcastOk and broadcastMode == "legacy" then
            QueueLootLedgerMetaCheckpoint(resolvedProfileName, characterKey, "member_meta_checkpoint")
          end
          RefreshManualLedgerViews()
        end
        return ok, result, "BROADCAST"
      end

      if type(SendSessionComm) ~= "function" then
        return false, "Session comms are unavailable."
      end
      local sent = SendSessionComm(
        "LL_MA_REQ",
        "WHISPER",
        activeSession.host,
        tostring(activeSession.id or ""),
        GetSessionCommProfileName(activeSession, resolvedProfileName),
        requestId,
        ClipManualLedgerText(NormalizeCharacterKey(characterKey), MAX_LOOT_LEDGER_CHARACTER_LENGTH),
        resolvedRole,
        ClipManualLedgerText(NormalizeCharacterKey(mainCharacter), MAX_LOOT_LEDGER_CHARACTER_LENGTH),
        tostring(changedAt)
      )
      if sent then
        return true, "Main / Alt update sent to the session host.", "REQUEST_SENT"
      end
      return false, "Could not send Main / Alt update to the session host."
    end

    local ok, result = ApplyLootLedgerMainAlt(resolvedProfileName, characterKey, resolvedRole, mainCharacter)
    if ok then
      RefreshManualLedgerViews()
    end
    return ok, result, "LOCAL"
  end

  local function RequestLootLedgerCharacterNoteFlow(profileName, characterKey, noteText)
    local activeSession, activeProfileName = GetActiveLootSession()
    local resolvedProfileName = TrimText(profileName)
    if resolvedProfileName == "" then
      resolvedProfileName = TrimText(activeProfileName)
    end
    if resolvedProfileName == "" then
      return false, "No profile is active."
    end
    local blocked, blockedMessage = RejectCombatLockedLootEdit("Edit Character Notes")
    if blocked then
      return false, blockedMessage
    end

    local selfKey = GetSelfKey()
    local access = type(GetLootProfileAccessInfo) == "function" and GetLootProfileAccessInfo(resolvedProfileName, selfKey) or nil
    if not (type(access) == "table" and access.canEditNotes) then
      return false, "Your current role cannot edit notes."
    end

    local requestId = BuildManualLedgerRequestId("NT")
    local changedAt = GetCurrentTimestamp()
    local openSession = type(activeSession) == "table"
      and DoesRuntimeSessionMatch(activeSession, activeProfileName, TrimText(activeSession.id), resolvedProfileName)

    if openSession then
      if not IsJoinedSessionCharacter(activeSession, selfKey) then
        return false, "You are not joined to the active session."
      end
      if IsSelfHost(activeSession) then
        local ok, result = ApplyLootLedgerCharacterNote(resolvedProfileName, characterKey, noteText)
        if ok then
          local broadcastOk, broadcastMode = BroadcastLootChangeWithFallback(
            resolvedProfileName,
            BuildLootLedgerCharacterNoteDeltaChange(characterKey, noteText),
            BroadcastLootLedgerCharacterNote,
            activeSession,
            resolvedProfileName,
            characterKey,
            noteText,
            changedAt,
            selfKey
          )
          if broadcastOk and broadcastMode == "legacy" then
            QueueLootLedgerMetaCheckpoint(resolvedProfileName, characterKey, "member_meta_checkpoint")
          end
          RefreshManualLedgerViews()
        end
        return ok, result, "BROADCAST"
      end

      if type(SendSessionComm) ~= "function" then
        return false, "Session comms are unavailable."
      end
      local sent = SendSessionComm(
        "LL_NOTE_REQ",
        "WHISPER",
        activeSession.host,
        tostring(activeSession.id or ""),
        GetSessionCommProfileName(activeSession, resolvedProfileName),
        requestId,
        ClipManualLedgerText(NormalizeCharacterKey(characterKey), MAX_LOOT_LEDGER_CHARACTER_LENGTH),
        ClipManualLedgerText(noteText, MAX_LOOT_LEDGER_NOTE_LENGTH),
        tostring(changedAt)
      )
      if sent then
        return true, "Character note update sent to the session host.", "REQUEST_SENT"
      end
      return false, "Could not send character note update to the session host."
    end

    local ok, result = ApplyLootLedgerCharacterNote(resolvedProfileName, characterKey, noteText)
    if ok then
      RefreshManualLedgerViews()
    end
    return ok, result, "LOCAL"
  end

  local function RequestLootLedgerCharacterDeleteFlow(profileName, characterKey)
    local activeSession, activeProfileName = GetActiveLootSession()
    local resolvedProfileName = TrimText(profileName)
    if resolvedProfileName == "" then
      resolvedProfileName = TrimText(activeProfileName)
    end
    if resolvedProfileName == "" then
      return false, "No profile is active."
    end
    local blocked, blockedMessage = RejectCombatLockedLootEdit("Delete Loot List Characters")
    if blocked then
      return false, blockedMessage
    end

    local selfKey = GetSelfKey()
    local access = type(GetLootProfileAccessInfo) == "function" and GetLootProfileAccessInfo(resolvedProfileName, selfKey) or nil
    if not (type(access) == "table" and access.canDeleteLootListCharacter) then
      return false, "Your current role cannot delete Loot List characters."
    end

    local requestId = BuildManualLedgerRequestId("CD")
    local changedAt = GetCurrentTimestamp()
    local openSession = type(activeSession) == "table"
      and DoesRuntimeSessionMatch(activeSession, activeProfileName, TrimText(activeSession.id), resolvedProfileName)

    if openSession then
      if not IsJoinedSessionCharacter(activeSession, selfKey) then
        return false, "You are not joined to the active session."
      end
      if IsSelfHost(activeSession) then
        local ok, result = ApplyLootLedgerCharacterDelete(resolvedProfileName, characterKey)
        if ok then
          local broadcastOk, broadcastMode = BroadcastLootChangeWithFallback(
            resolvedProfileName,
            BuildLootLedgerCharacterDeleteDeltaChange(characterKey),
            BroadcastLootLedgerCharacterDelete,
            activeSession,
            resolvedProfileName,
            characterKey,
            changedAt,
            selfKey
          )
          if broadcastOk and broadcastMode == "legacy" then
            QueueLootLedgerCharacterCheckpoint(resolvedProfileName, characterKey, "member_delete_checkpoint")
          end
          RefreshManualLedgerViews()
        end
        return ok, result, "BROADCAST"
      end

      if type(SendSessionComm) ~= "function" then
        return false, "Session comms are unavailable."
      end
      local sent = SendSessionComm(
        "LL_CHAR_DEL_REQ",
        "WHISPER",
        activeSession.host,
        tostring(activeSession.id or ""),
        GetSessionCommProfileName(activeSession, resolvedProfileName),
        requestId,
        ClipManualLedgerText(NormalizeCharacterKey(characterKey), MAX_LOOT_LEDGER_CHARACTER_LENGTH),
        tostring(changedAt)
      )
      if sent then
        return true, "Character delete request sent to the session host.", "REQUEST_SENT"
      end
      return false, "Could not send character delete request to the session host."
    end

    local ok, result = ApplyLootLedgerCharacterDelete(resolvedProfileName, characterKey)
    if ok then
      RefreshManualLedgerViews()
    end
    return ok, result, "LOCAL"
  end

  function boardSyncTransactions.HandleManualLedgerAddRequest(fields, sender)
    if not HasExactFieldCount(fields, "LL_ADD_REQ") then
      return
    end
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not IsSelfHost(activeSession) then
      return
    end

    local sessionId = TrimText(fields[2])
    local incomingProfile = TrimText(fields[3])
    local requestId = ClipManualLedgerText(fields[4], MAX_MANUAL_LEDGER_ID_LENGTH)
    local memberKey = NormalizeCharacterKey(fields[5])
    local itemName = ClipManualLedgerText(fields[6], MAX_MANUAL_LEDGER_NAME_LENGTH)
    local points = tonumber(fields[7]) or 0
    local note = ClipManualLedgerText(fields[8], MAX_MANUAL_LEDGER_NOTE_LENGTH)
    local requestedAt = GetIncomingTimestamp(fields[9]) or GetCurrentTimestamp()
    local senderKey = NormalizeSenderKey(sender)

    if requestId == "" or not DoesRuntimeSessionMatch(activeSession, profileName, sessionId, incomingProfile) then
      return
    end
    if not CanSessionCharacterEditManualPoints(activeSession, profileName, senderKey) then
      return
    end
    local ok, entry = ApplyManualLedgerAdd(profileName, memberKey, itemName, points, note, senderKey, requestId, "", requestedAt, sessionId)
    if ok and type(entry) == "table" then
      local broadcastOk, broadcastMode = BroadcastLootChangeWithFallback(
        profileName,
        BuildManualLedgerAddDeltaChange(activeSession, memberKey, entry, senderKey),
        BroadcastManualLedgerAdd,
        activeSession,
        profileName,
        memberKey,
        entry,
        senderKey
      )
      if broadcastOk and broadcastMode == "legacy" then
        QueueLootLedgerRowCheckpoint(profileName, memberKey, "manual_ledger_checkpoint")
      end
      RefreshManualLedgerViews()
    end
  end

  function boardSyncTransactions.HandleManualLedgerAddBroadcast(fields, sender)
    if not HasExactFieldCount(fields, "LL_ADD") then
      return
    end
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or IsSelfHost(activeSession) then
      return
    end

    local sessionId = TrimText(fields[2])
    local incomingProfile = TrimText(fields[3])
    local entryId = ClipManualLedgerText(fields[4], MAX_MANUAL_LEDGER_ID_LENGTH)
    local memberKey = NormalizeCharacterKey(fields[5])
    local itemName = ClipManualLedgerText(fields[6], MAX_MANUAL_LEDGER_NAME_LENGTH)
    local points = tonumber(fields[7]) or 0
    local note = ClipManualLedgerText(fields[8], MAX_MANUAL_LEDGER_NOTE_LENGTH)
    local awardedAt = GetIncomingTimestamp(fields[9]) or GetCurrentTimestamp()
    local grantedBy = NormalizeCharacterKey(fields[10])

    if entryId == "" or not DoesRuntimeSessionMatch(activeSession, profileName, sessionId, incomingProfile) then
      return
    end
    if not IsSessionHostKey(activeSession, sender) then
      return
    end
    local ok = ApplyManualLedgerAdd(profileName, memberKey, itemName, points, note, grantedBy, "", entryId, awardedAt, sessionId)
    if ok then
      RefreshManualLedgerViews()
    end
  end

  function boardSyncTransactions.HandleManualLedgerDeleteRequest(fields, sender)
    if not HasExactFieldCount(fields, "LL_DEL_REQ") then
      return
    end
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not IsSelfHost(activeSession) then
      return
    end

    local sessionId = TrimText(fields[2])
    local incomingProfile = TrimText(fields[3])
    local requestId = ClipManualLedgerText(fields[4], MAX_MANUAL_LEDGER_ID_LENGTH)
    local memberKey = NormalizeCharacterKey(fields[5])
    local entryId = ClipManualLedgerText(fields[6], MAX_MANUAL_LEDGER_ID_LENGTH)
    local senderKey = NormalizeSenderKey(sender)

    if requestId == "" or entryId == "" or not DoesRuntimeSessionMatch(activeSession, profileName, sessionId, incomingProfile) then
      return
    end
    if not CanSessionCharacterEditManualPoints(activeSession, profileName, senderKey) then
      return
    end
    local ok = ApplyManualLedgerDelete(profileName, memberKey, entryId)
    if ok then
      local broadcastOk, broadcastMode = BroadcastLootChangeWithFallback(
        profileName,
        BuildManualLedgerDeleteDeltaChange(memberKey, entryId),
        BroadcastManualLedgerDelete,
        activeSession,
        profileName,
        memberKey,
        entryId,
        GetCurrentTimestamp()
      )
      if broadcastOk and broadcastMode == "legacy" then
        QueueLootLedgerRowCheckpoint(profileName, memberKey, "manual_ledger_checkpoint")
      end
      RefreshManualLedgerViews()
    end
  end

  function boardSyncTransactions.HandleManualLedgerDeleteBroadcast(fields, sender)
    if not HasExactFieldCount(fields, "LL_DEL") then
      return
    end
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or IsSelfHost(activeSession) then
      return
    end

    local sessionId = TrimText(fields[2])
    local incomingProfile = TrimText(fields[3])
    local entryId = ClipManualLedgerText(fields[4], MAX_MANUAL_LEDGER_ID_LENGTH)
    local memberKey = NormalizeCharacterKey(fields[5])
    if entryId == "" or not DoesRuntimeSessionMatch(activeSession, profileName, sessionId, incomingProfile) then
      return
    end
    if not IsSessionHostKey(activeSession, sender) then
      return
    end
    local ok = ApplyManualLedgerDelete(profileName, memberKey, entryId)
    if ok then
      RefreshManualLedgerViews()
    end
  end

  function boardSyncTransactions.HandleLootLedgerMainAltRequest(fields, sender)
    if not HasExactFieldCount(fields, "LL_MA_REQ") then
      return
    end
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not IsSelfHost(activeSession) then
      return
    end

    local sessionId = TrimText(fields[2])
    local incomingProfile = TrimText(fields[3])
    local requestId = ClipManualLedgerText(fields[4], MAX_MANUAL_LEDGER_ID_LENGTH)
    local characterKey = ClipManualLedgerText(NormalizeCharacterKey(fields[5]), MAX_LOOT_LEDGER_CHARACTER_LENGTH)
    local role = ResolveLootLedgerRole(fields[6])
    local mainCharacter = ClipManualLedgerText(NormalizeCharacterKey(fields[7]), MAX_LOOT_LEDGER_CHARACTER_LENGTH)
    local changedAt = GetIncomingTimestamp(fields[8]) or GetCurrentTimestamp()
    local senderKey = NormalizeSenderKey(sender)

    if requestId == "" or characterKey == "" or not DoesRuntimeSessionMatch(activeSession, profileName, sessionId, incomingProfile) then
      return
    end
    if not CanSessionCharacterEditMainAlt(activeSession, profileName, senderKey) then
      return
    end
    local ok = ApplyLootLedgerMainAlt(profileName, characterKey, role, mainCharacter)
    if ok then
      local broadcastOk, broadcastMode = BroadcastLootChangeWithFallback(
        profileName,
        BuildLootLedgerMainAltDeltaChange(characterKey, role, mainCharacter),
        BroadcastLootLedgerMainAlt,
        activeSession,
        profileName,
        characterKey,
        role,
        mainCharacter,
        changedAt,
        senderKey
      )
      if broadcastOk and broadcastMode == "legacy" then
        QueueLootLedgerMetaCheckpoint(profileName, characterKey, "member_meta_checkpoint")
      end
      RefreshManualLedgerViews()
    end
  end

  function boardSyncTransactions.HandleLootLedgerMainAltBroadcast(fields, sender)
    if not HasExactFieldCount(fields, "LL_MA") then
      return
    end
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or IsSelfHost(activeSession) then
      return
    end

    local sessionId = TrimText(fields[2])
    local incomingProfile = TrimText(fields[3])
    local characterKey = ClipManualLedgerText(NormalizeCharacterKey(fields[4]), MAX_LOOT_LEDGER_CHARACTER_LENGTH)
    local role = ResolveLootLedgerRole(fields[5])
    local mainCharacter = ClipManualLedgerText(NormalizeCharacterKey(fields[6]), MAX_LOOT_LEDGER_CHARACTER_LENGTH)
    if characterKey == "" or not DoesRuntimeSessionMatch(activeSession, profileName, sessionId, incomingProfile) then
      return
    end
    if not IsSessionHostKey(activeSession, sender) then
      return
    end
    local ok = ApplyLootLedgerMainAlt(profileName, characterKey, role, mainCharacter)
    if ok then
      RefreshManualLedgerViews()
    end
  end

  function boardSyncTransactions.HandleLootLedgerCharacterNoteRequest(fields, sender)
    if not HasExactFieldCount(fields, "LL_NOTE_REQ") then
      return
    end
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not IsSelfHost(activeSession) then
      return
    end

    local sessionId = TrimText(fields[2])
    local incomingProfile = TrimText(fields[3])
    local requestId = ClipManualLedgerText(fields[4], MAX_MANUAL_LEDGER_ID_LENGTH)
    local characterKey = ClipManualLedgerText(NormalizeCharacterKey(fields[5]), MAX_LOOT_LEDGER_CHARACTER_LENGTH)
    local noteText = ClipManualLedgerText(fields[6], MAX_LOOT_LEDGER_NOTE_LENGTH)
    local changedAt = GetIncomingTimestamp(fields[7]) or GetCurrentTimestamp()
    local senderKey = NormalizeSenderKey(sender)

    if requestId == "" or characterKey == "" or not DoesRuntimeSessionMatch(activeSession, profileName, sessionId, incomingProfile) then
      return
    end
    if not CanSessionCharacterEditNotes(activeSession, profileName, senderKey) then
      return
    end
    local ok = ApplyLootLedgerCharacterNote(profileName, characterKey, noteText)
    if ok then
      local broadcastOk, broadcastMode = BroadcastLootChangeWithFallback(
        profileName,
        BuildLootLedgerCharacterNoteDeltaChange(characterKey, noteText),
        BroadcastLootLedgerCharacterNote,
        activeSession,
        profileName,
        characterKey,
        noteText,
        changedAt,
        senderKey
      )
      if broadcastOk and broadcastMode == "legacy" then
        QueueLootLedgerMetaCheckpoint(profileName, characterKey, "member_meta_checkpoint")
      end
      RefreshManualLedgerViews()
    end
  end

  function boardSyncTransactions.HandleLootLedgerCharacterNoteBroadcast(fields, sender)
    if not HasExactFieldCount(fields, "LL_NOTE") then
      return
    end
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or IsSelfHost(activeSession) then
      return
    end

    local sessionId = TrimText(fields[2])
    local incomingProfile = TrimText(fields[3])
    local characterKey = ClipManualLedgerText(NormalizeCharacterKey(fields[4]), MAX_LOOT_LEDGER_CHARACTER_LENGTH)
    local noteText = ClipManualLedgerText(fields[5], MAX_LOOT_LEDGER_NOTE_LENGTH)
    if characterKey == "" or not DoesRuntimeSessionMatch(activeSession, profileName, sessionId, incomingProfile) then
      return
    end
    if not IsSessionHostKey(activeSession, sender) then
      return
    end
    local ok = ApplyLootLedgerCharacterNote(profileName, characterKey, noteText)
    if ok then
      RefreshManualLedgerViews()
    end
  end

  function boardSyncTransactions.HandleLootLedgerCharacterDeleteRequest(fields, sender)
    if not HasExactFieldCount(fields, "LL_CHAR_DEL_REQ") then
      return
    end
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not IsSelfHost(activeSession) then
      return
    end

    local sessionId = TrimText(fields[2])
    local incomingProfile = TrimText(fields[3])
    local requestId = ClipManualLedgerText(fields[4], MAX_MANUAL_LEDGER_ID_LENGTH)
    local characterKey = ClipManualLedgerText(NormalizeCharacterKey(fields[5]), MAX_LOOT_LEDGER_CHARACTER_LENGTH)
    local changedAt = GetIncomingTimestamp(fields[6]) or GetCurrentTimestamp()
    local senderKey = NormalizeSenderKey(sender)

    if requestId == "" or characterKey == "" or not DoesRuntimeSessionMatch(activeSession, profileName, sessionId, incomingProfile) then
      return
    end
    if not CanSessionCharacterDeleteLootListCharacter(activeSession, profileName, senderKey) then
      return
    end
    local ok = ApplyLootLedgerCharacterDelete(profileName, characterKey)
    if ok then
      local broadcastOk, broadcastMode = BroadcastLootChangeWithFallback(
        profileName,
        BuildLootLedgerCharacterDeleteDeltaChange(characterKey),
        BroadcastLootLedgerCharacterDelete,
        activeSession,
        profileName,
        characterKey,
        changedAt,
        senderKey
      )
      if broadcastOk and broadcastMode == "legacy" then
        QueueLootLedgerCharacterCheckpoint(profileName, characterKey, "member_delete_checkpoint")
      end
      RefreshManualLedgerViews()
    end
  end

  function boardSyncTransactions.HandleLootLedgerCharacterDeleteBroadcast(fields, sender)
    if not HasExactFieldCount(fields, "LL_CHAR_DEL") then
      return
    end
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or IsSelfHost(activeSession) then
      return
    end

    local sessionId = TrimText(fields[2])
    local incomingProfile = TrimText(fields[3])
    local characterKey = ClipManualLedgerText(NormalizeCharacterKey(fields[4]), MAX_LOOT_LEDGER_CHARACTER_LENGTH)
    if characterKey == "" or not DoesRuntimeSessionMatch(activeSession, profileName, sessionId, incomingProfile) then
      return
    end
    if not IsSessionHostKey(activeSession, sender) then
      return
    end
    local ok = ApplyLootLedgerCharacterDelete(profileName, characterKey)
    if ok then
      RefreshManualLedgerViews()
    end
  end

  function boardSyncTransactions.HandleItemReportMessage(fields, sender)
    if not HasExactFieldCount(fields, "ITEM_REPORT") then
      return
    end
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not IsSelfHost(activeSession) then
      return
    end
    if not EnsureRuntimeSession(activeSession, profileName) then
      return
    end

    local sessionId = TrimText(fields[2])
    local incomingProfile = TrimText(fields[3])
    local reporterKey = NormalizeCharacterKey(fields[4] ~= "" and fields[4] or sender)
    local rollID = TrimText(fields[5])
    if not DoesRuntimeSessionMatch(activeSession, profileName, sessionId, incomingProfile) then
      return
    end
    if reporterKey == "" or not IsClaimedActorSenderMatch(sender, reporterKey) or not IsJoinedSessionCharacter(activeSession, reporterKey) then
      return
    end

    OpenAuthoritativeLootItem(activeSession, profileName, {
      rollID = tonumber(rollID) or nil,
      itemID = tonumber(fields[6]) or nil,
      itemLevel = tonumber(fields[7]) or nil,
      quality = tonumber(fields[8]) or nil,
      icon = fields[9],
      name = fields[10],
      link = fields[11],
      createdAt = tonumber(fields[12]) or nil,
    }, reporterKey, rollID)
  end

  function boardSyncTransactions.HandleItemOpenMessage(fields, sender)
    if not HasExactFieldCount(fields, "ITEM_OPEN") then
      return
    end
    local sessionId = TrimText(fields[2])
    local incomingProfile = TrimText(fields[3])
    local itemKey = TrimText(fields[4])
    if sessionId == "" or incomingProfile == "" or itemKey == "" then
      return
    end

    local activeSession, profileName = GetActiveLootSession()
    if not DoesRuntimeSessionMatch(activeSession, profileName, sessionId, incomingProfile) then
      return
    end
    if not IsSessionHostKey(activeSession, sender) then
      return
    end
    if IsSelfHost(activeSession) then
      return
    end
    if not EnsureRuntimeSession(activeSession, profileName) then
      return
    end

    EnsureRuntimeAuthorityMaps()
    PrimeSequence(itemKey)
    if IsRealSimulationItemKey(itemKey) and type(runtime.items[itemKey]) ~= "table" then
      boardSyncTransactions.ClearSimulationRuntimeItems()
    end
    local payload = NormalizeLootItemPayload({
      itemID = tonumber(fields[5]) or nil,
      itemLevel = tonumber(fields[6]) or nil,
      quality = tonumber(fields[7]) or nil,
      icon = fields[8],
      name = fields[9],
      link = fields[10],
      createdAt = tonumber(fields[11]) or nil,
      distributionMode = fields[14],
    })
    local entry = EnsureLiveEntry(activeSession, profileName, itemKey, payload)
    entry.isSimulation = IsRealSimulationItemKey(itemKey) == true
    entry.__transportSimulation = entry.isSimulation == true
    entry.__authoritativeLoot = true
    entry.__lootItemSignature = BuildLootItemSignature(payload)
    local sourceMemberKey = NormalizeCharacterKey(fields[12])
    local sourceRollID = TrimText(fields[13])
    if AreCharacterKeysSame(sourceMemberKey, GetSelfKey()) and sourceRollID ~= "" then
      runtime.localRollItemKeys[sourceRollID] = itemKey
      local reportIdentity = GetReportToken(
        sourceMemberKey,
        sourceRollID,
        BuildLootItemSignature(payload),
        payload.createdAt
      )
      local reportKey = string.lower(sessionId) .. "\031" .. string.lower(reportIdentity)
      local pendingReport = type(runtime.pendingItemReports) == "table"
        and runtime.pendingItemReports[reportKey]
        or nil
      if type(pendingReport) == "table" then
        runtime.pendingItemReports[reportKey] = nil
        runtime.lastItemReportReceipt = {
          sessionId = sessionId,
          reporterKey = sourceMemberKey,
          rollID = sourceRollID,
          itemKey = itemKey,
          state = "confirmed",
          attempts = tonumber(pendingReport.attempts) or 0,
          confirmedAt = type(GetServerTime) == "function"
            and math.max(0, tonumber(GetServerTime()) or 0)
            or math.max(0, tonumber(time and time() or 0) or 0),
        }
      end
    end

    local choiceQueued, choiceQueueReason = QueueLocalChoiceForItem(activeSession, itemKey)
    local receiptToken = TrimText(fields[15])
    runtime.itemOpenReceiverReplay = type(runtime.itemOpenReceiverReplay) == "table"
      and runtime.itemOpenReceiverReplay
      or {}
    local _, localMemberKey = GetSessionMember(activeSession, GetSelfKey())
    local localSelection = ResolveEntrySelection(entry, localMemberKey or GetSelfKey())
    local replayAccepted, replayRecord, duplicateDelivery = boardSyncTransactions.RecordItemOpenReceiverReplay(
      runtime.itemOpenReceiverReplay,
      sessionId,
      itemKey,
      receiptToken,
      type(localSelection) == "table" and (localSelection.optionKey or localSelection.label) or "pending",
      (type(GetServerTime) == "function" and GetServerTime()) or (time and time() or 0)
    )
    local receiptSent = receiptToken == ""
    if receiptToken ~= "" and type(SendSessionComm) == "function" then
      receiptSent = SendSessionComm(
        "ITEM_ACK",
        "WHISPER",
        NormalizeCharacterKey(activeSession.host),
        sessionId,
        incomingProfile,
        itemKey,
        receiptToken,
        "RECEIVED",
        duplicateDelivery == true and "duplicate_replay"
          or (choiceQueued == true and "choice_queued" or "item_admitted")
      ) == true
    end
    local receiverTelemetry = {
      sessionId = sessionId,
      profileName = incomingProfile,
      itemKey = itemKey,
      sender = NormalizeCharacterKey(sender),
      state = replayAccepted == true and TrimText(type(replayRecord) == "table" and replayRecord.state or "admitted")
        or "admitted",
      simulationOnly = entry.isSimulation == true,
      choiceQueued = choiceQueued == true,
      choiceQueueReason = TrimText(choiceQueueReason),
      duplicateDelivery = duplicateDelivery == true,
      deliveryCount = tonumber(type(replayRecord) == "table" and replayRecord.deliveryCount or 1) or 1,
      ackIntentCount = tonumber(type(replayRecord) == "table" and replayRecord.ackIntentCount or 1) or 1,
      preservedChoice = TrimText(type(replayRecord) == "table" and replayRecord.choiceState or ""),
      receiptToken = receiptToken,
      receiptSent = receiptSent == true,
      popupOpened = false,
      popupState = "pending",
      popupReason = "",
      inCombat = type(InCombatLockdown) == "function" and InCombatLockdown() == true or false,
      updatedAt = (type(GetServerTime) == "function" and GetServerTime()) or (time and time() or 0),
      activityClockAt = (type(GetTime) == "function" and GetTime()) or 0,
    }
    runtime.lastItemOpenReceiver = receiverTelemetry
    RefreshBoardAndEditor({
      reason = "track",
      itemKey = itemKey,
    })
    local popupOpened = false
    if type(RefreshChoicePopup) == "function" then
      popupOpened = RefreshChoicePopup({
        reason = "track",
        itemKey = itemKey,
      }) == true
    end
    local popupState = type(runtime.lastChoicePopupState) == "table" and runtime.lastChoicePopupState or {}
    receiverTelemetry.popupOpened = popupOpened
    receiverTelemetry.popupState = TrimText(popupState.state)
    receiverTelemetry.popupReason = TrimText(popupState.reason)
    receiverTelemetry.updatedAt = (type(GetServerTime) == "function" and GetServerTime()) or (time and time() or 0)
  end

  function boardSyncTransactions.HandleItemOpenReceipt(fields, sender)
    if not HasExactFieldCount(fields, "ITEM_ACK") then
      return false
    end
    local activeSession, profileName = GetActiveLootSession()
    if type(activeSession) ~= "table" or not IsSelfHost(activeSession) then
      return false
    end
    local sessionId = TrimText(fields[2])
    local incomingProfile = TrimText(fields[3])
    local itemKey = TrimText(fields[4])
    local token = TrimText(fields[5])
    local state = string.upper(TrimText(fields[6]))
    if token == "" or state ~= "RECEIVED"
      or not DoesRuntimeSessionMatch(activeSession, profileName, sessionId, incomingProfile)
    then
      return false
    end
    local receiptKey = boardSyncTransactions.GetItemOpenReceiptKey(token, sender)
    local transaction = boardSyncTransactions.itemOpenOutgoing[receiptKey]
      or boardSyncTransactions.completedItemOpenReceipts[receiptKey]
    if type(transaction) ~= "table"
      or TrimText(transaction.sessionId) ~= sessionId
      or TrimText(transaction.profileName) ~= incomingProfile
      or TrimText(transaction.itemKey) ~= itemKey
      or not AreCharacterKeysSame(transaction.targetKey, sender)
    then
      return false
    end
    if transaction.state == "acknowledged" then
      return true
    end
    local report = boardSyncTransactions.itemOpenReports[TrimText(transaction.reportKey)]
    if not boardSyncTransactions.ApplyItemOpenDispatchState(
      report,
      transaction,
      "acknowledged",
      TrimText(fields[7]),
      (type(GetServerTime) == "function" and GetServerTime()) or (time and time() or 0)
    ) then
      return false
    end
    boardSyncTransactions.itemOpenOutgoing[receiptKey] = nil
    boardSyncTransactions.completedItemOpenReceipts[receiptKey] = transaction
    return true
  end

  function boardSyncTransactions.HandleChoiceMessage(fields, sender)
    if not HasExactFieldCount(fields, "CHOICE") then
      return
    end
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not IsSelfHost(activeSession) then
      return
    end
    if not EnsureRuntimeSession(activeSession, profileName) then
      return
    end

    local sessionId = TrimText(fields[2])
    local incomingProfile = TrimText(fields[3])
    local itemKey = TrimText(fields[4])
    local memberKey = NormalizeCharacterKey(fields[5] ~= "" and fields[5] or sender)
    local optionKey = TrimText(fields[6])
    local optionLabel = TrimText(fields[7])
    local optionNote = NormalizeSelectionNote(fields[8])
    local optionRollValue = tonumber(fields[9])
    local optionSelectedAt = GetIncomingTimestamp(fields[10])
    local optionSelectedSeq = math.floor(tonumber(fields[11]) or 0)
    if not optionSelectedAt or not optionSelectedSeq or optionSelectedSeq <= 0 then
      return
    end
    if not DoesRuntimeSessionMatch(activeSession, profileName, sessionId, incomingProfile) then
      return
    end
    if itemKey == "" or memberKey == "" then
      return
    end
    if not IsClaimedActorSenderMatch(sender, memberKey) then
      return
    end
    if not IsJoinedSessionCharacter(activeSession, memberKey) then
      return
    end

    local entry = type(runtime.items) == "table" and runtime.items[itemKey] or nil
    if type(entry) ~= "table" then
      return
    end
    local option = ResolveConfiguredRollOption(activeSession, profileName, optionKey, optionLabel)
    if type(option) ~= "table" then
      return
    end
    PrimeSequence(itemKey)
    local currentSelectedSeq = GetSelectionSequence(entry, memberKey)
    local currentSelectedAt = GetSelectionUpdatedAt(entry, memberKey)
    local currentSelection = ResolveEntrySelection(entry, memberKey)
    local exactReplay = boardSyncTransactions.IsExactChoiceReplay(
      currentSelection,
      option.key,
      optionNote,
      optionRollValue,
      optionSelectedSeq,
      optionSelectedAt
    )
    if exactReplay then
      -- A member retry only needs another direct receipt. Re-broadcasting an
      -- unchanged choice would multiply group traffic and council ACK work.
      SendChoicePacket(
        "RCHOICE", "WHISPER", memberKey, activeSession.id,
        GetSessionCommProfileName(activeSession, profileName), itemKey, memberKey,
        currentSelection.optionKey, currentSelection.label, currentSelection.note,
        currentSelection.rollValue or "", currentSelectedAt, currentSelectedSeq
      )
      return
    end
    if optionSelectedSeq == currentSelectedSeq and currentSelectedSeq > 0 then
      -- One member sequence is immutable on the host. A contradictory replay
      -- with the same sequence/timestamp must not replace the accepted choice.
      return
    end
    if not boardSyncTransactions.ShouldAcceptIncomingChoice(
      currentSelectedSeq,
      currentSelectedAt,
      optionSelectedSeq,
      optionSelectedAt
    ) then
      return
    end
    option.note = optionNote
    option.rollValue = optionRollValue
    option.selectedAt = optionSelectedAt
    option.selectedSeq = optionSelectedSeq
    RecordChoice(entry, memberKey, option, "REMOTE")
    local storedSelectedAt = GetSelectionUpdatedAt(entry, memberKey)
    local storedSelectedSeq = GetSelectionSequence(entry, memberKey)
    BroadcastAuthoritativeChoice(
      activeSession,
      profileName,
      itemKey,
      memberKey,
      option.key,
      option.label,
      optionNote,
      optionRollValue or "",
      storedSelectedAt or "",
      storedSelectedSeq or "",
      memberKey
    )
    RefreshBoardAndEditor({
      reason = "choice",
      itemKey = itemKey,
    })
  end

  function boardSyncTransactions.HandleMirroredChoiceMessage(fields, sender)
    if not HasExactFieldCount(fields, "RCHOICE") then
      return
    end
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or IsSelfHost(activeSession) then
      return
    end
    if not EnsureRuntimeSession(activeSession, profileName) then
      return
    end

    local sessionId = TrimText(fields[2])
    local incomingProfile = TrimText(fields[3])
    local itemKey = TrimText(fields[4])
    local memberKey = NormalizeCharacterKey(fields[5] ~= "" and fields[5] or sender)
    local optionKey = TrimText(fields[6])
    local optionLabel = TrimText(fields[7])
    local optionNote = NormalizeSelectionNote(fields[8])
    local optionRollValue = tonumber(fields[9])
    local optionSelectedAt = GetIncomingTimestamp(fields[10])
    local optionSelectedSeq = math.floor(tonumber(fields[11]) or 0)
    if not optionSelectedAt or not optionSelectedSeq or optionSelectedSeq <= 0 then
      return
    end
    if not DoesRuntimeSessionMatch(activeSession, profileName, sessionId, incomingProfile) then
      return
    end
    if itemKey == "" or memberKey == "" then
      return
    end
    if not IsSessionHostKey(activeSession, sender) then
      return
    end
    if not IsJoinedSessionCharacter(activeSession, memberKey) then
      return
    end

    PrimeSequence(itemKey)
    local entry = EnsureLiveEntry(activeSession, profileName, itemKey, {
      name = runtime.items[itemKey] and runtime.items[itemKey].name or "Awaiting item info",
    })
    local currentSelectedSeq = GetSelectionSequence(entry, memberKey)
    local currentSelectedAt = GetSelectionUpdatedAt(entry, memberKey)
    local currentSelection = ResolveEntrySelection(entry, memberKey)
    local exactReplay = boardSyncTransactions.IsExactChoiceReplay(
      currentSelection,
      optionKey,
      optionNote,
      optionRollValue,
      optionSelectedSeq,
      optionSelectedAt
    )
    local shouldApply = boardSyncTransactions.ShouldAcceptIncomingChoice(
      currentSelectedSeq,
      currentSelectedAt,
      optionSelectedSeq,
      optionSelectedAt
    )
    local applied = false
    if shouldApply and not exactReplay then
      local option = ResolveConfiguredRollOption(activeSession, profileName, optionKey, optionLabel)
      if type(option) ~= "table" then
        return
      end
      option.note = optionNote
      option.rollValue = optionRollValue
      option.selectedAt = optionSelectedAt
      option.selectedSeq = optionSelectedSeq
      RecordChoice(entry, memberKey, option, "MIRROR")
      applied = true
    end
    local storedSelection = ResolveEntrySelection(entry, memberKey)
    local mirrorsExactChoice = boardSyncTransactions.IsExactChoiceReplay(
      storedSelection,
      optionKey,
      optionNote,
      optionRollValue,
      optionSelectedSeq,
      optionSelectedAt
    )
    if mirrorsExactChoice and AreCharacterKeysSame(memberKey, GetSelfKey()) then
      -- The host first whispers this authoritative mirror as the receipt, then
      -- broadcasts it to the group. Either copy confirms this exact choice.
      ConfirmPendingChoiceReceipt(sessionId, itemKey, memberKey, optionSelectedAt, optionSelectedSeq)
    end
    if mirrorsExactChoice
      and CanSessionCharacterVote(activeSession, profileName, GetSelfKey())
      and type(SendSessionComm) == "function"
    then
      SendSessionComm(
        "RCHOICE_ACK",
        "WHISPER",
        NormalizeCharacterKey(activeSession.host),
        sessionId,
        GetSessionCommProfileName(activeSession, profileName),
        itemKey,
        memberKey,
        tostring(math.max(0, math.floor(optionSelectedSeq))),
        "RECEIVED"
      )
    end
    if applied then
      RefreshBoardAndEditor({
        reason = "choice",
        itemKey = itemKey,
      })
    end
  end

  function boardSyncTransactions.HandleMirroredChoiceReceipt(fields, sender)
    if not HasExactFieldCount(fields, "RCHOICE_ACK") then
      return
    end
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not IsSelfHost(activeSession) then
      return
    end
    local sessionId = TrimText(fields[2])
    local incomingProfile = TrimText(fields[3])
    local itemKey = TrimText(fields[4])
    local memberKey = NormalizeCharacterKey(fields[5])
    local selectedSeq = math.max(0, math.floor(tonumber(fields[6]) or 0))
    local targetKey = NormalizeCharacterKey(sender)
    if selectedSeq <= 0
      or not DoesRuntimeSessionMatch(activeSession, profileName, sessionId, incomingProfile)
      or not IsJoinedSessionCharacter(activeSession, targetKey)
      or not CanSessionCharacterVote(activeSession, profileName, targetKey)
    then
      return
    end
    local identity = BuildChoiceMirrorIdentity(sessionId, itemKey, memberKey, selectedSeq, targetKey)
    local transaction = boardSyncTransactions.choiceMirrorOutgoing[identity]
    if type(transaction) ~= "table" then
      return
    end
    if boardSyncTransactions.ApplyChoiceMirrorReceipt(transaction, fields[7]) then
      boardSyncTransactions.choiceMirrorOutgoing[identity] = nil
      RefreshChoiceMirrorDispatch(transaction.report)
    end
  end

  function boardSyncTransactions.HandleAwardMessage(fields, sender)
    if not HasExactFieldCount(fields, "AWARD") then
      return
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local itemKey = TrimText(fields[4])
    local memberKey = NormalizeCharacterKey(fields[5])
    local itemName = TrimText(fields[6])
    local itemLevel = tonumber(fields[7])
    local points = tonumber(fields[8]) or 0
    local note = TrimText(fields[9])
    local changedAt = GetIncomingTimestamp(fields[10])
    if not changedAt then
      return
    end
    if sessionId == "" or profileName == "" or itemKey == "" or memberKey == "" then
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    if not DoesRuntimeSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if type(IsSelfHost) == "function" and IsSelfHost(activeSession) then
      -- An awarded member returns the same authoritative payload as a receipt.
      -- It confirms delivery only; the host never reapplies an incoming receipt.
      if not IsClaimedActorSenderMatch(sender, memberKey) then
        return
      end
      local localEntry = runtime.items[itemKey]
      if type(localEntry) ~= "table"
        or not AreCharacterKeysSame(localEntry.awardedTo, memberKey)
        or tonumber(localEntry.awardUpdatedAt or localEntry.awardedAt) ~= changedAt
      then
        return
      end
      local receiptKey = string.lower(sessionId)
        .. "\031" .. string.lower(itemKey)
        .. "\031" .. string.lower(memberKey)
        .. "\031" .. tostring(changedAt)
      local pendingReceipt = type(runtime.pendingAwardReceipts) == "table"
        and runtime.pendingAwardReceipts[receiptKey]
        or nil
      if type(pendingReceipt) == "table" then
        runtime.pendingAwardReceipts[receiptKey] = nil
        runtime.lastAwardReceipt = {
          sessionId = sessionId,
          itemKey = itemKey,
          memberKey = memberKey,
          changedAt = changedAt,
          state = "confirmed",
          attempts = tonumber(pendingReceipt.attempts) or 0,
          confirmedAt = type(GetServerTime) == "function"
            and math.max(0, tonumber(GetServerTime()) or 0)
            or math.max(0, tonumber(time and time() or 0) or 0),
        }
      end
      return
    end
    if not IsSessionHostKey(activeSession, sender) then
      return
    end

    local entry = runtime.items[itemKey]
    if changedAt and changedAt < GetAwardUpdatedAt(entry) then
      return
    end

    local ok = ApplyAwardMessage(itemKey, memberKey, itemName, itemLevel, points, note, activeSession, activeProfileName, changedAt)
    if ok then
      RefreshBoardAndEditor({
        reason = "award",
        itemKey = itemKey,
      })
      if AreCharacterKeysSame(memberKey, GetSelfKey()) then
        boardSyncTransactions.SendAwardPacket(
          "WHISPER",
          activeSession.host,
          sessionId,
          GetSessionCommProfileName(activeSession, activeProfileName),
          itemKey,
          memberKey,
          itemName,
          itemLevel or "",
          points,
          note,
          changedAt
        )
      end
    end
  end

  function boardSyncTransactions.HandleUnassignMessage(fields, sender)
    if not HasExactFieldCount(fields, "UNASSIGN") then
      return
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local itemKey = TrimText(fields[4])
    local changedAt = GetIncomingTimestamp(fields[5])
    if not changedAt then
      return
    end
    if sessionId == "" or profileName == "" or itemKey == "" then
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    if not DoesRuntimeSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if not IsSessionHostKey(activeSession, sender) then
      return
    end

    if not EnsureRuntimeSession(activeSession, activeProfileName) then
      return
    end

    local entry = runtime.items[itemKey]
    if not entry or not entry.awardedAt then
      return
    end
    if changedAt and changedAt < GetAwardUpdatedAt(entry) then
      return
    end

    local ok = RemoveAwardFromEntry(activeProfileName, entry, changedAt)
    if ok then
      RefreshBoardAndEditor({
        reason = "unassign",
        itemKey = itemKey,
      })
    end
  end

  function boardSyncTransactions.HandleTradeMessage(fields, sender)
    if not HasExactFieldCount(fields, "TRADE") then
      return
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local itemKey = TrimText(fields[4])
    local tradeState = string.upper(TrimText(fields[5]))
    local changedAt = GetIncomingTimestamp(fields[6])
    local changedBy = NormalizeCharacterKey(fields[7])
    if not changedAt then
      return
    end
    if sessionId == "" or profileName == "" or itemKey == "" then
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    if not DoesRuntimeSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if type(IsSelfHost) == "function" and IsSelfHost(activeSession) then
      -- Trade receipts confirm that the recipient received the host's state;
      -- they do not claim that the native WoW trade itself succeeded.
      local localEntry = runtime.items[itemKey]
      if not IsClaimedActorSenderMatch(sender, type(localEntry) == "table" and localEntry.awardedTo or "")
        or type(localEntry) ~= "table"
        or not AreCharacterKeysSame(localEntry.awardedTo, sender)
        or string.upper(TrimText(localEntry.tradeState)) ~= tradeState
        or tonumber(localEntry.tradeUpdatedAt) ~= changedAt
      then
        return
      end
      local receiptKey = string.lower(sessionId)
        .. "\031" .. string.lower(itemKey)
        .. "\031" .. string.lower(NormalizeCharacterKey(sender))
        .. "\031" .. tostring(changedAt)
      local pendingReceipt = type(runtime.pendingTradeReceipts) == "table"
        and runtime.pendingTradeReceipts[receiptKey]
        or nil
      if type(pendingReceipt) == "table" then
        runtime.pendingTradeReceipts[receiptKey] = nil
        runtime.lastTradeReceipt = {
          sessionId = sessionId,
          itemKey = itemKey,
          memberKey = NormalizeCharacterKey(sender),
          changedAt = changedAt,
          state = "confirmed",
          attempts = tonumber(pendingReceipt.attempts) or 0,
          confirmedAt = type(GetServerTime) == "function"
            and math.max(0, tonumber(GetServerTime()) or 0)
            or math.max(0, tonumber(time and time() or 0) or 0),
        }
      end
      return
    end
    if not IsSessionHostKey(activeSession, sender) then
      return
    end
    if not EnsureRuntimeSession(activeSession, activeProfileName) then
      return
    end

    local entry = runtime.items[itemKey]
    if type(entry) ~= "table" or not entry.awardedAt then
      return
    end
    if changedAt < GetTradeUpdatedAt(entry) then
      return
    end

    if tradeState == "TRADED" then
      entry.tradeState = "TRADED"
      entry.tradedAt = changedAt
      entry.tradedBy = changedBy ~= "" and changedBy or NormalizeSenderKey(sender)
      entry.tradeUpdatedAt = changedAt
    else
      entry.tradeState = nil
      entry.tradedAt = nil
      entry.tradedBy = nil
      entry.tradeUpdatedAt = changedAt
    end
    runtime.boardUpdatedAt = math.max(tonumber(runtime.boardUpdatedAt) or 0, changedAt)
    PersistRuntimeBoardHistory({
      itemKey = itemKey,
      fieldKeys = {
        "awardedTo",
        "awardedPoints",
        "awardedNote",
        "awardedAt",
        "ledgerEntryId",
        "awardUpdatedAt",
        "tradeState",
        "tradedAt",
        "tradedBy",
        "tradeUpdatedAt",
      },
    })
    RefreshBoardAndEditor({
      reason = "trade",
      itemKey = itemKey,
    })
    if AreCharacterKeysSame(entry.awardedTo, GetSelfKey()) and type(SendSessionComm) == "function" then
      SendSessionComm(
        "TRADE",
        "WHISPER",
        activeSession.host,
        sessionId,
        GetSessionCommProfileName(activeSession, activeProfileName),
        itemKey,
        tradeState,
        changedAt,
        changedBy
      )
    end
  end

  function boardSyncTransactions.HandleVoteMessage(fields, sender)
    if not HasExactFieldCount(fields, "VOTE") then
      return
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local itemKey = TrimText(fields[4])
    local voterKey = NormalizeCharacterKey(fields[5] ~= "" and fields[5] or sender)
    local targetKey = NormalizeCharacterKey(fields[6])
    local changedAt = GetIncomingTimestamp(fields[7])
    local voteSeq = tonumber(fields[8])
    if not changedAt or not voteSeq or voteSeq <= 0 then
      return
    end
    if sessionId == "" or profileName == "" or itemKey == "" or voterKey == "" then
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    if not DoesRuntimeSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    local isAuthoritativeHost = IsSessionHostKey(activeSession, sender)
    if not isAuthoritativeHost and not IsClaimedActorSenderMatch(sender, voterKey) then
      return
    end
    if not IsJoinedSessionCharacter(activeSession, voterKey) then
      return
    end
    if not CanSessionCharacterVote(activeSession, activeProfileName, voterKey) then
      return
    end
    if not EnsureRuntimeSession(activeSession, activeProfileName) then
      return
    end

    local entry = runtime.items[itemKey]
    if not entry then
      entry = EnsureLiveEntry(activeSession, activeProfileName, itemKey, {
        name = "Awaiting item info",
      })
    end
    if not entry or entry.awardedAt then
      return
    end

    local function ConfirmPendingVoteReceipt()
      if type(runtime.pendingVoteReceipts) ~= "table" then
        return false
      end
      local receiptKey = string.lower(sessionId)
        .. "\031" .. string.lower(itemKey)
        .. "\031" .. string.lower(voterKey)
        .. "\031" .. tostring(math.max(0, math.floor(voteSeq)))
      local receipt = runtime.pendingVoteReceipts[receiptKey]
      if type(receipt) ~= "table" then
        return false
      end
      local expectedAt = tonumber(receipt.changedAt) or 0
      if expectedAt > 0 and expectedAt ~= changedAt then
        return false
      end
      if NormalizeCharacterKey(receipt.targetKey) ~= targetKey then
        return false
      end
      runtime.pendingVoteReceipts[receiptKey] = nil
      runtime.lastVoteReceipt = {
        sessionId = sessionId,
        itemKey = itemKey,
        voterKey = voterKey,
        targetKey = targetKey,
        changedAt = changedAt,
        voteSeq = voteSeq,
        confirmedAt = type(GetServerTime) == "function"
          and math.max(0, tonumber(GetServerTime()) or 0)
          or math.max(0, tonumber(time and time() or 0) or 0),
      }
      return true
    end

    local currentVoteSeq = GetVoteSequence(entry, voterKey)
    local currentVoteChangedAt = GetVoteUpdatedAt(entry, voterKey)
    if voteSeq < currentVoteSeq or (voteSeq == currentVoteSeq and changedAt < currentVoteChangedAt) then
      return
    end

    local function SendAuthoritativeVoteMirror()
      if type(IsSelfHost) ~= "function" or not IsSelfHost(activeSession)
          or isAuthoritativeHost or type(SendSessionComm) ~= "function" then
        return
      end
      -- The direct copy is the voter's receipt; the broadcast is the canonical
      -- board update for every other current client.
      SendSessionComm(
        "VOTE",
        "WHISPER",
        voterKey,
        sessionId,
        GetSessionCommProfileName(activeSession, activeProfileName),
        itemKey,
        voterKey,
        targetKey,
        changedAt,
        voteSeq
      )
      local distribution = GetBroadcastDistribution()
      if distribution then
        SendSessionComm(
          "VOTE",
          distribution,
          nil,
          sessionId,
          GetSessionCommProfileName(activeSession, activeProfileName),
          itemKey,
          voterKey,
          targetKey,
          changedAt,
          voteSeq
        )
      end
    end

    if isAuthoritativeHost and AreCharacterKeysSame(voterKey, GetSelfKey()) then
      if ConfirmPendingVoteReceipt() then
        RefreshBoardAndEditor({
          reason = "vote_receipt",
          itemKey = itemKey,
        })
      end
    end
    if voteSeq == currentVoteSeq and changedAt == currentVoteChangedAt then
      SendAuthoritativeVoteMirror()
      return
    end

    SetEntryVoteTarget(entry, voterKey, targetKey ~= "" and targetKey or nil)
    SetVoteUpdatedAt(entry, voterKey, changedAt or ((type(GetServerTime) == "function" and GetServerTime()) or (time and time() or 0)))
    SetVoteSequence(entry, voterKey, voteSeq)
    local isRealSimulationItem = (type(entry) == "table" and entry.isSimulation == true)
      or (type(IsRealSimulationItemKey) == "function" and IsRealSimulationItemKey(itemKey))
    if type(RecordLootVoteStat) == "function"
      and type(IsSelfHost) == "function"
      and IsSelfHost(activeSession)
      and not isRealSimulationItem
    then
      RecordLootVoteStat(activeProfileName, {
        sessionId = sessionId,
        itemKey = itemKey,
        voter = voterKey,
        target = targetKey,
        votedAt = changedAt,
        isSimulation = isRealSimulationItem,
      })
    end
    PersistRuntimeBoardHistory({
      itemKey = itemKey,
      voterKey = voterKey,
    })
    SendAuthoritativeVoteMirror()
    RefreshBoardAndEditor({
      reason = "vote",
      itemKey = itemKey,
    })
  end

  GetBoardSyncToken = function(sessionId, profileName, senderKey)
    return string.lower(TrimText(sessionId) .. "|" .. TrimText(profileName) .. "|" .. NormalizeCharacterKey(senderKey))
  end

  function boardSyncTransactions.RecordReceiver(state, syncState, sender, reason, extra)
    syncState = type(syncState) == "table" and syncState or {}
    extra = type(extra) == "table" and extra or {}
    local sessionId = TrimText(syncState.sessionId or extra.sessionId)
    local profileName = TrimText(syncState.profileName or extra.profileName)
    local boardId = TrimText(syncState.boardId or extra.boardId)
    local token = TrimText(syncState.token or extra.token)
    local senderKey = NormalizeCharacterKey(sender or extra.sender)
    local previous = type(runtime.lastBoardSyncReceiver) == "table" and runtime.lastBoardSyncReceiver or {}
    local sameTransaction = sessionId ~= ""
      and sessionId == TrimText(previous.sessionId)
      and profileName == TrimText(previous.profileName)
      and (token == "" or TrimText(previous.token) == "" or token == TrimText(previous.token))
    local record = sameTransaction and previous or {}
    local now = GetCurrentTimestamp()

    record.sessionId = sessionId
    record.profileName = profileName
    record.boardId = boardId
    record.token = token
    record.sender = senderKey
    record.state = string.lower(TrimText(state))
    record.reason = TrimText(reason)
    record.expectedItems = math.max(0, tonumber(syncState.expectedItems or extra.expectedItems) or 0)
    record.expectedSelections = math.max(0, tonumber(syncState.expectedSelections or extra.expectedSelections) or 0)
    record.expectedVotes = math.max(0, tonumber(syncState.expectedVotes or extra.expectedVotes) or 0)
    record.receivedItems = boardSyncTransactions.CountIndexedRows(syncState.itemSignatures)
    record.receivedSelections = boardSyncTransactions.CountIndexedRows(syncState.selectionSignatures)
    record.receivedVotes = boardSyncTransactions.CountIndexedRows(syncState.voteSignatures)
    record.missingCount = math.max(0, tonumber(extra.missingCount) or tonumber(record.missingCount) or 0)
    if extra.checksumMatched ~= nil then
      record.checksumMatched = extra.checksumMatched == true
    end
    if TrimText(extra.ackStatus) ~= "" then
      record.ackStatus = string.upper(TrimText(extra.ackStatus))
    end
    if extra.ackSent ~= nil then
      record.ackSent = extra.ackSent == true
    end
    if extra.popupQueueCount ~= nil then
      record.popupQueueCount = math.max(0, tonumber(extra.popupQueueCount) or 0)
    end
    if extra.popupOpened ~= nil then
      record.popupOpened = extra.popupOpened == true
    end
    if TrimText(extra.popupState) ~= "" then
      record.popupState = string.lower(TrimText(extra.popupState))
    end
    if TrimText(extra.popupReason) ~= "" then
      record.popupReason = TrimText(extra.popupReason)
    end
    record.startedAt = math.max(0, tonumber(record.startedAt) or now)
    record.updatedAt = now
    record.activityClockAt = (type(GetTime) == "function" and GetTime()) or 0
    runtime.lastBoardSyncReceiver = record
    return record
  end

  function boardSyncTransactions.HandleBoardSyncStart(fields, sender)
    if not HasExactFieldCount(fields, "BSYNC_START") then
      boardSyncTransactions.RecordReceiver("rejected", nil, sender, "invalid_start_field_count")
      return
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local boardUpdatedAt = GetIncomingTimestamp(fields[4])
    if not boardUpdatedAt then
      boardSyncTransactions.RecordReceiver("rejected", nil, sender, "invalid_board_timestamp", {
        sessionId = sessionId,
        profileName = profileName,
      })
      return
    end
    local boardId = TrimText(fields[5])
    local historyProfileName = TrimText(fields[6])
    local selectedItemKey = TrimText(fields[7])
    local transactionToken = TrimText(fields[8])
    local expectedItems = math.max(0, tonumber(fields[9]) or 0)
    local expectedSelections = math.max(0, tonumber(fields[10]) or 0)
    local expectedVotes = math.max(0, tonumber(fields[11]) or 0)
    local expectedChecksum = TrimText(fields[12])
    RecordRaidTraceEvent("BSYNC_RECEIVER_START", "Member received a board transaction start.", {
      boardId = boardId,
      token = transactionToken,
      sender = NormalizeCharacterKey(sender),
      items = expectedItems,
      selections = expectedSelections,
      votes = expectedVotes,
    })
    if sessionId == "" or profileName == "" then
      boardSyncTransactions.RecordReceiver("rejected", nil, sender, "missing_session_or_profile", {
        sessionId = sessionId,
        profileName = profileName,
        boardId = boardId,
        token = transactionToken,
      })
      return
    end
    if transactionToken ~= ""
      and (expectedChecksum == "" or expectedItems > 2000 or expectedSelections > 5000 or expectedVotes > 5000)
    then
      boardSyncTransactions.RecordReceiver("rejected", nil, sender, "invalid_manifest_bounds", {
        sessionId = sessionId,
        profileName = profileName,
        boardId = boardId,
        token = transactionToken,
        expectedItems = expectedItems,
        expectedSelections = expectedSelections,
        expectedVotes = expectedVotes,
      })
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    if not DoesRuntimeSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      boardSyncTransactions.RecordReceiver("rejected", nil, sender, "session_or_profile_mismatch", {
        sessionId = sessionId,
        profileName = profileName,
        boardId = boardId,
        token = transactionToken,
      })
      return
    end
    if not IsSessionHostKey(activeSession, sender) then
      boardSyncTransactions.RecordReceiver("rejected", nil, sender, "sender_is_not_session_host", {
        sessionId = sessionId,
        profileName = profileName,
        boardId = boardId,
        token = transactionToken,
      })
      return
    end
    if boardUpdatedAt > 0 and boardUpdatedAt < (tonumber(runtime.boardUpdatedAt) or 0) then
      boardSyncTransactions.RecordReceiver("rejected", nil, sender, "stale_board_revision", {
        sessionId = sessionId,
        profileName = profileName,
        boardId = boardId,
        token = transactionToken,
      })
      return
    end
    if not EnsureRuntimeSession(activeSession, activeProfileName) then
      boardSyncTransactions.RecordReceiver("rejected", nil, sender, "runtime_session_unavailable", {
        sessionId = sessionId,
        profileName = profileName,
        boardId = boardId,
        token = transactionToken,
      })
      return
    end

    local localChoiceSnapshots = {}
    local selfKey = GetSelfKey()
    local _, localMemberKey = GetSessionMember(activeSession, selfKey)
    local choiceMemberKey = localMemberKey or selfKey
    if choiceMemberKey ~= "" then
      for _, localItemKey in ipairs(runtime.itemOrder or {}) do
        local localEntry = type(runtime.items) == "table" and runtime.items[localItemKey] or nil
        local localSelection, storedMemberKey = ResolveEntrySelection(localEntry, choiceMemberKey)
        if type(localSelection) == "table"
          and string.lower(TrimText(localSelection.source)) == "local"
          and not IsPendingSelection(localSelection)
          and (tonumber(localSelection.selectedSeq) or 0) > 0
        then
          localChoiceSnapshots[TrimText(localItemKey)] = {
            memberKey = TrimText(storedMemberKey) ~= "" and storedMemberKey or choiceMemberKey,
            selection = type(DeepCopy) == "function" and DeepCopy(localSelection) or localSelection,
          }
        end
      end
    end

    runtime.boardId = boardId ~= "" and boardId or runtime.boardId
    runtime.historyProfileName = historyProfileName ~= "" and historyProfileName or profileName
    runtime.selectedItemKey = nil
    runtime.selectedMemberKey = nil
    runtime.itemCounts = {}
    runtime.itemOrder = {}
    runtime.items = {}
    runtime.popupQueue = {}
    local completedPrefix = string.lower(table.concat({ sessionId, profileName, NormalizeCharacterKey(sender) }, "|")) .. "|"
    for completedKey in pairs(boardSyncTransactions.completedReceipts) do
      if string.sub(completedKey, 1, #completedPrefix) == completedPrefix then
        boardSyncTransactions.completedReceipts[completedKey] = nil
      end
    end
    local syncState = {
      sessionId = sessionId,
      profileName = profileName,
      selectedItemKey = selectedItemKey,
      updatedAt = boardUpdatedAt,
      boardId = boardId,
      token = transactionToken,
      expectedItems = expectedItems,
      expectedSelections = expectedSelections,
      expectedVotes = expectedVotes,
      expectedChecksum = expectedChecksum,
      itemSignatures = {},
      selectionSignatures = {},
      voteSignatures = {},
      localChoiceSnapshots = localChoiceSnapshots,
    }
    incomingBoardSyncs[GetBoardSyncToken(sessionId, profileName, sender)] = syncState
    boardSyncTransactions.RecordReceiver("start_received", syncState, sender, "")
  end

  function boardSyncTransactions.HandleBoardSyncItem(fields, sender)
    if not HasExactFieldCount(fields, "BSYNC_ITEM") and not (type(fields) == "table" and #fields == 18) then
      return
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local orderIndex = tonumber(fields[4]) or 0
    local itemKey = TrimText(fields[5])
    if sessionId == "" or profileName == "" or itemKey == "" or orderIndex <= 0 then
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    if not DoesRuntimeSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if not IsSessionHostKey(activeSession, sender) or not HasBoardSyncState(sessionId, profileName, sender) then
      return
    end
    if not EnsureRuntimeSession(activeSession, activeProfileName) then
      return
    end

    local entry = {
      key = itemKey,
      name = TrimText(fields[6]),
      link = fields[7] ~= "" and fields[7] or nil,
      icon = fields[8] ~= "" and fields[8] or nil,
      quality = tonumber(fields[9]) or nil,
      itemID = tonumber(fields[10]) or ExtractItemID(fields[10]),
      itemLevel = tonumber(fields[11]) or nil,
      createdAt = tonumber(fields[12]) or nil,
      awardedTo = NormalizeCharacterKey(fields[13]),
      awardedPoints = tonumber(fields[14]) or nil,
      awardedNote = TrimText(fields[15]),
      awardedAt = tonumber(fields[16]) or nil,
      ledgerEntryId = TrimText(fields[17]),
      awardUpdatedAt = tonumber(fields[18]) or nil,
      tradeState = TrimText(fields[19]),
      tradedAt = tonumber(fields[20]) or nil,
      tradedBy = NormalizeCharacterKey(fields[21]),
      distributionMode = NormalizeDistributionMode(fields[22]),
      selections = {},
      votesByVoter = {},
      voteUpdatedAtByVoter = {},
      voteSequenceByVoter = {},
      sessionId = sessionId,
      profileName = profileName,
    }

    runtime.items[itemKey] = entry
    runtime.itemOrder[orderIndex] = itemKey
    local syncState = incomingBoardSyncs[GetBoardSyncToken(sessionId, profileName, sender)]
    if type(syncState) == "table" and TrimText(syncState.token) ~= "" then
      syncState.itemSignatures[orderIndex] = boardSyncTransactions.BuildRowSignature(
        "I", orderIndex, itemKey, "", "", orderIndex
      )
      boardSyncTransactions.RecordReceiver("receiving", syncState, sender, "")
    end
  end

  function boardSyncTransactions.HandleBoardSyncSelection(fields, sender)
    if not HasExactFieldCount(fields, "BSYNC_SEL") then
      return
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local itemKey = TrimText(fields[4])
    local memberKey = NormalizeCharacterKey(fields[5])
    if sessionId == "" or profileName == "" or itemKey == "" or memberKey == "" then
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    if not DoesRuntimeSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if not IsSessionHostKey(activeSession, sender) or not HasBoardSyncState(sessionId, profileName, sender) then
      return
    end
    if not EnsureRuntimeSession(activeSession, activeProfileName) then
      return
    end

    local entry = runtime.items[itemKey]
    if type(entry) ~= "table" then
      return
    end

    entry.selections = entry.selections or {}
    local selectedAt = GetIncomingTimestamp(fields[15])
    local selectedSeq = tonumber(fields[17])
    local rowIndex = math.max(0, tonumber(fields[18]) or 0)
    local incomingSelectionKey = string.lower(TrimText(fields[6] ~= "" and fields[6] or fields[7]))
    if not selectedAt and (incomingSelectionKey == "" or incomingSelectionKey == "pending") then
      local syncState = incomingBoardSyncs[GetBoardSyncToken(sessionId, profileName, sender)]
      selectedAt = GetIncomingTimestamp(entry.createdAt)
        or GetIncomingTimestamp(type(syncState) == "table" and syncState.updatedAt)
        or GetCurrentTimestamp()
    end
    if not selectedAt or not selectedSeq or selectedSeq <= 0 then
      return
    end
    local _, storedMemberKey = ResolveEntrySelection(entry, memberKey)
    entry.selections[storedMemberKey or memberKey] = {
      optionKey = TrimText(fields[6]),
      label = TrimText(fields[7]),
      color = {
        tonumber(fields[8]) or 0.82,
        tonumber(fields[9]) or 0.82,
        tonumber(fields[10]) or 0.86,
      },
      icon = fields[11] ~= "" and fields[11] or nil,
      note = NormalizeSelectionNote(fields[12]),
      rollValue = tonumber(fields[13]) or nil,
      pointBehavior = TrimText(fields[14]),
      selectedAt = selectedAt,
      source = TrimText(fields[16]),
      selectedSeq = math.floor(selectedSeq),
    }
    local syncState = incomingBoardSyncs[GetBoardSyncToken(sessionId, profileName, sender)]
    if type(syncState) == "table" and TrimText(syncState.token) ~= "" and rowIndex > 0 then
      syncState.selectionSignatures[rowIndex] = boardSyncTransactions.BuildRowSignature(
        "S", rowIndex, itemKey, memberKey, "", selectedSeq
      )
      boardSyncTransactions.RecordReceiver("receiving", syncState, sender, "")
    end
  end

  function boardSyncTransactions.HandleBoardSyncVote(fields, sender)
    if not HasExactFieldCount(fields, "BSYNC_VOTE") then
      return
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local itemKey = TrimText(fields[4])
    local voterKey = NormalizeCharacterKey(fields[5])
    local targetKey = NormalizeCharacterKey(fields[6])
    local changedAt = GetIncomingTimestamp(fields[7])
    local voteSeq = tonumber(fields[8])
    local rowIndex = math.max(0, tonumber(fields[9]) or 0)
    if sessionId == "" or profileName == "" or itemKey == "" or voterKey == "" or targetKey == "" or not changedAt or not voteSeq or voteSeq <= 0 then
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    if not DoesRuntimeSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if not IsSessionHostKey(activeSession, sender) or not HasBoardSyncState(sessionId, profileName, sender) then
      return
    end
    if not IsJoinedSessionCharacter(activeSession, voterKey) or not CanSessionCharacterVote(activeSession, activeProfileName, voterKey) then
      return
    end
    if not EnsureRuntimeSession(activeSession, activeProfileName) then
      return
    end

    local entry = runtime.items[itemKey]
    if type(entry) ~= "table" then
      return
    end
    entry.votesByVoter = entry.votesByVoter or {}
    entry.votesByVoter[voterKey] = targetKey
    SetVoteUpdatedAt(entry, voterKey, changedAt or (time and time() or 0))
    SetVoteSequence(entry, voterKey, voteSeq)
    local syncState = incomingBoardSyncs[GetBoardSyncToken(sessionId, profileName, sender)]
    if type(syncState) == "table" and TrimText(syncState.token) ~= "" and rowIndex > 0 then
      syncState.voteSignatures[rowIndex] = boardSyncTransactions.BuildRowSignature(
        "V", rowIndex, itemKey, voterKey, targetKey, voteSeq
      )
      boardSyncTransactions.RecordReceiver("receiving", syncState, sender, "")
    end
  end

  function boardSyncTransactions.SendReceipt(syncState, sender, status)
    if type(syncState) ~= "table" or TrimText(syncState.token) == "" then
      return false
    end
    local counts = {
      items = boardSyncTransactions.CountIndexedRows(syncState.itemSignatures),
      selections = boardSyncTransactions.CountIndexedRows(syncState.selectionSignatures),
      votes = boardSyncTransactions.CountIndexedRows(syncState.voteSignatures),
    }
    local checksum = boardSyncTransactions.CalculateManifestChecksum(
      syncState.itemSignatures,
      syncState.selectionSignatures,
      syncState.voteSignatures,
      {
        items = tonumber(syncState.expectedItems) or counts.items,
        selections = tonumber(syncState.expectedSelections) or counts.selections,
        votes = tonumber(syncState.expectedVotes) or counts.votes,
      }
    )
    return SendSessionComm(
      "BSYNC_ACK",
      "WHISPER",
      NormalizeCharacterKey(sender),
      TrimText(syncState.sessionId),
      TrimText(syncState.profileName),
      TrimText(syncState.boardId),
      TrimText(syncState.token),
      tostring(counts.items),
      tostring(counts.selections),
      tostring(counts.votes),
      checksum,
      string.upper(TrimText(status))
    )
  end

  function boardSyncTransactions.SendMissingRequests(syncState, sender, missing)
    local sent = 0
    for _, descriptor in ipairs({
      { kind = "I", rows = missing.item },
      { kind = "S", rows = missing.selection },
      { kind = "V", rows = missing.vote },
    }) do
      for _, rowIndex in ipairs(descriptor.rows or {}) do
        if sent >= boardSyncTransactions.maxMissingPerReceipt then
          return sent
        end
        if SendSessionComm(
          "BSYNC_MISS",
          "WHISPER",
          NormalizeCharacterKey(sender),
          TrimText(syncState.sessionId),
          TrimText(syncState.profileName),
          TrimText(syncState.boardId),
          TrimText(syncState.token),
          descriptor.kind,
          tostring(rowIndex)
        ) then
          sent = sent + 1
        end
      end
    end
    return sent
  end

  function boardSyncTransactions.HandleMissing(fields, sender)
    if not HasExactFieldCount(fields, "BSYNC_MISS") then
      return
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local boardId = TrimText(fields[4])
    local token = TrimText(fields[5])
    local kind = string.upper(TrimText(fields[6]))
    local rowIndex = math.max(0, tonumber(fields[7]) or 0)
    local activeSession, activeProfileName = GetActiveLootSession()
    if rowIndex <= 0
      or not DoesRuntimeSessionMatch(activeSession, activeProfileName, sessionId, profileName)
      or not IsSelfHost(activeSession)
    then
      return
    end
    local transaction = boardSyncTransactions.outgoing[
      boardSyncTransactions.GetOutgoingKey(sessionId, profileName, sender, token)
    ]
    if type(transaction) ~= "table" or TrimText(transaction.boardId) ~= boardId then
      RecordRaidTraceEvent("BSYNC_ACK_IGNORED", "Receipt did not match an active transaction.", {
        boardId = boardId,
        token = token,
        target = NormalizeCharacterKey(sender),
        status = status,
      })
      return
    end
    RecordRaidTraceEvent("BSYNC_ACK_RECEIVED", status, {
      boardId = boardId,
      token = token,
      target = NormalizeCharacterKey(sender),
      items = receivedItems,
      selections = receivedSelections,
      votes = receivedVotes,
      checksumMatched = string.lower(checksum) == string.lower(TrimText(transaction.checksum)),
    })
    local scope = kind == "I" and "item" or (kind == "S" and "selection" or (kind == "V" and "vote" or ""))
    local rows = scope ~= "" and transaction[scope .. "Rows"] or nil
    if type(rows) ~= "table" or type(rows[rowIndex]) ~= "table" then
      return
    end
    transaction.missing[scope][rowIndex] = true
  end

  function boardSyncTransactions.HandleReceipt(fields, sender)
    if not HasExactFieldCount(fields, "BSYNC_ACK") then
      return
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local boardId = TrimText(fields[4])
    local token = TrimText(fields[5])
    local receivedItems = math.max(0, tonumber(fields[6]) or 0)
    local receivedSelections = math.max(0, tonumber(fields[7]) or 0)
    local receivedVotes = math.max(0, tonumber(fields[8]) or 0)
    local checksum = TrimText(fields[9])
    local status = string.upper(TrimText(fields[10]))
    local activeSession, activeProfileName = GetActiveLootSession()
    if not DoesRuntimeSessionMatch(activeSession, activeProfileName, sessionId, profileName)
      or not IsSelfHost(activeSession)
    then
      return
    end
    local transaction = boardSyncTransactions.outgoing[
      boardSyncTransactions.GetOutgoingKey(sessionId, profileName, sender, token)
    ]
    if type(transaction) ~= "table" or TrimText(transaction.boardId) ~= boardId then
      return
    end
    transaction.receiptWatch = math.max(0, tonumber(transaction.receiptWatch) or 0) + 1
    transaction.lastReceiptStatus = status
    transaction.lastReceiptAt = GetCurrentTimestamp()
    if status == "COMPLETE"
      and receivedItems == transaction.itemCount
      and receivedSelections == transaction.selectionCount
      and receivedVotes == transaction.voteCount
      and string.lower(checksum) == string.lower(TrimText(transaction.checksum))
    then
      transaction.state = "complete"
      runtime.lastBoardSyncReceipt = {
        target = transaction.targetKey,
        boardId = transaction.boardId,
        token = transaction.token,
        itemCount = receivedItems,
        selectionCount = receivedSelections,
        voteCount = receivedVotes,
        checksum = checksum,
        at = transaction.lastReceiptAt,
      }
      boardSyncTransactions.UpdateRealSimulationDispatch(transaction, "acknowledged", "")
      boardSyncTransactions.outgoing[transaction.key] = nil
      if type(boardSyncTransactions.OnStagedTransactionTerminal) == "function" then
        boardSyncTransactions.OnStagedTransactionTerminal(transaction, "acknowledged", "")
      end
      RecordRaidTraceEvent("BSYNC_ACK_COMPLETE", "Board transaction acknowledged.", {
        boardId = boardId,
        token = token,
        target = NormalizeCharacterKey(sender),
        items = receivedItems,
        selections = receivedSelections,
        votes = receivedVotes,
      })
      return
    end
    if status == "MISSING" then
      local missingCount = 0
      for _, rows in pairs(transaction.missing or {}) do
        for _ in pairs(rows) do
          missingCount = missingCount + 1
        end
      end
      if missingCount > 0 then
        boardSyncTransactions.SendSelectiveRepair(transaction)
      elseif type(C_Timer) == "table" and type(C_Timer.After) == "function" then
        C_Timer.After(0.1, function()
          if boardSyncTransactions.outgoing[transaction.key] ~= transaction then
            return
          end
          local delayedMissingCount = 0
          for _, rows in pairs(transaction.missing or {}) do
            for _ in pairs(rows) do
              delayedMissingCount = delayedMissingCount + 1
            end
          end
          if delayedMissingCount > 0 then
            boardSyncTransactions.SendSelectiveRepair(transaction)
          else
            boardSyncTransactions.SendFullRebuild(transaction, "missing_manifest_without_rows")
          end
        end)
      else
        boardSyncTransactions.SendFullRebuild(transaction, "missing_manifest_without_rows")
      end
      return
    end
    boardSyncTransactions.SendFullRebuild(transaction, status ~= "" and status or "checksum_mismatch")
  end

  function boardSyncTransactions.HandleBoardSyncEnd(fields, sender)
    if not HasExactFieldCount(fields, "BSYNC_END") then
      boardSyncTransactions.RecordReceiver("rejected", nil, sender, "invalid_end_field_count")
      return
    end
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local boardId = TrimText(fields[4])
    local selectedItemKey = TrimText(fields[5])
    local transactionToken = TrimText(fields[6])
    RecordRaidTraceEvent("BSYNC_RECEIVER_END", "Member received a board transaction end.", {
      boardId = boardId,
      token = transactionToken,
      sender = NormalizeCharacterKey(sender),
    })
    if sessionId == "" or profileName == "" then
      boardSyncTransactions.RecordReceiver("rejected", nil, sender, "missing_session_or_profile", {
        sessionId = sessionId,
        profileName = profileName,
        boardId = boardId,
        token = transactionToken,
      })
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    if not DoesRuntimeSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      boardSyncTransactions.RecordReceiver("rejected", nil, sender, "session_or_profile_mismatch", {
        sessionId = sessionId,
        profileName = profileName,
        boardId = boardId,
        token = transactionToken,
      })
      return
    end
    if not IsSessionHostKey(activeSession, sender) then
      boardSyncTransactions.RecordReceiver("rejected", nil, sender, "sender_is_not_session_host", {
        sessionId = sessionId,
        profileName = profileName,
        boardId = boardId,
        token = transactionToken,
      })
      return
    end
    if not EnsureRuntimeSession(activeSession, activeProfileName) then
      boardSyncTransactions.RecordReceiver("rejected", nil, sender, "runtime_session_unavailable", {
        sessionId = sessionId,
        profileName = profileName,
        boardId = boardId,
        token = transactionToken,
      })
      return
    end

    local token = GetBoardSyncToken(sessionId, profileName, sender)
    local syncState = incomingBoardSyncs[token]
    if type(syncState) ~= "table" then
      local completedReceipt = transactionToken ~= "" and boardSyncTransactions.completedReceipts[
        boardSyncTransactions.GetCompletedKey(sessionId, profileName, sender, transactionToken)
      ] or nil
      if type(completedReceipt) == "table" then
        local ackSent = boardSyncTransactions.SendReceipt(completedReceipt, sender, "COMPLETE")
        boardSyncTransactions.RecordReceiver("duplicate_complete", completedReceipt, sender, "end_replayed", {
          checksumMatched = true,
          missingCount = 0,
          ackStatus = "COMPLETE",
          ackSent = ackSent,
        })
      else
        boardSyncTransactions.RecordReceiver("rejected", nil, sender, "end_without_start", {
          sessionId = sessionId,
          profileName = profileName,
          boardId = boardId,
          token = transactionToken,
        })
      end
      return
    end
    if transactionToken ~= "" and TrimText(syncState.token) ~= transactionToken then
      boardSyncTransactions.RecordReceiver("rejected", syncState, sender, "transaction_token_mismatch")
      return
    end
    if TrimText(syncState.token) ~= "" then
      local missing, missingCount = boardSyncTransactions.CollectMissing(syncState)
      if missingCount > 0 then
        boardSyncTransactions.SendMissingRequests(syncState, sender, missing)
        local ackSent = boardSyncTransactions.SendReceipt(syncState, sender, "MISSING")
        boardSyncTransactions.RecordReceiver("incomplete", syncState, sender, "missing_rows", {
          missingCount = missingCount,
          ackStatus = "MISSING",
          ackSent = ackSent,
        })
        return
      end
      local receivedChecksum = boardSyncTransactions.CalculateManifestChecksum(
        syncState.itemSignatures,
        syncState.selectionSignatures,
        syncState.voteSignatures,
        {
          items = syncState.expectedItems,
          selections = syncState.expectedSelections,
          votes = syncState.expectedVotes,
        }
      )
      if string.lower(receivedChecksum) ~= string.lower(TrimText(syncState.expectedChecksum)) then
        local ackSent = boardSyncTransactions.SendReceipt(syncState, sender, "CHECKSUM")
        boardSyncTransactions.RecordReceiver("checksum_mismatch", syncState, sender, "manifest_checksum_mismatch", {
          checksumMatched = false,
          ackStatus = "CHECKSUM",
          ackSent = ackSent,
        })
        return
      end
    end
    incomingBoardSyncs[token] = nil

    local restoredLocalChoices = 0
    local confirmedLocalChoices = 0
    for localItemKey, snapshot in pairs(type(syncState.localChoiceSnapshots) == "table" and syncState.localChoiceSnapshots or {}) do
      local entry = type(runtime.items) == "table" and runtime.items[localItemKey] or nil
      local localSelection = type(snapshot) == "table" and snapshot.selection or nil
      local memberKey = NormalizeCharacterKey(type(snapshot) == "table" and snapshot.memberKey or "")
      if type(entry) == "table" and type(localSelection) == "table" and memberKey ~= "" then
        local hostSelection, storedMemberKey = ResolveEntrySelection(entry, memberKey)
        local localSeq = math.max(0, math.floor(tonumber(localSelection.selectedSeq) or 0))
        local hostSeq = math.max(0, math.floor(tonumber(type(hostSelection) == "table" and hostSelection.selectedSeq) or 0))
        local exactHostChoice = type(hostSelection) == "table"
          and not IsPendingSelection(hostSelection)
          and hostSeq == localSeq
          and string.lower(TrimText(hostSelection.optionKey)) == string.lower(TrimText(localSelection.optionKey))
        if exactHostChoice then
          if ConfirmPendingChoiceReceipt(
            sessionId,
            localItemKey,
            memberKey,
            tonumber(hostSelection.selectedAt),
            hostSeq
          ) then
            confirmedLocalChoices = confirmedLocalChoices + 1
          end
        elseif hostSeq < localSeq or IsPendingSelection(hostSelection) then
          entry.selections = type(entry.selections) == "table" and entry.selections or {}
          entry.selections[TrimText(storedMemberKey) ~= "" and storedMemberKey or memberKey] = type(DeepCopy) == "function"
            and DeepCopy(localSelection)
            or localSelection
          restoredLocalChoices = restoredLocalChoices + 1
        end
      end
    end

    local compactOrder = {}
    for _, itemKey in ipairs(runtime.itemOrder or {}) do
      if TrimText(itemKey) ~= "" and type(runtime.items[itemKey]) == "table" then
        compactOrder[#compactOrder + 1] = itemKey
      end
    end
    runtime.itemOrder = compactOrder
    runtime.boardId = boardId ~= "" and boardId or runtime.boardId
    runtime.selectedItemKey = selectedItemKey ~= "" and selectedItemKey or (type(syncState) == "table" and TrimText(syncState.selectedItemKey)) or runtime.itemOrder[#runtime.itemOrder]
    if runtime.selectedItemKey ~= "" and type(runtime.items[runtime.selectedItemKey]) ~= "table" then
      runtime.selectedItemKey = runtime.itemOrder[#runtime.itemOrder]
    end
    runtime.popupQueue = {}
    for _, itemKey in ipairs(runtime.itemOrder) do
      local entry = runtime.items[itemKey]
      if type(entry) == "table" then
        NormalizeEntryVotes(entry)
        NormalizeVoteUpdatedAt(entry)
        if type(NormalizeVoteSequence) == "function" then
          NormalizeVoteSequence(entry)
        end
        local selfKey = GetSelfKey()
        local _, localMemberKey = GetSessionMember(activeSession, selfKey)
        local choiceMemberKey = localMemberKey or (IsSessionHostKey(activeSession, selfKey) and TrimText(activeSession.host) or selfKey)
        local pendingReady = boardSyncTransactions.EnsurePendingSelectionForMember(entry, choiceMemberKey)
        if not tonumber(entry.awardedAt) and pendingReady == true then
          runtime.popupQueue[#runtime.popupQueue + 1] = itemKey
        end
      end
    end
    runtime.boardUpdatedAt = math.max(tonumber(runtime.boardUpdatedAt) or 0, tonumber(type(syncState) == "table" and syncState.updatedAt) or 0)
    runtime.lastBoardSyncSender = NormalizeSenderKey(sender)
    if type(ClearPreviewState) == "function" then
      ClearPreviewState()
    end
    PersistRuntimeBoardHistory()
    if restoredLocalChoices > 0 and type(RearmUnconfirmedChoiceReceipts) == "function" then
      RearmUnconfirmedChoiceReceipts({
        reason = "board_sync_missing_local_choice",
        restored = restoredLocalChoices,
        confirmed = confirmedLocalChoices,
      })
    end
    local ackSent = false
    if TrimText(syncState.token) ~= "" then
      boardSyncTransactions.completedReceipts[
        boardSyncTransactions.GetCompletedKey(sessionId, profileName, sender, syncState.token)
      ] = syncState
      ackSent = boardSyncTransactions.SendReceipt(syncState, sender, "COMPLETE")
    end
    boardSyncTransactions.RecordReceiver("complete", syncState, sender, "", {
      checksumMatched = true,
      missingCount = 0,
      ackStatus = TrimText(syncState.token) ~= "" and "COMPLETE" or "LEGACY",
      ackSent = TrimText(syncState.token) == "" or ackSent,
      popupQueueCount = #(runtime.popupQueue or {}),
      popupOpened = false,
      popupState = "pending",
      popupReason = "ui_refresh_pending",
    })
    RefreshBoardAndEditor({
      reason = "sync",
      itemKey = runtime.selectedItemKey,
      editorRefresh = { refreshPages = { Panels = true, LiveBoard = true, Backgrounds = true } },
    })
    local popupOpened = false
    if type(RefreshChoicePopup) == "function" then
      popupOpened = RefreshChoicePopup({
        reason = "sync",
        itemKey = runtime.selectedItemKey,
      }) == true
    end
    local popupState = type(runtime.lastChoicePopupState) == "table" and runtime.lastChoicePopupState or {}
    boardSyncTransactions.RecordReceiver("complete", syncState, sender, "", {
      checksumMatched = true,
      missingCount = 0,
      ackStatus = TrimText(syncState.token) ~= "" and "COMPLETE" or "LEGACY",
      ackSent = TrimText(syncState.token) == "" or ackSent,
      popupQueueCount = #(runtime.popupQueue or {}),
      popupOpened = popupOpened,
      popupState = popupState.state,
      popupReason = popupState.reason,
    })
    if type(Print) == "function" then
      Print("Received a Live Board sync from " .. tostring(sender or "session host") .. ".")
    end
  end

  local function ApplyCombatStagedRuntimeOp(entry)
    local payload = type(entry) == "table" and type(entry.payload) == "table" and entry.payload or {}
    local opcode = string.upper(TrimText(type(entry) == "table" and entry.opcode or ""))
    local fields = type(payload.fields) == "table" and payload.fields or nil
    local sender = payload.sender
    if opcode == "LL_ADD_REQ" then
      boardSyncTransactions.HandleManualLedgerAddRequest(fields, sender)
    elseif opcode == "LL_ADD" then
      boardSyncTransactions.HandleManualLedgerAddBroadcast(fields, sender)
    elseif opcode == "LL_DEL_REQ" then
      boardSyncTransactions.HandleManualLedgerDeleteRequest(fields, sender)
    elseif opcode == "LL_DEL" then
      boardSyncTransactions.HandleManualLedgerDeleteBroadcast(fields, sender)
    elseif opcode == "LL_MA_REQ" then
      boardSyncTransactions.HandleLootLedgerMainAltRequest(fields, sender)
    elseif opcode == "LL_MA" then
      boardSyncTransactions.HandleLootLedgerMainAltBroadcast(fields, sender)
    elseif opcode == "LL_NOTE_REQ" then
      boardSyncTransactions.HandleLootLedgerCharacterNoteRequest(fields, sender)
    elseif opcode == "LL_NOTE" then
      boardSyncTransactions.HandleLootLedgerCharacterNoteBroadcast(fields, sender)
    elseif opcode == "LL_CHAR_DEL_REQ" then
      boardSyncTransactions.HandleLootLedgerCharacterDeleteRequest(fields, sender)
    elseif opcode == "LL_CHAR_DEL" then
      boardSyncTransactions.HandleLootLedgerCharacterDeleteBroadcast(fields, sender)
    elseif opcode == "BSYNC_START" then
      boardSyncTransactions.HandleBoardSyncStart(fields, sender)
    elseif opcode == "BSYNC_ITEM" then
      boardSyncTransactions.HandleBoardSyncItem(fields, sender)
    elseif opcode == "BSYNC_SEL" then
      boardSyncTransactions.HandleBoardSyncSelection(fields, sender)
    elseif opcode == "BSYNC_VOTE" then
      boardSyncTransactions.HandleBoardSyncVote(fields, sender)
    elseif opcode == "BSYNC_END" then
      boardSyncTransactions.HandleBoardSyncEnd(fields, sender)
    elseif opcode == "BSYNC_MISS" then
      boardSyncTransactions.HandleMissing(fields, sender)
    elseif opcode == "BSYNC_ACK" then
      boardSyncTransactions.HandleReceipt(fields, sender)
    else
      return false, "unsupported_runtime_opcode"
    end
    return true, "applied"
  end

  local function HandleSessionComm(fields, sender)
    local opcode = TrimText(type(fields) == "table" and fields[1] or "")
    if opcode ~= "" then
      runtime.lastReceivedOpcode = opcode
      runtime.lastReceivedSender = NormalizeSenderKey(sender)
    end
    local activeSession, activeProfileName = GetActiveLootSession()
    local allowPreparedOpcode = COMBAT_STAGED_RUNTIME_OPCODE_SET.__preparedSession[opcode] == true
    if activeSession and not IsLiveSession(activeSession) and not allowPreparedOpcode then
      return false
    end
    if type(activeSession) == "table"
      and IsCombatLocked()
      and COMBAT_STAGED_RUNTIME_OPCODE_SET[opcode] == true
      and DoesRuntimeSessionMatch(
        activeSession,
        activeProfileName,
        TrimText(type(fields) == "table" and fields[2] or ""),
        TrimText(type(fields) == "table" and fields[3] or "")
      )
    then
      local queued, queueReason = QueueRuntimeCombatOp(opcode, fields, sender)
      runtime.lastCombatStagedOpcode = opcode
      runtime.lastCombatStagedReason = TrimText(queueReason)
      runtime.lastCombatStagedAccepted = queued == true
      runtime.lastCombatStagedAt = type(GetServerTime) == "function"
        and math.max(0, tonumber(GetServerTime()) or 0)
        or math.max(0, tonumber(time and time() or 0) or 0)
      return true
    end
    if opcode == "CHOICE" then
      boardSyncTransactions.HandleChoiceMessage(fields, sender)
      return true
    elseif opcode == "RCHOICE" then
      boardSyncTransactions.HandleMirroredChoiceMessage(fields, sender)
      return true
    elseif opcode == "RCHOICE_ACK" then
      boardSyncTransactions.HandleMirroredChoiceReceipt(fields, sender)
      return true
    elseif opcode == "ITEM_REPORT" then
      boardSyncTransactions.HandleItemReportMessage(fields, sender)
      return true
    elseif opcode == "ITEM_OPEN" then
      boardSyncTransactions.HandleItemOpenMessage(fields, sender)
      return true
    elseif opcode == "ITEM_ACK" then
      boardSyncTransactions.HandleItemOpenReceipt(fields, sender)
      return true
    elseif opcode == "AWARD" then
      boardSyncTransactions.HandleAwardMessage(fields, sender)
      return true
    elseif opcode == "UNASSIGN" then
      boardSyncTransactions.HandleUnassignMessage(fields, sender)
      return true
    elseif opcode == "TRADE" then
      boardSyncTransactions.HandleTradeMessage(fields, sender)
      return true
    elseif opcode == "VOTE" then
      boardSyncTransactions.HandleVoteMessage(fields, sender)
      return true
    elseif opcode == "LL_ADD_REQ" then
      boardSyncTransactions.HandleManualLedgerAddRequest(fields, sender)
      return true
    elseif opcode == "LL_ADD" then
      boardSyncTransactions.HandleManualLedgerAddBroadcast(fields, sender)
      return true
    elseif opcode == "LL_DEL_REQ" then
      boardSyncTransactions.HandleManualLedgerDeleteRequest(fields, sender)
      return true
    elseif opcode == "LL_DEL" then
      boardSyncTransactions.HandleManualLedgerDeleteBroadcast(fields, sender)
      return true
    elseif opcode == "LL_MA_REQ" then
      boardSyncTransactions.HandleLootLedgerMainAltRequest(fields, sender)
      return true
    elseif opcode == "LL_MA" then
      boardSyncTransactions.HandleLootLedgerMainAltBroadcast(fields, sender)
      return true
    elseif opcode == "LL_NOTE_REQ" then
      boardSyncTransactions.HandleLootLedgerCharacterNoteRequest(fields, sender)
      return true
    elseif opcode == "LL_NOTE" then
      boardSyncTransactions.HandleLootLedgerCharacterNoteBroadcast(fields, sender)
      return true
    elseif opcode == "LL_CHAR_DEL_REQ" then
      boardSyncTransactions.HandleLootLedgerCharacterDeleteRequest(fields, sender)
      return true
    elseif opcode == "LL_CHAR_DEL" then
      boardSyncTransactions.HandleLootLedgerCharacterDeleteBroadcast(fields, sender)
      return true
    elseif opcode == "BSYNC_START" then
      boardSyncTransactions.HandleBoardSyncStart(fields, sender)
      return true
    elseif opcode == "BSYNC_ITEM" then
      boardSyncTransactions.HandleBoardSyncItem(fields, sender)
      return true
    elseif opcode == "BSYNC_SEL" then
      boardSyncTransactions.HandleBoardSyncSelection(fields, sender)
      return true
    elseif opcode == "BSYNC_VOTE" then
      boardSyncTransactions.HandleBoardSyncVote(fields, sender)
      return true
    elseif opcode == "BSYNC_END" then
      boardSyncTransactions.HandleBoardSyncEnd(fields, sender)
      return true
    elseif opcode == "BSYNC_MISS" then
      boardSyncTransactions.HandleMissing(fields, sender)
      return true
    elseif opcode == "BSYNC_ACK" then
      boardSyncTransactions.HandleReceipt(fields, sender)
      return true
    end
    return false
  end

  local function ClearRuntimeCommSessionState(sessionId)
    local resolvedSessionId = string.lower(TrimText(sessionId))
    local prefix = resolvedSessionId ~= "" and (resolvedSessionId .. "|") or ""
    local cleared = 0
    for token in pairs(incomingBoardSyncs) do
      if prefix == "" or string.sub(token, 1, #prefix) == prefix then
        incomingBoardSyncs[token] = nil
        cleared = cleared + 1
      end
    end
    for token in pairs(boardSyncTransactions.completedReceipts) do
      if prefix == "" or string.sub(token, 1, #prefix) == prefix then
        boardSyncTransactions.completedReceipts[token] = nil
        cleared = cleared + 1
      end
    end
    for token, transaction in pairs(boardSyncTransactions.outgoing) do
      if prefix == ""
        or string.lower(TrimText(type(transaction) == "table" and transaction.sessionId or "")) == resolvedSessionId
      then
        boardSyncTransactions.outgoing[token] = nil
        cleared = cleared + 1
      end
    end
    for dispatchKey, dispatch in pairs(boardSyncTransactions.stagedDispatches) do
      if prefix == ""
        or string.lower(TrimText(type(dispatch) == "table" and dispatch.sessionId or "")) == resolvedSessionId
      then
        if type(dispatch) == "table" then
          dispatch.state = "cancelled"
          dispatch.lastCapacityReason = "session_state_cleared"
          dispatch.pumpWatch = math.max(0, tonumber(dispatch.pumpWatch) or 0) + 1
          boardSyncTransactions.UpdateStagedDispatchRuntime(dispatch)
        end
        boardSyncTransactions.stagedDispatches[dispatchKey] = nil
        cleared = cleared + 1
      end
    end
    for token, transaction in pairs(boardSyncTransactions.itemOpenOutgoing) do
      if prefix == ""
        or string.lower(TrimText(type(transaction) == "table" and transaction.sessionId or "")) == resolvedSessionId
      then
        boardSyncTransactions.itemOpenOutgoing[token] = nil
        cleared = cleared + 1
      end
    end
    for token, transaction in pairs(boardSyncTransactions.completedItemOpenReceipts) do
      if prefix == ""
        or string.lower(TrimText(type(transaction) == "table" and transaction.sessionId or "")) == resolvedSessionId
      then
        boardSyncTransactions.completedItemOpenReceipts[token] = nil
        cleared = cleared + 1
      end
    end
    for identity, transaction in pairs(boardSyncTransactions.itemOpenByIdentity) do
      if prefix == ""
        or string.lower(TrimText(type(transaction) == "table" and transaction.sessionId or "")) == resolvedSessionId
      then
        boardSyncTransactions.itemOpenByIdentity[identity] = nil
      end
    end
    for reportKey, report in pairs(boardSyncTransactions.itemOpenReports) do
      if prefix == ""
        or string.lower(TrimText(type(report) == "table" and report.sessionId or "")) == resolvedSessionId
      then
        boardSyncTransactions.itemOpenReports[reportKey] = nil
      end
    end
    for identity, transaction in pairs(boardSyncTransactions.choiceMirrorOutgoing) do
      if prefix == ""
        or string.lower(TrimText(type(transaction) == "table" and transaction.sessionId or "")) == resolvedSessionId
      then
        boardSyncTransactions.choiceMirrorOutgoing[identity] = nil
        cleared = cleared + 1
      end
    end
    return cleared
  end

  if type(INTERNAL_API.LIDCOUNCIL_RegisterCombatSyncInboxApplier_Impl) ~= "function" then
    error("LidCouncil missing runtime combat inbox registration.")
  end
  for _, opcode in ipairs(COMBAT_STAGED_RUNTIME_OPCODES) do
    if not INTERNAL_API.LIDCOUNCIL_RegisterCombatSyncInboxApplier_Impl(
      opcode,
      "loot_runtime",
      ApplyCombatStagedRuntimeOp
    )
    then
      error("LidCouncil could not register runtime combat inbox opcode " .. tostring(opcode) .. ".")
    end
  end
  INTERNAL_API.LIDCOUNCIL_ClearLootRuntimeCommSessionState_Impl = ClearRuntimeCommSessionState

  return {
    SendActiveLiveBoardSyncFlow = SendActiveLiveBoardSyncFlow,
    ReportLootRollToHost = ReportLootRollToHost,
    OpenAuthoritativeLootItem = OpenAuthoritativeLootItem,
    OpenTransportSimulationItem = boardSyncTransactions.OpenTransportSimulationItem,
    RequestManualLootLedgerEntryFlow = RequestManualLootLedgerEntryFlow,
    RequestManualLootLedgerDeleteFlow = RequestManualLootLedgerDeleteFlow,
    RequestLootLedgerMainAltFlow = RequestLootLedgerMainAltFlow,
    RequestLootLedgerCharacterNoteFlow = RequestLootLedgerCharacterNoteFlow,
    RequestLootLedgerCharacterDeleteFlow = RequestLootLedgerCharacterDeleteFlow,
    HandleSessionComm = HandleSessionComm,
    SendChoicePacket = SendChoicePacket,
    PrepareChoicePacket = PrepareChoicePacket,
    SendAwardPacket = boardSyncTransactions.SendAwardPacket,
    PrepareAwardPacket = boardSyncTransactions.PrepareAwardPacket,
    BroadcastAuthoritativeChoice = BroadcastAuthoritativeChoice,
    RunChoiceBurstValidation = boardSyncTransactions.RunChoiceBurstValidation,
    RunBoardSyncReceiptValidation = boardSyncTransactions.RunBoardSyncReceiptValidation,
  }
end
